0d53256c3c35f094e0720ef8023fa2bca66a7d3f
[dragonfly.git] / sys / kern / kern_proc.c
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/sysctl.h>
34 #include <sys/malloc.h>
35 #include <sys/proc.h>
36 #include <sys/vnode.h>
37 #include <sys/jail.h>
38 #include <sys/filedesc.h>
39 #include <sys/tty.h>
40 #include <sys/dsched.h>
41 #include <sys/signalvar.h>
42 #include <sys/spinlock.h>
43 #include <sys/random.h>
44 #include <sys/vnode.h>
45 #include <sys/exec.h>
46 #include <vm/vm.h>
47 #include <sys/lock.h>
48 #include <vm/pmap.h>
49 #include <vm/vm_map.h>
50 #include <sys/user.h>
51 #include <machine/smp.h>
52
53 #include <sys/refcount.h>
54 #include <sys/spinlock2.h>
55
56 /*
57  * Hash table size must be a power of two and is not currently dynamically
58  * sized.  There is a trade-off between the linear scans which must iterate
59  * all HSIZE elements and the number of elements which might accumulate
60  * within each hash chain.
61  */
62 #define ALLPROC_HSIZE   256
63 #define ALLPROC_HMASK   (ALLPROC_HSIZE - 1)
64 #define ALLPROC_HASH(pid)       (pid & ALLPROC_HMASK)
65 #define PGRP_HASH(pid)  (pid & ALLPROC_HMASK)
66 #define SESS_HASH(pid)  (pid & ALLPROC_HMASK)
67
68 /*
69  * pid_doms[] management, used to control how quickly a PID can be recycled.
70  * Must be a multiple of ALLPROC_HSIZE for the proc_makepid() inner loops.
71  *
72  * WARNING! PIDDOM_DELAY should not be defined > 20 or so unless you change
73  *          the array from int8_t's to int16_t's.
74  */
75 #define PIDDOM_COUNT    10      /* 10 pids per domain - reduce array size */
76 #define PIDDOM_DELAY    10      /* min 10 seconds after exit before reuse */
77 #define PIDDOM_SCALE    10      /* (10,000*SCALE)/sec performance guarantee */
78 #define PIDSEL_DOMAINS  (PID_MAX * PIDDOM_SCALE / PIDDOM_COUNT /        \
79                          ALLPROC_HSIZE * ALLPROC_HSIZE)
80
81 /* Used by libkvm */
82 int allproc_hsize = ALLPROC_HSIZE;
83
84 LIST_HEAD(pidhashhead, proc);
85
86 static MALLOC_DEFINE(M_PGRP, "pgrp", "process group header");
87 MALLOC_DEFINE(M_SESSION, "session", "session header");
88 MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
89 MALLOC_DEFINE(M_LWP, "lwp", "lwp structures");
90 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
91
92 int ps_showallprocs = 1;
93 static int ps_showallthreads = 1;
94 SYSCTL_INT(_security, OID_AUTO, ps_showallprocs, CTLFLAG_RW,
95     &ps_showallprocs, 0,
96     "Unprivileged processes can see processes with different UID/GID");
97 SYSCTL_INT(_security, OID_AUTO, ps_showallthreads, CTLFLAG_RW,
98     &ps_showallthreads, 0,
99     "Unprivileged processes can see kernel threads");
100 static u_int pid_domain_skips;
101 SYSCTL_UINT(_kern, OID_AUTO, pid_domain_skips, CTLFLAG_RW,
102     &pid_domain_skips, 0,
103     "Number of pid_doms[] skipped");
104 static u_int pid_inner_skips;
105 SYSCTL_UINT(_kern, OID_AUTO, pid_inner_skips, CTLFLAG_RW,
106     &pid_inner_skips, 0,
107     "Number of pid_doms[] skipped");
108
109 static void orphanpg(struct pgrp *pg);
110 static void proc_makepid(struct proc *p, int random_offset);
111
112 /*
113  * Process related lists (for proc_token, allproc, allpgrp, and allsess)
114  */
115 typedef struct procglob procglob_t;
116
117 static procglob_t       procglob[ALLPROC_HSIZE];
118
119 /*
120  * We try our best to avoid recycling a PID too quickly.  We do this by
121  * storing (uint8_t)time_second in the related pid domain on-reap and then
122  * using that to skip-over the domain on-allocate.
123  *
124  * This array has to be fairly large to support a high fork/exec rate.
125  * A ~100,000 entry array will support a 10-second reuse latency at
126  * 10,000 execs/second, worst case.  Best-case multiply by PIDDOM_COUNT
127  * (approximately 100,000 execs/second).
128  *
129  * Currently we allocate around a megabyte, making the worst-case fork
130  * rate around 100,000/second.
131  */
132 static uint8_t *pid_doms;
133
134 /*
135  * Random component to nextpid generation.  We mix in a random factor to make
136  * it a little harder to predict.  We sanity check the modulus value to avoid
137  * doing it in critical paths.  Don't let it be too small or we pointlessly
138  * waste randomness entropy, and don't let it be impossibly large.  Using a
139  * modulus that is too big causes a LOT more process table scans and slows
140  * down fork processing as the pidchecked caching is defeated.
141  */
142 static int randompid = 0;
143
144 static __inline
145 struct ucred *
146 pcredcache(struct ucred *cr, struct proc *p)
147 {
148         if (cr != p->p_ucred) {
149                 if (cr)
150                         crfree(cr);
151                 spin_lock(&p->p_spin);
152                 if ((cr = p->p_ucred) != NULL)
153                         crhold(cr);
154                 spin_unlock(&p->p_spin);
155         }
156         return cr;
157 }
158
159 /*
160  * No requirements.
161  */
162 static int
163 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
164 {
165         int error, pid;
166
167         pid = randompid;
168         error = sysctl_handle_int(oidp, &pid, 0, req);
169         if (error || !req->newptr)
170                 return (error);
171         if (pid < 0 || pid > PID_MAX - 100)     /* out of range */
172                 pid = PID_MAX - 100;
173         else if (pid < 2)                       /* NOP */
174                 pid = 0;
175         else if (pid < 100)                     /* Make it reasonable */
176                 pid = 100;
177         randompid = pid;
178         return (error);
179 }
180
181 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
182             0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
183
184 /*
185  * Initialize global process hashing structures.
186  *
187  * These functions are ONLY called from the low level boot code and do
188  * not lock their operations.
189  */
190 void
191 procinit(void)
192 {
193         u_long i;
194
195         /*
196          * Allocate dynamically.  This array can be large (~1MB) so don't
197          * waste boot loader space.
198          */
199         pid_doms = kmalloc(sizeof(pid_doms[0]) * PIDSEL_DOMAINS,
200                            M_PROC, M_WAITOK | M_ZERO);
201
202         /*
203          * Avoid unnecessary stalls due to pid_doms[] values all being
204          * the same.  Make sure that the allocation of pid 1 and pid 2
205          * succeeds.
206          */
207         for (i = 0; i < PIDSEL_DOMAINS; ++i)
208                 pid_doms[i] = (int8_t)i - (int8_t)(PIDDOM_DELAY + 1);
209
210         /*
211          * Other misc init.
212          */
213         for (i = 0; i < ALLPROC_HSIZE; ++i) {
214                 procglob_t *prg = &procglob[i];
215                 LIST_INIT(&prg->allproc);
216                 LIST_INIT(&prg->allsess);
217                 LIST_INIT(&prg->allpgrp);
218                 lwkt_token_init(&prg->proc_token, "allproc");
219         }
220         uihashinit();
221 }
222
223 void
224 procinsertinit(struct proc *p)
225 {
226         LIST_INSERT_HEAD(&procglob[ALLPROC_HASH(p->p_pid)].allproc,
227                          p, p_list);
228 }
229
230 void
231 pgrpinsertinit(struct pgrp *pg)
232 {
233         LIST_INSERT_HEAD(&procglob[ALLPROC_HASH(pg->pg_id)].allpgrp,
234                          pg, pg_list);
235 }
236
237 void
238 sessinsertinit(struct session *sess)
239 {
240         LIST_INSERT_HEAD(&procglob[ALLPROC_HASH(sess->s_sid)].allsess,
241                          sess, s_list);
242 }
243
244 /*
245  * Process hold/release support functions.  Called via the PHOLD(),
246  * PRELE(), and PSTALL() macros.
247  *
248  * p->p_lock is a simple hold count with a waiting interlock.  No wakeup()
249  * is issued unless someone is actually waiting for the process.
250  *
251  * Most holds are short-term, allowing a process scan or other similar
252  * operation to access a proc structure without it getting ripped out from
253  * under us.  procfs and process-list sysctl ops also use the hold function
254  * interlocked with various p_flags to keep the vmspace intact when reading
255  * or writing a user process's address space.
256  *
257  * There are two situations where a hold count can be longer.  Exiting lwps
258  * hold the process until the lwp is reaped, and the parent will hold the
259  * child during vfork()/exec() sequences while the child is marked P_PPWAIT.
260  *
261  * The kernel waits for the hold count to drop to 0 (or 1 in some cases) at
262  * various critical points in the fork/exec and exit paths before proceeding.
263  */
264 #define PLOCK_ZOMB      0x20000000
265 #define PLOCK_WAITING   0x40000000
266 #define PLOCK_MASK      0x1FFFFFFF
267
268 void
269 pstall(struct proc *p, const char *wmesg, int count)
270 {
271         int o;
272         int n;
273
274         for (;;) {
275                 o = p->p_lock;
276                 cpu_ccfence();
277                 if ((o & PLOCK_MASK) <= count)
278                         break;
279                 n = o | PLOCK_WAITING;
280                 tsleep_interlock(&p->p_lock, 0);
281
282                 /*
283                  * If someone is trying to single-step the process during
284                  * an exec or an exit they can deadlock us because procfs
285                  * sleeps with the process held.
286                  */
287                 if (p->p_stops) {
288                         if (p->p_flags & P_INEXEC) {
289                                 wakeup(&p->p_stype);
290                         } else if (p->p_flags & P_POSTEXIT) {
291                                 spin_lock(&p->p_spin);
292                                 p->p_stops = 0;
293                                 p->p_step = 0;
294                                 spin_unlock(&p->p_spin);
295                                 wakeup(&p->p_stype);
296                         }
297                 }
298
299                 if (atomic_cmpset_int(&p->p_lock, o, n)) {
300                         tsleep(&p->p_lock, PINTERLOCKED, wmesg, 0);
301                 }
302         }
303 }
304
305 void
306 phold(struct proc *p)
307 {
308         atomic_add_int(&p->p_lock, 1);
309 }
310
311 /*
312  * WARNING!  On last release (p) can become instantly invalid due to
313  *           MP races.
314  */
315 void
316 prele(struct proc *p)
317 {
318         int o;
319         int n;
320
321         /*
322          * Fast path
323          */
324         if (atomic_cmpset_int(&p->p_lock, 1, 0))
325                 return;
326
327         /*
328          * Slow path
329          */
330         for (;;) {
331                 o = p->p_lock;
332                 KKASSERT((o & PLOCK_MASK) > 0);
333                 cpu_ccfence();
334                 n = (o - 1) & ~PLOCK_WAITING;
335                 if (atomic_cmpset_int(&p->p_lock, o, n)) {
336                         if (o & PLOCK_WAITING)
337                                 wakeup(&p->p_lock);
338                         break;
339                 }
340         }
341 }
342
343 /*
344  * Hold and flag serialized for zombie reaping purposes.
345  *
346  * This function will fail if it has to block, returning non-zero with
347  * neither the flag set or the hold count bumped.  Note that (p) may
348  * not be valid in this case if the caller does not have some other
349  * reference on (p).
350  *
351  * This function does not block on other PHOLD()s, only on other
352  * PHOLDZOMB()s.
353  *
354  * Zero is returned on success.  The hold count will be incremented and
355  * the serialization flag acquired.  Note that serialization is only against
356  * other pholdzomb() calls, not against phold() calls.
357  */
358 int
359 pholdzomb(struct proc *p)
360 {
361         int o;
362         int n;
363
364         /*
365          * Fast path
366          */
367         if (atomic_cmpset_int(&p->p_lock, 0, PLOCK_ZOMB | 1))
368                 return(0);
369
370         /*
371          * Slow path
372          */
373         for (;;) {
374                 o = p->p_lock;
375                 cpu_ccfence();
376                 if ((o & PLOCK_ZOMB) == 0) {
377                         n = (o + 1) | PLOCK_ZOMB;
378                         if (atomic_cmpset_int(&p->p_lock, o, n))
379                                 return(0);
380                 } else {
381                         KKASSERT((o & PLOCK_MASK) > 0);
382                         n = o | PLOCK_WAITING;
383                         tsleep_interlock(&p->p_lock, 0);
384                         if (atomic_cmpset_int(&p->p_lock, o, n)) {
385                                 tsleep(&p->p_lock, PINTERLOCKED, "phldz", 0);
386                                 /* (p) can be ripped out at this point */
387                                 return(1);
388                         }
389                 }
390         }
391 }
392
393 /*
394  * Release PLOCK_ZOMB and the hold count, waking up any waiters.
395  *
396  * WARNING!  On last release (p) can become instantly invalid due to
397  *           MP races.
398  */
399 void
400 prelezomb(struct proc *p)
401 {
402         int o;
403         int n;
404
405         /*
406          * Fast path
407          */
408         if (atomic_cmpset_int(&p->p_lock, PLOCK_ZOMB | 1, 0))
409                 return;
410
411         /*
412          * Slow path
413          */
414         KKASSERT(p->p_lock & PLOCK_ZOMB);
415         for (;;) {
416                 o = p->p_lock;
417                 KKASSERT((o & PLOCK_MASK) > 0);
418                 cpu_ccfence();
419                 n = (o - 1) & ~(PLOCK_ZOMB | PLOCK_WAITING);
420                 if (atomic_cmpset_int(&p->p_lock, o, n)) {
421                         if (o & PLOCK_WAITING)
422                                 wakeup(&p->p_lock);
423                         break;
424                 }
425         }
426 }
427
428 /*
429  * Is p an inferior of the current process?
430  *
431  * No requirements.
432  */
433 int
434 inferior(struct proc *p)
435 {
436         struct proc *p2;
437
438         PHOLD(p);
439         lwkt_gettoken_shared(&p->p_token);
440         while (p != curproc) {
441                 if (p->p_pid == 0) {
442                         lwkt_reltoken(&p->p_token);
443                         return (0);
444                 }
445                 p2 = p->p_pptr;
446                 PHOLD(p2);
447                 lwkt_reltoken(&p->p_token);
448                 PRELE(p);
449                 lwkt_gettoken_shared(&p2->p_token);
450                 p = p2;
451         }
452         lwkt_reltoken(&p->p_token);
453         PRELE(p);
454
455         return (1);
456 }
457
458 /*
459  * Locate a process by number.  The returned process will be referenced and
460  * must be released with PRELE().
461  *
462  * No requirements.
463  */
464 struct proc *
465 pfind(pid_t pid)
466 {
467         struct proc *p = curproc;
468         procglob_t *prg;
469         int n;
470
471         /*
472          * Shortcut the current process
473          */
474         if (p && p->p_pid == pid) {
475                 PHOLD(p);
476                 return (p);
477         }
478
479         /*
480          * Otherwise find it in the hash table.
481          */
482         n = ALLPROC_HASH(pid);
483         prg = &procglob[n];
484
485         lwkt_gettoken_shared(&prg->proc_token);
486         LIST_FOREACH(p, &prg->allproc, p_list) {
487                 if (p->p_stat == SZOMB)
488                         continue;
489                 if (p->p_pid == pid) {
490                         PHOLD(p);
491                         lwkt_reltoken(&prg->proc_token);
492                         return (p);
493                 }
494         }
495         lwkt_reltoken(&prg->proc_token);
496
497         return (NULL);
498 }
499
500 /*
501  * Locate a process by number.  The returned process is NOT referenced.
502  * The result will not be stable and is typically only used to validate
503  * against a process that the caller has in-hand.
504  *
505  * No requirements.
506  */
507 struct proc *
508 pfindn(pid_t pid)
509 {
510         struct proc *p = curproc;
511         procglob_t *prg;
512         int n;
513
514         /*
515          * Shortcut the current process
516          */
517         if (p && p->p_pid == pid)
518                 return (p);
519
520         /*
521          * Otherwise find it in the hash table.
522          */
523         n = ALLPROC_HASH(pid);
524         prg = &procglob[n];
525
526         lwkt_gettoken_shared(&prg->proc_token);
527         LIST_FOREACH(p, &prg->allproc, p_list) {
528                 if (p->p_stat == SZOMB)
529                         continue;
530                 if (p->p_pid == pid) {
531                         lwkt_reltoken(&prg->proc_token);
532                         return (p);
533                 }
534         }
535         lwkt_reltoken(&prg->proc_token);
536
537         return (NULL);
538 }
539
540 /*
541  * Locate a process on the zombie list.  Return a process or NULL.
542  * The returned process will be referenced and the caller must release
543  * it with PRELE().
544  *
545  * No other requirements.
546  */
547 struct proc *
548 zpfind(pid_t pid)
549 {
550         struct proc *p = curproc;
551         procglob_t *prg;
552         int n;
553
554         /*
555          * Shortcut the current process
556          */
557         if (p && p->p_pid == pid) {
558                 PHOLD(p);
559                 return (p);
560         }
561
562         /*
563          * Otherwise find it in the hash table.
564          */
565         n = ALLPROC_HASH(pid);
566         prg = &procglob[n];
567
568         lwkt_gettoken_shared(&prg->proc_token);
569         LIST_FOREACH(p, &prg->allproc, p_list) {
570                 if (p->p_stat != SZOMB)
571                         continue;
572                 if (p->p_pid == pid) {
573                         PHOLD(p);
574                         lwkt_reltoken(&prg->proc_token);
575                         return (p);
576                 }
577         }
578         lwkt_reltoken(&prg->proc_token);
579
580         return (NULL);
581 }
582
583
584 void
585 pgref(struct pgrp *pgrp)
586 {
587         refcount_acquire(&pgrp->pg_refs);
588 }
589
590 void
591 pgrel(struct pgrp *pgrp)
592 {
593         procglob_t *prg;
594         int count;
595         int n;
596
597         n = PGRP_HASH(pgrp->pg_id);
598         prg = &procglob[n];
599
600         for (;;) {
601                 count = pgrp->pg_refs;
602                 cpu_ccfence();
603                 KKASSERT(count > 0);
604                 if (count == 1) {
605                         lwkt_gettoken(&prg->proc_token);
606                         if (atomic_cmpset_int(&pgrp->pg_refs, 1, 0))
607                                 break;
608                         lwkt_reltoken(&prg->proc_token);
609                         /* retry */
610                 } else {
611                         if (atomic_cmpset_int(&pgrp->pg_refs, count, count - 1))
612                                 return;
613                         /* retry */
614                 }
615         }
616
617         /*
618          * Successful 1->0 transition, pghash_spin is held.
619          */
620         LIST_REMOVE(pgrp, pg_list);
621         if (pid_doms[pgrp->pg_id % PIDSEL_DOMAINS] != (uint8_t)time_second)
622                 pid_doms[pgrp->pg_id % PIDSEL_DOMAINS] = (uint8_t)time_second;
623
624         /*
625          * Reset any sigio structures pointing to us as a result of
626          * F_SETOWN with our pgid.
627          */
628         funsetownlst(&pgrp->pg_sigiolst);
629
630         if (pgrp->pg_session->s_ttyp != NULL &&
631             pgrp->pg_session->s_ttyp->t_pgrp == pgrp) {
632                 pgrp->pg_session->s_ttyp->t_pgrp = NULL;
633         }
634         lwkt_reltoken(&prg->proc_token);
635
636         sess_rele(pgrp->pg_session);
637         kfree(pgrp, M_PGRP);
638 }
639
640 /*
641  * Locate a process group by number.  The returned process group will be
642  * referenced w/pgref() and must be released with pgrel() (or assigned
643  * somewhere if you wish to keep the reference).
644  *
645  * No requirements.
646  */
647 struct pgrp *
648 pgfind(pid_t pgid)
649 {
650         struct pgrp *pgrp;
651         procglob_t *prg;
652         int n;
653
654         n = PGRP_HASH(pgid);
655         prg = &procglob[n];
656         lwkt_gettoken_shared(&prg->proc_token);
657
658         LIST_FOREACH(pgrp, &prg->allpgrp, pg_list) {
659                 if (pgrp->pg_id == pgid) {
660                         refcount_acquire(&pgrp->pg_refs);
661                         lwkt_reltoken(&prg->proc_token);
662                         return (pgrp);
663                 }
664         }
665         lwkt_reltoken(&prg->proc_token);
666         return (NULL);
667 }
668
669 /*
670  * Move p to a new or existing process group (and session)
671  *
672  * No requirements.
673  */
674 int
675 enterpgrp(struct proc *p, pid_t pgid, int mksess)
676 {
677         struct pgrp *pgrp;
678         struct pgrp *opgrp;
679         int error;
680
681         pgrp = pgfind(pgid);
682
683         KASSERT(pgrp == NULL || !mksess,
684                 ("enterpgrp: setsid into non-empty pgrp"));
685         KASSERT(!SESS_LEADER(p),
686                 ("enterpgrp: session leader attempted setpgrp"));
687
688         if (pgrp == NULL) {
689                 pid_t savepid = p->p_pid;
690                 struct proc *np;
691                 procglob_t *prg;
692                 int n;
693
694                 /*
695                  * new process group
696                  */
697                 KASSERT(p->p_pid == pgid,
698                         ("enterpgrp: new pgrp and pid != pgid"));
699                 pgrp = kmalloc(sizeof(struct pgrp), M_PGRP, M_WAITOK | M_ZERO);
700                 pgrp->pg_id = pgid;
701                 LIST_INIT(&pgrp->pg_members);
702                 pgrp->pg_jobc = 0;
703                 SLIST_INIT(&pgrp->pg_sigiolst);
704                 lwkt_token_init(&pgrp->pg_token, "pgrp_token");
705                 refcount_init(&pgrp->pg_refs, 1);
706                 lockinit(&pgrp->pg_lock, "pgwt", 0, 0);
707
708                 n = PGRP_HASH(pgid);
709                 prg = &procglob[n];
710
711                 if ((np = pfindn(savepid)) == NULL || np != p) {
712                         lwkt_reltoken(&prg->proc_token);
713                         error = ESRCH;
714                         kfree(pgrp, M_PGRP);
715                         goto fatal;
716                 }
717
718                 lwkt_gettoken(&prg->proc_token);
719                 if (mksess) {
720                         struct session *sess;
721
722                         /*
723                          * new session
724                          */
725                         sess = kmalloc(sizeof(struct session), M_SESSION,
726                                        M_WAITOK | M_ZERO);
727                         lwkt_gettoken(&p->p_token);
728                         sess->s_leader = p;
729                         sess->s_sid = p->p_pid;
730                         sess->s_count = 1;
731                         sess->s_ttyvp = NULL;
732                         sess->s_ttyp = NULL;
733                         bcopy(p->p_session->s_login, sess->s_login,
734                               sizeof(sess->s_login));
735                         pgrp->pg_session = sess;
736                         KASSERT(p == curproc,
737                                 ("enterpgrp: mksession and p != curproc"));
738                         p->p_flags &= ~P_CONTROLT;
739                         LIST_INSERT_HEAD(&prg->allsess, sess, s_list);
740                         lwkt_reltoken(&p->p_token);
741                 } else {
742                         lwkt_gettoken(&p->p_token);
743                         pgrp->pg_session = p->p_session;
744                         sess_hold(pgrp->pg_session);
745                         lwkt_reltoken(&p->p_token);
746                 }
747                 LIST_INSERT_HEAD(&prg->allpgrp, pgrp, pg_list);
748
749                 lwkt_reltoken(&prg->proc_token);
750         } else if (pgrp == p->p_pgrp) {
751                 pgrel(pgrp);
752                 goto done;
753         } /* else pgfind() referenced the pgrp */
754
755         lwkt_gettoken(&pgrp->pg_token);
756         lwkt_gettoken(&p->p_token);
757
758         /*
759          * Replace p->p_pgrp, handling any races that occur.
760          */
761         while ((opgrp = p->p_pgrp) != NULL) {
762                 pgref(opgrp);
763                 lwkt_gettoken(&opgrp->pg_token);
764                 if (opgrp != p->p_pgrp) {
765                         lwkt_reltoken(&opgrp->pg_token);
766                         pgrel(opgrp);
767                         continue;
768                 }
769                 LIST_REMOVE(p, p_pglist);
770                 break;
771         }
772         p->p_pgrp = pgrp;
773         LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
774
775         /*
776          * Adjust eligibility of affected pgrps to participate in job control.
777          * Increment eligibility counts before decrementing, otherwise we
778          * could reach 0 spuriously during the first call.
779          */
780         fixjobc(p, pgrp, 1);
781         if (opgrp) {
782                 fixjobc(p, opgrp, 0);
783                 lwkt_reltoken(&opgrp->pg_token);
784                 pgrel(opgrp);   /* manual pgref */
785                 pgrel(opgrp);   /* p->p_pgrp ref */
786         }
787         lwkt_reltoken(&p->p_token);
788         lwkt_reltoken(&pgrp->pg_token);
789 done:
790         error = 0;
791 fatal:
792         return (error);
793 }
794
795 /*
796  * Remove process from process group
797  *
798  * No requirements.
799  */
800 int
801 leavepgrp(struct proc *p)
802 {
803         struct pgrp *pg = p->p_pgrp;
804
805         lwkt_gettoken(&p->p_token);
806         while ((pg = p->p_pgrp) != NULL) {
807                 pgref(pg);
808                 lwkt_gettoken(&pg->pg_token);
809                 if (p->p_pgrp != pg) {
810                         lwkt_reltoken(&pg->pg_token);
811                         pgrel(pg);
812                         continue;
813                 }
814                 p->p_pgrp = NULL;
815                 LIST_REMOVE(p, p_pglist);
816                 lwkt_reltoken(&pg->pg_token);
817                 pgrel(pg);      /* manual pgref */
818                 pgrel(pg);      /* p->p_pgrp ref */
819                 break;
820         }
821         lwkt_reltoken(&p->p_token);
822
823         return (0);
824 }
825
826 /*
827  * Adjust the ref count on a session structure.  When the ref count falls to
828  * zero the tty is disassociated from the session and the session structure
829  * is freed.  Note that tty assocation is not itself ref-counted.
830  *
831  * No requirements.
832  */
833 void
834 sess_hold(struct session *sp)
835 {
836         atomic_add_int(&sp->s_count, 1);
837 }
838
839 /*
840  * No requirements.
841  */
842 void
843 sess_rele(struct session *sess)
844 {
845         procglob_t *prg;
846         struct tty *tp;
847         int count;
848         int n;
849
850         n = SESS_HASH(sess->s_sid);
851         prg = &procglob[n];
852
853         for (;;) {
854                 count = sess->s_count;
855                 cpu_ccfence();
856                 KKASSERT(count > 0);
857                 if (count == 1) {
858                         lwkt_gettoken(&tty_token);
859                         lwkt_gettoken(&prg->proc_token);
860                         if (atomic_cmpset_int(&sess->s_count, 1, 0))
861                                 break;
862                         lwkt_reltoken(&prg->proc_token);
863                         lwkt_reltoken(&tty_token);
864                         /* retry */
865                 } else {
866                         if (atomic_cmpset_int(&sess->s_count, count, count - 1))
867                                 return;
868                         /* retry */
869                 }
870         }
871
872         /*
873          * Successful 1->0 transition and tty_token is held.
874          */
875         LIST_REMOVE(sess, s_list);
876         if (pid_doms[sess->s_sid % PIDSEL_DOMAINS] != (uint8_t)time_second)
877                 pid_doms[sess->s_sid % PIDSEL_DOMAINS] = (uint8_t)time_second;
878
879         if (sess->s_ttyp && sess->s_ttyp->t_session) {
880 #ifdef TTY_DO_FULL_CLOSE
881                 /* FULL CLOSE, see ttyclearsession() */
882                 KKASSERT(sess->s_ttyp->t_session == sess);
883                 sess->s_ttyp->t_session = NULL;
884 #else
885                 /* HALF CLOSE, see ttyclearsession() */
886                 if (sess->s_ttyp->t_session == sess)
887                         sess->s_ttyp->t_session = NULL;
888 #endif
889         }
890         if ((tp = sess->s_ttyp) != NULL) {
891                 sess->s_ttyp = NULL;
892                 ttyunhold(tp);
893         }
894         lwkt_reltoken(&prg->proc_token);
895         lwkt_reltoken(&tty_token);
896
897         kfree(sess, M_SESSION);
898 }
899
900 /*
901  * Adjust pgrp jobc counters when specified process changes process group.
902  * We count the number of processes in each process group that "qualify"
903  * the group for terminal job control (those with a parent in a different
904  * process group of the same session).  If that count reaches zero, the
905  * process group becomes orphaned.  Check both the specified process'
906  * process group and that of its children.
907  * entering == 0 => p is leaving specified group.
908  * entering == 1 => p is entering specified group.
909  *
910  * No requirements.
911  */
912 void
913 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
914 {
915         struct pgrp *hispgrp;
916         struct session *mysession;
917         struct proc *np;
918
919         /*
920          * Check p's parent to see whether p qualifies its own process
921          * group; if so, adjust count for p's process group.
922          */
923         lwkt_gettoken(&p->p_token);     /* p_children scan */
924         lwkt_gettoken(&pgrp->pg_token);
925
926         mysession = pgrp->pg_session;
927         if ((hispgrp = p->p_pptr->p_pgrp) != pgrp &&
928             hispgrp->pg_session == mysession) {
929                 if (entering)
930                         pgrp->pg_jobc++;
931                 else if (--pgrp->pg_jobc == 0)
932                         orphanpg(pgrp);
933         }
934
935         /*
936          * Check this process' children to see whether they qualify
937          * their process groups; if so, adjust counts for children's
938          * process groups.
939          */
940         LIST_FOREACH(np, &p->p_children, p_sibling) {
941                 PHOLD(np);
942                 lwkt_gettoken(&np->p_token);
943                 if ((hispgrp = np->p_pgrp) != pgrp &&
944                     hispgrp->pg_session == mysession &&
945                     np->p_stat != SZOMB) {
946                         pgref(hispgrp);
947                         lwkt_gettoken(&hispgrp->pg_token);
948                         if (entering)
949                                 hispgrp->pg_jobc++;
950                         else if (--hispgrp->pg_jobc == 0)
951                                 orphanpg(hispgrp);
952                         lwkt_reltoken(&hispgrp->pg_token);
953                         pgrel(hispgrp);
954                 }
955                 lwkt_reltoken(&np->p_token);
956                 PRELE(np);
957         }
958         KKASSERT(pgrp->pg_refs > 0);
959         lwkt_reltoken(&pgrp->pg_token);
960         lwkt_reltoken(&p->p_token);
961 }
962
963 /*
964  * A process group has become orphaned;
965  * if there are any stopped processes in the group,
966  * hang-up all process in that group.
967  *
968  * The caller must hold pg_token.
969  */
970 static void
971 orphanpg(struct pgrp *pg)
972 {
973         struct proc *p;
974
975         LIST_FOREACH(p, &pg->pg_members, p_pglist) {
976                 if (p->p_stat == SSTOP) {
977                         LIST_FOREACH(p, &pg->pg_members, p_pglist) {
978                                 ksignal(p, SIGHUP);
979                                 ksignal(p, SIGCONT);
980                         }
981                         return;
982                 }
983         }
984 }
985
986 /*
987  * Add a new process to the allproc list and the PID hash.  This
988  * also assigns a pid to the new process.
989  *
990  * No requirements.
991  */
992 void
993 proc_add_allproc(struct proc *p)
994 {
995         int random_offset;
996
997         if ((random_offset = randompid) != 0) {
998                 read_random(&random_offset, sizeof(random_offset));
999                 random_offset = (random_offset & 0x7FFFFFFF) % randompid;
1000         }
1001         proc_makepid(p, random_offset);
1002 }
1003
1004 /*
1005  * Calculate a new process pid.  This function is integrated into
1006  * proc_add_allproc() to guarentee that the new pid is not reused before
1007  * the new process can be added to the allproc list.
1008  *
1009  * p_pid is assigned and the process is added to the allproc hash table
1010  *
1011  * WARNING! We need to allocate PIDs sequentially during early boot.
1012  *          In particular, init needs to have a pid of 1.
1013  */
1014 static
1015 void
1016 proc_makepid(struct proc *p, int random_offset)
1017 {
1018         static pid_t nextpid = 1;       /* heuristic, allowed to race */
1019         procglob_t *prg;
1020         struct pgrp *pg;
1021         struct proc *ps;
1022         struct session *sess;
1023         pid_t base;
1024         int8_t delta8;
1025         int retries;
1026         int n;
1027
1028         /*
1029          * Select the next pid base candidate.
1030          *
1031          * Check cyclement, do not allow a pid < 100.
1032          */
1033         retries = 0;
1034 retry:
1035         base = atomic_fetchadd_int(&nextpid, 1) + random_offset;
1036         if (base <= 0 || base >= PID_MAX) {
1037                 base = base % PID_MAX;
1038                 if (base < 0)
1039                         base = 100;
1040                 if (base < 100)
1041                         base += 100;
1042                 nextpid = base;         /* reset (SMP race ok) */
1043         }
1044
1045         /*
1046          * Do not allow a base pid to be selected from a domain that has
1047          * recently seen a pid/pgid/sessid reap.  Sleep a little if we looped
1048          * through all available domains.
1049          *
1050          * WARNING: We want the early pids to be allocated linearly,
1051          *          particularly pid 1 and pid 2.
1052          */
1053         if (++retries >= PIDSEL_DOMAINS)
1054                 tsleep(&nextpid, 0, "makepid", 1);
1055         if (base >= 100) {
1056                 delta8 = (int8_t)time_second -
1057                          (int8_t)pid_doms[base % PIDSEL_DOMAINS];
1058                 if (delta8 >= 0 && delta8 <= PIDDOM_DELAY) {
1059                         ++pid_domain_skips;
1060                         goto retry;
1061                 }
1062         }
1063
1064         /*
1065          * Calculate a hash index and find an unused process id within
1066          * the table, looping if we cannot find one.
1067          *
1068          * The inner loop increments by ALLPROC_HSIZE which keeps the
1069          * PID at the same pid_doms[] index as well as the same hash index.
1070          */
1071         n = ALLPROC_HASH(base);
1072         prg = &procglob[n];
1073         lwkt_gettoken(&prg->proc_token);
1074
1075 restart1:
1076         LIST_FOREACH(ps, &prg->allproc, p_list) {
1077                 if (ps->p_pid == base) {
1078                         base += ALLPROC_HSIZE;
1079                         if (base >= PID_MAX) {
1080                                 lwkt_reltoken(&prg->proc_token);
1081                                 goto retry;
1082                         }
1083                         ++pid_inner_skips;
1084                         goto restart1;
1085                 }
1086         }
1087         LIST_FOREACH(pg, &prg->allpgrp, pg_list) {
1088                 if (pg->pg_id == base) {
1089                         base += ALLPROC_HSIZE;
1090                         if (base >= PID_MAX) {
1091                                 lwkt_reltoken(&prg->proc_token);
1092                                 goto retry;
1093                         }
1094                         ++pid_inner_skips;
1095                         goto restart1;
1096                 }
1097         }
1098         LIST_FOREACH(sess, &prg->allsess, s_list) {
1099                 if (sess->s_sid == base) {
1100                         base += ALLPROC_HSIZE;
1101                         if (base >= PID_MAX) {
1102                                 lwkt_reltoken(&prg->proc_token);
1103                                 goto retry;
1104                         }
1105                         ++pid_inner_skips;
1106                         goto restart1;
1107                 }
1108         }
1109
1110         /*
1111          * Assign the pid and insert the process.
1112          */
1113         p->p_pid = base;
1114         LIST_INSERT_HEAD(&prg->allproc, p, p_list);
1115         lwkt_reltoken(&prg->proc_token);
1116 }
1117
1118 /*
1119  * Called from exit1 to place the process into a zombie state.
1120  * The process is removed from the pid hash and p_stat is set
1121  * to SZOMB.  Normal pfind[n]() calls will not find it any more.
1122  *
1123  * Caller must hold p->p_token.  We are required to wait until p_lock
1124  * becomes zero before we can manipulate the list, allowing allproc
1125  * scans to guarantee consistency during a list scan.
1126  */
1127 void
1128 proc_move_allproc_zombie(struct proc *p)
1129 {
1130         procglob_t *prg;
1131         int n;
1132
1133         n = ALLPROC_HASH(p->p_pid);
1134         prg = &procglob[n];
1135         PSTALL(p, "reap1", 0);
1136         lwkt_gettoken(&prg->proc_token);
1137
1138         PSTALL(p, "reap1a", 0);
1139         p->p_stat = SZOMB;
1140
1141         lwkt_reltoken(&prg->proc_token);
1142         dsched_exit_proc(p);
1143 }
1144
1145 /*
1146  * This routine is called from kern_wait() and will remove the process
1147  * from the zombie list and the sibling list.  This routine will block
1148  * if someone has a lock on the proces (p_lock).
1149  *
1150  * Caller must hold p->p_token.  We are required to wait until p_lock
1151  * becomes one before we can manipulate the list, allowing allproc
1152  * scans to guarantee consistency during a list scan.
1153  *
1154  * Assumes caller has one ref.
1155  */
1156 void
1157 proc_remove_zombie(struct proc *p)
1158 {
1159         procglob_t *prg;
1160         int n;
1161
1162         n = ALLPROC_HASH(p->p_pid);
1163         prg = &procglob[n];
1164
1165         PSTALL(p, "reap2", 1);
1166         lwkt_gettoken(&prg->proc_token);
1167         PSTALL(p, "reap2a", 1);
1168         LIST_REMOVE(p, p_list);         /* from remove master list */
1169         LIST_REMOVE(p, p_sibling);      /* and from sibling list */
1170         p->p_pptr = NULL;
1171         p->p_ppid = 0;
1172         if (pid_doms[p->p_pid % PIDSEL_DOMAINS] != (uint8_t)time_second)
1173                 pid_doms[p->p_pid % PIDSEL_DOMAINS] = (uint8_t)time_second;
1174         lwkt_reltoken(&prg->proc_token);
1175 }
1176
1177 /*
1178  * Handle various requirements prior to returning to usermode.  Called from
1179  * platform trap and system call code.
1180  */
1181 void
1182 lwpuserret(struct lwp *lp)
1183 {
1184         struct proc *p = lp->lwp_proc;
1185
1186         if (lp->lwp_mpflags & LWP_MP_VNLRU) {
1187                 atomic_clear_int(&lp->lwp_mpflags, LWP_MP_VNLRU);
1188                 allocvnode_gc();
1189         }
1190         if (lp->lwp_mpflags & LWP_MP_WEXIT) {
1191                 lwkt_gettoken(&p->p_token);
1192                 lwp_exit(0, NULL);
1193                 lwkt_reltoken(&p->p_token);     /* NOT REACHED */
1194         }
1195 }
1196
1197 /*
1198  * Kernel threads run from user processes can also accumulate deferred
1199  * actions which need to be acted upon.  Callers include:
1200  *
1201  * nfsd         - Can allocate lots of vnodes
1202  */
1203 void
1204 lwpkthreaddeferred(void)
1205 {
1206         struct lwp *lp = curthread->td_lwp;
1207
1208         if (lp) {
1209                 if (lp->lwp_mpflags & LWP_MP_VNLRU) {
1210                         atomic_clear_int(&lp->lwp_mpflags, LWP_MP_VNLRU);
1211                         allocvnode_gc();
1212                 }
1213         }
1214 }
1215
1216 void
1217 proc_usermap(struct proc *p, int invfork)
1218 {
1219         struct sys_upmap *upmap;
1220
1221         lwkt_gettoken(&p->p_token);
1222         upmap = kmalloc(roundup2(sizeof(*upmap), PAGE_SIZE), M_PROC,
1223                         M_WAITOK | M_ZERO);
1224         if (p->p_upmap == NULL) {
1225                 upmap->header[0].type = UKPTYPE_VERSION;
1226                 upmap->header[0].offset = offsetof(struct sys_upmap, version);
1227                 upmap->header[1].type = UPTYPE_RUNTICKS;
1228                 upmap->header[1].offset = offsetof(struct sys_upmap, runticks);
1229                 upmap->header[2].type = UPTYPE_FORKID;
1230                 upmap->header[2].offset = offsetof(struct sys_upmap, forkid);
1231                 upmap->header[3].type = UPTYPE_PID;
1232                 upmap->header[3].offset = offsetof(struct sys_upmap, pid);
1233                 upmap->header[4].type = UPTYPE_PROC_TITLE;
1234                 upmap->header[4].offset = offsetof(struct sys_upmap,proc_title);
1235                 upmap->header[5].type = UPTYPE_INVFORK;
1236                 upmap->header[5].offset = offsetof(struct sys_upmap, invfork);
1237
1238                 upmap->version = UPMAP_VERSION;
1239                 upmap->pid = p->p_pid;
1240                 upmap->forkid = p->p_forkid;
1241                 upmap->invfork = invfork;
1242                 p->p_upmap = upmap;
1243         } else {
1244                 kfree(upmap, M_PROC);
1245         }
1246         lwkt_reltoken(&p->p_token);
1247 }
1248
1249 void
1250 proc_userunmap(struct proc *p)
1251 {
1252         struct sys_upmap *upmap;
1253
1254         lwkt_gettoken(&p->p_token);
1255         if ((upmap = p->p_upmap) != NULL) {
1256                 p->p_upmap = NULL;
1257                 kfree(upmap, M_PROC);
1258         }
1259         lwkt_reltoken(&p->p_token);
1260 }
1261
1262 /*
1263  * Scan all processes on the allproc list.  The process is automatically
1264  * held for the callback.  A return value of -1 terminates the loop.
1265  * Zombie procs are skipped.
1266  *
1267  * The callback is made with the process held and proc_token held.
1268  *
1269  * We limit the scan to the number of processes as-of the start of
1270  * the scan so as not to get caught up in an endless loop if new processes
1271  * are created more quickly than we can scan the old ones.  Add a little
1272  * slop to try to catch edge cases since nprocs can race.
1273  *
1274  * No requirements.
1275  */
1276 void
1277 allproc_scan(int (*callback)(struct proc *, void *), void *data, int segmented)
1278 {
1279         int limit = nprocs + ncpus;
1280         struct proc *p;
1281         int ns;
1282         int ne;
1283         int r;
1284         int n;
1285
1286         if (segmented) {
1287                 int id = mycpu->gd_cpuid;
1288                 ns = id * ALLPROC_HSIZE / ncpus;
1289                 ne = (id + 1) * ALLPROC_HSIZE / ncpus;
1290         } else {
1291                 ns = 0;
1292                 ne = ALLPROC_HSIZE;
1293         }
1294
1295         /*
1296          * prg->proc_token protects the allproc list and PHOLD() prevents the
1297          * process from being removed from the allproc list or the zombproc
1298          * list.
1299          */
1300         for (n = ns; n < ne; ++n) {
1301                 procglob_t *prg = &procglob[n];
1302                 if (LIST_FIRST(&prg->allproc) == NULL)
1303                         continue;
1304                 lwkt_gettoken(&prg->proc_token);
1305                 LIST_FOREACH(p, &prg->allproc, p_list) {
1306                         if (p->p_stat == SZOMB)
1307                                 continue;
1308                         PHOLD(p);
1309                         r = callback(p, data);
1310                         PRELE(p);
1311                         if (r < 0)
1312                                 break;
1313                         if (--limit < 0)
1314                                 break;
1315                 }
1316                 lwkt_reltoken(&prg->proc_token);
1317
1318                 /*
1319                  * Check if asked to stop early
1320                  */
1321                 if (p)
1322                         break;
1323         }
1324 }
1325
1326 /*
1327  * Scan all lwps of processes on the allproc list.  The lwp is automatically
1328  * held for the callback.  A return value of -1 terminates the loop.
1329  *
1330  * The callback is made with the proces and lwp both held, and proc_token held.
1331  *
1332  * No requirements.
1333  */
1334 void
1335 alllwp_scan(int (*callback)(struct lwp *, void *), void *data, int segmented)
1336 {
1337         struct proc *p;
1338         struct lwp *lp;
1339         int ns;
1340         int ne;
1341         int r = 0;
1342         int n;
1343
1344         if (segmented) {
1345                 int id = mycpu->gd_cpuid;
1346                 ns = id * ALLPROC_HSIZE / ncpus;
1347                 ne = (id + 1) * ALLPROC_HSIZE / ncpus;
1348         } else {
1349                 ns = 0;
1350                 ne = ALLPROC_HSIZE;
1351         }
1352
1353         for (n = ns; n < ne; ++n) {
1354                 procglob_t *prg = &procglob[n];
1355
1356                 if (LIST_FIRST(&prg->allproc) == NULL)
1357                         continue;
1358                 lwkt_gettoken(&prg->proc_token);
1359                 LIST_FOREACH(p, &prg->allproc, p_list) {
1360                         if (p->p_stat == SZOMB)
1361                                 continue;
1362                         PHOLD(p);
1363                         lwkt_gettoken(&p->p_token);
1364                         FOREACH_LWP_IN_PROC(lp, p) {
1365                                 LWPHOLD(lp);
1366                                 r = callback(lp, data);
1367                                 LWPRELE(lp);
1368                         }
1369                         lwkt_reltoken(&p->p_token);
1370                         PRELE(p);
1371                         if (r < 0)
1372                                 break;
1373                 }
1374                 lwkt_reltoken(&prg->proc_token);
1375
1376                 /*
1377                  * Asked to exit early
1378                  */
1379                 if (p)
1380                         break;
1381         }
1382 }
1383
1384 /*
1385  * Scan all processes on the zombproc list.  The process is automatically
1386  * held for the callback.  A return value of -1 terminates the loop.
1387  *
1388  * No requirements.
1389  * The callback is made with the proces held and proc_token held.
1390  */
1391 void
1392 zombproc_scan(int (*callback)(struct proc *, void *), void *data)
1393 {
1394         struct proc *p;
1395         int r;
1396         int n;
1397
1398         /*
1399          * prg->proc_token protects the allproc list and PHOLD() prevents the
1400          * process from being removed from the allproc list or the zombproc
1401          * list.
1402          */
1403         for (n = 0; n < ALLPROC_HSIZE; ++n) {
1404                 procglob_t *prg = &procglob[n];
1405
1406                 if (LIST_FIRST(&prg->allproc) == NULL)
1407                         continue;
1408                 lwkt_gettoken(&prg->proc_token);
1409                 LIST_FOREACH(p, &prg->allproc, p_list) {
1410                         if (p->p_stat != SZOMB)
1411                                 continue;
1412                         PHOLD(p);
1413                         r = callback(p, data);
1414                         PRELE(p);
1415                         if (r < 0)
1416                                 break;
1417                 }
1418                 lwkt_reltoken(&prg->proc_token);
1419
1420                 /*
1421                  * Check if asked to stop early
1422                  */
1423                 if (p)
1424                         break;
1425         }
1426 }
1427
1428 #include "opt_ddb.h"
1429 #ifdef DDB
1430 #include <ddb/ddb.h>
1431
1432 /*
1433  * Debugging only
1434  */
1435 DB_SHOW_COMMAND(pgrpdump, pgrpdump)
1436 {
1437         struct pgrp *pgrp;
1438         struct proc *p;
1439         procglob_t *prg;
1440         int i;
1441
1442         for (i = 0; i < ALLPROC_HSIZE; ++i) {
1443                 prg = &procglob[i];
1444
1445                 if (LIST_EMPTY(&prg->allpgrp))
1446                         continue;
1447                 kprintf("\tindx %d\n", i);
1448                 LIST_FOREACH(pgrp, &prg->allpgrp, pg_list) {
1449                         kprintf("\tpgrp %p, pgid %ld, sess %p, "
1450                                 "sesscnt %d, mem %p\n",
1451                                 (void *)pgrp, (long)pgrp->pg_id,
1452                                 (void *)pgrp->pg_session,
1453                                 pgrp->pg_session->s_count,
1454                                 (void *)LIST_FIRST(&pgrp->pg_members));
1455                         LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
1456                                 kprintf("\t\tpid %ld addr %p pgrp %p\n",
1457                                         (long)p->p_pid, (void *)p,
1458                                         (void *)p->p_pgrp);
1459                         }
1460                 }
1461         }
1462 }
1463 #endif /* DDB */
1464
1465 /*
1466  * The caller must hold proc_token.
1467  */
1468 static int
1469 sysctl_out_proc(struct proc *p, struct sysctl_req *req, int flags)
1470 {
1471         struct kinfo_proc ki;
1472         struct lwp *lp;
1473         int skp = 0, had_output = 0;
1474         int error;
1475
1476         bzero(&ki, sizeof(ki));
1477         lwkt_gettoken_shared(&p->p_token);
1478         fill_kinfo_proc(p, &ki);
1479         if ((flags & KERN_PROC_FLAG_LWP) == 0)
1480                 skp = 1;
1481         error = 0;
1482         FOREACH_LWP_IN_PROC(lp, p) {
1483                 LWPHOLD(lp);
1484                 fill_kinfo_lwp(lp, &ki.kp_lwp);
1485                 had_output = 1;
1486                 error = SYSCTL_OUT(req, &ki, sizeof(ki));
1487                 LWPRELE(lp);
1488                 if (error)
1489                         break;
1490                 if (skp)
1491                         break;
1492         }
1493         lwkt_reltoken(&p->p_token);
1494         /* We need to output at least the proc, even if there is no lwp. */
1495         if (had_output == 0) {
1496                 error = SYSCTL_OUT(req, &ki, sizeof(ki));
1497         }
1498         return (error);
1499 }
1500
1501 /*
1502  * The caller must hold proc_token.
1503  */
1504 static int
1505 sysctl_out_proc_kthread(struct thread *td, struct sysctl_req *req)
1506 {
1507         struct kinfo_proc ki;
1508         int error;
1509
1510         fill_kinfo_proc_kthread(td, &ki);
1511         error = SYSCTL_OUT(req, &ki, sizeof(ki));
1512         if (error)
1513                 return error;
1514         return(0);
1515 }
1516
1517 /*
1518  * No requirements.
1519  */
1520 static int
1521 sysctl_kern_proc(SYSCTL_HANDLER_ARGS)
1522 {
1523         int *name = (int *)arg1;
1524         int oid = oidp->oid_number;
1525         u_int namelen = arg2;
1526         struct proc *p;
1527         struct thread *td;
1528         struct thread *marker;
1529         int flags = 0;
1530         int error = 0;
1531         int n;
1532         int origcpu;
1533         struct ucred *cr1 = curproc->p_ucred;
1534         struct ucred *crcache = NULL;
1535
1536         flags = oid & KERN_PROC_FLAGMASK;
1537         oid &= ~KERN_PROC_FLAGMASK;
1538
1539         if ((oid == KERN_PROC_ALL && namelen != 0) ||
1540             (oid != KERN_PROC_ALL && namelen != 1)) {
1541                 return (EINVAL);
1542         }
1543
1544         /*
1545          * proc_token protects the allproc list and PHOLD() prevents the
1546          * process from being removed from the allproc list or the zombproc
1547          * list.
1548          */
1549         if (oid == KERN_PROC_PID) {
1550                 p = pfind((pid_t)name[0]);
1551                 if (p) {
1552                         crcache = pcredcache(crcache, p);
1553                         if (PRISON_CHECK(cr1, crcache))
1554                                 error = sysctl_out_proc(p, req, flags);
1555                         PRELE(p);
1556                 }
1557                 goto post_threads;
1558         }
1559         p = NULL;
1560
1561         if (!req->oldptr) {
1562                 /* overestimate by 5 procs */
1563                 error = SYSCTL_OUT(req, 0, sizeof (struct kinfo_proc) * 5);
1564                 if (error)
1565                         goto post_threads;
1566         }
1567
1568         for (n = 0; n < ALLPROC_HSIZE; ++n) {
1569                 procglob_t *prg = &procglob[n];
1570
1571                 if (LIST_EMPTY(&prg->allproc))
1572                         continue;
1573                 lwkt_gettoken_shared(&prg->proc_token);
1574                 LIST_FOREACH(p, &prg->allproc, p_list) {
1575                         /*
1576                          * Show a user only their processes.
1577                          */
1578                         if (ps_showallprocs == 0) {
1579                                 crcache = pcredcache(crcache, p);
1580                                 if (crcache == NULL ||
1581                                     p_trespass(cr1, crcache)) {
1582                                         continue;
1583                                 }
1584                         }
1585
1586                         /*
1587                          * Skip embryonic processes.
1588                          */
1589                         if (p->p_stat == SIDL)
1590                                 continue;
1591                         /*
1592                          * TODO - make more efficient (see notes below).
1593                          * do by session.
1594                          */
1595                         switch (oid) {
1596                         case KERN_PROC_PGRP:
1597                                 /* could do this by traversing pgrp */
1598                                 if (p->p_pgrp == NULL || 
1599                                     p->p_pgrp->pg_id != (pid_t)name[0])
1600                                         continue;
1601                                 break;
1602
1603                         case KERN_PROC_TTY:
1604                                 if ((p->p_flags & P_CONTROLT) == 0 ||
1605                                     p->p_session == NULL ||
1606                                     p->p_session->s_ttyp == NULL ||
1607                                     dev2udev(p->p_session->s_ttyp->t_dev) != 
1608                                         (udev_t)name[0])
1609                                         continue;
1610                                 break;
1611
1612                         case KERN_PROC_UID:
1613                                 crcache = pcredcache(crcache, p);
1614                                 if (crcache == NULL ||
1615                                     crcache->cr_uid != (uid_t)name[0]) {
1616                                         continue;
1617                                 }
1618                                 break;
1619
1620                         case KERN_PROC_RUID:
1621                                 crcache = pcredcache(crcache, p);
1622                                 if (crcache == NULL ||
1623                                     crcache->cr_ruid != (uid_t)name[0]) {
1624                                         continue;
1625                                 }
1626                                 break;
1627                         }
1628
1629                         crcache = pcredcache(crcache, p);
1630                         if (!PRISON_CHECK(cr1, crcache))
1631                                 continue;
1632                         PHOLD(p);
1633                         error = sysctl_out_proc(p, req, flags);
1634                         PRELE(p);
1635                         if (error) {
1636                                 lwkt_reltoken(&prg->proc_token);
1637                                 goto post_threads;
1638                         }
1639                 }
1640                 lwkt_reltoken(&prg->proc_token);
1641         }
1642
1643         /*
1644          * Iterate over all active cpus and scan their thread list.  Start
1645          * with the next logical cpu and end with our original cpu.  We
1646          * migrate our own thread to each target cpu in order to safely scan
1647          * its thread list.  In the last loop we migrate back to our original
1648          * cpu.
1649          */
1650         origcpu = mycpu->gd_cpuid;
1651         if (!ps_showallthreads || jailed(cr1))
1652                 goto post_threads;
1653
1654         marker = kmalloc(sizeof(struct thread), M_TEMP, M_WAITOK|M_ZERO);
1655         marker->td_flags = TDF_MARKER;
1656         error = 0;
1657
1658         for (n = 1; n <= ncpus; ++n) {
1659                 globaldata_t rgd;
1660                 int nid;
1661
1662                 nid = (origcpu + n) % ncpus;
1663                 if (CPUMASK_TESTBIT(smp_active_mask, nid) == 0)
1664                         continue;
1665                 rgd = globaldata_find(nid);
1666                 lwkt_setcpu_self(rgd);
1667
1668                 crit_enter();
1669                 TAILQ_INSERT_TAIL(&rgd->gd_tdallq, marker, td_allq);
1670
1671                 while ((td = TAILQ_PREV(marker, lwkt_queue, td_allq)) != NULL) {
1672                         TAILQ_REMOVE(&rgd->gd_tdallq, marker, td_allq);
1673                         TAILQ_INSERT_BEFORE(td, marker, td_allq);
1674                         if (td->td_flags & TDF_MARKER)
1675                                 continue;
1676                         if (td->td_proc)
1677                                 continue;
1678
1679                         lwkt_hold(td);
1680                         crit_exit();
1681
1682                         switch (oid) {
1683                         case KERN_PROC_PGRP:
1684                         case KERN_PROC_TTY:
1685                         case KERN_PROC_UID:
1686                         case KERN_PROC_RUID:
1687                                 break;
1688                         default:
1689                                 error = sysctl_out_proc_kthread(td, req);
1690                                 break;
1691                         }
1692                         lwkt_rele(td);
1693                         crit_enter();
1694                         if (error)
1695                                 break;
1696                 }
1697                 TAILQ_REMOVE(&rgd->gd_tdallq, marker, td_allq);
1698                 crit_exit();
1699
1700                 if (error)
1701                         break;
1702         }
1703
1704         /*
1705          * Userland scheduler expects us to return on the same cpu we
1706          * started on.
1707          */
1708         if (mycpu->gd_cpuid != origcpu)
1709                 lwkt_setcpu_self(globaldata_find(origcpu));
1710
1711         kfree(marker, M_TEMP);
1712
1713 post_threads:
1714         if (crcache)
1715                 crfree(crcache);
1716         return (error);
1717 }
1718
1719 /*
1720  * This sysctl allows a process to retrieve the argument list or process
1721  * title for another process without groping around in the address space
1722  * of the other process.  It also allow a process to set its own "process 
1723  * title to a string of its own choice.
1724  *
1725  * No requirements.
1726  */
1727 static int
1728 sysctl_kern_proc_args(SYSCTL_HANDLER_ARGS)
1729 {
1730         int *name = (int*) arg1;
1731         u_int namelen = arg2;
1732         struct proc *p;
1733         struct pargs *opa;
1734         struct pargs *pa;
1735         int error = 0;
1736         struct ucred *cr1 = curproc->p_ucred;
1737
1738         if (namelen != 1) 
1739                 return (EINVAL);
1740
1741         p = pfind((pid_t)name[0]);
1742         if (p == NULL)
1743                 goto done;
1744         lwkt_gettoken(&p->p_token);
1745
1746         if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
1747                 goto done;
1748
1749         if (req->newptr && curproc != p) {
1750                 error = EPERM;
1751                 goto done;
1752         }
1753         if (req->oldptr) {
1754                 if (p->p_upmap != NULL && p->p_upmap->proc_title[0]) {
1755                         /*
1756                          * Args set via writable user process mmap.
1757                          * We must calculate the string length manually
1758                          * because the user data can change at any time.
1759                          */
1760                         size_t n;
1761                         char *base;
1762
1763                         base = p->p_upmap->proc_title;
1764                         for (n = 0; n < UPMAP_MAXPROCTITLE - 1; ++n) {
1765                                 if (base[n] == 0)
1766                                         break;
1767                         }
1768                         error = SYSCTL_OUT(req, base, n);
1769                         if (error == 0)
1770                                 error = SYSCTL_OUT(req, "", 1);
1771                 } else if ((pa = p->p_args) != NULL) {
1772                         /*
1773                          * Args set by setproctitle() sysctl.
1774                          */
1775                         refcount_acquire(&pa->ar_ref);
1776                         error = SYSCTL_OUT(req, pa->ar_args, pa->ar_length);
1777                         if (refcount_release(&pa->ar_ref))
1778                                 kfree(pa, M_PARGS);
1779                 }
1780         }
1781         if (req->newptr == NULL)
1782                 goto done;
1783
1784         if (req->newlen + sizeof(struct pargs) > ps_arg_cache_limit) {
1785                 goto done;
1786         }
1787
1788         pa = kmalloc(sizeof(struct pargs) + req->newlen, M_PARGS, M_WAITOK);
1789         refcount_init(&pa->ar_ref, 1);
1790         pa->ar_length = req->newlen;
1791         error = SYSCTL_IN(req, pa->ar_args, req->newlen);
1792         if (error) {
1793                 kfree(pa, M_PARGS);
1794                 goto done;
1795         }
1796
1797
1798         /*
1799          * Replace p_args with the new pa.  p_args may have previously
1800          * been NULL.
1801          */
1802         opa = p->p_args;
1803         p->p_args = pa;
1804
1805         if (opa) {
1806                 KKASSERT(opa->ar_ref > 0);
1807                 if (refcount_release(&opa->ar_ref)) {
1808                         kfree(opa, M_PARGS);
1809                         /* opa = NULL; */
1810                 }
1811         }
1812 done:
1813         if (p) {
1814                 lwkt_reltoken(&p->p_token);
1815                 PRELE(p);
1816         }
1817         return (error);
1818 }
1819
1820 static int
1821 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
1822 {
1823         int *name = (int*) arg1;
1824         u_int namelen = arg2;
1825         struct proc *p;
1826         int error = 0;
1827         char *fullpath, *freepath;
1828         struct ucred *cr1 = curproc->p_ucred;
1829
1830         if (namelen != 1) 
1831                 return (EINVAL);
1832
1833         p = pfind((pid_t)name[0]);
1834         if (p == NULL)
1835                 goto done;
1836         lwkt_gettoken_shared(&p->p_token);
1837
1838         /*
1839          * If we are not allowed to see other args, we certainly shouldn't
1840          * get the cwd either. Also check the usual trespassing.
1841          */
1842         if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
1843                 goto done;
1844
1845         if (req->oldptr && p->p_fd != NULL && p->p_fd->fd_ncdir.ncp) {
1846                 struct nchandle nch;
1847
1848                 cache_copy(&p->p_fd->fd_ncdir, &nch);
1849                 error = cache_fullpath(p, &nch, NULL,
1850                                        &fullpath, &freepath, 0);
1851                 cache_drop(&nch);
1852                 if (error)
1853                         goto done;
1854                 error = SYSCTL_OUT(req, fullpath, strlen(fullpath) + 1);
1855                 kfree(freepath, M_TEMP);
1856         }
1857
1858 done:
1859         if (p) {
1860                 lwkt_reltoken(&p->p_token);
1861                 PRELE(p);
1862         }
1863         return (error);
1864 }
1865
1866 /*
1867  * This sysctl allows a process to retrieve the path of the executable for
1868  * itself or another process.
1869  */
1870 static int
1871 sysctl_kern_proc_pathname(SYSCTL_HANDLER_ARGS)
1872 {
1873         pid_t *pidp = (pid_t *)arg1;
1874         unsigned int arglen = arg2;
1875         struct proc *p;
1876         char *retbuf, *freebuf;
1877         int error = 0;
1878         struct nchandle nch;
1879
1880         if (arglen != 1)
1881                 return (EINVAL);
1882         if (*pidp == -1) {      /* -1 means this process */
1883                 p = curproc;
1884         } else {
1885                 p = pfind(*pidp);
1886                 if (p == NULL)
1887                         return (ESRCH);
1888         }
1889
1890         cache_copy(&p->p_textnch, &nch);
1891         error = cache_fullpath(p, &nch, NULL, &retbuf, &freebuf, 0);
1892         cache_drop(&nch);
1893         if (error)
1894                 goto done;
1895         error = SYSCTL_OUT(req, retbuf, strlen(retbuf) + 1);
1896         kfree(freebuf, M_TEMP);
1897 done:
1898         if (*pidp != -1)
1899                 PRELE(p);
1900
1901         return (error);
1902 }
1903
1904 static int
1905 sysctl_kern_proc_sigtramp(SYSCTL_HANDLER_ARGS)
1906 {
1907         /*int *name = (int *)arg1;*/
1908         u_int namelen = arg2;
1909         struct kinfo_sigtramp kst;
1910         const struct sysentvec *sv;
1911         int error;
1912
1913         if (namelen > 1)
1914                 return (EINVAL);
1915         /* ignore pid if passed in (freebsd compatibility) */
1916
1917         sv = curproc->p_sysent;
1918         bzero(&kst, sizeof(kst));
1919         if (sv->sv_szsigcode) {
1920                 intptr_t sigbase;
1921
1922                 sigbase = trunc_page64((intptr_t)PS_STRINGS -
1923                                        *sv->sv_szsigcode);
1924                 sigbase -= SZSIGCODE_EXTRA_BYTES;
1925
1926                 kst.ksigtramp_start = (void *)sigbase;
1927                 kst.ksigtramp_end = (void *)(sigbase + *sv->sv_szsigcode);
1928         }
1929         error = SYSCTL_OUT(req, &kst, sizeof(kst));
1930
1931         return (error);
1932 }
1933
1934 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD,  0, "Process table");
1935
1936 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all,
1937         CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_NOLOCK,
1938         0, 0, sysctl_kern_proc, "S,proc", "Return entire process table");
1939
1940 SYSCTL_NODE(_kern_proc, KERN_PROC_PGRP, pgrp,
1941         CTLFLAG_RD | CTLFLAG_NOLOCK,
1942         sysctl_kern_proc, "Process table");
1943
1944 SYSCTL_NODE(_kern_proc, KERN_PROC_TTY, tty,
1945         CTLFLAG_RD | CTLFLAG_NOLOCK,
1946         sysctl_kern_proc, "Process table");
1947
1948 SYSCTL_NODE(_kern_proc, KERN_PROC_UID, uid,
1949         CTLFLAG_RD | CTLFLAG_NOLOCK,
1950         sysctl_kern_proc, "Process table");
1951
1952 SYSCTL_NODE(_kern_proc, KERN_PROC_RUID, ruid,
1953         CTLFLAG_RD | CTLFLAG_NOLOCK,
1954         sysctl_kern_proc, "Process table");
1955
1956 SYSCTL_NODE(_kern_proc, KERN_PROC_PID, pid,
1957         CTLFLAG_RD | CTLFLAG_NOLOCK,
1958         sysctl_kern_proc, "Process table");
1959
1960 SYSCTL_NODE(_kern_proc, (KERN_PROC_ALL | KERN_PROC_FLAG_LWP), all_lwp,
1961         CTLFLAG_RD | CTLFLAG_NOLOCK,
1962         sysctl_kern_proc, "Process table");
1963
1964 SYSCTL_NODE(_kern_proc, (KERN_PROC_PGRP | KERN_PROC_FLAG_LWP), pgrp_lwp,
1965         CTLFLAG_RD | CTLFLAG_NOLOCK,
1966         sysctl_kern_proc, "Process table");
1967
1968 SYSCTL_NODE(_kern_proc, (KERN_PROC_TTY | KERN_PROC_FLAG_LWP), tty_lwp,
1969         CTLFLAG_RD | CTLFLAG_NOLOCK,
1970         sysctl_kern_proc, "Process table");
1971
1972 SYSCTL_NODE(_kern_proc, (KERN_PROC_UID | KERN_PROC_FLAG_LWP), uid_lwp,
1973         CTLFLAG_RD | CTLFLAG_NOLOCK,
1974         sysctl_kern_proc, "Process table");
1975
1976 SYSCTL_NODE(_kern_proc, (KERN_PROC_RUID | KERN_PROC_FLAG_LWP), ruid_lwp,
1977         CTLFLAG_RD | CTLFLAG_NOLOCK,
1978         sysctl_kern_proc, "Process table");
1979
1980 SYSCTL_NODE(_kern_proc, (KERN_PROC_PID | KERN_PROC_FLAG_LWP), pid_lwp,
1981         CTLFLAG_RD | CTLFLAG_NOLOCK,
1982         sysctl_kern_proc, "Process table");
1983
1984 SYSCTL_NODE(_kern_proc, KERN_PROC_ARGS, args,
1985         CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NOLOCK,
1986         sysctl_kern_proc_args, "Process argument list");
1987
1988 SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd,
1989         CTLFLAG_RD | CTLFLAG_ANYBODY | CTLFLAG_NOLOCK,
1990         sysctl_kern_proc_cwd, "Process argument list");
1991
1992 static SYSCTL_NODE(_kern_proc, KERN_PROC_PATHNAME, pathname,
1993         CTLFLAG_RD | CTLFLAG_NOLOCK,
1994         sysctl_kern_proc_pathname, "Process executable path");
1995
1996 SYSCTL_PROC(_kern_proc, KERN_PROC_SIGTRAMP, sigtramp,
1997         CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_NOLOCK,
1998         0, 0, sysctl_kern_proc_sigtramp, "S,sigtramp",
1999         "Return sigtramp address range");