]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/kern/kern_proc.c
MFC 287864:
[FreeBSD/stable/10.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  * 4. 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  *      @(#)kern_proc.c 8.7 (Berkeley) 2/14/95
30  */
31
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include "opt_compat.h"
36 #include "opt_ddb.h"
37 #include "opt_kdtrace.h"
38 #include "opt_ktrace.h"
39 #include "opt_kstack_pages.h"
40 #include "opt_stack.h"
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/elf.h>
45 #include <sys/exec.h>
46 #include <sys/kernel.h>
47 #include <sys/limits.h>
48 #include <sys/lock.h>
49 #include <sys/loginclass.h>
50 #include <sys/malloc.h>
51 #include <sys/mman.h>
52 #include <sys/mount.h>
53 #include <sys/mutex.h>
54 #include <sys/proc.h>
55 #include <sys/ptrace.h>
56 #include <sys/refcount.h>
57 #include <sys/resourcevar.h>
58 #include <sys/rwlock.h>
59 #include <sys/sbuf.h>
60 #include <sys/sysent.h>
61 #include <sys/sched.h>
62 #include <sys/smp.h>
63 #include <sys/stack.h>
64 #include <sys/stat.h>
65 #include <sys/sysctl.h>
66 #include <sys/filedesc.h>
67 #include <sys/tty.h>
68 #include <sys/signalvar.h>
69 #include <sys/sdt.h>
70 #include <sys/sx.h>
71 #include <sys/user.h>
72 #include <sys/jail.h>
73 #include <sys/vnode.h>
74 #include <sys/eventhandler.h>
75
76 #ifdef DDB
77 #include <ddb/ddb.h>
78 #endif
79
80 #include <vm/vm.h>
81 #include <vm/vm_param.h>
82 #include <vm/vm_extern.h>
83 #include <vm/pmap.h>
84 #include <vm/vm_map.h>
85 #include <vm/vm_object.h>
86 #include <vm/vm_page.h>
87 #include <vm/uma.h>
88
89 #ifdef COMPAT_FREEBSD32
90 #include <compat/freebsd32/freebsd32.h>
91 #include <compat/freebsd32/freebsd32_util.h>
92 #endif
93
94 SDT_PROVIDER_DEFINE(proc);
95 SDT_PROBE_DEFINE4(proc, kernel, ctor, entry, "struct proc *", "int",
96     "void *", "int");
97 SDT_PROBE_DEFINE4(proc, kernel, ctor, return, "struct proc *", "int",
98     "void *", "int");
99 SDT_PROBE_DEFINE4(proc, kernel, dtor, entry, "struct proc *", "int",
100     "void *", "struct thread *");
101 SDT_PROBE_DEFINE3(proc, kernel, dtor, return, "struct proc *", "int",
102     "void *");
103 SDT_PROBE_DEFINE3(proc, kernel, init, entry, "struct proc *", "int",
104     "int");
105 SDT_PROBE_DEFINE3(proc, kernel, init, return, "struct proc *", "int",
106     "int");
107
108 MALLOC_DEFINE(M_PGRP, "pgrp", "process group header");
109 MALLOC_DEFINE(M_SESSION, "session", "session header");
110 static MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
111 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
112
113 static void doenterpgrp(struct proc *, struct pgrp *);
114 static void orphanpg(struct pgrp *pg);
115 static void fill_kinfo_aggregate(struct proc *p, struct kinfo_proc *kp);
116 static void fill_kinfo_proc_only(struct proc *p, struct kinfo_proc *kp);
117 static void fill_kinfo_thread(struct thread *td, struct kinfo_proc *kp,
118     int preferthread);
119 static void pgadjustjobc(struct pgrp *pgrp, int entering);
120 static void pgdelete(struct pgrp *);
121 static int proc_ctor(void *mem, int size, void *arg, int flags);
122 static void proc_dtor(void *mem, int size, void *arg);
123 static int proc_init(void *mem, int size, int flags);
124 static void proc_fini(void *mem, int size);
125 static void pargs_free(struct pargs *pa);
126 static struct proc *zpfind_locked(pid_t pid);
127
128 /*
129  * Other process lists
130  */
131 struct pidhashhead *pidhashtbl;
132 u_long pidhash;
133 struct pgrphashhead *pgrphashtbl;
134 u_long pgrphash;
135 struct proclist allproc;
136 struct proclist zombproc;
137 struct sx allproc_lock;
138 struct sx proctree_lock;
139 struct mtx ppeers_lock;
140 uma_zone_t proc_zone;
141
142 int kstack_pages = KSTACK_PAGES;
143 SYSCTL_INT(_kern, OID_AUTO, kstack_pages, CTLFLAG_RD, &kstack_pages, 0,
144     "Kernel stack size in pages");
145 static int vmmap_skip_res_cnt = 0;
146 SYSCTL_INT(_kern, OID_AUTO, proc_vmmap_skip_resident_count, CTLFLAG_RW,
147     &vmmap_skip_res_cnt, 0,
148     "Skip calculation of the pages resident count in kern.proc.vmmap");
149
150 CTASSERT(sizeof(struct kinfo_proc) == KINFO_PROC_SIZE);
151 #ifdef COMPAT_FREEBSD32
152 CTASSERT(sizeof(struct kinfo_proc32) == KINFO_PROC32_SIZE);
153 #endif
154
155 /*
156  * Initialize global process hashing structures.
157  */
158 void
159 procinit()
160 {
161
162         sx_init(&allproc_lock, "allproc");
163         sx_init(&proctree_lock, "proctree");
164         mtx_init(&ppeers_lock, "p_peers", NULL, MTX_DEF);
165         LIST_INIT(&allproc);
166         LIST_INIT(&zombproc);
167         pidhashtbl = hashinit(maxproc / 4, M_PROC, &pidhash);
168         pgrphashtbl = hashinit(maxproc / 4, M_PROC, &pgrphash);
169         proc_zone = uma_zcreate("PROC", sched_sizeof_proc(),
170             proc_ctor, proc_dtor, proc_init, proc_fini,
171             UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
172         uihashinit();
173 }
174
175 /*
176  * Prepare a proc for use.
177  */
178 static int
179 proc_ctor(void *mem, int size, void *arg, int flags)
180 {
181         struct proc *p;
182
183         p = (struct proc *)mem;
184         SDT_PROBE(proc, kernel, ctor , entry, p, size, arg, flags, 0);
185         EVENTHANDLER_INVOKE(process_ctor, p);
186         SDT_PROBE(proc, kernel, ctor , return, p, size, arg, flags, 0);
187         return (0);
188 }
189
190 /*
191  * Reclaim a proc after use.
192  */
193 static void
194 proc_dtor(void *mem, int size, void *arg)
195 {
196         struct proc *p;
197         struct thread *td;
198
199         /* INVARIANTS checks go here */
200         p = (struct proc *)mem;
201         td = FIRST_THREAD_IN_PROC(p);
202         SDT_PROBE(proc, kernel, dtor, entry, p, size, arg, td, 0);
203         if (td != NULL) {
204 #ifdef INVARIANTS
205                 KASSERT((p->p_numthreads == 1),
206                     ("bad number of threads in exiting process"));
207                 KASSERT(STAILQ_EMPTY(&p->p_ktr), ("proc_dtor: non-empty p_ktr"));
208 #endif
209                 /* Free all OSD associated to this thread. */
210                 osd_thread_exit(td);
211         }
212         EVENTHANDLER_INVOKE(process_dtor, p);
213         if (p->p_ksi != NULL)
214                 KASSERT(! KSI_ONQ(p->p_ksi), ("SIGCHLD queue"));
215         SDT_PROBE(proc, kernel, dtor, return, p, size, arg, 0, 0);
216 }
217
218 /*
219  * Initialize type-stable parts of a proc (when newly created).
220  */
221 static int
222 proc_init(void *mem, int size, int flags)
223 {
224         struct proc *p;
225
226         p = (struct proc *)mem;
227         SDT_PROBE(proc, kernel, init, entry, p, size, flags, 0, 0);
228         p->p_sched = (struct p_sched *)&p[1];
229         bzero(&p->p_mtx, sizeof(struct mtx));
230         mtx_init(&p->p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
231         mtx_init(&p->p_slock, "process slock", NULL, MTX_SPIN | MTX_RECURSE);
232         cv_init(&p->p_pwait, "ppwait");
233         cv_init(&p->p_dbgwait, "dbgwait");
234         TAILQ_INIT(&p->p_threads);           /* all threads in proc */
235         EVENTHANDLER_INVOKE(process_init, p);
236         p->p_stats = pstats_alloc();
237         SDT_PROBE(proc, kernel, init, return, p, size, flags, 0, 0);
238         return (0);
239 }
240
241 /*
242  * UMA should ensure that this function is never called.
243  * Freeing a proc structure would violate type stability.
244  */
245 static void
246 proc_fini(void *mem, int size)
247 {
248 #ifdef notnow
249         struct proc *p;
250
251         p = (struct proc *)mem;
252         EVENTHANDLER_INVOKE(process_fini, p);
253         pstats_free(p->p_stats);
254         thread_free(FIRST_THREAD_IN_PROC(p));
255         mtx_destroy(&p->p_mtx);
256         if (p->p_ksi != NULL)
257                 ksiginfo_free(p->p_ksi);
258 #else
259         panic("proc reclaimed");
260 #endif
261 }
262
263 /*
264  * Is p an inferior of the current process?
265  */
266 int
267 inferior(struct proc *p)
268 {
269
270         sx_assert(&proctree_lock, SX_LOCKED);
271         PROC_LOCK_ASSERT(p, MA_OWNED);
272         for (; p != curproc; p = proc_realparent(p)) {
273                 if (p->p_pid == 0)
274                         return (0);
275         }
276         return (1);
277 }
278
279 struct proc *
280 pfind_locked(pid_t pid)
281 {
282         struct proc *p;
283
284         sx_assert(&allproc_lock, SX_LOCKED);
285         LIST_FOREACH(p, PIDHASH(pid), p_hash) {
286                 if (p->p_pid == pid) {
287                         PROC_LOCK(p);
288                         if (p->p_state == PRS_NEW) {
289                                 PROC_UNLOCK(p);
290                                 p = NULL;
291                         }
292                         break;
293                 }
294         }
295         return (p);
296 }
297
298 /*
299  * Locate a process by number; return only "live" processes -- i.e., neither
300  * zombies nor newly born but incompletely initialized processes.  By not
301  * returning processes in the PRS_NEW state, we allow callers to avoid
302  * testing for that condition to avoid dereferencing p_ucred, et al.
303  */
304 struct proc *
305 pfind(pid_t pid)
306 {
307         struct proc *p;
308
309         sx_slock(&allproc_lock);
310         p = pfind_locked(pid);
311         sx_sunlock(&allproc_lock);
312         return (p);
313 }
314
315 static struct proc *
316 pfind_tid_locked(pid_t tid)
317 {
318         struct proc *p;
319         struct thread *td;
320
321         sx_assert(&allproc_lock, SX_LOCKED);
322         FOREACH_PROC_IN_SYSTEM(p) {
323                 PROC_LOCK(p);
324                 if (p->p_state == PRS_NEW) {
325                         PROC_UNLOCK(p);
326                         continue;
327                 }
328                 FOREACH_THREAD_IN_PROC(p, td) {
329                         if (td->td_tid == tid)
330                                 goto found;
331                 }
332                 PROC_UNLOCK(p);
333         }
334 found:
335         return (p);
336 }
337
338 /*
339  * Locate a process group by number.
340  * The caller must hold proctree_lock.
341  */
342 struct pgrp *
343 pgfind(pgid)
344         register pid_t pgid;
345 {
346         register struct pgrp *pgrp;
347
348         sx_assert(&proctree_lock, SX_LOCKED);
349
350         LIST_FOREACH(pgrp, PGRPHASH(pgid), pg_hash) {
351                 if (pgrp->pg_id == pgid) {
352                         PGRP_LOCK(pgrp);
353                         return (pgrp);
354                 }
355         }
356         return (NULL);
357 }
358
359 /*
360  * Locate process and do additional manipulations, depending on flags.
361  */
362 int
363 pget(pid_t pid, int flags, struct proc **pp)
364 {
365         struct proc *p;
366         int error;
367
368         sx_slock(&allproc_lock);
369         if (pid <= PID_MAX) {
370                 p = pfind_locked(pid);
371                 if (p == NULL && (flags & PGET_NOTWEXIT) == 0)
372                         p = zpfind_locked(pid);
373         } else if ((flags & PGET_NOTID) == 0) {
374                 p = pfind_tid_locked(pid);
375         } else {
376                 p = NULL;
377         }
378         sx_sunlock(&allproc_lock);
379         if (p == NULL)
380                 return (ESRCH);
381         if ((flags & PGET_CANSEE) != 0) {
382                 error = p_cansee(curthread, p);
383                 if (error != 0)
384                         goto errout;
385         }
386         if ((flags & PGET_CANDEBUG) != 0) {
387                 error = p_candebug(curthread, p);
388                 if (error != 0)
389                         goto errout;
390         }
391         if ((flags & PGET_ISCURRENT) != 0 && curproc != p) {
392                 error = EPERM;
393                 goto errout;
394         }
395         if ((flags & PGET_NOTWEXIT) != 0 && (p->p_flag & P_WEXIT) != 0) {
396                 error = ESRCH;
397                 goto errout;
398         }
399         if ((flags & PGET_NOTINEXEC) != 0 && (p->p_flag & P_INEXEC) != 0) {
400                 /*
401                  * XXXRW: Not clear ESRCH is the right error during proc
402                  * execve().
403                  */
404                 error = ESRCH;
405                 goto errout;
406         }
407         if ((flags & PGET_HOLD) != 0) {
408                 _PHOLD(p);
409                 PROC_UNLOCK(p);
410         }
411         *pp = p;
412         return (0);
413 errout:
414         PROC_UNLOCK(p);
415         return (error);
416 }
417
418 /*
419  * Create a new process group.
420  * pgid must be equal to the pid of p.
421  * Begin a new session if required.
422  */
423 int
424 enterpgrp(p, pgid, pgrp, sess)
425         register struct proc *p;
426         pid_t pgid;
427         struct pgrp *pgrp;
428         struct session *sess;
429 {
430
431         sx_assert(&proctree_lock, SX_XLOCKED);
432
433         KASSERT(pgrp != NULL, ("enterpgrp: pgrp == NULL"));
434         KASSERT(p->p_pid == pgid,
435             ("enterpgrp: new pgrp and pid != pgid"));
436         KASSERT(pgfind(pgid) == NULL,
437             ("enterpgrp: pgrp with pgid exists"));
438         KASSERT(!SESS_LEADER(p),
439             ("enterpgrp: session leader attempted setpgrp"));
440
441         mtx_init(&pgrp->pg_mtx, "process group", NULL, MTX_DEF | MTX_DUPOK);
442
443         if (sess != NULL) {
444                 /*
445                  * new session
446                  */
447                 mtx_init(&sess->s_mtx, "session", NULL, MTX_DEF);
448                 PROC_LOCK(p);
449                 p->p_flag &= ~P_CONTROLT;
450                 PROC_UNLOCK(p);
451                 PGRP_LOCK(pgrp);
452                 sess->s_leader = p;
453                 sess->s_sid = p->p_pid;
454                 refcount_init(&sess->s_count, 1);
455                 sess->s_ttyvp = NULL;
456                 sess->s_ttydp = NULL;
457                 sess->s_ttyp = NULL;
458                 bcopy(p->p_session->s_login, sess->s_login,
459                             sizeof(sess->s_login));
460                 pgrp->pg_session = sess;
461                 KASSERT(p == curproc,
462                     ("enterpgrp: mksession and p != curproc"));
463         } else {
464                 pgrp->pg_session = p->p_session;
465                 sess_hold(pgrp->pg_session);
466                 PGRP_LOCK(pgrp);
467         }
468         pgrp->pg_id = pgid;
469         LIST_INIT(&pgrp->pg_members);
470
471         /*
472          * As we have an exclusive lock of proctree_lock,
473          * this should not deadlock.
474          */
475         LIST_INSERT_HEAD(PGRPHASH(pgid), pgrp, pg_hash);
476         pgrp->pg_jobc = 0;
477         SLIST_INIT(&pgrp->pg_sigiolst);
478         PGRP_UNLOCK(pgrp);
479
480         doenterpgrp(p, pgrp);
481
482         return (0);
483 }
484
485 /*
486  * Move p to an existing process group
487  */
488 int
489 enterthispgrp(p, pgrp)
490         register struct proc *p;
491         struct pgrp *pgrp;
492 {
493
494         sx_assert(&proctree_lock, SX_XLOCKED);
495         PROC_LOCK_ASSERT(p, MA_NOTOWNED);
496         PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
497         PGRP_LOCK_ASSERT(p->p_pgrp, MA_NOTOWNED);
498         SESS_LOCK_ASSERT(p->p_session, MA_NOTOWNED);
499         KASSERT(pgrp->pg_session == p->p_session,
500                 ("%s: pgrp's session %p, p->p_session %p.\n",
501                 __func__,
502                 pgrp->pg_session,
503                 p->p_session));
504         KASSERT(pgrp != p->p_pgrp,
505                 ("%s: p belongs to pgrp.", __func__));
506
507         doenterpgrp(p, pgrp);
508
509         return (0);
510 }
511
512 /*
513  * Move p to a process group
514  */
515 static void
516 doenterpgrp(p, pgrp)
517         struct proc *p;
518         struct pgrp *pgrp;
519 {
520         struct pgrp *savepgrp;
521
522         sx_assert(&proctree_lock, SX_XLOCKED);
523         PROC_LOCK_ASSERT(p, MA_NOTOWNED);
524         PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
525         PGRP_LOCK_ASSERT(p->p_pgrp, MA_NOTOWNED);
526         SESS_LOCK_ASSERT(p->p_session, MA_NOTOWNED);
527
528         savepgrp = p->p_pgrp;
529
530         /*
531          * Adjust eligibility of affected pgrps to participate in job control.
532          * Increment eligibility counts before decrementing, otherwise we
533          * could reach 0 spuriously during the first call.
534          */
535         fixjobc(p, pgrp, 1);
536         fixjobc(p, p->p_pgrp, 0);
537
538         PGRP_LOCK(pgrp);
539         PGRP_LOCK(savepgrp);
540         PROC_LOCK(p);
541         LIST_REMOVE(p, p_pglist);
542         p->p_pgrp = pgrp;
543         PROC_UNLOCK(p);
544         LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
545         PGRP_UNLOCK(savepgrp);
546         PGRP_UNLOCK(pgrp);
547         if (LIST_EMPTY(&savepgrp->pg_members))
548                 pgdelete(savepgrp);
549 }
550
551 /*
552  * remove process from process group
553  */
554 int
555 leavepgrp(p)
556         register struct proc *p;
557 {
558         struct pgrp *savepgrp;
559
560         sx_assert(&proctree_lock, SX_XLOCKED);
561         savepgrp = p->p_pgrp;
562         PGRP_LOCK(savepgrp);
563         PROC_LOCK(p);
564         LIST_REMOVE(p, p_pglist);
565         p->p_pgrp = NULL;
566         PROC_UNLOCK(p);
567         PGRP_UNLOCK(savepgrp);
568         if (LIST_EMPTY(&savepgrp->pg_members))
569                 pgdelete(savepgrp);
570         return (0);
571 }
572
573 /*
574  * delete a process group
575  */
576 static void
577 pgdelete(pgrp)
578         register struct pgrp *pgrp;
579 {
580         struct session *savesess;
581         struct tty *tp;
582
583         sx_assert(&proctree_lock, SX_XLOCKED);
584         PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
585         SESS_LOCK_ASSERT(pgrp->pg_session, MA_NOTOWNED);
586
587         /*
588          * Reset any sigio structures pointing to us as a result of
589          * F_SETOWN with our pgid.
590          */
591         funsetownlst(&pgrp->pg_sigiolst);
592
593         PGRP_LOCK(pgrp);
594         tp = pgrp->pg_session->s_ttyp;
595         LIST_REMOVE(pgrp, pg_hash);
596         savesess = pgrp->pg_session;
597         PGRP_UNLOCK(pgrp);
598
599         /* Remove the reference to the pgrp before deallocating it. */
600         if (tp != NULL) {
601                 tty_lock(tp);
602                 tty_rel_pgrp(tp, pgrp);
603         }
604
605         mtx_destroy(&pgrp->pg_mtx);
606         free(pgrp, M_PGRP);
607         sess_release(savesess);
608 }
609
610 static void
611 pgadjustjobc(pgrp, entering)
612         struct pgrp *pgrp;
613         int entering;
614 {
615
616         PGRP_LOCK(pgrp);
617         if (entering)
618                 pgrp->pg_jobc++;
619         else {
620                 --pgrp->pg_jobc;
621                 if (pgrp->pg_jobc == 0)
622                         orphanpg(pgrp);
623         }
624         PGRP_UNLOCK(pgrp);
625 }
626
627 /*
628  * Adjust pgrp jobc counters when specified process changes process group.
629  * We count the number of processes in each process group that "qualify"
630  * the group for terminal job control (those with a parent in a different
631  * process group of the same session).  If that count reaches zero, the
632  * process group becomes orphaned.  Check both the specified process'
633  * process group and that of its children.
634  * entering == 0 => p is leaving specified group.
635  * entering == 1 => p is entering specified group.
636  */
637 void
638 fixjobc(p, pgrp, entering)
639         register struct proc *p;
640         register struct pgrp *pgrp;
641         int entering;
642 {
643         register struct pgrp *hispgrp;
644         register struct session *mysession;
645
646         sx_assert(&proctree_lock, SX_LOCKED);
647         PROC_LOCK_ASSERT(p, MA_NOTOWNED);
648         PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
649         SESS_LOCK_ASSERT(pgrp->pg_session, MA_NOTOWNED);
650
651         /*
652          * Check p's parent to see whether p qualifies its own process
653          * group; if so, adjust count for p's process group.
654          */
655         mysession = pgrp->pg_session;
656         if ((hispgrp = p->p_pptr->p_pgrp) != pgrp &&
657             hispgrp->pg_session == mysession)
658                 pgadjustjobc(pgrp, entering);
659
660         /*
661          * Check this process' children to see whether they qualify
662          * their process groups; if so, adjust counts for children's
663          * process groups.
664          */
665         LIST_FOREACH(p, &p->p_children, p_sibling) {
666                 hispgrp = p->p_pgrp;
667                 if (hispgrp == pgrp ||
668                     hispgrp->pg_session != mysession)
669                         continue;
670                 PROC_LOCK(p);
671                 if (p->p_state == PRS_ZOMBIE) {
672                         PROC_UNLOCK(p);
673                         continue;
674                 }
675                 PROC_UNLOCK(p);
676                 pgadjustjobc(hispgrp, entering);
677         }
678 }
679
680 /*
681  * A process group has become orphaned;
682  * if there are any stopped processes in the group,
683  * hang-up all process in that group.
684  */
685 static void
686 orphanpg(pg)
687         struct pgrp *pg;
688 {
689         register struct proc *p;
690
691         PGRP_LOCK_ASSERT(pg, MA_OWNED);
692
693         LIST_FOREACH(p, &pg->pg_members, p_pglist) {
694                 PROC_LOCK(p);
695                 if (P_SHOULDSTOP(p) == P_STOPPED_SIG) {
696                         PROC_UNLOCK(p);
697                         LIST_FOREACH(p, &pg->pg_members, p_pglist) {
698                                 PROC_LOCK(p);
699                                 kern_psignal(p, SIGHUP);
700                                 kern_psignal(p, SIGCONT);
701                                 PROC_UNLOCK(p);
702                         }
703                         return;
704                 }
705                 PROC_UNLOCK(p);
706         }
707 }
708
709 void
710 sess_hold(struct session *s)
711 {
712
713         refcount_acquire(&s->s_count);
714 }
715
716 void
717 sess_release(struct session *s)
718 {
719
720         if (refcount_release(&s->s_count)) {
721                 if (s->s_ttyp != NULL) {
722                         tty_lock(s->s_ttyp);
723                         tty_rel_sess(s->s_ttyp, s);
724                 }
725                 mtx_destroy(&s->s_mtx);
726                 free(s, M_SESSION);
727         }
728 }
729
730 #ifdef DDB
731
732 DB_SHOW_COMMAND(pgrpdump, pgrpdump)
733 {
734         register struct pgrp *pgrp;
735         register struct proc *p;
736         register int i;
737
738         for (i = 0; i <= pgrphash; i++) {
739                 if (!LIST_EMPTY(&pgrphashtbl[i])) {
740                         printf("\tindx %d\n", i);
741                         LIST_FOREACH(pgrp, &pgrphashtbl[i], pg_hash) {
742                                 printf(
743                         "\tpgrp %p, pgid %ld, sess %p, sesscnt %d, mem %p\n",
744                                     (void *)pgrp, (long)pgrp->pg_id,
745                                     (void *)pgrp->pg_session,
746                                     pgrp->pg_session->s_count,
747                                     (void *)LIST_FIRST(&pgrp->pg_members));
748                                 LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
749                                         printf("\t\tpid %ld addr %p pgrp %p\n", 
750                                             (long)p->p_pid, (void *)p,
751                                             (void *)p->p_pgrp);
752                                 }
753                         }
754                 }
755         }
756 }
757 #endif /* DDB */
758
759 /*
760  * Calculate the kinfo_proc members which contain process-wide
761  * informations.
762  * Must be called with the target process locked.
763  */
764 static void
765 fill_kinfo_aggregate(struct proc *p, struct kinfo_proc *kp)
766 {
767         struct thread *td;
768
769         PROC_LOCK_ASSERT(p, MA_OWNED);
770
771         kp->ki_estcpu = 0;
772         kp->ki_pctcpu = 0;
773         FOREACH_THREAD_IN_PROC(p, td) {
774                 thread_lock(td);
775                 kp->ki_pctcpu += sched_pctcpu(td);
776                 kp->ki_estcpu += td->td_estcpu;
777                 thread_unlock(td);
778         }
779 }
780
781 /*
782  * Clear kinfo_proc and fill in any information that is common
783  * to all threads in the process.
784  * Must be called with the target process locked.
785  */
786 static void
787 fill_kinfo_proc_only(struct proc *p, struct kinfo_proc *kp)
788 {
789         struct thread *td0;
790         struct tty *tp;
791         struct session *sp;
792         struct ucred *cred;
793         struct sigacts *ps;
794
795         PROC_LOCK_ASSERT(p, MA_OWNED);
796         bzero(kp, sizeof(*kp));
797
798         kp->ki_structsize = sizeof(*kp);
799         kp->ki_paddr = p;
800         kp->ki_addr =/* p->p_addr; */0; /* XXX */
801         kp->ki_args = p->p_args;
802         kp->ki_textvp = p->p_textvp;
803 #ifdef KTRACE
804         kp->ki_tracep = p->p_tracevp;
805         kp->ki_traceflag = p->p_traceflag;
806 #endif
807         kp->ki_fd = p->p_fd;
808         kp->ki_vmspace = p->p_vmspace;
809         kp->ki_flag = p->p_flag;
810         kp->ki_flag2 = p->p_flag2;
811         cred = p->p_ucred;
812         if (cred) {
813                 kp->ki_uid = cred->cr_uid;
814                 kp->ki_ruid = cred->cr_ruid;
815                 kp->ki_svuid = cred->cr_svuid;
816                 kp->ki_cr_flags = 0;
817                 if (cred->cr_flags & CRED_FLAG_CAPMODE)
818                         kp->ki_cr_flags |= KI_CRF_CAPABILITY_MODE;
819                 /* XXX bde doesn't like KI_NGROUPS */
820                 if (cred->cr_ngroups > KI_NGROUPS) {
821                         kp->ki_ngroups = KI_NGROUPS;
822                         kp->ki_cr_flags |= KI_CRF_GRP_OVERFLOW;
823                 } else
824                         kp->ki_ngroups = cred->cr_ngroups;
825                 bcopy(cred->cr_groups, kp->ki_groups,
826                     kp->ki_ngroups * sizeof(gid_t));
827                 kp->ki_rgid = cred->cr_rgid;
828                 kp->ki_svgid = cred->cr_svgid;
829                 /* If jailed(cred), emulate the old P_JAILED flag. */
830                 if (jailed(cred)) {
831                         kp->ki_flag |= P_JAILED;
832                         /* If inside the jail, use 0 as a jail ID. */
833                         if (cred->cr_prison != curthread->td_ucred->cr_prison)
834                                 kp->ki_jid = cred->cr_prison->pr_id;
835                 }
836                 strlcpy(kp->ki_loginclass, cred->cr_loginclass->lc_name,
837                     sizeof(kp->ki_loginclass));
838         }
839         ps = p->p_sigacts;
840         if (ps) {
841                 mtx_lock(&ps->ps_mtx);
842                 kp->ki_sigignore = ps->ps_sigignore;
843                 kp->ki_sigcatch = ps->ps_sigcatch;
844                 mtx_unlock(&ps->ps_mtx);
845         }
846         if (p->p_state != PRS_NEW &&
847             p->p_state != PRS_ZOMBIE &&
848             p->p_vmspace != NULL) {
849                 struct vmspace *vm = p->p_vmspace;
850
851                 kp->ki_size = vm->vm_map.size;
852                 kp->ki_rssize = vmspace_resident_count(vm); /*XXX*/
853                 FOREACH_THREAD_IN_PROC(p, td0) {
854                         if (!TD_IS_SWAPPED(td0))
855                                 kp->ki_rssize += td0->td_kstack_pages;
856                 }
857                 kp->ki_swrss = vm->vm_swrss;
858                 kp->ki_tsize = vm->vm_tsize;
859                 kp->ki_dsize = vm->vm_dsize;
860                 kp->ki_ssize = vm->vm_ssize;
861         } else if (p->p_state == PRS_ZOMBIE)
862                 kp->ki_stat = SZOMB;
863         if (kp->ki_flag & P_INMEM)
864                 kp->ki_sflag = PS_INMEM;
865         else
866                 kp->ki_sflag = 0;
867         /* Calculate legacy swtime as seconds since 'swtick'. */
868         kp->ki_swtime = (ticks - p->p_swtick) / hz;
869         kp->ki_pid = p->p_pid;
870         kp->ki_nice = p->p_nice;
871         kp->ki_fibnum = p->p_fibnum;
872         kp->ki_start = p->p_stats->p_start;
873         timevaladd(&kp->ki_start, &boottime);
874         PROC_SLOCK(p);
875         rufetch(p, &kp->ki_rusage);
876         kp->ki_runtime = cputick2usec(p->p_rux.rux_runtime);
877         calcru(p, &kp->ki_rusage.ru_utime, &kp->ki_rusage.ru_stime);
878         PROC_SUNLOCK(p);
879         calccru(p, &kp->ki_childutime, &kp->ki_childstime);
880         /* Some callers want child times in a single value. */
881         kp->ki_childtime = kp->ki_childstime;
882         timevaladd(&kp->ki_childtime, &kp->ki_childutime);
883
884         FOREACH_THREAD_IN_PROC(p, td0)
885                 kp->ki_cow += td0->td_cow;
886
887         tp = NULL;
888         if (p->p_pgrp) {
889                 kp->ki_pgid = p->p_pgrp->pg_id;
890                 kp->ki_jobc = p->p_pgrp->pg_jobc;
891                 sp = p->p_pgrp->pg_session;
892
893                 if (sp != NULL) {
894                         kp->ki_sid = sp->s_sid;
895                         SESS_LOCK(sp);
896                         strlcpy(kp->ki_login, sp->s_login,
897                             sizeof(kp->ki_login));
898                         if (sp->s_ttyvp)
899                                 kp->ki_kiflag |= KI_CTTY;
900                         if (SESS_LEADER(p))
901                                 kp->ki_kiflag |= KI_SLEADER;
902                         /* XXX proctree_lock */
903                         tp = sp->s_ttyp;
904                         SESS_UNLOCK(sp);
905                 }
906         }
907         if ((p->p_flag & P_CONTROLT) && tp != NULL) {
908                 kp->ki_tdev = tty_udev(tp);
909                 kp->ki_tpgid = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
910                 if (tp->t_session)
911                         kp->ki_tsid = tp->t_session->s_sid;
912         } else
913                 kp->ki_tdev = NODEV;
914         if (p->p_comm[0] != '\0')
915                 strlcpy(kp->ki_comm, p->p_comm, sizeof(kp->ki_comm));
916         if (p->p_sysent && p->p_sysent->sv_name != NULL &&
917             p->p_sysent->sv_name[0] != '\0')
918                 strlcpy(kp->ki_emul, p->p_sysent->sv_name, sizeof(kp->ki_emul));
919         kp->ki_siglist = p->p_siglist;
920         kp->ki_xstat = p->p_xstat;
921         kp->ki_acflag = p->p_acflag;
922         kp->ki_lock = p->p_lock;
923         if (p->p_pptr)
924                 kp->ki_ppid = p->p_pptr->p_pid;
925 }
926
927 /*
928  * Fill in information that is thread specific.  Must be called with
929  * target process locked.  If 'preferthread' is set, overwrite certain
930  * process-related fields that are maintained for both threads and
931  * processes.
932  */
933 static void
934 fill_kinfo_thread(struct thread *td, struct kinfo_proc *kp, int preferthread)
935 {
936         struct proc *p;
937
938         p = td->td_proc;
939         kp->ki_tdaddr = td;
940         PROC_LOCK_ASSERT(p, MA_OWNED);
941
942         if (preferthread)
943                 PROC_SLOCK(p);
944         thread_lock(td);
945         if (td->td_wmesg != NULL)
946                 strlcpy(kp->ki_wmesg, td->td_wmesg, sizeof(kp->ki_wmesg));
947         else
948                 bzero(kp->ki_wmesg, sizeof(kp->ki_wmesg));
949         strlcpy(kp->ki_tdname, td->td_name, sizeof(kp->ki_tdname));
950         if (TD_ON_LOCK(td)) {
951                 kp->ki_kiflag |= KI_LOCKBLOCK;
952                 strlcpy(kp->ki_lockname, td->td_lockname,
953                     sizeof(kp->ki_lockname));
954         } else {
955                 kp->ki_kiflag &= ~KI_LOCKBLOCK;
956                 bzero(kp->ki_lockname, sizeof(kp->ki_lockname));
957         }
958
959         if (p->p_state == PRS_NORMAL) { /* approximate. */
960                 if (TD_ON_RUNQ(td) ||
961                     TD_CAN_RUN(td) ||
962                     TD_IS_RUNNING(td)) {
963                         kp->ki_stat = SRUN;
964                 } else if (P_SHOULDSTOP(p)) {
965                         kp->ki_stat = SSTOP;
966                 } else if (TD_IS_SLEEPING(td)) {
967                         kp->ki_stat = SSLEEP;
968                 } else if (TD_ON_LOCK(td)) {
969                         kp->ki_stat = SLOCK;
970                 } else {
971                         kp->ki_stat = SWAIT;
972                 }
973         } else if (p->p_state == PRS_ZOMBIE) {
974                 kp->ki_stat = SZOMB;
975         } else {
976                 kp->ki_stat = SIDL;
977         }
978
979         /* Things in the thread */
980         kp->ki_wchan = td->td_wchan;
981         kp->ki_pri.pri_level = td->td_priority;
982         kp->ki_pri.pri_native = td->td_base_pri;
983         kp->ki_lastcpu = td->td_lastcpu;
984         kp->ki_oncpu = td->td_oncpu;
985         kp->ki_tdflags = td->td_flags;
986         kp->ki_tid = td->td_tid;
987         kp->ki_numthreads = p->p_numthreads;
988         kp->ki_pcb = td->td_pcb;
989         kp->ki_kstack = (void *)td->td_kstack;
990         kp->ki_slptime = (ticks - td->td_slptick) / hz;
991         kp->ki_pri.pri_class = td->td_pri_class;
992         kp->ki_pri.pri_user = td->td_user_pri;
993
994         if (preferthread) {
995                 rufetchtd(td, &kp->ki_rusage);
996                 kp->ki_runtime = cputick2usec(td->td_rux.rux_runtime);
997                 kp->ki_pctcpu = sched_pctcpu(td);
998                 kp->ki_estcpu = td->td_estcpu;
999                 kp->ki_cow = td->td_cow;
1000         }
1001
1002         /* We can't get this anymore but ps etc never used it anyway. */
1003         kp->ki_rqindex = 0;
1004
1005         if (preferthread)
1006                 kp->ki_siglist = td->td_siglist;
1007         kp->ki_sigmask = td->td_sigmask;
1008         thread_unlock(td);
1009         if (preferthread)
1010                 PROC_SUNLOCK(p);
1011 }
1012
1013 /*
1014  * Fill in a kinfo_proc structure for the specified process.
1015  * Must be called with the target process locked.
1016  */
1017 void
1018 fill_kinfo_proc(struct proc *p, struct kinfo_proc *kp)
1019 {
1020
1021         MPASS(FIRST_THREAD_IN_PROC(p) != NULL);
1022
1023         fill_kinfo_proc_only(p, kp);
1024         fill_kinfo_thread(FIRST_THREAD_IN_PROC(p), kp, 0);
1025         fill_kinfo_aggregate(p, kp);
1026 }
1027
1028 struct pstats *
1029 pstats_alloc(void)
1030 {
1031
1032         return (malloc(sizeof(struct pstats), M_SUBPROC, M_ZERO|M_WAITOK));
1033 }
1034
1035 /*
1036  * Copy parts of p_stats; zero the rest of p_stats (statistics).
1037  */
1038 void
1039 pstats_fork(struct pstats *src, struct pstats *dst)
1040 {
1041
1042         bzero(&dst->pstat_startzero,
1043             __rangeof(struct pstats, pstat_startzero, pstat_endzero));
1044         bcopy(&src->pstat_startcopy, &dst->pstat_startcopy,
1045             __rangeof(struct pstats, pstat_startcopy, pstat_endcopy));
1046 }
1047
1048 void
1049 pstats_free(struct pstats *ps)
1050 {
1051
1052         free(ps, M_SUBPROC);
1053 }
1054
1055 static struct proc *
1056 zpfind_locked(pid_t pid)
1057 {
1058         struct proc *p;
1059
1060         sx_assert(&allproc_lock, SX_LOCKED);
1061         LIST_FOREACH(p, &zombproc, p_list) {
1062                 if (p->p_pid == pid) {
1063                         PROC_LOCK(p);
1064                         break;
1065                 }
1066         }
1067         return (p);
1068 }
1069
1070 /*
1071  * Locate a zombie process by number
1072  */
1073 struct proc *
1074 zpfind(pid_t pid)
1075 {
1076         struct proc *p;
1077
1078         sx_slock(&allproc_lock);
1079         p = zpfind_locked(pid);
1080         sx_sunlock(&allproc_lock);
1081         return (p);
1082 }
1083
1084 #ifdef COMPAT_FREEBSD32
1085
1086 /*
1087  * This function is typically used to copy out the kernel address, so
1088  * it can be replaced by assignment of zero.
1089  */
1090 static inline uint32_t
1091 ptr32_trim(void *ptr)
1092 {
1093         uintptr_t uptr;
1094
1095         uptr = (uintptr_t)ptr;
1096         return ((uptr > UINT_MAX) ? 0 : uptr);
1097 }
1098
1099 #define PTRTRIM_CP(src,dst,fld) \
1100         do { (dst).fld = ptr32_trim((src).fld); } while (0)
1101
1102 static void
1103 freebsd32_kinfo_proc_out(const struct kinfo_proc *ki, struct kinfo_proc32 *ki32)
1104 {
1105         int i;
1106
1107         bzero(ki32, sizeof(struct kinfo_proc32));
1108         ki32->ki_structsize = sizeof(struct kinfo_proc32);
1109         CP(*ki, *ki32, ki_layout);
1110         PTRTRIM_CP(*ki, *ki32, ki_args);
1111         PTRTRIM_CP(*ki, *ki32, ki_paddr);
1112         PTRTRIM_CP(*ki, *ki32, ki_addr);
1113         PTRTRIM_CP(*ki, *ki32, ki_tracep);
1114         PTRTRIM_CP(*ki, *ki32, ki_textvp);
1115         PTRTRIM_CP(*ki, *ki32, ki_fd);
1116         PTRTRIM_CP(*ki, *ki32, ki_vmspace);
1117         PTRTRIM_CP(*ki, *ki32, ki_wchan);
1118         CP(*ki, *ki32, ki_pid);
1119         CP(*ki, *ki32, ki_ppid);
1120         CP(*ki, *ki32, ki_pgid);
1121         CP(*ki, *ki32, ki_tpgid);
1122         CP(*ki, *ki32, ki_sid);
1123         CP(*ki, *ki32, ki_tsid);
1124         CP(*ki, *ki32, ki_jobc);
1125         CP(*ki, *ki32, ki_tdev);
1126         CP(*ki, *ki32, ki_siglist);
1127         CP(*ki, *ki32, ki_sigmask);
1128         CP(*ki, *ki32, ki_sigignore);
1129         CP(*ki, *ki32, ki_sigcatch);
1130         CP(*ki, *ki32, ki_uid);
1131         CP(*ki, *ki32, ki_ruid);
1132         CP(*ki, *ki32, ki_svuid);
1133         CP(*ki, *ki32, ki_rgid);
1134         CP(*ki, *ki32, ki_svgid);
1135         CP(*ki, *ki32, ki_ngroups);
1136         for (i = 0; i < KI_NGROUPS; i++)
1137                 CP(*ki, *ki32, ki_groups[i]);
1138         CP(*ki, *ki32, ki_size);
1139         CP(*ki, *ki32, ki_rssize);
1140         CP(*ki, *ki32, ki_swrss);
1141         CP(*ki, *ki32, ki_tsize);
1142         CP(*ki, *ki32, ki_dsize);
1143         CP(*ki, *ki32, ki_ssize);
1144         CP(*ki, *ki32, ki_xstat);
1145         CP(*ki, *ki32, ki_acflag);
1146         CP(*ki, *ki32, ki_pctcpu);
1147         CP(*ki, *ki32, ki_estcpu);
1148         CP(*ki, *ki32, ki_slptime);
1149         CP(*ki, *ki32, ki_swtime);
1150         CP(*ki, *ki32, ki_cow);
1151         CP(*ki, *ki32, ki_runtime);
1152         TV_CP(*ki, *ki32, ki_start);
1153         TV_CP(*ki, *ki32, ki_childtime);
1154         CP(*ki, *ki32, ki_flag);
1155         CP(*ki, *ki32, ki_kiflag);
1156         CP(*ki, *ki32, ki_traceflag);
1157         CP(*ki, *ki32, ki_stat);
1158         CP(*ki, *ki32, ki_nice);
1159         CP(*ki, *ki32, ki_lock);
1160         CP(*ki, *ki32, ki_rqindex);
1161         CP(*ki, *ki32, ki_oncpu);
1162         CP(*ki, *ki32, ki_lastcpu);
1163         bcopy(ki->ki_tdname, ki32->ki_tdname, TDNAMLEN + 1);
1164         bcopy(ki->ki_wmesg, ki32->ki_wmesg, WMESGLEN + 1);
1165         bcopy(ki->ki_login, ki32->ki_login, LOGNAMELEN + 1);
1166         bcopy(ki->ki_lockname, ki32->ki_lockname, LOCKNAMELEN + 1);
1167         bcopy(ki->ki_comm, ki32->ki_comm, COMMLEN + 1);
1168         bcopy(ki->ki_emul, ki32->ki_emul, KI_EMULNAMELEN + 1);
1169         bcopy(ki->ki_loginclass, ki32->ki_loginclass, LOGINCLASSLEN + 1);
1170         CP(*ki, *ki32, ki_flag2);
1171         CP(*ki, *ki32, ki_fibnum);
1172         CP(*ki, *ki32, ki_cr_flags);
1173         CP(*ki, *ki32, ki_jid);
1174         CP(*ki, *ki32, ki_numthreads);
1175         CP(*ki, *ki32, ki_tid);
1176         CP(*ki, *ki32, ki_pri);
1177         freebsd32_rusage_out(&ki->ki_rusage, &ki32->ki_rusage);
1178         freebsd32_rusage_out(&ki->ki_rusage_ch, &ki32->ki_rusage_ch);
1179         PTRTRIM_CP(*ki, *ki32, ki_pcb);
1180         PTRTRIM_CP(*ki, *ki32, ki_kstack);
1181         PTRTRIM_CP(*ki, *ki32, ki_udata);
1182         CP(*ki, *ki32, ki_sflag);
1183         CP(*ki, *ki32, ki_tdflags);
1184 }
1185 #endif
1186
1187 int
1188 kern_proc_out(struct proc *p, struct sbuf *sb, int flags)
1189 {
1190         struct thread *td;
1191         struct kinfo_proc ki;
1192 #ifdef COMPAT_FREEBSD32
1193         struct kinfo_proc32 ki32;
1194 #endif
1195         int error;
1196
1197         PROC_LOCK_ASSERT(p, MA_OWNED);
1198         MPASS(FIRST_THREAD_IN_PROC(p) != NULL);
1199
1200         error = 0;
1201         fill_kinfo_proc(p, &ki);
1202         if ((flags & KERN_PROC_NOTHREADS) != 0) {
1203 #ifdef COMPAT_FREEBSD32
1204                 if ((flags & KERN_PROC_MASK32) != 0) {
1205                         freebsd32_kinfo_proc_out(&ki, &ki32);
1206                         if (sbuf_bcat(sb, &ki32, sizeof(ki32)) != 0)
1207                                 error = ENOMEM;
1208                 } else
1209 #endif
1210                         if (sbuf_bcat(sb, &ki, sizeof(ki)) != 0)
1211                                 error = ENOMEM;
1212         } else {
1213                 FOREACH_THREAD_IN_PROC(p, td) {
1214                         fill_kinfo_thread(td, &ki, 1);
1215 #ifdef COMPAT_FREEBSD32
1216                         if ((flags & KERN_PROC_MASK32) != 0) {
1217                                 freebsd32_kinfo_proc_out(&ki, &ki32);
1218                                 if (sbuf_bcat(sb, &ki32, sizeof(ki32)) != 0)
1219                                         error = ENOMEM;
1220                         } else
1221 #endif
1222                                 if (sbuf_bcat(sb, &ki, sizeof(ki)) != 0)
1223                                         error = ENOMEM;
1224                         if (error != 0)
1225                                 break;
1226                 }
1227         }
1228         PROC_UNLOCK(p);
1229         return (error);
1230 }
1231
1232 static int
1233 sysctl_out_proc(struct proc *p, struct sysctl_req *req, int flags,
1234     int doingzomb)
1235 {
1236         struct sbuf sb;
1237         struct kinfo_proc ki;
1238         struct proc *np;
1239         int error, error2;
1240         pid_t pid;
1241
1242         pid = p->p_pid;
1243         sbuf_new_for_sysctl(&sb, (char *)&ki, sizeof(ki), req);
1244         error = kern_proc_out(p, &sb, flags);
1245         error2 = sbuf_finish(&sb);
1246         sbuf_delete(&sb);
1247         if (error != 0)
1248                 return (error);
1249         else if (error2 != 0)
1250                 return (error2);
1251         if (doingzomb)
1252                 np = zpfind(pid);
1253         else {
1254                 if (pid == 0)
1255                         return (0);
1256                 np = pfind(pid);
1257         }
1258         if (np == NULL)
1259                 return (ESRCH);
1260         if (np != p) {
1261                 PROC_UNLOCK(np);
1262                 return (ESRCH);
1263         }
1264         PROC_UNLOCK(np);
1265         return (0);
1266 }
1267
1268 static int
1269 sysctl_kern_proc(SYSCTL_HANDLER_ARGS)
1270 {
1271         int *name = (int *)arg1;
1272         u_int namelen = arg2;
1273         struct proc *p;
1274         int flags, doingzomb, oid_number;
1275         int error = 0;
1276
1277         oid_number = oidp->oid_number;
1278         if (oid_number != KERN_PROC_ALL &&
1279             (oid_number & KERN_PROC_INC_THREAD) == 0)
1280                 flags = KERN_PROC_NOTHREADS;
1281         else {
1282                 flags = 0;
1283                 oid_number &= ~KERN_PROC_INC_THREAD;
1284         }
1285 #ifdef COMPAT_FREEBSD32
1286         if (req->flags & SCTL_MASK32)
1287                 flags |= KERN_PROC_MASK32;
1288 #endif
1289         if (oid_number == KERN_PROC_PID) {
1290                 if (namelen != 1)
1291                         return (EINVAL);
1292                 error = sysctl_wire_old_buffer(req, 0);
1293                 if (error)
1294                         return (error);
1295                 error = pget((pid_t)name[0], PGET_CANSEE, &p);
1296                 if (error != 0)
1297                         return (error);
1298                 error = sysctl_out_proc(p, req, flags, 0);
1299                 return (error);
1300         }
1301
1302         switch (oid_number) {
1303         case KERN_PROC_ALL:
1304                 if (namelen != 0)
1305                         return (EINVAL);
1306                 break;
1307         case KERN_PROC_PROC:
1308                 if (namelen != 0 && namelen != 1)
1309                         return (EINVAL);
1310                 break;
1311         default:
1312                 if (namelen != 1)
1313                         return (EINVAL);
1314                 break;
1315         }
1316
1317         if (!req->oldptr) {
1318                 /* overestimate by 5 procs */
1319                 error = SYSCTL_OUT(req, 0, sizeof (struct kinfo_proc) * 5);
1320                 if (error)
1321                         return (error);
1322         }
1323         error = sysctl_wire_old_buffer(req, 0);
1324         if (error != 0)
1325                 return (error);
1326         sx_slock(&allproc_lock);
1327         for (doingzomb=0 ; doingzomb < 2 ; doingzomb++) {
1328                 if (!doingzomb)
1329                         p = LIST_FIRST(&allproc);
1330                 else
1331                         p = LIST_FIRST(&zombproc);
1332                 for (; p != 0; p = LIST_NEXT(p, p_list)) {
1333                         /*
1334                          * Skip embryonic processes.
1335                          */
1336                         PROC_LOCK(p);
1337                         if (p->p_state == PRS_NEW) {
1338                                 PROC_UNLOCK(p);
1339                                 continue;
1340                         }
1341                         KASSERT(p->p_ucred != NULL,
1342                             ("process credential is NULL for non-NEW proc"));
1343                         /*
1344                          * Show a user only appropriate processes.
1345                          */
1346                         if (p_cansee(curthread, p)) {
1347                                 PROC_UNLOCK(p);
1348                                 continue;
1349                         }
1350                         /*
1351                          * TODO - make more efficient (see notes below).
1352                          * do by session.
1353                          */
1354                         switch (oid_number) {
1355
1356                         case KERN_PROC_GID:
1357                                 if (p->p_ucred->cr_gid != (gid_t)name[0]) {
1358                                         PROC_UNLOCK(p);
1359                                         continue;
1360                                 }
1361                                 break;
1362
1363                         case KERN_PROC_PGRP:
1364                                 /* could do this by traversing pgrp */
1365                                 if (p->p_pgrp == NULL ||
1366                                     p->p_pgrp->pg_id != (pid_t)name[0]) {
1367                                         PROC_UNLOCK(p);
1368                                         continue;
1369                                 }
1370                                 break;
1371
1372                         case KERN_PROC_RGID:
1373                                 if (p->p_ucred->cr_rgid != (gid_t)name[0]) {
1374                                         PROC_UNLOCK(p);
1375                                         continue;
1376                                 }
1377                                 break;
1378
1379                         case KERN_PROC_SESSION:
1380                                 if (p->p_session == NULL ||
1381                                     p->p_session->s_sid != (pid_t)name[0]) {
1382                                         PROC_UNLOCK(p);
1383                                         continue;
1384                                 }
1385                                 break;
1386
1387                         case KERN_PROC_TTY:
1388                                 if ((p->p_flag & P_CONTROLT) == 0 ||
1389                                     p->p_session == NULL) {
1390                                         PROC_UNLOCK(p);
1391                                         continue;
1392                                 }
1393                                 /* XXX proctree_lock */
1394                                 SESS_LOCK(p->p_session);
1395                                 if (p->p_session->s_ttyp == NULL ||
1396                                     tty_udev(p->p_session->s_ttyp) !=
1397                                     (dev_t)name[0]) {
1398                                         SESS_UNLOCK(p->p_session);
1399                                         PROC_UNLOCK(p);
1400                                         continue;
1401                                 }
1402                                 SESS_UNLOCK(p->p_session);
1403                                 break;
1404
1405                         case KERN_PROC_UID:
1406                                 if (p->p_ucred->cr_uid != (uid_t)name[0]) {
1407                                         PROC_UNLOCK(p);
1408                                         continue;
1409                                 }
1410                                 break;
1411
1412                         case KERN_PROC_RUID:
1413                                 if (p->p_ucred->cr_ruid != (uid_t)name[0]) {
1414                                         PROC_UNLOCK(p);
1415                                         continue;
1416                                 }
1417                                 break;
1418
1419                         case KERN_PROC_PROC:
1420                                 break;
1421
1422                         default:
1423                                 break;
1424
1425                         }
1426
1427                         error = sysctl_out_proc(p, req, flags, doingzomb);
1428                         if (error) {
1429                                 sx_sunlock(&allproc_lock);
1430                                 return (error);
1431                         }
1432                 }
1433         }
1434         sx_sunlock(&allproc_lock);
1435         return (0);
1436 }
1437
1438 struct pargs *
1439 pargs_alloc(int len)
1440 {
1441         struct pargs *pa;
1442
1443         pa = malloc(sizeof(struct pargs) + len, M_PARGS,
1444                 M_WAITOK);
1445         refcount_init(&pa->ar_ref, 1);
1446         pa->ar_length = len;
1447         return (pa);
1448 }
1449
1450 static void
1451 pargs_free(struct pargs *pa)
1452 {
1453
1454         free(pa, M_PARGS);
1455 }
1456
1457 void
1458 pargs_hold(struct pargs *pa)
1459 {
1460
1461         if (pa == NULL)
1462                 return;
1463         refcount_acquire(&pa->ar_ref);
1464 }
1465
1466 void
1467 pargs_drop(struct pargs *pa)
1468 {
1469
1470         if (pa == NULL)
1471                 return;
1472         if (refcount_release(&pa->ar_ref))
1473                 pargs_free(pa);
1474 }
1475
1476 static int
1477 proc_read_mem(struct thread *td, struct proc *p, vm_offset_t offset, void* buf,
1478     size_t len)
1479 {
1480         struct iovec iov;
1481         struct uio uio;
1482
1483         iov.iov_base = (caddr_t)buf;
1484         iov.iov_len = len;
1485         uio.uio_iov = &iov;
1486         uio.uio_iovcnt = 1;
1487         uio.uio_offset = offset;
1488         uio.uio_resid = (ssize_t)len;
1489         uio.uio_segflg = UIO_SYSSPACE;
1490         uio.uio_rw = UIO_READ;
1491         uio.uio_td = td;
1492
1493         return (proc_rwmem(p, &uio));
1494 }
1495
1496 static int
1497 proc_read_string(struct thread *td, struct proc *p, const char *sptr, char *buf,
1498     size_t len)
1499 {
1500         size_t i;
1501         int error;
1502
1503         error = proc_read_mem(td, p, (vm_offset_t)sptr, buf, len);
1504         /*
1505          * Reading the chunk may validly return EFAULT if the string is shorter
1506          * than the chunk and is aligned at the end of the page, assuming the
1507          * next page is not mapped.  So if EFAULT is returned do a fallback to
1508          * one byte read loop.
1509          */
1510         if (error == EFAULT) {
1511                 for (i = 0; i < len; i++, buf++, sptr++) {
1512                         error = proc_read_mem(td, p, (vm_offset_t)sptr, buf, 1);
1513                         if (error != 0)
1514                                 return (error);
1515                         if (*buf == '\0')
1516                                 break;
1517                 }
1518                 error = 0;
1519         }
1520         return (error);
1521 }
1522
1523 #define PROC_AUXV_MAX   256     /* Safety limit on auxv size. */
1524
1525 enum proc_vector_type {
1526         PROC_ARG,
1527         PROC_ENV,
1528         PROC_AUX,
1529 };
1530
1531 #ifdef COMPAT_FREEBSD32
1532 static int
1533 get_proc_vector32(struct thread *td, struct proc *p, char ***proc_vectorp,
1534     size_t *vsizep, enum proc_vector_type type)
1535 {
1536         struct freebsd32_ps_strings pss;
1537         Elf32_Auxinfo aux;
1538         vm_offset_t vptr, ptr;
1539         uint32_t *proc_vector32;
1540         char **proc_vector;
1541         size_t vsize, size;
1542         int i, error;
1543
1544         error = proc_read_mem(td, p, (vm_offset_t)(p->p_sysent->sv_psstrings),
1545             &pss, sizeof(pss));
1546         if (error != 0)
1547                 return (error);
1548         switch (type) {
1549         case PROC_ARG:
1550                 vptr = (vm_offset_t)PTRIN(pss.ps_argvstr);
1551                 vsize = pss.ps_nargvstr;
1552                 if (vsize > ARG_MAX)
1553                         return (ENOEXEC);
1554                 size = vsize * sizeof(int32_t);
1555                 break;
1556         case PROC_ENV:
1557                 vptr = (vm_offset_t)PTRIN(pss.ps_envstr);
1558                 vsize = pss.ps_nenvstr;
1559                 if (vsize > ARG_MAX)
1560                         return (ENOEXEC);
1561                 size = vsize * sizeof(int32_t);
1562                 break;
1563         case PROC_AUX:
1564                 vptr = (vm_offset_t)PTRIN(pss.ps_envstr) +
1565                     (pss.ps_nenvstr + 1) * sizeof(int32_t);
1566                 if (vptr % 4 != 0)
1567                         return (ENOEXEC);
1568                 for (ptr = vptr, i = 0; i < PROC_AUXV_MAX; i++) {
1569                         error = proc_read_mem(td, p, ptr, &aux, sizeof(aux));
1570                         if (error != 0)
1571                                 return (error);
1572                         if (aux.a_type == AT_NULL)
1573                                 break;
1574                         ptr += sizeof(aux);
1575                 }
1576                 if (aux.a_type != AT_NULL)
1577                         return (ENOEXEC);
1578                 vsize = i + 1;
1579                 size = vsize * sizeof(aux);
1580                 break;
1581         default:
1582                 KASSERT(0, ("Wrong proc vector type: %d", type));
1583                 return (EINVAL);
1584         }
1585         proc_vector32 = malloc(size, M_TEMP, M_WAITOK);
1586         error = proc_read_mem(td, p, vptr, proc_vector32, size);
1587         if (error != 0)
1588                 goto done;
1589         if (type == PROC_AUX) {
1590                 *proc_vectorp = (char **)proc_vector32;
1591                 *vsizep = vsize;
1592                 return (0);
1593         }
1594         proc_vector = malloc(vsize * sizeof(char *), M_TEMP, M_WAITOK);
1595         for (i = 0; i < (int)vsize; i++)
1596                 proc_vector[i] = PTRIN(proc_vector32[i]);
1597         *proc_vectorp = proc_vector;
1598         *vsizep = vsize;
1599 done:
1600         free(proc_vector32, M_TEMP);
1601         return (error);
1602 }
1603 #endif
1604
1605 static int
1606 get_proc_vector(struct thread *td, struct proc *p, char ***proc_vectorp,
1607     size_t *vsizep, enum proc_vector_type type)
1608 {
1609         struct ps_strings pss;
1610         Elf_Auxinfo aux;
1611         vm_offset_t vptr, ptr;
1612         char **proc_vector;
1613         size_t vsize, size;
1614         int error, i;
1615
1616 #ifdef COMPAT_FREEBSD32
1617         if (SV_PROC_FLAG(p, SV_ILP32) != 0)
1618                 return (get_proc_vector32(td, p, proc_vectorp, vsizep, type));
1619 #endif
1620         error = proc_read_mem(td, p, (vm_offset_t)(p->p_sysent->sv_psstrings),
1621             &pss, sizeof(pss));
1622         if (error != 0)
1623                 return (error);
1624         switch (type) {
1625         case PROC_ARG:
1626                 vptr = (vm_offset_t)pss.ps_argvstr;
1627                 vsize = pss.ps_nargvstr;
1628                 if (vsize > ARG_MAX)
1629                         return (ENOEXEC);
1630                 size = vsize * sizeof(char *);
1631                 break;
1632         case PROC_ENV:
1633                 vptr = (vm_offset_t)pss.ps_envstr;
1634                 vsize = pss.ps_nenvstr;
1635                 if (vsize > ARG_MAX)
1636                         return (ENOEXEC);
1637                 size = vsize * sizeof(char *);
1638                 break;
1639         case PROC_AUX:
1640                 /*
1641                  * The aux array is just above env array on the stack. Check
1642                  * that the address is naturally aligned.
1643                  */
1644                 vptr = (vm_offset_t)pss.ps_envstr + (pss.ps_nenvstr + 1)
1645                     * sizeof(char *);
1646 #if __ELF_WORD_SIZE == 64
1647                 if (vptr % sizeof(uint64_t) != 0)
1648 #else
1649                 if (vptr % sizeof(uint32_t) != 0)
1650 #endif
1651                         return (ENOEXEC);
1652                 /*
1653                  * We count the array size reading the aux vectors from the
1654                  * stack until AT_NULL vector is returned.  So (to keep the code
1655                  * simple) we read the process stack twice: the first time here
1656                  * to find the size and the second time when copying the vectors
1657                  * to the allocated proc_vector.
1658                  */
1659                 for (ptr = vptr, i = 0; i < PROC_AUXV_MAX; i++) {
1660                         error = proc_read_mem(td, p, ptr, &aux, sizeof(aux));
1661                         if (error != 0)
1662                                 return (error);
1663                         if (aux.a_type == AT_NULL)
1664                                 break;
1665                         ptr += sizeof(aux);
1666                 }
1667                 /*
1668                  * If the PROC_AUXV_MAX entries are iterated over, and we have
1669                  * not reached AT_NULL, it is most likely we are reading wrong
1670                  * data: either the process doesn't have auxv array or data has
1671                  * been modified. Return the error in this case.
1672                  */
1673                 if (aux.a_type != AT_NULL)
1674                         return (ENOEXEC);
1675                 vsize = i + 1;
1676                 size = vsize * sizeof(aux);
1677                 break;
1678         default:
1679                 KASSERT(0, ("Wrong proc vector type: %d", type));
1680                 return (EINVAL); /* In case we are built without INVARIANTS. */
1681         }
1682         proc_vector = malloc(size, M_TEMP, M_WAITOK);
1683         if (proc_vector == NULL)
1684                 return (ENOMEM);
1685         error = proc_read_mem(td, p, vptr, proc_vector, size);
1686         if (error != 0) {
1687                 free(proc_vector, M_TEMP);
1688                 return (error);
1689         }
1690         *proc_vectorp = proc_vector;
1691         *vsizep = vsize;
1692
1693         return (0);
1694 }
1695
1696 #define GET_PS_STRINGS_CHUNK_SZ 256     /* Chunk size (bytes) for ps_strings operations. */
1697
1698 static int
1699 get_ps_strings(struct thread *td, struct proc *p, struct sbuf *sb,
1700     enum proc_vector_type type)
1701 {
1702         size_t done, len, nchr, vsize;
1703         int error, i;
1704         char **proc_vector, *sptr;
1705         char pss_string[GET_PS_STRINGS_CHUNK_SZ];
1706
1707         PROC_ASSERT_HELD(p);
1708
1709         /*
1710          * We are not going to read more than 2 * (PATH_MAX + ARG_MAX) bytes.
1711          */
1712         nchr = 2 * (PATH_MAX + ARG_MAX);
1713
1714         error = get_proc_vector(td, p, &proc_vector, &vsize, type);
1715         if (error != 0)
1716                 return (error);
1717         for (done = 0, i = 0; i < (int)vsize && done < nchr; i++) {
1718                 /*
1719                  * The program may have scribbled into its argv array, e.g. to
1720                  * remove some arguments.  If that has happened, break out
1721                  * before trying to read from NULL.
1722                  */
1723                 if (proc_vector[i] == NULL)
1724                         break;
1725                 for (sptr = proc_vector[i]; ; sptr += GET_PS_STRINGS_CHUNK_SZ) {
1726                         error = proc_read_string(td, p, sptr, pss_string,
1727                             sizeof(pss_string));
1728                         if (error != 0)
1729                                 goto done;
1730                         len = strnlen(pss_string, GET_PS_STRINGS_CHUNK_SZ);
1731                         if (done + len >= nchr)
1732                                 len = nchr - done - 1;
1733                         sbuf_bcat(sb, pss_string, len);
1734                         if (len != GET_PS_STRINGS_CHUNK_SZ)
1735                                 break;
1736                         done += GET_PS_STRINGS_CHUNK_SZ;
1737                 }
1738                 sbuf_bcat(sb, "", 1);
1739                 done += len + 1;
1740         }
1741 done:
1742         free(proc_vector, M_TEMP);
1743         return (error);
1744 }
1745
1746 int
1747 proc_getargv(struct thread *td, struct proc *p, struct sbuf *sb)
1748 {
1749
1750         return (get_ps_strings(curthread, p, sb, PROC_ARG));
1751 }
1752
1753 int
1754 proc_getenvv(struct thread *td, struct proc *p, struct sbuf *sb)
1755 {
1756
1757         return (get_ps_strings(curthread, p, sb, PROC_ENV));
1758 }
1759
1760 int
1761 proc_getauxv(struct thread *td, struct proc *p, struct sbuf *sb)
1762 {
1763         size_t vsize, size;
1764         char **auxv;
1765         int error;
1766
1767         error = get_proc_vector(td, p, &auxv, &vsize, PROC_AUX);
1768         if (error == 0) {
1769 #ifdef COMPAT_FREEBSD32
1770                 if (SV_PROC_FLAG(p, SV_ILP32) != 0)
1771                         size = vsize * sizeof(Elf32_Auxinfo);
1772                 else
1773 #endif
1774                         size = vsize * sizeof(Elf_Auxinfo);
1775                 if (sbuf_bcat(sb, auxv, size) != 0)
1776                         error = ENOMEM;
1777                 free(auxv, M_TEMP);
1778         }
1779         return (error);
1780 }
1781
1782 /*
1783  * This sysctl allows a process to retrieve the argument list or process
1784  * title for another process without groping around in the address space
1785  * of the other process.  It also allow a process to set its own "process 
1786  * title to a string of its own choice.
1787  */
1788 static int
1789 sysctl_kern_proc_args(SYSCTL_HANDLER_ARGS)
1790 {
1791         int *name = (int *)arg1;
1792         u_int namelen = arg2;
1793         struct pargs *newpa, *pa;
1794         struct proc *p;
1795         struct sbuf sb;
1796         int flags, error = 0, error2;
1797
1798         if (namelen != 1)
1799                 return (EINVAL);
1800
1801         flags = PGET_CANSEE;
1802         if (req->newptr != NULL)
1803                 flags |= PGET_ISCURRENT;
1804         error = pget((pid_t)name[0], flags, &p);
1805         if (error)
1806                 return (error);
1807
1808         pa = p->p_args;
1809         if (pa != NULL) {
1810                 pargs_hold(pa);
1811                 PROC_UNLOCK(p);
1812                 error = SYSCTL_OUT(req, pa->ar_args, pa->ar_length);
1813                 pargs_drop(pa);
1814         } else if ((p->p_flag & (P_WEXIT | P_SYSTEM)) == 0) {
1815                 _PHOLD(p);
1816                 PROC_UNLOCK(p);
1817                 sbuf_new_for_sysctl(&sb, NULL, GET_PS_STRINGS_CHUNK_SZ, req);
1818                 error = proc_getargv(curthread, p, &sb);
1819                 error2 = sbuf_finish(&sb);
1820                 PRELE(p);
1821                 sbuf_delete(&sb);
1822                 if (error == 0 && error2 != 0)
1823                         error = error2;
1824         } else {
1825                 PROC_UNLOCK(p);
1826         }
1827         if (error != 0 || req->newptr == NULL)
1828                 return (error);
1829
1830         if (req->newlen + sizeof(struct pargs) > ps_arg_cache_limit)
1831                 return (ENOMEM);
1832         newpa = pargs_alloc(req->newlen);
1833         error = SYSCTL_IN(req, newpa->ar_args, req->newlen);
1834         if (error != 0) {
1835                 pargs_free(newpa);
1836                 return (error);
1837         }
1838         PROC_LOCK(p);
1839         pa = p->p_args;
1840         p->p_args = newpa;
1841         PROC_UNLOCK(p);
1842         pargs_drop(pa);
1843         return (0);
1844 }
1845
1846 /*
1847  * This sysctl allows a process to retrieve environment of another process.
1848  */
1849 static int
1850 sysctl_kern_proc_env(SYSCTL_HANDLER_ARGS)
1851 {
1852         int *name = (int *)arg1;
1853         u_int namelen = arg2;
1854         struct proc *p;
1855         struct sbuf sb;
1856         int error, error2;
1857
1858         if (namelen != 1)
1859                 return (EINVAL);
1860
1861         error = pget((pid_t)name[0], PGET_WANTREAD, &p);
1862         if (error != 0)
1863                 return (error);
1864         if ((p->p_flag & P_SYSTEM) != 0) {
1865                 PRELE(p);
1866                 return (0);
1867         }
1868
1869         sbuf_new_for_sysctl(&sb, NULL, GET_PS_STRINGS_CHUNK_SZ, req);
1870         error = proc_getenvv(curthread, p, &sb);
1871         error2 = sbuf_finish(&sb);
1872         PRELE(p);
1873         sbuf_delete(&sb);
1874         return (error != 0 ? error : error2);
1875 }
1876
1877 /*
1878  * This sysctl allows a process to retrieve ELF auxiliary vector of
1879  * another process.
1880  */
1881 static int
1882 sysctl_kern_proc_auxv(SYSCTL_HANDLER_ARGS)
1883 {
1884         int *name = (int *)arg1;
1885         u_int namelen = arg2;
1886         struct proc *p;
1887         struct sbuf sb;
1888         int error, error2;
1889
1890         if (namelen != 1)
1891                 return (EINVAL);
1892
1893         error = pget((pid_t)name[0], PGET_WANTREAD, &p);
1894         if (error != 0)
1895                 return (error);
1896         if ((p->p_flag & P_SYSTEM) != 0) {
1897                 PRELE(p);
1898                 return (0);
1899         }
1900         sbuf_new_for_sysctl(&sb, NULL, GET_PS_STRINGS_CHUNK_SZ, req);
1901         error = proc_getauxv(curthread, p, &sb);
1902         error2 = sbuf_finish(&sb);
1903         PRELE(p);
1904         sbuf_delete(&sb);
1905         return (error != 0 ? error : error2);
1906 }
1907
1908 /*
1909  * This sysctl allows a process to retrieve the path of the executable for
1910  * itself or another process.
1911  */
1912 static int
1913 sysctl_kern_proc_pathname(SYSCTL_HANDLER_ARGS)
1914 {
1915         pid_t *pidp = (pid_t *)arg1;
1916         unsigned int arglen = arg2;
1917         struct proc *p;
1918         struct vnode *vp;
1919         char *retbuf, *freebuf;
1920         int error;
1921
1922         if (arglen != 1)
1923                 return (EINVAL);
1924         if (*pidp == -1) {      /* -1 means this process */
1925                 p = req->td->td_proc;
1926         } else {
1927                 error = pget(*pidp, PGET_CANSEE, &p);
1928                 if (error != 0)
1929                         return (error);
1930         }
1931
1932         vp = p->p_textvp;
1933         if (vp == NULL) {
1934                 if (*pidp != -1)
1935                         PROC_UNLOCK(p);
1936                 return (0);
1937         }
1938         vref(vp);
1939         if (*pidp != -1)
1940                 PROC_UNLOCK(p);
1941         error = vn_fullpath(req->td, vp, &retbuf, &freebuf);
1942         vrele(vp);
1943         if (error)
1944                 return (error);
1945         error = SYSCTL_OUT(req, retbuf, strlen(retbuf) + 1);
1946         free(freebuf, M_TEMP);
1947         return (error);
1948 }
1949
1950 static int
1951 sysctl_kern_proc_sv_name(SYSCTL_HANDLER_ARGS)
1952 {
1953         struct proc *p;
1954         char *sv_name;
1955         int *name;
1956         int namelen;
1957         int error;
1958
1959         namelen = arg2;
1960         if (namelen != 1)
1961                 return (EINVAL);
1962
1963         name = (int *)arg1;
1964         error = pget((pid_t)name[0], PGET_CANSEE, &p);
1965         if (error != 0)
1966                 return (error);
1967         sv_name = p->p_sysent->sv_name;
1968         PROC_UNLOCK(p);
1969         return (sysctl_handle_string(oidp, sv_name, 0, req));
1970 }
1971
1972 #ifdef KINFO_OVMENTRY_SIZE
1973 CTASSERT(sizeof(struct kinfo_ovmentry) == KINFO_OVMENTRY_SIZE);
1974 #endif
1975
1976 #ifdef COMPAT_FREEBSD7
1977 static int
1978 sysctl_kern_proc_ovmmap(SYSCTL_HANDLER_ARGS)
1979 {
1980         vm_map_entry_t entry, tmp_entry;
1981         unsigned int last_timestamp;
1982         char *fullpath, *freepath;
1983         struct kinfo_ovmentry *kve;
1984         struct vattr va;
1985         struct ucred *cred;
1986         int error, *name;
1987         struct vnode *vp;
1988         struct proc *p;
1989         vm_map_t map;
1990         struct vmspace *vm;
1991
1992         name = (int *)arg1;
1993         error = pget((pid_t)name[0], PGET_WANTREAD, &p);
1994         if (error != 0)
1995                 return (error);
1996         vm = vmspace_acquire_ref(p);
1997         if (vm == NULL) {
1998                 PRELE(p);
1999                 return (ESRCH);
2000         }
2001         kve = malloc(sizeof(*kve), M_TEMP, M_WAITOK);
2002
2003         map = &vm->vm_map;
2004         vm_map_lock_read(map);
2005         for (entry = map->header.next; entry != &map->header;
2006             entry = entry->next) {
2007                 vm_object_t obj, tobj, lobj;
2008                 vm_offset_t addr;
2009
2010                 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
2011                         continue;
2012
2013                 bzero(kve, sizeof(*kve));
2014                 kve->kve_structsize = sizeof(*kve);
2015
2016                 kve->kve_private_resident = 0;
2017                 obj = entry->object.vm_object;
2018                 if (obj != NULL) {
2019                         VM_OBJECT_RLOCK(obj);
2020                         if (obj->shadow_count == 1)
2021                                 kve->kve_private_resident =
2022                                     obj->resident_page_count;
2023                 }
2024                 kve->kve_resident = 0;
2025                 addr = entry->start;
2026                 while (addr < entry->end) {
2027                         if (pmap_extract(map->pmap, addr))
2028                                 kve->kve_resident++;
2029                         addr += PAGE_SIZE;
2030                 }
2031
2032                 for (lobj = tobj = obj; tobj; tobj = tobj->backing_object) {
2033                         if (tobj != obj)
2034                                 VM_OBJECT_RLOCK(tobj);
2035                         if (lobj != obj)
2036                                 VM_OBJECT_RUNLOCK(lobj);
2037                         lobj = tobj;
2038                 }
2039
2040                 kve->kve_start = (void*)entry->start;
2041                 kve->kve_end = (void*)entry->end;
2042                 kve->kve_offset = (off_t)entry->offset;
2043
2044                 if (entry->protection & VM_PROT_READ)
2045                         kve->kve_protection |= KVME_PROT_READ;
2046                 if (entry->protection & VM_PROT_WRITE)
2047                         kve->kve_protection |= KVME_PROT_WRITE;
2048                 if (entry->protection & VM_PROT_EXECUTE)
2049                         kve->kve_protection |= KVME_PROT_EXEC;
2050
2051                 if (entry->eflags & MAP_ENTRY_COW)
2052                         kve->kve_flags |= KVME_FLAG_COW;
2053                 if (entry->eflags & MAP_ENTRY_NEEDS_COPY)
2054                         kve->kve_flags |= KVME_FLAG_NEEDS_COPY;
2055                 if (entry->eflags & MAP_ENTRY_NOCOREDUMP)
2056                         kve->kve_flags |= KVME_FLAG_NOCOREDUMP;
2057
2058                 last_timestamp = map->timestamp;
2059                 vm_map_unlock_read(map);
2060
2061                 kve->kve_fileid = 0;
2062                 kve->kve_fsid = 0;
2063                 freepath = NULL;
2064                 fullpath = "";
2065                 if (lobj) {
2066                         vp = NULL;
2067                         switch (lobj->type) {
2068                         case OBJT_DEFAULT:
2069                                 kve->kve_type = KVME_TYPE_DEFAULT;
2070                                 break;
2071                         case OBJT_VNODE:
2072                                 kve->kve_type = KVME_TYPE_VNODE;
2073                                 vp = lobj->handle;
2074                                 vref(vp);
2075                                 break;
2076                         case OBJT_SWAP:
2077                                 if ((lobj->flags & OBJ_TMPFS_NODE) != 0) {
2078                                         kve->kve_type = KVME_TYPE_VNODE;
2079                                         if ((lobj->flags & OBJ_TMPFS) != 0) {
2080                                                 vp = lobj->un_pager.swp.swp_tmpfs;
2081                                                 vref(vp);
2082                                         }
2083                                 } else {
2084                                         kve->kve_type = KVME_TYPE_SWAP;
2085                                 }
2086                                 break;
2087                         case OBJT_DEVICE:
2088                                 kve->kve_type = KVME_TYPE_DEVICE;
2089                                 break;
2090                         case OBJT_PHYS:
2091                                 kve->kve_type = KVME_TYPE_PHYS;
2092                                 break;
2093                         case OBJT_DEAD:
2094                                 kve->kve_type = KVME_TYPE_DEAD;
2095                                 break;
2096                         case OBJT_SG:
2097                                 kve->kve_type = KVME_TYPE_SG;
2098                                 break;
2099                         default:
2100                                 kve->kve_type = KVME_TYPE_UNKNOWN;
2101                                 break;
2102                         }
2103                         if (lobj != obj)
2104                                 VM_OBJECT_RUNLOCK(lobj);
2105
2106                         kve->kve_ref_count = obj->ref_count;
2107                         kve->kve_shadow_count = obj->shadow_count;
2108                         VM_OBJECT_RUNLOCK(obj);
2109                         if (vp != NULL) {
2110                                 vn_fullpath(curthread, vp, &fullpath,
2111                                     &freepath);
2112                                 cred = curthread->td_ucred;
2113                                 vn_lock(vp, LK_SHARED | LK_RETRY);
2114                                 if (VOP_GETATTR(vp, &va, cred) == 0) {
2115                                         kve->kve_fileid = va.va_fileid;
2116                                         kve->kve_fsid = va.va_fsid;
2117                                 }
2118                                 vput(vp);
2119                         }
2120                 } else {
2121                         kve->kve_type = KVME_TYPE_NONE;
2122                         kve->kve_ref_count = 0;
2123                         kve->kve_shadow_count = 0;
2124                 }
2125
2126                 strlcpy(kve->kve_path, fullpath, sizeof(kve->kve_path));
2127                 if (freepath != NULL)
2128                         free(freepath, M_TEMP);
2129
2130                 error = SYSCTL_OUT(req, kve, sizeof(*kve));
2131                 vm_map_lock_read(map);
2132                 if (error)
2133                         break;
2134                 if (last_timestamp != map->timestamp) {
2135                         vm_map_lookup_entry(map, addr - 1, &tmp_entry);
2136                         entry = tmp_entry;
2137                 }
2138         }
2139         vm_map_unlock_read(map);
2140         vmspace_free(vm);
2141         PRELE(p);
2142         free(kve, M_TEMP);
2143         return (error);
2144 }
2145 #endif  /* COMPAT_FREEBSD7 */
2146
2147 #ifdef KINFO_VMENTRY_SIZE
2148 CTASSERT(sizeof(struct kinfo_vmentry) == KINFO_VMENTRY_SIZE);
2149 #endif
2150
2151 static void
2152 kern_proc_vmmap_resident(vm_map_t map, vm_map_entry_t entry,
2153     struct kinfo_vmentry *kve)
2154 {
2155         vm_object_t obj, tobj;
2156         vm_page_t m, m_adv;
2157         vm_offset_t addr;
2158         vm_paddr_t locked_pa;
2159         vm_pindex_t pi, pi_adv, pindex;
2160
2161         locked_pa = 0;
2162         obj = entry->object.vm_object;
2163         addr = entry->start;
2164         m_adv = NULL;
2165         pi = OFF_TO_IDX(entry->offset);
2166         for (; addr < entry->end; addr += IDX_TO_OFF(pi_adv), pi += pi_adv) {
2167                 if (m_adv != NULL) {
2168                         m = m_adv;
2169                 } else {
2170                         pi_adv = OFF_TO_IDX(entry->end - addr);
2171                         pindex = pi;
2172                         for (tobj = obj;; tobj = tobj->backing_object) {
2173                                 m = vm_page_find_least(tobj, pindex);
2174                                 if (m != NULL) {
2175                                         if (m->pindex == pindex)
2176                                                 break;
2177                                         if (pi_adv > m->pindex - pindex) {
2178                                                 pi_adv = m->pindex - pindex;
2179                                                 m_adv = m;
2180                                         }
2181                                 }
2182                                 if (tobj->backing_object == NULL)
2183                                         goto next;
2184                                 pindex += OFF_TO_IDX(tobj->
2185                                     backing_object_offset);
2186                         }
2187                 }
2188                 m_adv = NULL;
2189                 if (m->psind != 0 && addr + pagesizes[1] <= entry->end &&
2190                     (addr & (pagesizes[1] - 1)) == 0 &&
2191                     (pmap_mincore(map->pmap, addr, &locked_pa) &
2192                     MINCORE_SUPER) != 0) {
2193                         kve->kve_flags |= KVME_FLAG_SUPER;
2194                         pi_adv = OFF_TO_IDX(pagesizes[1]);
2195                 } else {
2196                         /*
2197                          * We do not test the found page on validity.
2198                          * Either the page is busy and being paged in,
2199                          * or it was invalidated.  The first case
2200                          * should be counted as resident, the second
2201                          * is not so clear; we do account both.
2202                          */
2203                         pi_adv = 1;
2204                 }
2205                 kve->kve_resident += pi_adv;
2206 next:;
2207         }
2208         PA_UNLOCK_COND(locked_pa);
2209 }
2210
2211 /*
2212  * Must be called with the process locked and will return unlocked.
2213  */
2214 int
2215 kern_proc_vmmap_out(struct proc *p, struct sbuf *sb)
2216 {
2217         vm_map_entry_t entry, tmp_entry;
2218         struct vattr va;
2219         vm_map_t map;
2220         vm_object_t obj, tobj, lobj;
2221         char *fullpath, *freepath;
2222         struct kinfo_vmentry *kve;
2223         struct ucred *cred;
2224         struct vnode *vp;
2225         struct vmspace *vm;
2226         vm_offset_t addr;
2227         unsigned int last_timestamp;
2228         int error;
2229
2230         PROC_LOCK_ASSERT(p, MA_OWNED);
2231
2232         _PHOLD(p);
2233         PROC_UNLOCK(p);
2234         vm = vmspace_acquire_ref(p);
2235         if (vm == NULL) {
2236                 PRELE(p);
2237                 return (ESRCH);
2238         }
2239         kve = malloc(sizeof(*kve), M_TEMP, M_WAITOK);
2240
2241         error = 0;
2242         map = &vm->vm_map;
2243         vm_map_lock_read(map);
2244         for (entry = map->header.next; entry != &map->header;
2245             entry = entry->next) {
2246                 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
2247                         continue;
2248
2249                 addr = entry->end;
2250                 bzero(kve, sizeof(*kve));
2251                 obj = entry->object.vm_object;
2252                 if (obj != NULL) {
2253                         for (tobj = obj; tobj != NULL;
2254                             tobj = tobj->backing_object) {
2255                                 VM_OBJECT_RLOCK(tobj);
2256                                 lobj = tobj;
2257                         }
2258                         if (obj->backing_object == NULL)
2259                                 kve->kve_private_resident =
2260                                     obj->resident_page_count;
2261                         if (!vmmap_skip_res_cnt)
2262                                 kern_proc_vmmap_resident(map, entry, kve);
2263                         for (tobj = obj; tobj != NULL;
2264                             tobj = tobj->backing_object) {
2265                                 if (tobj != obj && tobj != lobj)
2266                                         VM_OBJECT_RUNLOCK(tobj);
2267                         }
2268                 } else {
2269                         lobj = NULL;
2270                 }
2271
2272                 kve->kve_start = entry->start;
2273                 kve->kve_end = entry->end;
2274                 kve->kve_offset = entry->offset;
2275
2276                 if (entry->protection & VM_PROT_READ)
2277                         kve->kve_protection |= KVME_PROT_READ;
2278                 if (entry->protection & VM_PROT_WRITE)
2279                         kve->kve_protection |= KVME_PROT_WRITE;
2280                 if (entry->protection & VM_PROT_EXECUTE)
2281                         kve->kve_protection |= KVME_PROT_EXEC;
2282
2283                 if (entry->eflags & MAP_ENTRY_COW)
2284                         kve->kve_flags |= KVME_FLAG_COW;
2285                 if (entry->eflags & MAP_ENTRY_NEEDS_COPY)
2286                         kve->kve_flags |= KVME_FLAG_NEEDS_COPY;
2287                 if (entry->eflags & MAP_ENTRY_NOCOREDUMP)
2288                         kve->kve_flags |= KVME_FLAG_NOCOREDUMP;
2289                 if (entry->eflags & MAP_ENTRY_GROWS_UP)
2290                         kve->kve_flags |= KVME_FLAG_GROWS_UP;
2291                 if (entry->eflags & MAP_ENTRY_GROWS_DOWN)
2292                         kve->kve_flags |= KVME_FLAG_GROWS_DOWN;
2293
2294                 last_timestamp = map->timestamp;
2295                 vm_map_unlock_read(map);
2296
2297                 freepath = NULL;
2298                 fullpath = "";
2299                 if (lobj != NULL) {
2300                         vp = NULL;
2301                         switch (lobj->type) {
2302                         case OBJT_DEFAULT:
2303                                 kve->kve_type = KVME_TYPE_DEFAULT;
2304                                 break;
2305                         case OBJT_VNODE:
2306                                 kve->kve_type = KVME_TYPE_VNODE;
2307                                 vp = lobj->handle;
2308                                 vref(vp);
2309                                 break;
2310                         case OBJT_SWAP:
2311                                 if ((lobj->flags & OBJ_TMPFS_NODE) != 0) {
2312                                         kve->kve_type = KVME_TYPE_VNODE;
2313                                         if ((lobj->flags & OBJ_TMPFS) != 0) {
2314                                                 vp = lobj->un_pager.swp.swp_tmpfs;
2315                                                 vref(vp);
2316                                         }
2317                                 } else {
2318                                         kve->kve_type = KVME_TYPE_SWAP;
2319                                 }
2320                                 break;
2321                         case OBJT_DEVICE:
2322                                 kve->kve_type = KVME_TYPE_DEVICE;
2323                                 break;
2324                         case OBJT_PHYS:
2325                                 kve->kve_type = KVME_TYPE_PHYS;
2326                                 break;
2327                         case OBJT_DEAD:
2328                                 kve->kve_type = KVME_TYPE_DEAD;
2329                                 break;
2330                         case OBJT_SG:
2331                                 kve->kve_type = KVME_TYPE_SG;
2332                                 break;
2333                         case OBJT_MGTDEVICE:
2334                                 kve->kve_type = KVME_TYPE_MGTDEVICE;
2335                                 break;
2336                         default:
2337                                 kve->kve_type = KVME_TYPE_UNKNOWN;
2338                                 break;
2339                         }
2340                         if (lobj != obj)
2341                                 VM_OBJECT_RUNLOCK(lobj);
2342
2343                         kve->kve_ref_count = obj->ref_count;
2344                         kve->kve_shadow_count = obj->shadow_count;
2345                         VM_OBJECT_RUNLOCK(obj);
2346                         if (vp != NULL) {
2347                                 vn_fullpath(curthread, vp, &fullpath,
2348                                     &freepath);
2349                                 kve->kve_vn_type = vntype_to_kinfo(vp->v_type);
2350                                 cred = curthread->td_ucred;
2351                                 vn_lock(vp, LK_SHARED | LK_RETRY);
2352                                 if (VOP_GETATTR(vp, &va, cred) == 0) {
2353                                         kve->kve_vn_fileid = va.va_fileid;
2354                                         kve->kve_vn_fsid = va.va_fsid;
2355                                         kve->kve_vn_mode =
2356                                             MAKEIMODE(va.va_type, va.va_mode);
2357                                         kve->kve_vn_size = va.va_size;
2358                                         kve->kve_vn_rdev = va.va_rdev;
2359                                         kve->kve_status = KF_ATTR_VALID;
2360                                 }
2361                                 vput(vp);
2362                         }
2363                 } else {
2364                         kve->kve_type = KVME_TYPE_NONE;
2365                         kve->kve_ref_count = 0;
2366                         kve->kve_shadow_count = 0;
2367                 }
2368
2369                 strlcpy(kve->kve_path, fullpath, sizeof(kve->kve_path));
2370                 if (freepath != NULL)
2371                         free(freepath, M_TEMP);
2372
2373                 /* Pack record size down */
2374                 kve->kve_structsize = offsetof(struct kinfo_vmentry, kve_path) +
2375                     strlen(kve->kve_path) + 1;
2376                 kve->kve_structsize = roundup(kve->kve_structsize,
2377                     sizeof(uint64_t));
2378                 if (sbuf_bcat(sb, kve, kve->kve_structsize) != 0)
2379                         error = ENOMEM;
2380                 vm_map_lock_read(map);
2381                 if (error != 0)
2382                         break;
2383                 if (last_timestamp != map->timestamp) {
2384                         vm_map_lookup_entry(map, addr - 1, &tmp_entry);
2385                         entry = tmp_entry;
2386                 }
2387         }
2388         vm_map_unlock_read(map);
2389         vmspace_free(vm);
2390         PRELE(p);
2391         free(kve, M_TEMP);
2392         return (error);
2393 }
2394
2395 static int
2396 sysctl_kern_proc_vmmap(SYSCTL_HANDLER_ARGS)
2397 {
2398         struct proc *p;
2399         struct sbuf sb;
2400         int error, error2, *name;
2401
2402         name = (int *)arg1;
2403         sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_vmentry), req);
2404         error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
2405         if (error != 0) {
2406                 sbuf_delete(&sb);
2407                 return (error);
2408         }
2409         error = kern_proc_vmmap_out(p, &sb);
2410         error2 = sbuf_finish(&sb);
2411         sbuf_delete(&sb);
2412         return (error != 0 ? error : error2);
2413 }
2414
2415 #if defined(STACK) || defined(DDB)
2416 static int
2417 sysctl_kern_proc_kstack(SYSCTL_HANDLER_ARGS)
2418 {
2419         struct kinfo_kstack *kkstp;
2420         int error, i, *name, numthreads;
2421         lwpid_t *lwpidarray;
2422         struct thread *td;
2423         struct stack *st;
2424         struct sbuf sb;
2425         struct proc *p;
2426
2427         name = (int *)arg1;
2428         error = pget((pid_t)name[0], PGET_NOTINEXEC | PGET_WANTREAD, &p);
2429         if (error != 0)
2430                 return (error);
2431
2432         kkstp = malloc(sizeof(*kkstp), M_TEMP, M_WAITOK);
2433         st = stack_create();
2434
2435         lwpidarray = NULL;
2436         numthreads = 0;
2437         PROC_LOCK(p);
2438 repeat:
2439         if (numthreads < p->p_numthreads) {
2440                 if (lwpidarray != NULL) {
2441                         free(lwpidarray, M_TEMP);
2442                         lwpidarray = NULL;
2443                 }
2444                 numthreads = p->p_numthreads;
2445                 PROC_UNLOCK(p);
2446                 lwpidarray = malloc(sizeof(*lwpidarray) * numthreads, M_TEMP,
2447                     M_WAITOK | M_ZERO);
2448                 PROC_LOCK(p);
2449                 goto repeat;
2450         }
2451         i = 0;
2452
2453         /*
2454          * XXXRW: During the below loop, execve(2) and countless other sorts
2455          * of changes could have taken place.  Should we check to see if the
2456          * vmspace has been replaced, or the like, in order to prevent
2457          * giving a snapshot that spans, say, execve(2), with some threads
2458          * before and some after?  Among other things, the credentials could
2459          * have changed, in which case the right to extract debug info might
2460          * no longer be assured.
2461          */
2462         FOREACH_THREAD_IN_PROC(p, td) {
2463                 KASSERT(i < numthreads,
2464                     ("sysctl_kern_proc_kstack: numthreads"));
2465                 lwpidarray[i] = td->td_tid;
2466                 i++;
2467         }
2468         numthreads = i;
2469         for (i = 0; i < numthreads; i++) {
2470                 td = thread_find(p, lwpidarray[i]);
2471                 if (td == NULL) {
2472                         continue;
2473                 }
2474                 bzero(kkstp, sizeof(*kkstp));
2475                 (void)sbuf_new(&sb, kkstp->kkst_trace,
2476                     sizeof(kkstp->kkst_trace), SBUF_FIXEDLEN);
2477                 thread_lock(td);
2478                 kkstp->kkst_tid = td->td_tid;
2479                 if (TD_IS_SWAPPED(td))
2480                         kkstp->kkst_state = KKST_STATE_SWAPPED;
2481                 else if (TD_IS_RUNNING(td))
2482                         kkstp->kkst_state = KKST_STATE_RUNNING;
2483                 else {
2484                         kkstp->kkst_state = KKST_STATE_STACKOK;
2485                         stack_save_td(st, td);
2486                 }
2487                 thread_unlock(td);
2488                 PROC_UNLOCK(p);
2489                 stack_sbuf_print(&sb, st);
2490                 sbuf_finish(&sb);
2491                 sbuf_delete(&sb);
2492                 error = SYSCTL_OUT(req, kkstp, sizeof(*kkstp));
2493                 PROC_LOCK(p);
2494                 if (error)
2495                         break;
2496         }
2497         _PRELE(p);
2498         PROC_UNLOCK(p);
2499         if (lwpidarray != NULL)
2500                 free(lwpidarray, M_TEMP);
2501         stack_destroy(st);
2502         free(kkstp, M_TEMP);
2503         return (error);
2504 }
2505 #endif
2506
2507 /*
2508  * This sysctl allows a process to retrieve the full list of groups from
2509  * itself or another process.
2510  */
2511 static int
2512 sysctl_kern_proc_groups(SYSCTL_HANDLER_ARGS)
2513 {
2514         pid_t *pidp = (pid_t *)arg1;
2515         unsigned int arglen = arg2;
2516         struct proc *p;
2517         struct ucred *cred;
2518         int error;
2519
2520         if (arglen != 1)
2521                 return (EINVAL);
2522         if (*pidp == -1) {      /* -1 means this process */
2523                 p = req->td->td_proc;
2524         } else {
2525                 error = pget(*pidp, PGET_CANSEE, &p);
2526                 if (error != 0)
2527                         return (error);
2528         }
2529
2530         cred = crhold(p->p_ucred);
2531         if (*pidp != -1)
2532                 PROC_UNLOCK(p);
2533
2534         error = SYSCTL_OUT(req, cred->cr_groups,
2535             cred->cr_ngroups * sizeof(gid_t));
2536         crfree(cred);
2537         return (error);
2538 }
2539
2540 /*
2541  * This sysctl allows a process to retrieve or/and set the resource limit for
2542  * another process.
2543  */
2544 static int
2545 sysctl_kern_proc_rlimit(SYSCTL_HANDLER_ARGS)
2546 {
2547         int *name = (int *)arg1;
2548         u_int namelen = arg2;
2549         struct rlimit rlim;
2550         struct proc *p;
2551         u_int which;
2552         int flags, error;
2553
2554         if (namelen != 2)
2555                 return (EINVAL);
2556
2557         which = (u_int)name[1];
2558         if (which >= RLIM_NLIMITS)
2559                 return (EINVAL);
2560
2561         if (req->newptr != NULL && req->newlen != sizeof(rlim))
2562                 return (EINVAL);
2563
2564         flags = PGET_HOLD | PGET_NOTWEXIT;
2565         if (req->newptr != NULL)
2566                 flags |= PGET_CANDEBUG;
2567         else
2568                 flags |= PGET_CANSEE;
2569         error = pget((pid_t)name[0], flags, &p);
2570         if (error != 0)
2571                 return (error);
2572
2573         /*
2574          * Retrieve limit.
2575          */
2576         if (req->oldptr != NULL) {
2577                 PROC_LOCK(p);
2578                 lim_rlimit(p, which, &rlim);
2579                 PROC_UNLOCK(p);
2580         }
2581         error = SYSCTL_OUT(req, &rlim, sizeof(rlim));
2582         if (error != 0)
2583                 goto errout;
2584
2585         /*
2586          * Set limit.
2587          */
2588         if (req->newptr != NULL) {
2589                 error = SYSCTL_IN(req, &rlim, sizeof(rlim));
2590                 if (error == 0)
2591                         error = kern_proc_setrlimit(curthread, p, which, &rlim);
2592         }
2593
2594 errout:
2595         PRELE(p);
2596         return (error);
2597 }
2598
2599 /*
2600  * This sysctl allows a process to retrieve ps_strings structure location of
2601  * another process.
2602  */
2603 static int
2604 sysctl_kern_proc_ps_strings(SYSCTL_HANDLER_ARGS)
2605 {
2606         int *name = (int *)arg1;
2607         u_int namelen = arg2;
2608         struct proc *p;
2609         vm_offset_t ps_strings;
2610         int error;
2611 #ifdef COMPAT_FREEBSD32
2612         uint32_t ps_strings32;
2613 #endif
2614
2615         if (namelen != 1)
2616                 return (EINVAL);
2617
2618         error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
2619         if (error != 0)
2620                 return (error);
2621 #ifdef COMPAT_FREEBSD32
2622         if ((req->flags & SCTL_MASK32) != 0) {
2623                 /*
2624                  * We return 0 if the 32 bit emulation request is for a 64 bit
2625                  * process.
2626                  */
2627                 ps_strings32 = SV_PROC_FLAG(p, SV_ILP32) != 0 ?
2628                     PTROUT(p->p_sysent->sv_psstrings) : 0;
2629                 PROC_UNLOCK(p);
2630                 error = SYSCTL_OUT(req, &ps_strings32, sizeof(ps_strings32));
2631                 return (error);
2632         }
2633 #endif
2634         ps_strings = p->p_sysent->sv_psstrings;
2635         PROC_UNLOCK(p);
2636         error = SYSCTL_OUT(req, &ps_strings, sizeof(ps_strings));
2637         return (error);
2638 }
2639
2640 /*
2641  * This sysctl allows a process to retrieve umask of another process.
2642  */
2643 static int
2644 sysctl_kern_proc_umask(SYSCTL_HANDLER_ARGS)
2645 {
2646         int *name = (int *)arg1;
2647         u_int namelen = arg2;
2648         struct proc *p;
2649         int error;
2650         u_short fd_cmask;
2651
2652         if (namelen != 1)
2653                 return (EINVAL);
2654
2655         error = pget((pid_t)name[0], PGET_WANTREAD, &p);
2656         if (error != 0)
2657                 return (error);
2658
2659         FILEDESC_SLOCK(p->p_fd);
2660         fd_cmask = p->p_fd->fd_cmask;
2661         FILEDESC_SUNLOCK(p->p_fd);
2662         PRELE(p);
2663         error = SYSCTL_OUT(req, &fd_cmask, sizeof(fd_cmask));
2664         return (error);
2665 }
2666
2667 /*
2668  * This sysctl allows a process to set and retrieve binary osreldate of
2669  * another process.
2670  */
2671 static int
2672 sysctl_kern_proc_osrel(SYSCTL_HANDLER_ARGS)
2673 {
2674         int *name = (int *)arg1;
2675         u_int namelen = arg2;
2676         struct proc *p;
2677         int flags, error, osrel;
2678
2679         if (namelen != 1)
2680                 return (EINVAL);
2681
2682         if (req->newptr != NULL && req->newlen != sizeof(osrel))
2683                 return (EINVAL);
2684
2685         flags = PGET_HOLD | PGET_NOTWEXIT;
2686         if (req->newptr != NULL)
2687                 flags |= PGET_CANDEBUG;
2688         else
2689                 flags |= PGET_CANSEE;
2690         error = pget((pid_t)name[0], flags, &p);
2691         if (error != 0)
2692                 return (error);
2693
2694         error = SYSCTL_OUT(req, &p->p_osrel, sizeof(p->p_osrel));
2695         if (error != 0)
2696                 goto errout;
2697
2698         if (req->newptr != NULL) {
2699                 error = SYSCTL_IN(req, &osrel, sizeof(osrel));
2700                 if (error != 0)
2701                         goto errout;
2702                 if (osrel < 0) {
2703                         error = EINVAL;
2704                         goto errout;
2705                 }
2706                 p->p_osrel = osrel;
2707         }
2708 errout:
2709         PRELE(p);
2710         return (error);
2711 }
2712
2713 static int
2714 sysctl_kern_proc_sigtramp(SYSCTL_HANDLER_ARGS)
2715 {
2716         int *name = (int *)arg1;
2717         u_int namelen = arg2;
2718         struct proc *p;
2719         struct kinfo_sigtramp kst;
2720         const struct sysentvec *sv;
2721         int error;
2722 #ifdef COMPAT_FREEBSD32
2723         struct kinfo_sigtramp32 kst32;
2724 #endif
2725
2726         if (namelen != 1)
2727                 return (EINVAL);
2728
2729         error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
2730         if (error != 0)
2731                 return (error);
2732         sv = p->p_sysent;
2733 #ifdef COMPAT_FREEBSD32
2734         if ((req->flags & SCTL_MASK32) != 0) {
2735                 bzero(&kst32, sizeof(kst32));
2736                 if (SV_PROC_FLAG(p, SV_ILP32)) {
2737                         if (sv->sv_sigcode_base != 0) {
2738                                 kst32.ksigtramp_start = sv->sv_sigcode_base;
2739                                 kst32.ksigtramp_end = sv->sv_sigcode_base +
2740                                     *sv->sv_szsigcode;
2741                         } else {
2742                                 kst32.ksigtramp_start = sv->sv_psstrings -
2743                                     *sv->sv_szsigcode;
2744                                 kst32.ksigtramp_end = sv->sv_psstrings;
2745                         }
2746                 }
2747                 PROC_UNLOCK(p);
2748                 error = SYSCTL_OUT(req, &kst32, sizeof(kst32));
2749                 return (error);
2750         }
2751 #endif
2752         bzero(&kst, sizeof(kst));
2753         if (sv->sv_sigcode_base != 0) {
2754                 kst.ksigtramp_start = (char *)sv->sv_sigcode_base;
2755                 kst.ksigtramp_end = (char *)sv->sv_sigcode_base +
2756                     *sv->sv_szsigcode;
2757         } else {
2758                 kst.ksigtramp_start = (char *)sv->sv_psstrings -
2759                     *sv->sv_szsigcode;
2760                 kst.ksigtramp_end = (char *)sv->sv_psstrings;
2761         }
2762         PROC_UNLOCK(p);
2763         error = SYSCTL_OUT(req, &kst, sizeof(kst));
2764         return (error);
2765 }
2766
2767 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD,  0, "Process table");
2768
2769 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all, CTLFLAG_RD|CTLTYPE_STRUCT|
2770         CTLFLAG_MPSAFE, 0, 0, sysctl_kern_proc, "S,proc",
2771         "Return entire process table");
2772
2773 static SYSCTL_NODE(_kern_proc, KERN_PROC_GID, gid, CTLFLAG_RD | CTLFLAG_MPSAFE,
2774         sysctl_kern_proc, "Process table");
2775
2776 static SYSCTL_NODE(_kern_proc, KERN_PROC_PGRP, pgrp, CTLFLAG_RD | CTLFLAG_MPSAFE,
2777         sysctl_kern_proc, "Process table");
2778
2779 static SYSCTL_NODE(_kern_proc, KERN_PROC_RGID, rgid, CTLFLAG_RD | CTLFLAG_MPSAFE,
2780         sysctl_kern_proc, "Process table");
2781
2782 static SYSCTL_NODE(_kern_proc, KERN_PROC_SESSION, sid, CTLFLAG_RD |
2783         CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2784
2785 static SYSCTL_NODE(_kern_proc, KERN_PROC_TTY, tty, CTLFLAG_RD | CTLFLAG_MPSAFE,
2786         sysctl_kern_proc, "Process table");
2787
2788 static SYSCTL_NODE(_kern_proc, KERN_PROC_UID, uid, CTLFLAG_RD | CTLFLAG_MPSAFE,
2789         sysctl_kern_proc, "Process table");
2790
2791 static SYSCTL_NODE(_kern_proc, KERN_PROC_RUID, ruid, CTLFLAG_RD | CTLFLAG_MPSAFE,
2792         sysctl_kern_proc, "Process table");
2793
2794 static SYSCTL_NODE(_kern_proc, KERN_PROC_PID, pid, CTLFLAG_RD | CTLFLAG_MPSAFE,
2795         sysctl_kern_proc, "Process table");
2796
2797 static SYSCTL_NODE(_kern_proc, KERN_PROC_PROC, proc, CTLFLAG_RD | CTLFLAG_MPSAFE,
2798         sysctl_kern_proc, "Return process table, no threads");
2799
2800 static SYSCTL_NODE(_kern_proc, KERN_PROC_ARGS, args,
2801         CTLFLAG_RW | CTLFLAG_CAPWR | CTLFLAG_ANYBODY | CTLFLAG_MPSAFE,
2802         sysctl_kern_proc_args, "Process argument list");
2803
2804 static SYSCTL_NODE(_kern_proc, KERN_PROC_ENV, env, CTLFLAG_RD | CTLFLAG_MPSAFE,
2805         sysctl_kern_proc_env, "Process environment");
2806
2807 static SYSCTL_NODE(_kern_proc, KERN_PROC_AUXV, auxv, CTLFLAG_RD |
2808         CTLFLAG_MPSAFE, sysctl_kern_proc_auxv, "Process ELF auxiliary vector");
2809
2810 static SYSCTL_NODE(_kern_proc, KERN_PROC_PATHNAME, pathname, CTLFLAG_RD |
2811         CTLFLAG_MPSAFE, sysctl_kern_proc_pathname, "Process executable path");
2812
2813 static SYSCTL_NODE(_kern_proc, KERN_PROC_SV_NAME, sv_name, CTLFLAG_RD |
2814         CTLFLAG_MPSAFE, sysctl_kern_proc_sv_name,
2815         "Process syscall vector name (ABI type)");
2816
2817 static SYSCTL_NODE(_kern_proc, (KERN_PROC_GID | KERN_PROC_INC_THREAD), gid_td,
2818         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2819
2820 static SYSCTL_NODE(_kern_proc, (KERN_PROC_PGRP | KERN_PROC_INC_THREAD), pgrp_td,
2821         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2822
2823 static SYSCTL_NODE(_kern_proc, (KERN_PROC_RGID | KERN_PROC_INC_THREAD), rgid_td,
2824         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2825
2826 static SYSCTL_NODE(_kern_proc, (KERN_PROC_SESSION | KERN_PROC_INC_THREAD),
2827         sid_td, CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2828
2829 static SYSCTL_NODE(_kern_proc, (KERN_PROC_TTY | KERN_PROC_INC_THREAD), tty_td,
2830         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2831
2832 static SYSCTL_NODE(_kern_proc, (KERN_PROC_UID | KERN_PROC_INC_THREAD), uid_td,
2833         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2834
2835 static SYSCTL_NODE(_kern_proc, (KERN_PROC_RUID | KERN_PROC_INC_THREAD), ruid_td,
2836         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2837
2838 static SYSCTL_NODE(_kern_proc, (KERN_PROC_PID | KERN_PROC_INC_THREAD), pid_td,
2839         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2840
2841 static SYSCTL_NODE(_kern_proc, (KERN_PROC_PROC | KERN_PROC_INC_THREAD), proc_td,
2842         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc,
2843         "Return process table, no threads");
2844
2845 #ifdef COMPAT_FREEBSD7
2846 static SYSCTL_NODE(_kern_proc, KERN_PROC_OVMMAP, ovmmap, CTLFLAG_RD |
2847         CTLFLAG_MPSAFE, sysctl_kern_proc_ovmmap, "Old Process vm map entries");
2848 #endif
2849
2850 static SYSCTL_NODE(_kern_proc, KERN_PROC_VMMAP, vmmap, CTLFLAG_RD |
2851         CTLFLAG_MPSAFE, sysctl_kern_proc_vmmap, "Process vm map entries");
2852
2853 #if defined(STACK) || defined(DDB)
2854 static SYSCTL_NODE(_kern_proc, KERN_PROC_KSTACK, kstack, CTLFLAG_RD |
2855         CTLFLAG_MPSAFE, sysctl_kern_proc_kstack, "Process kernel stacks");
2856 #endif
2857
2858 static SYSCTL_NODE(_kern_proc, KERN_PROC_GROUPS, groups, CTLFLAG_RD |
2859         CTLFLAG_MPSAFE, sysctl_kern_proc_groups, "Process groups");
2860
2861 static SYSCTL_NODE(_kern_proc, KERN_PROC_RLIMIT, rlimit, CTLFLAG_RW |
2862         CTLFLAG_ANYBODY | CTLFLAG_MPSAFE, sysctl_kern_proc_rlimit,
2863         "Process resource limits");
2864
2865 static SYSCTL_NODE(_kern_proc, KERN_PROC_PS_STRINGS, ps_strings, CTLFLAG_RD |
2866         CTLFLAG_MPSAFE, sysctl_kern_proc_ps_strings,
2867         "Process ps_strings location");
2868
2869 static SYSCTL_NODE(_kern_proc, KERN_PROC_UMASK, umask, CTLFLAG_RD |
2870         CTLFLAG_MPSAFE, sysctl_kern_proc_umask, "Process umask");
2871
2872 static SYSCTL_NODE(_kern_proc, KERN_PROC_OSREL, osrel, CTLFLAG_RW |
2873         CTLFLAG_ANYBODY | CTLFLAG_MPSAFE, sysctl_kern_proc_osrel,
2874         "Process binary osreldate");
2875
2876 static SYSCTL_NODE(_kern_proc, KERN_PROC_SIGTRAMP, sigtramp, CTLFLAG_RD |
2877         CTLFLAG_MPSAFE, sysctl_kern_proc_sigtramp,
2878         "Process signal trampoline location");
2879
2880 int allproc_gen;
2881
2882 void
2883 stop_all_proc(void)
2884 {
2885         struct proc *cp, *p;
2886         int r, gen;
2887         bool restart, seen_stopped, seen_exiting, stopped_some;
2888
2889         cp = curproc;
2890         /*
2891          * stop_all_proc() assumes that all process which have
2892          * usermode must be stopped, except current process, for
2893          * obvious reasons.  Since other threads in the process
2894          * establishing global stop could unstop something, disable
2895          * calls from multithreaded processes as precaution.  The
2896          * service must not be user-callable anyway.
2897          */
2898         KASSERT((cp->p_flag & P_HADTHREADS) == 0 ||
2899             (cp->p_flag & P_KTHREAD) != 0, ("mt stop_all_proc"));
2900
2901 allproc_loop:
2902         sx_xlock(&allproc_lock);
2903         gen = allproc_gen;
2904         seen_exiting = seen_stopped = stopped_some = restart = false;
2905         LIST_REMOVE(cp, p_list);
2906         LIST_INSERT_HEAD(&allproc, cp, p_list);
2907         for (;;) {
2908                 p = LIST_NEXT(cp, p_list);
2909                 if (p == NULL)
2910                         break;
2911                 LIST_REMOVE(cp, p_list);
2912                 LIST_INSERT_AFTER(p, cp, p_list);
2913                 PROC_LOCK(p);
2914                 if ((p->p_flag & (P_KTHREAD | P_SYSTEM |
2915                     P_TOTAL_STOP)) != 0) {
2916                         PROC_UNLOCK(p);
2917                         continue;
2918                 }
2919                 if ((p->p_flag & P_WEXIT) != 0) {
2920                         seen_exiting = true;
2921                         PROC_UNLOCK(p);
2922                         continue;
2923                 }
2924                 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
2925                         /*
2926                          * Stopped processes are tolerated when there
2927                          * are no other processes which might continue
2928                          * them.  P_STOPPED_SINGLE but not
2929                          * P_TOTAL_STOP process still has at least one
2930                          * thread running.
2931                          */
2932                         seen_stopped = true;
2933                         PROC_UNLOCK(p);
2934                         continue;
2935                 }
2936                 _PHOLD(p);
2937                 sx_xunlock(&allproc_lock);
2938                 r = thread_single(p, SINGLE_ALLPROC);
2939                 if (r != 0)
2940                         restart = true;
2941                 else
2942                         stopped_some = true;
2943                 _PRELE(p);
2944                 PROC_UNLOCK(p);
2945                 sx_xlock(&allproc_lock);
2946         }
2947         /* Catch forked children we did not see in iteration. */
2948         if (gen != allproc_gen)
2949                 restart = true;
2950         sx_xunlock(&allproc_lock);
2951         if (restart || stopped_some || seen_exiting || seen_stopped) {
2952                 kern_yield(PRI_USER);
2953                 goto allproc_loop;
2954         }
2955 }
2956
2957 void
2958 resume_all_proc(void)
2959 {
2960         struct proc *cp, *p;
2961
2962         cp = curproc;
2963         sx_xlock(&allproc_lock);
2964         LIST_REMOVE(cp, p_list);
2965         LIST_INSERT_HEAD(&allproc, cp, p_list);
2966         for (;;) {
2967                 p = LIST_NEXT(cp, p_list);
2968                 if (p == NULL)
2969                         break;
2970                 LIST_REMOVE(cp, p_list);
2971                 LIST_INSERT_AFTER(p, cp, p_list);
2972                 PROC_LOCK(p);
2973                 if ((p->p_flag & P_TOTAL_STOP) != 0) {
2974                         sx_xunlock(&allproc_lock);
2975                         _PHOLD(p);
2976                         thread_single_end(p, SINGLE_ALLPROC);
2977                         _PRELE(p);
2978                         PROC_UNLOCK(p);
2979                         sx_xlock(&allproc_lock);
2980                 } else {
2981                         PROC_UNLOCK(p);
2982                 }
2983         }
2984         sx_xunlock(&allproc_lock);
2985 }
2986
2987 #define TOTAL_STOP_DEBUG        1
2988 #ifdef TOTAL_STOP_DEBUG
2989 volatile static int ap_resume;
2990 #include <sys/mount.h>
2991
2992 static int
2993 sysctl_debug_stop_all_proc(SYSCTL_HANDLER_ARGS)
2994 {
2995         int error, val;
2996
2997         val = 0;
2998         ap_resume = 0;
2999         error = sysctl_handle_int(oidp, &val, 0, req);
3000         if (error != 0 || req->newptr == NULL)
3001                 return (error);
3002         if (val != 0) {
3003                 stop_all_proc();
3004                 syncer_suspend();
3005                 while (ap_resume == 0)
3006                         ;
3007                 syncer_resume();
3008                 resume_all_proc();
3009         }
3010         return (0);
3011 }
3012
3013 SYSCTL_PROC(_debug, OID_AUTO, stop_all_proc, CTLTYPE_INT | CTLFLAG_RW |
3014     CTLFLAG_MPSAFE, __DEVOLATILE(int *, &ap_resume), 0,
3015     sysctl_debug_stop_all_proc, "I",
3016     "");
3017 #endif