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