kernel - MPSAFE work - tokenize more vm stuff
[dragonfly.git] / sys / kern / kern_proc.c
1 /*
2  * (MPSAFE)
3  *
4  * Copyright (c) 1982, 1986, 1989, 1991, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *      This product includes software developed by the University of
18  *      California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  *      @(#)kern_proc.c 8.7 (Berkeley) 2/14/95
36  * $FreeBSD: src/sys/kern/kern_proc.c,v 1.63.2.9 2003/05/08 07:47:16 kbyanc Exp $
37  * $DragonFly: src/sys/kern/kern_proc.c,v 1.45 2008/06/12 23:25:02 dillon Exp $
38  */
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/sysctl.h>
44 #include <sys/malloc.h>
45 #include <sys/proc.h>
46 #include <sys/jail.h>
47 #include <sys/filedesc.h>
48 #include <sys/tty.h>
49 #include <sys/dsched.h>
50 #include <sys/signalvar.h>
51 #include <sys/spinlock.h>
52 #include <vm/vm.h>
53 #include <sys/lock.h>
54 #include <vm/pmap.h>
55 #include <vm/vm_map.h>
56 #include <sys/user.h>
57 #include <machine/smp.h>
58
59 #include <sys/spinlock2.h>
60 #include <sys/mplock2.h>
61
62 static MALLOC_DEFINE(M_PGRP, "pgrp", "process group header");
63 MALLOC_DEFINE(M_SESSION, "session", "session header");
64 MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
65 MALLOC_DEFINE(M_LWP, "lwp", "lwp structures");
66 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
67
68 int ps_showallprocs = 1;
69 static int ps_showallthreads = 1;
70 SYSCTL_INT(_security, OID_AUTO, ps_showallprocs, CTLFLAG_RW,
71     &ps_showallprocs, 0,
72     "Unprivileged processes can see proccesses with different UID/GID");
73 SYSCTL_INT(_security, OID_AUTO, ps_showallthreads, CTLFLAG_RW,
74     &ps_showallthreads, 0,
75     "Unprivileged processes can see kernel threads");
76
77 static void pgdelete(struct pgrp *);
78 static void orphanpg(struct pgrp *pg);
79 static pid_t proc_getnewpid_locked(int random_offset);
80
81 /*
82  * Other process lists
83  */
84 struct pidhashhead *pidhashtbl;
85 u_long pidhash;
86 struct pgrphashhead *pgrphashtbl;
87 u_long pgrphash;
88 struct proclist allproc;
89 struct proclist zombproc;
90
91 /*
92  * Random component to nextpid generation.  We mix in a random factor to make
93  * it a little harder to predict.  We sanity check the modulus value to avoid
94  * doing it in critical paths.  Don't let it be too small or we pointlessly
95  * waste randomness entropy, and don't let it be impossibly large.  Using a
96  * modulus that is too big causes a LOT more process table scans and slows
97  * down fork processing as the pidchecked caching is defeated.
98  */
99 static int randompid = 0;
100
101 /*
102  * No requirements.
103  */
104 static int
105 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
106 {
107         int error, pid;
108
109         pid = randompid;
110         error = sysctl_handle_int(oidp, &pid, 0, req);
111         if (error || !req->newptr)
112                 return (error);
113         if (pid < 0 || pid > PID_MAX - 100)     /* out of range */
114                 pid = PID_MAX - 100;
115         else if (pid < 2)                       /* NOP */
116                 pid = 0;
117         else if (pid < 100)                     /* Make it reasonable */
118                 pid = 100;
119         randompid = pid;
120         return (error);
121 }
122
123 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
124             0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
125
126 /*
127  * Initialize global process hashing structures.
128  *
129  * Called from the low level boot code only.
130  */
131 void
132 procinit(void)
133 {
134         LIST_INIT(&allproc);
135         LIST_INIT(&zombproc);
136         lwkt_init();
137         pidhashtbl = hashinit(maxproc / 4, M_PROC, &pidhash);
138         pgrphashtbl = hashinit(maxproc / 4, M_PROC, &pgrphash);
139         uihashinit();
140 }
141
142 /*
143  * Is p an inferior of the current process?
144  *
145  * No requirements.
146  * The caller must hold proc_token if the caller wishes a stable result.
147  */
148 int
149 inferior(struct proc *p)
150 {
151         lwkt_gettoken(&proc_token);
152         while (p != curproc) {
153                 if (p->p_pid == 0) {
154                         lwkt_reltoken(&proc_token);
155                         return (0);
156                 }
157                 p = p->p_pptr;
158         }
159         lwkt_reltoken(&proc_token);
160         return (1);
161 }
162
163 /*
164  * Locate a process by number
165  *
166  * XXX TODO - change API to PHOLD() the returned process ?
167  *
168  * No requirements.
169  * The caller must hold proc_token if the caller wishes a stable result.
170  */
171 struct proc *
172 pfind(pid_t pid)
173 {
174         struct proc *p;
175
176         lwkt_gettoken(&proc_token);
177         LIST_FOREACH(p, PIDHASH(pid), p_hash) {
178                 if (p->p_pid == pid) {
179                         lwkt_reltoken(&proc_token);
180                         return (p);
181                 }
182         }
183         lwkt_reltoken(&proc_token);
184         return (NULL);
185 }
186
187 /*
188  * Locate a process group by number
189  *
190  * No requirements.
191  * The caller must hold proc_token if the caller wishes a stable result.
192  */
193 struct pgrp *
194 pgfind(pid_t pgid)
195 {
196         struct pgrp *pgrp;
197
198         lwkt_gettoken(&proc_token);
199         LIST_FOREACH(pgrp, PGRPHASH(pgid), pg_hash) {
200                 if (pgrp->pg_id == pgid)
201                         return (pgrp);
202         }
203         lwkt_reltoken(&proc_token);
204         return (NULL);
205 }
206
207 /*
208  * Move p to a new or existing process group (and session)
209  *
210  * No requirements.
211  */
212 int
213 enterpgrp(struct proc *p, pid_t pgid, int mksess)
214 {
215         struct pgrp *pgrp;
216         int error;
217
218         lwkt_gettoken(&proc_token);
219         pgrp = pgfind(pgid);
220
221         KASSERT(pgrp == NULL || !mksess,
222                 ("enterpgrp: setsid into non-empty pgrp"));
223         KASSERT(!SESS_LEADER(p),
224                 ("enterpgrp: session leader attempted setpgrp"));
225
226         if (pgrp == NULL) {
227                 pid_t savepid = p->p_pid;
228                 struct proc *np;
229                 /*
230                  * new process group
231                  */
232                 KASSERT(p->p_pid == pgid,
233                         ("enterpgrp: new pgrp and pid != pgid"));
234                 if ((np = pfind(savepid)) == NULL || np != p) {
235                         error = ESRCH;
236                         goto fatal;
237                 }
238                 MALLOC(pgrp, struct pgrp *, sizeof(struct pgrp),
239                        M_PGRP, M_WAITOK);
240                 if (mksess) {
241                         struct session *sess;
242
243                         /*
244                          * new session
245                          */
246                         MALLOC(sess, struct session *, sizeof(struct session),
247                                M_SESSION, M_WAITOK);
248                         sess->s_leader = p;
249                         sess->s_sid = p->p_pid;
250                         sess->s_count = 1;
251                         sess->s_ttyvp = NULL;
252                         sess->s_ttyp = NULL;
253                         bcopy(p->p_session->s_login, sess->s_login,
254                               sizeof(sess->s_login));
255                         p->p_flag &= ~P_CONTROLT;
256                         pgrp->pg_session = sess;
257                         KASSERT(p == curproc,
258                                 ("enterpgrp: mksession and p != curproc"));
259                 } else {
260                         pgrp->pg_session = p->p_session;
261                         sess_hold(pgrp->pg_session);
262                 }
263                 pgrp->pg_id = pgid;
264                 LIST_INIT(&pgrp->pg_members);
265                 LIST_INSERT_HEAD(PGRPHASH(pgid), pgrp, pg_hash);
266                 pgrp->pg_jobc = 0;
267                 SLIST_INIT(&pgrp->pg_sigiolst);
268                 lockinit(&pgrp->pg_lock, "pgwt", 0, 0);
269         } else if (pgrp == p->p_pgrp) {
270                 goto done;
271         }
272
273         /*
274          * Adjust eligibility of affected pgrps to participate in job control.
275          * Increment eligibility counts before decrementing, otherwise we
276          * could reach 0 spuriously during the first call.
277          */
278         fixjobc(p, pgrp, 1);
279         fixjobc(p, p->p_pgrp, 0);
280
281         LIST_REMOVE(p, p_pglist);
282         if (LIST_EMPTY(&p->p_pgrp->pg_members))
283                 pgdelete(p->p_pgrp);
284         p->p_pgrp = pgrp;
285         LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
286 done:
287         error = 0;
288 fatal:
289         lwkt_reltoken(&proc_token);
290         return (error);
291 }
292
293 /*
294  * Remove process from process group
295  *
296  * No requirements.
297  */
298 int
299 leavepgrp(struct proc *p)
300 {
301         lwkt_gettoken(&proc_token);
302         LIST_REMOVE(p, p_pglist);
303         if (LIST_EMPTY(&p->p_pgrp->pg_members))
304                 pgdelete(p->p_pgrp);
305         p->p_pgrp = NULL;
306         lwkt_reltoken(&proc_token);
307         return (0);
308 }
309
310 /*
311  * Delete a process group
312  *
313  * The caller must hold proc_token.
314  */
315 static void
316 pgdelete(struct pgrp *pgrp)
317 {
318         /*
319          * Reset any sigio structures pointing to us as a result of
320          * F_SETOWN with our pgid.
321          */
322         funsetownlst(&pgrp->pg_sigiolst);
323
324         if (pgrp->pg_session->s_ttyp != NULL &&
325             pgrp->pg_session->s_ttyp->t_pgrp == pgrp)
326                 pgrp->pg_session->s_ttyp->t_pgrp = NULL;
327         LIST_REMOVE(pgrp, pg_hash);
328         sess_rele(pgrp->pg_session);
329         kfree(pgrp, M_PGRP);
330 }
331
332 /*
333  * Adjust the ref count on a session structure.  When the ref count falls to
334  * zero the tty is disassociated from the session and the session structure
335  * is freed.  Note that tty assocation is not itself ref-counted.
336  *
337  * No requirements.
338  */
339 void
340 sess_hold(struct session *sp)
341 {
342         lwkt_gettoken(&tty_token);
343         ++sp->s_count;
344         lwkt_reltoken(&tty_token);
345 }
346
347 /*
348  * No requirements.
349  */
350 void
351 sess_rele(struct session *sp)
352 {
353         KKASSERT(sp->s_count > 0);
354         lwkt_gettoken(&tty_token);
355         if (--sp->s_count == 0) {
356                 if (sp->s_ttyp && sp->s_ttyp->t_session) {
357 #ifdef TTY_DO_FULL_CLOSE
358                         /* FULL CLOSE, see ttyclearsession() */
359                         KKASSERT(sp->s_ttyp->t_session == sp);
360                         sp->s_ttyp->t_session = NULL;
361 #else
362                         /* HALF CLOSE, see ttyclearsession() */
363                         if (sp->s_ttyp->t_session == sp)
364                                 sp->s_ttyp->t_session = NULL;
365 #endif
366                 }
367                 kfree(sp, M_SESSION);
368         }
369         lwkt_reltoken(&tty_token);
370 }
371
372 /*
373  * Adjust pgrp jobc counters when specified process changes process group.
374  * We count the number of processes in each process group that "qualify"
375  * the group for terminal job control (those with a parent in a different
376  * process group of the same session).  If that count reaches zero, the
377  * process group becomes orphaned.  Check both the specified process'
378  * process group and that of its children.
379  * entering == 0 => p is leaving specified group.
380  * entering == 1 => p is entering specified group.
381  *
382  * No requirements.
383  */
384 void
385 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
386 {
387         struct pgrp *hispgrp;
388         struct session *mysession;
389
390         /*
391          * Check p's parent to see whether p qualifies its own process
392          * group; if so, adjust count for p's process group.
393          */
394         lwkt_gettoken(&proc_token);
395         mysession = pgrp->pg_session;
396         if ((hispgrp = p->p_pptr->p_pgrp) != pgrp &&
397             hispgrp->pg_session == mysession) {
398                 if (entering)
399                         pgrp->pg_jobc++;
400                 else if (--pgrp->pg_jobc == 0)
401                         orphanpg(pgrp);
402         }
403
404         /*
405          * Check this process' children to see whether they qualify
406          * their process groups; if so, adjust counts for children's
407          * process groups.
408          */
409         LIST_FOREACH(p, &p->p_children, p_sibling) {
410                 if ((hispgrp = p->p_pgrp) != pgrp &&
411                     hispgrp->pg_session == mysession &&
412                     p->p_stat != SZOMB) {
413                         if (entering)
414                                 hispgrp->pg_jobc++;
415                         else if (--hispgrp->pg_jobc == 0)
416                                 orphanpg(hispgrp);
417                 }
418         }
419         lwkt_reltoken(&proc_token);
420 }
421
422 /*
423  * A process group has become orphaned;
424  * if there are any stopped processes in the group,
425  * hang-up all process in that group.
426  *
427  * The caller must hold proc_token.
428  */
429 static void
430 orphanpg(struct pgrp *pg)
431 {
432         struct proc *p;
433
434         LIST_FOREACH(p, &pg->pg_members, p_pglist) {
435                 if (p->p_stat == SSTOP) {
436                         LIST_FOREACH(p, &pg->pg_members, p_pglist) {
437                                 ksignal(p, SIGHUP);
438                                 ksignal(p, SIGCONT);
439                         }
440                         return;
441                 }
442         }
443 }
444
445 /*
446  * Add a new process to the allproc list and the PID hash.  This
447  * also assigns a pid to the new process.
448  *
449  * No requirements.
450  */
451 void
452 proc_add_allproc(struct proc *p)
453 {
454         int random_offset;
455
456         if ((random_offset = randompid) != 0) {
457                 get_mplock();
458                 random_offset = karc4random() % random_offset;
459                 rel_mplock();
460         }
461
462         lwkt_gettoken(&proc_token);
463         p->p_pid = proc_getnewpid_locked(random_offset);
464         LIST_INSERT_HEAD(&allproc, p, p_list);
465         LIST_INSERT_HEAD(PIDHASH(p->p_pid), p, p_hash);
466         lwkt_reltoken(&proc_token);
467 }
468
469 /*
470  * Calculate a new process pid.  This function is integrated into
471  * proc_add_allproc() to guarentee that the new pid is not reused before
472  * the new process can be added to the allproc list.
473  *
474  * The caller must hold proc_token.
475  */
476 static
477 pid_t
478 proc_getnewpid_locked(int random_offset)
479 {
480         static pid_t nextpid;
481         static pid_t pidchecked;
482         struct proc *p;
483
484         /*
485          * Find an unused process ID.  We remember a range of unused IDs
486          * ready to use (from nextpid+1 through pidchecked-1).
487          */
488         nextpid = nextpid + 1 + random_offset;
489 retry:
490         /*
491          * If the process ID prototype has wrapped around,
492          * restart somewhat above 0, as the low-numbered procs
493          * tend to include daemons that don't exit.
494          */
495         if (nextpid >= PID_MAX) {
496                 nextpid = nextpid % PID_MAX;
497                 if (nextpid < 100)
498                         nextpid += 100;
499                 pidchecked = 0;
500         }
501         if (nextpid >= pidchecked) {
502                 int doingzomb = 0;
503
504                 pidchecked = PID_MAX;
505                 /*
506                  * Scan the active and zombie procs to check whether this pid
507                  * is in use.  Remember the lowest pid that's greater
508                  * than nextpid, so we can avoid checking for a while.
509                  */
510                 p = LIST_FIRST(&allproc);
511 again:
512                 for (; p != 0; p = LIST_NEXT(p, p_list)) {
513                         while (p->p_pid == nextpid ||
514                             p->p_pgrp->pg_id == nextpid ||
515                             p->p_session->s_sid == nextpid) {
516                                 nextpid++;
517                                 if (nextpid >= pidchecked)
518                                         goto retry;
519                         }
520                         if (p->p_pid > nextpid && pidchecked > p->p_pid)
521                                 pidchecked = p->p_pid;
522                         if (p->p_pgrp->pg_id > nextpid &&
523                             pidchecked > p->p_pgrp->pg_id)
524                                 pidchecked = p->p_pgrp->pg_id;
525                         if (p->p_session->s_sid > nextpid &&
526                             pidchecked > p->p_session->s_sid)
527                                 pidchecked = p->p_session->s_sid;
528                 }
529                 if (!doingzomb) {
530                         doingzomb = 1;
531                         p = LIST_FIRST(&zombproc);
532                         goto again;
533                 }
534         }
535         return(nextpid);
536 }
537
538 /*
539  * Called from exit1 to remove a process from the allproc
540  * list and move it to the zombie list.
541  *
542  * No requirements.
543  */
544 void
545 proc_move_allproc_zombie(struct proc *p)
546 {
547         lwkt_gettoken(&proc_token);
548         while (p->p_lock) {
549                 tsleep(p, 0, "reap1", hz / 10);
550         }
551         LIST_REMOVE(p, p_list);
552         LIST_INSERT_HEAD(&zombproc, p, p_list);
553         LIST_REMOVE(p, p_hash);
554         p->p_stat = SZOMB;
555         lwkt_reltoken(&proc_token);
556         dsched_exit_proc(p);
557 }
558
559 /*
560  * This routine is called from kern_wait() and will remove the process
561  * from the zombie list and the sibling list.  This routine will block
562  * if someone has a lock on the proces (p_lock).
563  *
564  * No requirements.
565  */
566 void
567 proc_remove_zombie(struct proc *p)
568 {
569         lwkt_gettoken(&proc_token);
570         while (p->p_lock) {
571                 tsleep(p, 0, "reap1", hz / 10);
572         }
573         LIST_REMOVE(p, p_list); /* off zombproc */
574         LIST_REMOVE(p, p_sibling);
575         lwkt_reltoken(&proc_token);
576 }
577
578 /*
579  * Scan all processes on the allproc list.  The process is automatically
580  * held for the callback.  A return value of -1 terminates the loop.
581  *
582  * No requirements.
583  * The callback is made with the process held and proc_token held.
584  */
585 void
586 allproc_scan(int (*callback)(struct proc *, void *), void *data)
587 {
588         struct proc *p;
589         int r;
590
591         lwkt_gettoken(&proc_token);
592         LIST_FOREACH(p, &allproc, p_list) {
593                 PHOLD(p);
594                 r = callback(p, data);
595                 PRELE(p);
596                 if (r < 0)
597                         break;
598         }
599         lwkt_reltoken(&proc_token);
600 }
601
602 /*
603  * Scan all lwps of processes on the allproc list.  The lwp is automatically
604  * held for the callback.  A return value of -1 terminates the loop.
605  *
606  * No requirements.
607  * The callback is made with the proces and lwp both held, and proc_token held.
608  */
609 void
610 alllwp_scan(int (*callback)(struct lwp *, void *), void *data)
611 {
612         struct proc *p;
613         struct lwp *lp;
614         int r = 0;
615
616         lwkt_gettoken(&proc_token);
617         LIST_FOREACH(p, &allproc, p_list) {
618                 PHOLD(p);
619                 FOREACH_LWP_IN_PROC(lp, p) {
620                         LWPHOLD(lp);
621                         r = callback(lp, data);
622                         LWPRELE(lp);
623                 }
624                 PRELE(p);
625                 if (r < 0)
626                         break;
627         }
628         lwkt_reltoken(&proc_token);
629 }
630
631 /*
632  * Scan all processes on the zombproc list.  The process is automatically
633  * held for the callback.  A return value of -1 terminates the loop.
634  *
635  * No requirements.
636  * The callback is made with the proces held and proc_token held.
637  */
638 void
639 zombproc_scan(int (*callback)(struct proc *, void *), void *data)
640 {
641         struct proc *p;
642         int r;
643
644         lwkt_gettoken(&proc_token);
645         LIST_FOREACH(p, &zombproc, p_list) {
646                 PHOLD(p);
647                 r = callback(p, data);
648                 PRELE(p);
649                 if (r < 0)
650                         break;
651         }
652         lwkt_reltoken(&proc_token);
653 }
654
655 #include "opt_ddb.h"
656 #ifdef DDB
657 #include <ddb/ddb.h>
658
659 /*
660  * Debugging only
661  */
662 DB_SHOW_COMMAND(pgrpdump, pgrpdump)
663 {
664         struct pgrp *pgrp;
665         struct proc *p;
666         int i;
667
668         for (i = 0; i <= pgrphash; i++) {
669                 if (!LIST_EMPTY(&pgrphashtbl[i])) {
670                         kprintf("\tindx %d\n", i);
671                         LIST_FOREACH(pgrp, &pgrphashtbl[i], pg_hash) {
672                                 kprintf(
673                         "\tpgrp %p, pgid %ld, sess %p, sesscnt %d, mem %p\n",
674                                     (void *)pgrp, (long)pgrp->pg_id,
675                                     (void *)pgrp->pg_session,
676                                     pgrp->pg_session->s_count,
677                                     (void *)LIST_FIRST(&pgrp->pg_members));
678                                 LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
679                                         kprintf("\t\tpid %ld addr %p pgrp %p\n", 
680                                             (long)p->p_pid, (void *)p,
681                                             (void *)p->p_pgrp);
682                                 }
683                         }
684                 }
685         }
686 }
687 #endif /* DDB */
688
689 /*
690  * Locate a process on the zombie list.  Return a held process or NULL.
691  *
692  * The caller must hold proc_token if a stable result is desired.
693  * No other requirements.
694  */
695 struct proc *
696 zpfind(pid_t pid)
697 {
698         struct proc *p;
699
700         lwkt_gettoken(&proc_token);
701         LIST_FOREACH(p, &zombproc, p_list) {
702                 if (p->p_pid == pid)
703                         return (p);
704         }
705         lwkt_reltoken(&proc_token);
706         return (NULL);
707 }
708
709 /*
710  * The caller must hold proc_token.
711  */
712 static int
713 sysctl_out_proc(struct proc *p, struct sysctl_req *req, int flags)
714 {
715         struct kinfo_proc ki;
716         struct lwp *lp;
717         int skp = 0, had_output = 0;
718         int error;
719
720         bzero(&ki, sizeof(ki));
721         fill_kinfo_proc(p, &ki);
722         if ((flags & KERN_PROC_FLAG_LWP) == 0)
723                 skp = 1;
724         error = 0;
725         FOREACH_LWP_IN_PROC(lp, p) {
726                 LWPHOLD(lp);
727                 fill_kinfo_lwp(lp, &ki.kp_lwp);
728                 had_output = 1;
729                 error = SYSCTL_OUT(req, &ki, sizeof(ki));
730                 LWPRELE(lp);
731                 if (error)
732                         break;
733                 if (skp)
734                         break;
735         }
736         /* We need to output at least the proc, even if there is no lwp. */
737         if (had_output == 0) {
738                 error = SYSCTL_OUT(req, &ki, sizeof(ki));
739         }
740         return (error);
741 }
742
743 /*
744  * The caller must hold proc_token.
745  */
746 static int
747 sysctl_out_proc_kthread(struct thread *td, struct sysctl_req *req, int flags)
748 {
749         struct kinfo_proc ki;
750         int error;
751
752         fill_kinfo_proc_kthread(td, &ki);
753         error = SYSCTL_OUT(req, &ki, sizeof(ki));
754         if (error)
755                 return error;
756         return(0);
757 }
758
759 /*
760  * No requirements.
761  */
762 static int
763 sysctl_kern_proc(SYSCTL_HANDLER_ARGS)
764 {
765         int *name = (int*) arg1;
766         int oid = oidp->oid_number;
767         u_int namelen = arg2;
768         struct proc *p;
769         struct proclist *plist;
770         struct thread *td;
771         int doingzomb, flags = 0;
772         int error = 0;
773         int n;
774         int origcpu;
775         struct ucred *cr1 = curproc->p_ucred;
776
777         flags = oid & KERN_PROC_FLAGMASK;
778         oid &= ~KERN_PROC_FLAGMASK;
779
780         if ((oid == KERN_PROC_ALL && namelen != 0) ||
781             (oid != KERN_PROC_ALL && namelen != 1))
782                 return (EINVAL);
783
784         lwkt_gettoken(&proc_token);
785         if (oid == KERN_PROC_PID) {
786                 p = pfind((pid_t)name[0]);
787                 if (p == NULL)
788                         goto post_threads;
789                 if (!PRISON_CHECK(cr1, p->p_ucred))
790                         goto post_threads;
791                 PHOLD(p);
792                 error = sysctl_out_proc(p, req, flags);
793                 PRELE(p);
794                 goto post_threads;
795         }
796
797         if (!req->oldptr) {
798                 /* overestimate by 5 procs */
799                 error = SYSCTL_OUT(req, 0, sizeof (struct kinfo_proc) * 5);
800                 if (error)
801                         goto post_threads;
802         }
803         for (doingzomb = 0; doingzomb <= 1; doingzomb++) {
804                 if (doingzomb)
805                         plist = &zombproc;
806                 else
807                         plist = &allproc;
808                 LIST_FOREACH(p, plist, p_list) {
809                         /*
810                          * Show a user only their processes.
811                          */
812                         if ((!ps_showallprocs) && p_trespass(cr1, p->p_ucred))
813                                 continue;
814                         /*
815                          * Skip embryonic processes.
816                          */
817                         if (p->p_stat == SIDL)
818                                 continue;
819                         /*
820                          * TODO - make more efficient (see notes below).
821                          * do by session.
822                          */
823                         switch (oid) {
824                         case KERN_PROC_PGRP:
825                                 /* could do this by traversing pgrp */
826                                 if (p->p_pgrp == NULL || 
827                                     p->p_pgrp->pg_id != (pid_t)name[0])
828                                         continue;
829                                 break;
830
831                         case KERN_PROC_TTY:
832                                 if ((p->p_flag & P_CONTROLT) == 0 ||
833                                     p->p_session == NULL ||
834                                     p->p_session->s_ttyp == NULL ||
835                                     dev2udev(p->p_session->s_ttyp->t_dev) != 
836                                         (udev_t)name[0])
837                                         continue;
838                                 break;
839
840                         case KERN_PROC_UID:
841                                 if (p->p_ucred == NULL || 
842                                     p->p_ucred->cr_uid != (uid_t)name[0])
843                                         continue;
844                                 break;
845
846                         case KERN_PROC_RUID:
847                                 if (p->p_ucred == NULL || 
848                                     p->p_ucred->cr_ruid != (uid_t)name[0])
849                                         continue;
850                                 break;
851                         }
852
853                         if (!PRISON_CHECK(cr1, p->p_ucred))
854                                 continue;
855                         PHOLD(p);
856                         error = sysctl_out_proc(p, req, flags);
857                         PRELE(p);
858                         if (error)
859                                 goto post_threads;
860                 }
861         }
862
863         /*
864          * Iterate over all active cpus and scan their thread list.  Start
865          * with the next logical cpu and end with our original cpu.  We
866          * migrate our own thread to each target cpu in order to safely scan
867          * its thread list.  In the last loop we migrate back to our original
868          * cpu.
869          */
870         origcpu = mycpu->gd_cpuid;
871         if (!ps_showallthreads || jailed(cr1))
872                 goto post_threads;
873
874         for (n = 1; n <= ncpus; ++n) {
875                 globaldata_t rgd;
876                 int nid;
877
878                 nid = (origcpu + n) % ncpus;
879                 if ((smp_active_mask & (1 << nid)) == 0)
880                         continue;
881                 rgd = globaldata_find(nid);
882                 lwkt_setcpu_self(rgd);
883
884                 TAILQ_FOREACH(td, &mycpu->gd_tdallq, td_allq) {
885                         if (td->td_proc)
886                                 continue;
887                         switch (oid) {
888                         case KERN_PROC_PGRP:
889                         case KERN_PROC_TTY:
890                         case KERN_PROC_UID:
891                         case KERN_PROC_RUID:
892                                 continue;
893                         default:
894                                 break;
895                         }
896                         lwkt_hold(td);
897                         error = sysctl_out_proc_kthread(td, req, doingzomb);
898                         lwkt_rele(td);
899                         if (error)
900                                 goto post_threads;
901                 }
902         }
903 post_threads:
904         lwkt_reltoken(&proc_token);
905         return (error);
906 }
907
908 /*
909  * This sysctl allows a process to retrieve the argument list or process
910  * title for another process without groping around in the address space
911  * of the other process.  It also allow a process to set its own "process 
912  * title to a string of its own choice.
913  *
914  * No requirements.
915  */
916 static int
917 sysctl_kern_proc_args(SYSCTL_HANDLER_ARGS)
918 {
919         int *name = (int*) arg1;
920         u_int namelen = arg2;
921         struct proc *p;
922         struct pargs *pa;
923         int error = 0;
924         struct ucred *cr1 = curproc->p_ucred;
925
926         if (namelen != 1) 
927                 return (EINVAL);
928
929         lwkt_gettoken(&proc_token);
930         p = pfind((pid_t)name[0]);
931         if (p == NULL)
932                 goto done;
933
934         if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
935                 goto done;
936
937         if (req->newptr && curproc != p) {
938                 error = EPERM;
939                 goto done;
940         }
941
942         PHOLD(p);
943         if (req->oldptr && p->p_args != NULL) {
944                 error = SYSCTL_OUT(req, p->p_args->ar_args,
945                                    p->p_args->ar_length);
946         }
947         if (req->newptr == NULL) {
948                 PRELE(p);
949                 goto done;
950         }
951
952         if (p->p_args && --p->p_args->ar_ref == 0) 
953                 FREE(p->p_args, M_PARGS);
954         p->p_args = NULL;
955
956         if (req->newlen + sizeof(struct pargs) > ps_arg_cache_limit) {
957                 PRELE(p);
958                 goto done;
959         }
960
961         MALLOC(pa, struct pargs *, sizeof(struct pargs) + req->newlen, 
962                M_PARGS, M_WAITOK);
963         pa->ar_ref = 1;
964         pa->ar_length = req->newlen;
965         error = SYSCTL_IN(req, pa->ar_args, req->newlen);
966         if (!error)
967                 p->p_args = pa;
968         else
969                 FREE(pa, M_PARGS);
970         PRELE(p);
971 done:
972         lwkt_reltoken(&proc_token);
973         return (error);
974 }
975
976 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD,  0, "Process table");
977
978 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all, CTLFLAG_RD|CTLTYPE_STRUCT,
979         0, 0, sysctl_kern_proc, "S,proc", "Return entire process table");
980
981 SYSCTL_NODE(_kern_proc, KERN_PROC_PGRP, pgrp, CTLFLAG_RD, 
982         sysctl_kern_proc, "Process table");
983
984 SYSCTL_NODE(_kern_proc, KERN_PROC_TTY, tty, CTLFLAG_RD, 
985         sysctl_kern_proc, "Process table");
986
987 SYSCTL_NODE(_kern_proc, KERN_PROC_UID, uid, CTLFLAG_RD, 
988         sysctl_kern_proc, "Process table");
989
990 SYSCTL_NODE(_kern_proc, KERN_PROC_RUID, ruid, CTLFLAG_RD, 
991         sysctl_kern_proc, "Process table");
992
993 SYSCTL_NODE(_kern_proc, KERN_PROC_PID, pid, CTLFLAG_RD, 
994         sysctl_kern_proc, "Process table");
995
996 SYSCTL_NODE(_kern_proc, (KERN_PROC_ALL | KERN_PROC_FLAG_LWP), all_lwp, CTLFLAG_RD,
997         sysctl_kern_proc, "Process table");
998
999 SYSCTL_NODE(_kern_proc, (KERN_PROC_PGRP | KERN_PROC_FLAG_LWP), pgrp_lwp, CTLFLAG_RD, 
1000         sysctl_kern_proc, "Process table");
1001
1002 SYSCTL_NODE(_kern_proc, (KERN_PROC_TTY | KERN_PROC_FLAG_LWP), tty_lwp, CTLFLAG_RD, 
1003         sysctl_kern_proc, "Process table");
1004
1005 SYSCTL_NODE(_kern_proc, (KERN_PROC_UID | KERN_PROC_FLAG_LWP), uid_lwp, CTLFLAG_RD, 
1006         sysctl_kern_proc, "Process table");
1007
1008 SYSCTL_NODE(_kern_proc, (KERN_PROC_RUID | KERN_PROC_FLAG_LWP), ruid_lwp, CTLFLAG_RD, 
1009         sysctl_kern_proc, "Process table");
1010
1011 SYSCTL_NODE(_kern_proc, (KERN_PROC_PID | KERN_PROC_FLAG_LWP), pid_lwp, CTLFLAG_RD, 
1012         sysctl_kern_proc, "Process table");
1013
1014 SYSCTL_NODE(_kern_proc, KERN_PROC_ARGS, args, CTLFLAG_RW | CTLFLAG_ANYBODY,
1015         sysctl_kern_proc_args, "Process argument list");