kernel - Improve vfork/exec and wait*() performance
[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. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/kernel.h>
35 #include <sys/sysctl.h>
36 #include <sys/malloc.h>
37 #include <sys/proc.h>
38 #include <sys/vnode.h>
39 #include <sys/jail.h>
40 #include <sys/filedesc.h>
41 #include <sys/tty.h>
42 #include <sys/dsched.h>
43 #include <sys/signalvar.h>
44 #include <sys/spinlock.h>
45 #include <vm/vm.h>
46 #include <sys/lock.h>
47 #include <vm/pmap.h>
48 #include <vm/vm_map.h>
49 #include <sys/user.h>
50 #include <machine/smp.h>
51
52 #include <sys/refcount.h>
53 #include <sys/spinlock2.h>
54 #include <sys/mplock2.h>
55
56 #define PIDHASH(pid)    (&pidhashtbl[(pid) & pidhash])
57 #define PIDSPIN(pid)    (&pidspintbl[(pid) & pidhash])
58 LIST_HEAD(pidhashhead, proc);
59
60 static MALLOC_DEFINE(M_PGRP, "pgrp", "process group header");
61 MALLOC_DEFINE(M_SESSION, "session", "session header");
62 MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
63 MALLOC_DEFINE(M_LWP, "lwp", "lwp structures");
64 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
65
66 int ps_showallprocs = 1;
67 static int ps_showallthreads = 1;
68 SYSCTL_INT(_security, OID_AUTO, ps_showallprocs, CTLFLAG_RW,
69     &ps_showallprocs, 0,
70     "Unprivileged processes can see processes with different UID/GID");
71 SYSCTL_INT(_security, OID_AUTO, ps_showallthreads, CTLFLAG_RW,
72     &ps_showallthreads, 0,
73     "Unprivileged processes can see kernel threads");
74
75 static void orphanpg(struct pgrp *pg);
76 static pid_t proc_getnewpid_locked(int random_offset);
77
78 /*
79  * Other process lists
80  */
81 static struct pidhashhead *pidhashtbl;
82 static struct spinlock *pidspintbl;
83 static u_long pidhash;
84
85 struct pgrphashhead *pgrphashtbl;
86 u_long pgrphash;
87
88 struct proclist allproc;
89 struct proclist zombproc;
90 struct spinlock pghash_spin = SPINLOCK_INITIALIZER(&pghash_spin);
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         u_long i;
136
137         LIST_INIT(&allproc);
138         LIST_INIT(&zombproc);
139         lwkt_init();
140         pidhashtbl = hashinit(maxproc / 4, M_PROC, &pidhash);
141         pidspintbl = kmalloc(sizeof(*pidspintbl) * (pidhash + 1), M_PROC,
142                              M_WAITOK | M_ZERO);
143         for (i = 0; i <= pidhash; ++i)
144                 spin_init(&pidspintbl[i]);
145
146         pgrphashtbl = hashinit(maxproc / 4, M_PROC, &pgrphash);
147         uihashinit();
148 }
149
150 /*
151  * Process hold/release support functions.  These functions must be MPSAFE.
152  * Called via the PHOLD(), PRELE(), and PSTALL() macros.
153  *
154  * p->p_lock is a simple hold count with a waiting interlock.  No wakeup()
155  * is issued unless someone is actually waiting for the process.
156  *
157  * Most holds are short-term, allowing a process scan or other similar
158  * operation to access a proc structure without it getting ripped out from
159  * under us.  procfs and process-list sysctl ops also use the hold function
160  * interlocked with various p_flags to keep the vmspace intact when reading
161  * or writing a user process's address space.
162  *
163  * There are two situations where a hold count can be longer.  Exiting lwps
164  * hold the process until the lwp is reaped, and the parent will hold the
165  * child during vfork()/exec() sequences while the child is marked P_PPWAIT.
166  *
167  * The kernel waits for the hold count to drop to 0 (or 1 in some cases) at
168  * various critical points in the fork/exec and exit paths before proceeding.
169  */
170 #define PLOCK_ZOMB      0x20000000
171 #define PLOCK_WAITING   0x40000000
172 #define PLOCK_MASK      0x1FFFFFFF
173
174 void
175 pstall(struct proc *p, const char *wmesg, int count)
176 {
177         int o;
178         int n;
179
180         for (;;) {
181                 o = p->p_lock;
182                 cpu_ccfence();
183                 if ((o & PLOCK_MASK) <= count)
184                         break;
185                 n = o | PLOCK_WAITING;
186                 tsleep_interlock(&p->p_lock, 0);
187
188                 /*
189                  * If someone is trying to single-step the process during
190                  * an exec or an exit they can deadlock us because procfs
191                  * sleeps with the process held.
192                  */
193                 if (p->p_stops) {
194                         if (p->p_flags & P_INEXEC) {
195                                 wakeup(&p->p_stype);
196                         } else if (p->p_flags & P_POSTEXIT) {
197                                 spin_lock(&p->p_spin);
198                                 p->p_stops = 0;
199                                 p->p_step = 0;
200                                 spin_unlock(&p->p_spin);
201                                 wakeup(&p->p_stype);
202                         }
203                 }
204
205                 if (atomic_cmpset_int(&p->p_lock, o, n)) {
206                         tsleep(&p->p_lock, PINTERLOCKED, wmesg, 0);
207                 }
208         }
209 }
210
211 void
212 phold(struct proc *p)
213 {
214         atomic_add_int(&p->p_lock, 1);
215 }
216
217 /*
218  * WARNING!  On last release (p) can become instantly invalid due to
219  *           MP races.
220  */
221 void
222 prele(struct proc *p)
223 {
224         int o;
225         int n;
226
227         /*
228          * Fast path
229          */
230         if (atomic_cmpset_int(&p->p_lock, 1, 0))
231                 return;
232
233         /*
234          * Slow path
235          */
236         for (;;) {
237                 o = p->p_lock;
238                 KKASSERT((o & PLOCK_MASK) > 0);
239                 cpu_ccfence();
240                 n = (o - 1) & ~PLOCK_WAITING;
241                 if (atomic_cmpset_int(&p->p_lock, o, n)) {
242                         if (o & PLOCK_WAITING)
243                                 wakeup(&p->p_lock);
244                         break;
245                 }
246         }
247 }
248
249 /*
250  * Hold and flag serialized for zombie reaping purposes.
251  *
252  * This function will fail if it has to block, returning non-zero with
253  * neither the flag set or the hold count bumped.  Note that we must block
254  * without holding a ref, meaning that the caller must ensure that (p)
255  * remains valid through some other interlock (typically on its parent
256  * process's p_token).
257  *
258  * Zero is returned on success.  The hold count will be incremented and
259  * the serialization flag acquired.  Note that serialization is only against
260  * other pholdzomb() calls, not against phold() calls.
261  */
262 int
263 pholdzomb(struct proc *p)
264 {
265         int o;
266         int n;
267
268         /*
269          * Fast path
270          */
271         if (atomic_cmpset_int(&p->p_lock, 0, PLOCK_ZOMB | 1))
272                 return(0);
273
274         /*
275          * Slow path
276          */
277         for (;;) {
278                 o = p->p_lock;
279                 cpu_ccfence();
280                 if ((o & PLOCK_ZOMB) == 0) {
281                         n = (o + 1) | PLOCK_ZOMB;
282                         if (atomic_cmpset_int(&p->p_lock, o, n))
283                                 return(0);
284                 } else {
285                         KKASSERT((o & PLOCK_MASK) > 0);
286                         n = o | PLOCK_WAITING;
287                         tsleep_interlock(&p->p_lock, 0);
288                         if (atomic_cmpset_int(&p->p_lock, o, n)) {
289                                 tsleep(&p->p_lock, PINTERLOCKED, "phldz", 0);
290                                 /* (p) can be ripped out at this point */
291                                 return(1);
292                         }
293                 }
294         }
295 }
296
297 /*
298  * Release PLOCK_ZOMB and the hold count, waking up any waiters.
299  *
300  * WARNING!  On last release (p) can become instantly invalid due to
301  *           MP races.
302  */
303 void
304 prelezomb(struct proc *p)
305 {
306         int o;
307         int n;
308
309         /*
310          * Fast path
311          */
312         if (atomic_cmpset_int(&p->p_lock, PLOCK_ZOMB | 1, 0))
313                 return;
314
315         /*
316          * Slow path
317          */
318         KKASSERT(p->p_lock & PLOCK_ZOMB);
319         for (;;) {
320                 o = p->p_lock;
321                 KKASSERT((o & PLOCK_MASK) > 0);
322                 cpu_ccfence();
323                 n = (o - 1) & ~(PLOCK_ZOMB | PLOCK_WAITING);
324                 if (atomic_cmpset_int(&p->p_lock, o, n)) {
325                         if (o & PLOCK_WAITING)
326                                 wakeup(&p->p_lock);
327                         break;
328                 }
329         }
330 }
331
332 /*
333  * Is p an inferior of the current process?
334  *
335  * No requirements.
336  * The caller must hold proc_token if the caller wishes a stable result.
337  */
338 int
339 inferior(struct proc *p)
340 {
341         lwkt_gettoken_shared(&proc_token);
342         while (p != curproc) {
343                 if (p->p_pid == 0) {
344                         lwkt_reltoken(&proc_token);
345                         return (0);
346                 }
347                 p = p->p_pptr;
348         }
349         lwkt_reltoken(&proc_token);
350         return (1);
351 }
352
353 /*
354  * Locate a process by number.  The returned process will be referenced and
355  * must be released with PRELE().
356  *
357  * No requirements.
358  */
359 struct proc *
360 pfind(pid_t pid)
361 {
362         struct proc *p = curproc;
363
364         /*
365          * Shortcut the current process
366          */
367         if (p && p->p_pid == pid) {
368                 PHOLD(p);
369                 return (p);
370         }
371
372         /*
373          * Otherwise find it in the hash table.
374          */
375         spin_lock_shared(PIDSPIN(pid));
376         LIST_FOREACH(p, PIDHASH(pid), p_hash) {
377                 if (p->p_pid == pid) {
378                         PHOLD(p);
379                         spin_unlock_shared(PIDSPIN(pid));
380                         return (p);
381                 }
382         }
383         spin_unlock_shared(PIDSPIN(pid));
384
385         return (NULL);
386 }
387
388 /*
389  * Locate a process by number.  The returned process is NOT referenced.
390  * The caller should hold proc_token if the caller wishes a stable result.
391  *
392  * No requirements.
393  */
394 struct proc *
395 pfindn(pid_t pid)
396 {
397         struct proc *p = curproc;
398
399         /*
400          * Shortcut the current process
401          */
402         if (p && p->p_pid == pid)
403                 return (p);
404
405         spin_lock_shared(PIDSPIN(pid));
406         LIST_FOREACH(p, PIDHASH(pid), p_hash) {
407                 if (p->p_pid == pid) {
408                         spin_unlock_shared(PIDSPIN(pid));
409                         return (p);
410                 }
411         }
412         spin_unlock_shared(PIDSPIN(pid));
413
414         return (NULL);
415 }
416
417 void
418 pgref(struct pgrp *pgrp)
419 {
420         refcount_acquire(&pgrp->pg_refs);
421 }
422
423 void
424 pgrel(struct pgrp *pgrp)
425 {
426         int count;
427
428         for (;;) {
429                 count = pgrp->pg_refs;
430                 cpu_ccfence();
431                 KKASSERT(count > 0);
432                 if (count == 1) {
433                         spin_lock(&pghash_spin);
434                         if (atomic_cmpset_int(&pgrp->pg_refs, 1, 0))
435                                 break;
436                         spin_unlock(&pghash_spin);
437                         /* retry */
438                 } else {
439                         if (atomic_cmpset_int(&pgrp->pg_refs, count, count - 1))
440                                 return;
441                         /* retry */
442                 }
443         }
444
445         /*
446          * Successful 1->0 transition, pghash_spin is held.
447          */
448         LIST_REMOVE(pgrp, pg_hash);
449         spin_unlock(&pghash_spin);
450
451         /*
452          * Reset any sigio structures pointing to us as a result of
453          * F_SETOWN with our pgid.
454          */
455         funsetownlst(&pgrp->pg_sigiolst);
456
457         if (pgrp->pg_session->s_ttyp != NULL &&
458             pgrp->pg_session->s_ttyp->t_pgrp == pgrp) {
459                 pgrp->pg_session->s_ttyp->t_pgrp = NULL;
460         }
461         sess_rele(pgrp->pg_session);
462         kfree(pgrp, M_PGRP);
463 }
464
465 /*
466  * Locate a process group by number.  The returned process group will be
467  * referenced w/pgref() and must be released with pgrel() (or assigned
468  * somewhere if you wish to keep the reference).
469  *
470  * No requirements.
471  */
472 struct pgrp *
473 pgfind(pid_t pgid)
474 {
475         struct pgrp *pgrp;
476
477         spin_lock_shared(&pghash_spin);
478         LIST_FOREACH(pgrp, PGRPHASH(pgid), pg_hash) {
479                 if (pgrp->pg_id == pgid) {
480                         refcount_acquire(&pgrp->pg_refs);
481                         spin_unlock_shared(&pghash_spin);
482                         return (pgrp);
483                 }
484         }
485         spin_unlock_shared(&pghash_spin);
486         return (NULL);
487 }
488
489 /*
490  * Move p to a new or existing process group (and session)
491  *
492  * No requirements.
493  */
494 int
495 enterpgrp(struct proc *p, pid_t pgid, int mksess)
496 {
497         struct pgrp *pgrp;
498         struct pgrp *opgrp;
499         int error;
500
501         pgrp = pgfind(pgid);
502
503         KASSERT(pgrp == NULL || !mksess,
504                 ("enterpgrp: setsid into non-empty pgrp"));
505         KASSERT(!SESS_LEADER(p),
506                 ("enterpgrp: session leader attempted setpgrp"));
507
508         if (pgrp == NULL) {
509                 pid_t savepid = p->p_pid;
510                 struct proc *np;
511                 /*
512                  * new process group
513                  */
514                 KASSERT(p->p_pid == pgid,
515                         ("enterpgrp: new pgrp and pid != pgid"));
516                 if ((np = pfindn(savepid)) == NULL || np != p) {
517                         error = ESRCH;
518                         goto fatal;
519                 }
520                 pgrp = kmalloc(sizeof(struct pgrp), M_PGRP, M_WAITOK);
521                 if (mksess) {
522                         struct session *sess;
523
524                         /*
525                          * new session
526                          */
527                         sess = kmalloc(sizeof(struct session), M_SESSION,
528                                        M_WAITOK);
529                         sess->s_leader = p;
530                         sess->s_sid = p->p_pid;
531                         sess->s_count = 1;
532                         sess->s_ttyvp = NULL;
533                         sess->s_ttyp = NULL;
534                         bcopy(p->p_session->s_login, sess->s_login,
535                               sizeof(sess->s_login));
536                         pgrp->pg_session = sess;
537                         KASSERT(p == curproc,
538                                 ("enterpgrp: mksession and p != curproc"));
539                         lwkt_gettoken(&p->p_token);
540                         p->p_flags &= ~P_CONTROLT;
541                         lwkt_reltoken(&p->p_token);
542                 } else {
543                         pgrp->pg_session = p->p_session;
544                         sess_hold(pgrp->pg_session);
545                 }
546                 pgrp->pg_id = pgid;
547                 LIST_INIT(&pgrp->pg_members);
548                 pgrp->pg_jobc = 0;
549                 SLIST_INIT(&pgrp->pg_sigiolst);
550                 lwkt_token_init(&pgrp->pg_token, "pgrp_token");
551                 refcount_init(&pgrp->pg_refs, 1);
552                 lockinit(&pgrp->pg_lock, "pgwt", 0, 0);
553                 spin_lock(&pghash_spin);
554                 LIST_INSERT_HEAD(PGRPHASH(pgid), pgrp, pg_hash);
555                 spin_unlock(&pghash_spin);
556         } else if (pgrp == p->p_pgrp) {
557                 pgrel(pgrp);
558                 goto done;
559         } /* else pgfind() referenced the pgrp */
560
561         lwkt_gettoken(&pgrp->pg_token);
562         lwkt_gettoken(&p->p_token);
563
564         /*
565          * Replace p->p_pgrp, handling any races that occur.
566          */
567         while ((opgrp = p->p_pgrp) != NULL) {
568                 pgref(opgrp);
569                 lwkt_gettoken(&opgrp->pg_token);
570                 if (opgrp != p->p_pgrp) {
571                         lwkt_reltoken(&opgrp->pg_token);
572                         pgrel(opgrp);
573                         continue;
574                 }
575                 LIST_REMOVE(p, p_pglist);
576                 break;
577         }
578         p->p_pgrp = pgrp;
579         LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
580
581         /*
582          * Adjust eligibility of affected pgrps to participate in job control.
583          * Increment eligibility counts before decrementing, otherwise we
584          * could reach 0 spuriously during the first call.
585          */
586         fixjobc(p, pgrp, 1);
587         if (opgrp) {
588                 fixjobc(p, opgrp, 0);
589                 lwkt_reltoken(&opgrp->pg_token);
590                 pgrel(opgrp);   /* manual pgref */
591                 pgrel(opgrp);   /* p->p_pgrp ref */
592         }
593         lwkt_reltoken(&p->p_token);
594         lwkt_reltoken(&pgrp->pg_token);
595 done:
596         error = 0;
597 fatal:
598         return (error);
599 }
600
601 /*
602  * Remove process from process group
603  *
604  * No requirements.
605  */
606 int
607 leavepgrp(struct proc *p)
608 {
609         struct pgrp *pg = p->p_pgrp;
610
611         lwkt_gettoken(&p->p_token);
612         while ((pg = p->p_pgrp) != NULL) {
613                 pgref(pg);
614                 lwkt_gettoken(&pg->pg_token);
615                 if (p->p_pgrp != pg) {
616                         lwkt_reltoken(&pg->pg_token);
617                         pgrel(pg);
618                         continue;
619                 }
620                 p->p_pgrp = NULL;
621                 LIST_REMOVE(p, p_pglist);
622                 lwkt_reltoken(&pg->pg_token);
623                 pgrel(pg);      /* manual pgref */
624                 pgrel(pg);      /* p->p_pgrp ref */
625                 break;
626         }
627         lwkt_reltoken(&p->p_token);
628
629         return (0);
630 }
631
632 /*
633  * Adjust the ref count on a session structure.  When the ref count falls to
634  * zero the tty is disassociated from the session and the session structure
635  * is freed.  Note that tty assocation is not itself ref-counted.
636  *
637  * No requirements.
638  */
639 void
640 sess_hold(struct session *sp)
641 {
642         atomic_add_int(&sp->s_count, 1);
643 }
644
645 /*
646  * No requirements.
647  */
648 void
649 sess_rele(struct session *sp)
650 {
651         struct tty *tp;
652         int count;
653
654         for (;;) {
655                 count = sp->s_count;
656                 cpu_ccfence();
657                 KKASSERT(count > 0);
658                 if (count == 1) {
659                         lwkt_gettoken(&tty_token);
660                         if (atomic_cmpset_int(&sp->s_count, 1, 0))
661                                 break;
662                         lwkt_reltoken(&tty_token);
663                         /* retry */
664                 } else {
665                         if (atomic_cmpset_int(&sp->s_count, count, count - 1))
666                                 return;
667                         /* retry */
668                 }
669         }
670
671         /*
672          * Successful 1->0 transition and tty_token is held.
673          */
674         if (sp->s_ttyp && sp->s_ttyp->t_session) {
675 #ifdef TTY_DO_FULL_CLOSE
676                 /* FULL CLOSE, see ttyclearsession() */
677                 KKASSERT(sp->s_ttyp->t_session == sp);
678                 sp->s_ttyp->t_session = NULL;
679 #else
680                 /* HALF CLOSE, see ttyclearsession() */
681                 if (sp->s_ttyp->t_session == sp)
682                         sp->s_ttyp->t_session = NULL;
683 #endif
684         }
685         if ((tp = sp->s_ttyp) != NULL) {
686                 sp->s_ttyp = NULL;
687                 ttyunhold(tp);
688         }
689         kfree(sp, M_SESSION);
690         lwkt_reltoken(&tty_token);
691 }
692
693 /*
694  * Adjust pgrp jobc counters when specified process changes process group.
695  * We count the number of processes in each process group that "qualify"
696  * the group for terminal job control (those with a parent in a different
697  * process group of the same session).  If that count reaches zero, the
698  * process group becomes orphaned.  Check both the specified process'
699  * process group and that of its children.
700  * entering == 0 => p is leaving specified group.
701  * entering == 1 => p is entering specified group.
702  *
703  * No requirements.
704  */
705 void
706 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
707 {
708         struct pgrp *hispgrp;
709         struct session *mysession;
710         struct proc *np;
711
712         /*
713          * Check p's parent to see whether p qualifies its own process
714          * group; if so, adjust count for p's process group.
715          */
716         lwkt_gettoken(&p->p_token);     /* p_children scan */
717         lwkt_gettoken(&pgrp->pg_token);
718
719         mysession = pgrp->pg_session;
720         if ((hispgrp = p->p_pptr->p_pgrp) != pgrp &&
721             hispgrp->pg_session == mysession) {
722                 if (entering)
723                         pgrp->pg_jobc++;
724                 else if (--pgrp->pg_jobc == 0)
725                         orphanpg(pgrp);
726         }
727
728         /*
729          * Check this process' children to see whether they qualify
730          * their process groups; if so, adjust counts for children's
731          * process groups.
732          */
733         LIST_FOREACH(np, &p->p_children, p_sibling) {
734                 PHOLD(np);
735                 lwkt_gettoken(&np->p_token);
736                 if ((hispgrp = np->p_pgrp) != pgrp &&
737                     hispgrp->pg_session == mysession &&
738                     np->p_stat != SZOMB) {
739                         pgref(hispgrp);
740                         lwkt_gettoken(&hispgrp->pg_token);
741                         if (entering)
742                                 hispgrp->pg_jobc++;
743                         else if (--hispgrp->pg_jobc == 0)
744                                 orphanpg(hispgrp);
745                         lwkt_reltoken(&hispgrp->pg_token);
746                         pgrel(hispgrp);
747                 }
748                 lwkt_reltoken(&np->p_token);
749                 PRELE(np);
750         }
751         KKASSERT(pgrp->pg_refs > 0);
752         lwkt_reltoken(&pgrp->pg_token);
753         lwkt_reltoken(&p->p_token);
754 }
755
756 /*
757  * A process group has become orphaned;
758  * if there are any stopped processes in the group,
759  * hang-up all process in that group.
760  *
761  * The caller must hold pg_token.
762  */
763 static void
764 orphanpg(struct pgrp *pg)
765 {
766         struct proc *p;
767
768         LIST_FOREACH(p, &pg->pg_members, p_pglist) {
769                 if (p->p_stat == SSTOP) {
770                         LIST_FOREACH(p, &pg->pg_members, p_pglist) {
771                                 ksignal(p, SIGHUP);
772                                 ksignal(p, SIGCONT);
773                         }
774                         return;
775                 }
776         }
777 }
778
779 /*
780  * Add a new process to the allproc list and the PID hash.  This
781  * also assigns a pid to the new process.
782  *
783  * No requirements.
784  */
785 void
786 proc_add_allproc(struct proc *p)
787 {
788         int random_offset;
789
790         if ((random_offset = randompid) != 0) {
791                 get_mplock();
792                 random_offset = karc4random() % random_offset;
793                 rel_mplock();
794         }
795
796         lwkt_gettoken(&proc_token);
797
798         p->p_pid = proc_getnewpid_locked(random_offset);
799         LIST_INSERT_HEAD(&allproc, p, p_list);
800
801         spin_lock(PIDSPIN(p->p_pid));
802         LIST_INSERT_HEAD(PIDHASH(p->p_pid), p, p_hash);
803         spin_unlock(PIDSPIN(p->p_pid));
804
805         lwkt_reltoken(&proc_token);
806 }
807
808 /*
809  * Calculate a new process pid.  This function is integrated into
810  * proc_add_allproc() to guarentee that the new pid is not reused before
811  * the new process can be added to the allproc list.
812  *
813  * The caller must hold proc_token.
814  */
815 static
816 pid_t
817 proc_getnewpid_locked(int random_offset)
818 {
819         static pid_t nextpid;
820         static pid_t pidchecked;
821         struct proc *p;
822
823         /*
824          * Find an unused process ID.  We remember a range of unused IDs
825          * ready to use (from nextpid+1 through pidchecked-1).
826          */
827         nextpid = nextpid + 1 + random_offset;
828 retry:
829         /*
830          * If the process ID prototype has wrapped around,
831          * restart somewhat above 0, as the low-numbered procs
832          * tend to include daemons that don't exit.
833          */
834         if (nextpid >= PID_MAX) {
835                 nextpid = nextpid % PID_MAX;
836                 if (nextpid < 100)
837                         nextpid += 100;
838                 pidchecked = 0;
839         }
840         if (nextpid >= pidchecked) {
841                 int doingzomb = 0;
842
843                 pidchecked = PID_MAX;
844
845                 /*
846                  * Scan the active and zombie procs to check whether this pid
847                  * is in use.  Remember the lowest pid that's greater
848                  * than nextpid, so we can avoid checking for a while.
849                  *
850                  * NOTE: Processes in the midst of being forked may not
851                  *       yet have p_pgrp and p_pgrp->pg_session set up
852                  *       yet, so we have to check for NULL.
853                  *
854                  *       Processes being torn down should be interlocked
855                  *       with proc_token prior to the clearing of their
856                  *       p_pgrp.
857                  */
858                 p = LIST_FIRST(&allproc);
859 again:
860                 for (; p != NULL; p = LIST_NEXT(p, p_list)) {
861                         while (p->p_pid == nextpid ||
862                             (p->p_pgrp && p->p_pgrp->pg_id == nextpid) ||
863                             (p->p_pgrp && p->p_session &&
864                              p->p_session->s_sid == nextpid)) {
865                                 nextpid++;
866                                 if (nextpid >= pidchecked)
867                                         goto retry;
868                         }
869                         if (p->p_pid > nextpid && pidchecked > p->p_pid)
870                                 pidchecked = p->p_pid;
871                         if (p->p_pgrp &&
872                             p->p_pgrp->pg_id > nextpid &&
873                             pidchecked > p->p_pgrp->pg_id) {
874                                 pidchecked = p->p_pgrp->pg_id;
875                         }
876                         if (p->p_pgrp && p->p_session &&
877                             p->p_session->s_sid > nextpid &&
878                             pidchecked > p->p_session->s_sid) {
879                                 pidchecked = p->p_session->s_sid;
880                         }
881                 }
882                 if (!doingzomb) {
883                         doingzomb = 1;
884                         p = LIST_FIRST(&zombproc);
885                         goto again;
886                 }
887         }
888         return(nextpid);
889 }
890
891 /*
892  * Called from exit1 to remove a process from the allproc
893  * list and move it to the zombie list.
894  *
895  * Caller must hold p->p_token.  We are required to wait until p_lock
896  * becomes zero before we can manipulate the list, allowing allproc
897  * scans to guarantee consistency during a list scan.
898  */
899 void
900 proc_move_allproc_zombie(struct proc *p)
901 {
902         PSTALL(p, "reap1", 0);
903
904         lwkt_gettoken(&proc_token);
905         PSTALL(p, "reap1a", 0);
906
907         LIST_REMOVE(p, p_list);
908         LIST_INSERT_HEAD(&zombproc, p, p_list);
909
910         spin_lock(PIDSPIN(p->p_pid));
911         LIST_REMOVE(p, p_hash);
912         spin_unlock(PIDSPIN(p->p_pid));
913
914         p->p_stat = SZOMB;
915         lwkt_reltoken(&proc_token);
916         dsched_exit_proc(p);
917 }
918
919 /*
920  * This routine is called from kern_wait() and will remove the process
921  * from the zombie list and the sibling list.  This routine will block
922  * if someone has a lock on the proces (p_lock).
923  *
924  * Caller must hold p->p_token.  We are required to wait until p_lock
925  * becomes zero before we can manipulate the list, allowing allproc
926  * scans to guarantee consistency during a list scan.
927  */
928 void
929 proc_remove_zombie(struct proc *p)
930 {
931         PSTALL(p, "reap2", 0);
932         lwkt_gettoken(&proc_token);
933         PSTALL(p, "reap2a", 0);
934         LIST_REMOVE(p, p_list); /* off zombproc */
935         LIST_REMOVE(p, p_sibling);
936         p->p_pptr = NULL;
937         lwkt_reltoken(&proc_token);
938 }
939
940 /*
941  * Handle various requirements prior to returning to usermode.  Called from
942  * platform trap and system call code.
943  */
944 void
945 lwpuserret(struct lwp *lp)
946 {
947         struct proc *p = lp->lwp_proc;
948
949         if (lp->lwp_mpflags & LWP_MP_VNLRU) {
950                 atomic_clear_int(&lp->lwp_mpflags, LWP_MP_VNLRU);
951                 allocvnode_gc();
952         }
953         if (lp->lwp_mpflags & LWP_MP_WEXIT) {
954                 lwkt_gettoken(&p->p_token);
955                 lwp_exit(0, NULL);
956                 lwkt_reltoken(&p->p_token);     /* NOT REACHED */
957         }
958 }
959
960 /*
961  * Kernel threads run from user processes can also accumulate deferred
962  * actions which need to be acted upon.  Callers include:
963  *
964  * nfsd         - Can allocate lots of vnodes
965  */
966 void
967 lwpkthreaddeferred(void)
968 {
969         struct lwp *lp = curthread->td_lwp;
970
971         if (lp) {
972                 if (lp->lwp_mpflags & LWP_MP_VNLRU) {
973                         atomic_clear_int(&lp->lwp_mpflags, LWP_MP_VNLRU);
974                         allocvnode_gc();
975                 }
976         }
977 }
978
979 /*
980  * Scan all processes on the allproc list.  The process is automatically
981  * held for the callback.  A return value of -1 terminates the loop.
982  *
983  * The callback is made with the process held and proc_token held.
984  *
985  * We limit the scan to the number of processes as-of the start of
986  * the scan so as not to get caught up in an endless loop if new processes
987  * are created more quickly than we can scan the old ones.  Add a little
988  * slop to try to catch edge cases since nprocs can race.
989  *
990  * No requirements.
991  */
992 void
993 allproc_scan(int (*callback)(struct proc *, void *), void *data)
994 {
995         struct proc *p;
996         int r;
997         int limit = nprocs + ncpus;
998
999         /*
1000          * proc_token protects the allproc list and PHOLD() prevents the
1001          * process from being removed from the allproc list or the zombproc
1002          * list.
1003          */
1004         lwkt_gettoken(&proc_token);
1005         LIST_FOREACH(p, &allproc, p_list) {
1006                 PHOLD(p);
1007                 r = callback(p, data);
1008                 PRELE(p);
1009                 if (r < 0)
1010                         break;
1011                 if (--limit < 0)
1012                         break;
1013         }
1014         lwkt_reltoken(&proc_token);
1015 }
1016
1017 /*
1018  * Scan all lwps of processes on the allproc list.  The lwp is automatically
1019  * held for the callback.  A return value of -1 terminates the loop.
1020  *
1021  * The callback is made with the proces and lwp both held, and proc_token held.
1022  *
1023  * No requirements.
1024  */
1025 void
1026 alllwp_scan(int (*callback)(struct lwp *, void *), void *data)
1027 {
1028         struct proc *p;
1029         struct lwp *lp;
1030         int r = 0;
1031
1032         /*
1033          * proc_token protects the allproc list and PHOLD() prevents the
1034          * process from being removed from the allproc list or the zombproc
1035          * list.
1036          */
1037         lwkt_gettoken(&proc_token);
1038         LIST_FOREACH(p, &allproc, p_list) {
1039                 PHOLD(p);
1040                 lwkt_gettoken(&p->p_token);
1041                 FOREACH_LWP_IN_PROC(lp, p) {
1042                         LWPHOLD(lp);
1043                         r = callback(lp, data);
1044                         LWPRELE(lp);
1045                 }
1046                 lwkt_reltoken(&p->p_token);
1047                 PRELE(p);
1048                 if (r < 0)
1049                         break;
1050         }
1051         lwkt_reltoken(&proc_token);
1052 }
1053
1054 /*
1055  * Scan all processes on the zombproc list.  The process is automatically
1056  * held for the callback.  A return value of -1 terminates the loop.
1057  *
1058  * No requirements.
1059  * The callback is made with the proces held and proc_token held.
1060  */
1061 void
1062 zombproc_scan(int (*callback)(struct proc *, void *), void *data)
1063 {
1064         struct proc *p;
1065         int r;
1066
1067         lwkt_gettoken(&proc_token);
1068         LIST_FOREACH(p, &zombproc, p_list) {
1069                 PHOLD(p);
1070                 r = callback(p, data);
1071                 PRELE(p);
1072                 if (r < 0)
1073                         break;
1074         }
1075         lwkt_reltoken(&proc_token);
1076 }
1077
1078 #include "opt_ddb.h"
1079 #ifdef DDB
1080 #include <ddb/ddb.h>
1081
1082 /*
1083  * Debugging only
1084  */
1085 DB_SHOW_COMMAND(pgrpdump, pgrpdump)
1086 {
1087         struct pgrp *pgrp;
1088         struct proc *p;
1089         int i;
1090
1091         for (i = 0; i <= pgrphash; i++) {
1092                 if (!LIST_EMPTY(&pgrphashtbl[i])) {
1093                         kprintf("\tindx %d\n", i);
1094                         LIST_FOREACH(pgrp, &pgrphashtbl[i], pg_hash) {
1095                                 kprintf(
1096                         "\tpgrp %p, pgid %ld, sess %p, sesscnt %d, mem %p\n",
1097                                     (void *)pgrp, (long)pgrp->pg_id,
1098                                     (void *)pgrp->pg_session,
1099                                     pgrp->pg_session->s_count,
1100                                     (void *)LIST_FIRST(&pgrp->pg_members));
1101                                 LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
1102                                         kprintf("\t\tpid %ld addr %p pgrp %p\n", 
1103                                             (long)p->p_pid, (void *)p,
1104                                             (void *)p->p_pgrp);
1105                                 }
1106                         }
1107                 }
1108         }
1109 }
1110 #endif /* DDB */
1111
1112 /*
1113  * Locate a process on the zombie list.  Return a process or NULL.
1114  * The returned process will be referenced and the caller must release
1115  * it with PRELE().
1116  *
1117  * No other requirements.
1118  */
1119 struct proc *
1120 zpfind(pid_t pid)
1121 {
1122         struct proc *p;
1123
1124         lwkt_gettoken_shared(&proc_token);
1125         LIST_FOREACH(p, &zombproc, p_list) {
1126                 if (p->p_pid == pid) {
1127                         PHOLD(p);
1128                         lwkt_reltoken(&proc_token);
1129                         return (p);
1130                 }
1131         }
1132         lwkt_reltoken(&proc_token);
1133         return (NULL);
1134 }
1135
1136 /*
1137  * The caller must hold proc_token.
1138  */
1139 static int
1140 sysctl_out_proc(struct proc *p, struct sysctl_req *req, int flags)
1141 {
1142         struct kinfo_proc ki;
1143         struct lwp *lp;
1144         int skp = 0, had_output = 0;
1145         int error;
1146
1147         bzero(&ki, sizeof(ki));
1148         lwkt_gettoken_shared(&p->p_token);
1149         fill_kinfo_proc(p, &ki);
1150         if ((flags & KERN_PROC_FLAG_LWP) == 0)
1151                 skp = 1;
1152         error = 0;
1153         FOREACH_LWP_IN_PROC(lp, p) {
1154                 LWPHOLD(lp);
1155                 fill_kinfo_lwp(lp, &ki.kp_lwp);
1156                 had_output = 1;
1157                 error = SYSCTL_OUT(req, &ki, sizeof(ki));
1158                 LWPRELE(lp);
1159                 if (error)
1160                         break;
1161                 if (skp)
1162                         break;
1163         }
1164         lwkt_reltoken(&p->p_token);
1165         /* We need to output at least the proc, even if there is no lwp. */
1166         if (had_output == 0) {
1167                 error = SYSCTL_OUT(req, &ki, sizeof(ki));
1168         }
1169         return (error);
1170 }
1171
1172 /*
1173  * The caller must hold proc_token.
1174  */
1175 static int
1176 sysctl_out_proc_kthread(struct thread *td, struct sysctl_req *req, int flags)
1177 {
1178         struct kinfo_proc ki;
1179         int error;
1180
1181         fill_kinfo_proc_kthread(td, &ki);
1182         error = SYSCTL_OUT(req, &ki, sizeof(ki));
1183         if (error)
1184                 return error;
1185         return(0);
1186 }
1187
1188 /*
1189  * No requirements.
1190  */
1191 static int
1192 sysctl_kern_proc(SYSCTL_HANDLER_ARGS)
1193 {
1194         int *name = (int*) arg1;
1195         int oid = oidp->oid_number;
1196         u_int namelen = arg2;
1197         struct proc *p;
1198         struct proclist *plist;
1199         struct thread *td;
1200         struct thread *marker;
1201         int doingzomb, flags = 0;
1202         int error = 0;
1203         int n;
1204         int origcpu;
1205         struct ucred *cr1 = curproc->p_ucred;
1206
1207         flags = oid & KERN_PROC_FLAGMASK;
1208         oid &= ~KERN_PROC_FLAGMASK;
1209
1210         if ((oid == KERN_PROC_ALL && namelen != 0) ||
1211             (oid != KERN_PROC_ALL && namelen != 1)) {
1212                 return (EINVAL);
1213         }
1214
1215         /*
1216          * proc_token protects the allproc list and PHOLD() prevents the
1217          * process from being removed from the allproc list or the zombproc
1218          * list.
1219          */
1220         if (oid == KERN_PROC_PID) {
1221                 p = pfind((pid_t)name[0]);
1222                 if (p) {
1223                         if (PRISON_CHECK(cr1, p->p_ucred))
1224                                 error = sysctl_out_proc(p, req, flags);
1225                         PRELE(p);
1226                 }
1227                 goto post_threads;
1228         }
1229         p = NULL;
1230
1231         if (!req->oldptr) {
1232                 /* overestimate by 5 procs */
1233                 error = SYSCTL_OUT(req, 0, sizeof (struct kinfo_proc) * 5);
1234                 if (error)
1235                         goto post_threads;
1236         }
1237         for (doingzomb = 0; doingzomb <= 1; doingzomb++) {
1238                 if (doingzomb)
1239                         plist = &zombproc;
1240                 else
1241                         plist = &allproc;
1242
1243                 lwkt_gettoken_shared(&proc_token);
1244
1245                 LIST_FOREACH(p, plist, p_list) {
1246                         /*
1247                          * Show a user only their processes.
1248                          */
1249                         if ((!ps_showallprocs) && p_trespass(cr1, p->p_ucred))
1250                                 continue;
1251                         /*
1252                          * Skip embryonic processes.
1253                          */
1254                         if (p->p_stat == SIDL)
1255                                 continue;
1256                         /*
1257                          * TODO - make more efficient (see notes below).
1258                          * do by session.
1259                          */
1260                         switch (oid) {
1261                         case KERN_PROC_PGRP:
1262                                 /* could do this by traversing pgrp */
1263                                 if (p->p_pgrp == NULL || 
1264                                     p->p_pgrp->pg_id != (pid_t)name[0])
1265                                         continue;
1266                                 break;
1267
1268                         case KERN_PROC_TTY:
1269                                 if ((p->p_flags & P_CONTROLT) == 0 ||
1270                                     p->p_session == NULL ||
1271                                     p->p_session->s_ttyp == NULL ||
1272                                     dev2udev(p->p_session->s_ttyp->t_dev) != 
1273                                         (udev_t)name[0])
1274                                         continue;
1275                                 break;
1276
1277                         case KERN_PROC_UID:
1278                                 if (p->p_ucred == NULL || 
1279                                     p->p_ucred->cr_uid != (uid_t)name[0])
1280                                         continue;
1281                                 break;
1282
1283                         case KERN_PROC_RUID:
1284                                 if (p->p_ucred == NULL || 
1285                                     p->p_ucred->cr_ruid != (uid_t)name[0])
1286                                         continue;
1287                                 break;
1288                         }
1289
1290                         if (!PRISON_CHECK(cr1, p->p_ucred))
1291                                 continue;
1292                         PHOLD(p);
1293                         error = sysctl_out_proc(p, req, flags);
1294                         PRELE(p);
1295                         if (error) {
1296                                 lwkt_reltoken(&proc_token);
1297                                 goto post_threads;
1298                         }
1299                 }
1300                 lwkt_reltoken(&proc_token);
1301         }
1302
1303         /*
1304          * Iterate over all active cpus and scan their thread list.  Start
1305          * with the next logical cpu and end with our original cpu.  We
1306          * migrate our own thread to each target cpu in order to safely scan
1307          * its thread list.  In the last loop we migrate back to our original
1308          * cpu.
1309          */
1310         origcpu = mycpu->gd_cpuid;
1311         if (!ps_showallthreads || jailed(cr1))
1312                 goto post_threads;
1313
1314         marker = kmalloc(sizeof(struct thread), M_TEMP, M_WAITOK|M_ZERO);
1315         marker->td_flags = TDF_MARKER;
1316         error = 0;
1317
1318         for (n = 1; n <= ncpus; ++n) {
1319                 globaldata_t rgd;
1320                 int nid;
1321
1322                 nid = (origcpu + n) % ncpus;
1323                 if ((smp_active_mask & CPUMASK(nid)) == 0)
1324                         continue;
1325                 rgd = globaldata_find(nid);
1326                 lwkt_setcpu_self(rgd);
1327
1328                 crit_enter();
1329                 TAILQ_INSERT_TAIL(&rgd->gd_tdallq, marker, td_allq);
1330
1331                 while ((td = TAILQ_PREV(marker, lwkt_queue, td_allq)) != NULL) {
1332                         TAILQ_REMOVE(&rgd->gd_tdallq, marker, td_allq);
1333                         TAILQ_INSERT_BEFORE(td, marker, td_allq);
1334                         if (td->td_flags & TDF_MARKER)
1335                                 continue;
1336                         if (td->td_proc)
1337                                 continue;
1338
1339                         lwkt_hold(td);
1340                         crit_exit();
1341
1342                         switch (oid) {
1343                         case KERN_PROC_PGRP:
1344                         case KERN_PROC_TTY:
1345                         case KERN_PROC_UID:
1346                         case KERN_PROC_RUID:
1347                                 break;
1348                         default:
1349                                 error = sysctl_out_proc_kthread(td, req,
1350                                                                 doingzomb);
1351                                 break;
1352                         }
1353                         lwkt_rele(td);
1354                         crit_enter();
1355                         if (error)
1356                                 break;
1357                 }
1358                 TAILQ_REMOVE(&rgd->gd_tdallq, marker, td_allq);
1359                 crit_exit();
1360
1361                 if (error)
1362                         break;
1363         }
1364
1365         /*
1366          * Userland scheduler expects us to return on the same cpu we
1367          * started on.
1368          */
1369         if (mycpu->gd_cpuid != origcpu)
1370                 lwkt_setcpu_self(globaldata_find(origcpu));
1371
1372         kfree(marker, M_TEMP);
1373
1374 post_threads:
1375         return (error);
1376 }
1377
1378 /*
1379  * This sysctl allows a process to retrieve the argument list or process
1380  * title for another process without groping around in the address space
1381  * of the other process.  It also allow a process to set its own "process 
1382  * title to a string of its own choice.
1383  *
1384  * No requirements.
1385  */
1386 static int
1387 sysctl_kern_proc_args(SYSCTL_HANDLER_ARGS)
1388 {
1389         int *name = (int*) arg1;
1390         u_int namelen = arg2;
1391         struct proc *p;
1392         struct pargs *opa;
1393         struct pargs *pa;
1394         int error = 0;
1395         struct ucred *cr1 = curproc->p_ucred;
1396
1397         if (namelen != 1) 
1398                 return (EINVAL);
1399
1400         p = pfind((pid_t)name[0]);
1401         if (p == NULL)
1402                 goto done;
1403         lwkt_gettoken(&p->p_token);
1404
1405         if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
1406                 goto done;
1407
1408         if (req->newptr && curproc != p) {
1409                 error = EPERM;
1410                 goto done;
1411         }
1412         if (req->oldptr && (pa = p->p_args) != NULL) {
1413                 refcount_acquire(&pa->ar_ref);
1414                 error = SYSCTL_OUT(req, pa->ar_args, pa->ar_length);
1415                 if (refcount_release(&pa->ar_ref))
1416                         kfree(pa, M_PARGS);
1417         }
1418         if (req->newptr == NULL)
1419                 goto done;
1420
1421         if (req->newlen + sizeof(struct pargs) > ps_arg_cache_limit) {
1422                 goto done;
1423         }
1424
1425         pa = kmalloc(sizeof(struct pargs) + req->newlen, M_PARGS, M_WAITOK);
1426         refcount_init(&pa->ar_ref, 1);
1427         pa->ar_length = req->newlen;
1428         error = SYSCTL_IN(req, pa->ar_args, req->newlen);
1429         if (error) {
1430                 kfree(pa, M_PARGS);
1431                 goto done;
1432         }
1433
1434
1435         /*
1436          * Replace p_args with the new pa.  p_args may have previously
1437          * been NULL.
1438          */
1439         opa = p->p_args;
1440         p->p_args = pa;
1441
1442         if (opa) {
1443                 KKASSERT(opa->ar_ref > 0);
1444                 if (refcount_release(&opa->ar_ref)) {
1445                         kfree(opa, M_PARGS);
1446                         /* opa = NULL; */
1447                 }
1448         }
1449 done:
1450         if (p) {
1451                 lwkt_reltoken(&p->p_token);
1452                 PRELE(p);
1453         }
1454         return (error);
1455 }
1456
1457 static int
1458 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
1459 {
1460         int *name = (int*) arg1;
1461         u_int namelen = arg2;
1462         struct proc *p;
1463         int error = 0;
1464         char *fullpath, *freepath;
1465         struct ucred *cr1 = curproc->p_ucred;
1466
1467         if (namelen != 1) 
1468                 return (EINVAL);
1469
1470         p = pfind((pid_t)name[0]);
1471         if (p == NULL)
1472                 goto done;
1473         lwkt_gettoken_shared(&p->p_token);
1474
1475         /*
1476          * If we are not allowed to see other args, we certainly shouldn't
1477          * get the cwd either. Also check the usual trespassing.
1478          */
1479         if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
1480                 goto done;
1481
1482         if (req->oldptr && p->p_fd != NULL && p->p_fd->fd_ncdir.ncp) {
1483                 struct nchandle nch;
1484
1485                 cache_copy(&p->p_fd->fd_ncdir, &nch);
1486                 error = cache_fullpath(p, &nch, NULL,
1487                                        &fullpath, &freepath, 0);
1488                 cache_drop(&nch);
1489                 if (error)
1490                         goto done;
1491                 error = SYSCTL_OUT(req, fullpath, strlen(fullpath) + 1);
1492                 kfree(freepath, M_TEMP);
1493         }
1494
1495 done:
1496         if (p) {
1497                 lwkt_reltoken(&p->p_token);
1498                 PRELE(p);
1499         }
1500         return (error);
1501 }
1502
1503 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD,  0, "Process table");
1504
1505 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all, CTLFLAG_RD|CTLTYPE_STRUCT,
1506         0, 0, sysctl_kern_proc, "S,proc", "Return entire process table");
1507
1508 SYSCTL_NODE(_kern_proc, KERN_PROC_PGRP, pgrp, CTLFLAG_RD, 
1509         sysctl_kern_proc, "Process table");
1510
1511 SYSCTL_NODE(_kern_proc, KERN_PROC_TTY, tty, CTLFLAG_RD, 
1512         sysctl_kern_proc, "Process table");
1513
1514 SYSCTL_NODE(_kern_proc, KERN_PROC_UID, uid, CTLFLAG_RD, 
1515         sysctl_kern_proc, "Process table");
1516
1517 SYSCTL_NODE(_kern_proc, KERN_PROC_RUID, ruid, CTLFLAG_RD, 
1518         sysctl_kern_proc, "Process table");
1519
1520 SYSCTL_NODE(_kern_proc, KERN_PROC_PID, pid, CTLFLAG_RD, 
1521         sysctl_kern_proc, "Process table");
1522
1523 SYSCTL_NODE(_kern_proc, (KERN_PROC_ALL | KERN_PROC_FLAG_LWP), all_lwp, CTLFLAG_RD,
1524         sysctl_kern_proc, "Process table");
1525
1526 SYSCTL_NODE(_kern_proc, (KERN_PROC_PGRP | KERN_PROC_FLAG_LWP), pgrp_lwp, CTLFLAG_RD, 
1527         sysctl_kern_proc, "Process table");
1528
1529 SYSCTL_NODE(_kern_proc, (KERN_PROC_TTY | KERN_PROC_FLAG_LWP), tty_lwp, CTLFLAG_RD, 
1530         sysctl_kern_proc, "Process table");
1531
1532 SYSCTL_NODE(_kern_proc, (KERN_PROC_UID | KERN_PROC_FLAG_LWP), uid_lwp, CTLFLAG_RD, 
1533         sysctl_kern_proc, "Process table");
1534
1535 SYSCTL_NODE(_kern_proc, (KERN_PROC_RUID | KERN_PROC_FLAG_LWP), ruid_lwp, CTLFLAG_RD, 
1536         sysctl_kern_proc, "Process table");
1537
1538 SYSCTL_NODE(_kern_proc, (KERN_PROC_PID | KERN_PROC_FLAG_LWP), pid_lwp, CTLFLAG_RD, 
1539         sysctl_kern_proc, "Process table");
1540
1541 SYSCTL_NODE(_kern_proc, KERN_PROC_ARGS, args, CTLFLAG_RW | CTLFLAG_ANYBODY,
1542         sysctl_kern_proc_args, "Process argument list");
1543
1544 SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD | CTLFLAG_ANYBODY,
1545         sysctl_kern_proc_cwd, "Process argument list");