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