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