]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_proc.c
Improve ddb 'show pgrpdump' command.
[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         p->p_treeflag |= P_TREE_GRPEXITED;
855
856         /*
857          * Check p's parent to see whether p qualifies its own process
858          * group; if so, adjust count for p's process group.
859          */
860         if (isjobproc(p->p_pptr, pgrp))
861                 pgadjustjobc(pgrp, false);
862
863         /*
864          * Check this process' children to see whether they qualify
865          * their process groups after reparenting to reaper.  If so,
866          * adjust counts for children's process groups.
867          */
868         LIST_FOREACH(q, &p->p_children, p_sibling) {
869                 if ((q->p_treeflag & P_TREE_GRPEXITED) != 0)
870                         continue;
871                 childpgrp = q->p_pgrp;
872                 if (isjobproc(q->p_reaper, childpgrp) &&
873                     !isjobproc(p, childpgrp))
874                         pgadjustjobc(childpgrp, true);
875         }
876         LIST_FOREACH(q, &p->p_children, p_sibling) {
877                 if ((q->p_treeflag & P_TREE_GRPEXITED) != 0)
878                         continue;
879                 childpgrp = q->p_pgrp;
880                 if (!isjobproc(q->p_reaper, childpgrp) &&
881                     isjobproc(p, childpgrp))
882                         pgadjustjobc(childpgrp, false);
883         }
884 }
885
886 void
887 killjobc(void)
888 {
889         struct session *sp;
890         struct tty *tp;
891         struct proc *p;
892         struct vnode *ttyvp;
893
894         p = curproc;
895         MPASS(p->p_flag & P_WEXIT);
896         sx_assert(&proctree_lock, SX_LOCKED);
897
898         if (SESS_LEADER(p)) {
899                 sp = p->p_session;
900
901                 /*
902                  * s_ttyp is not zero'd; we use this to indicate that
903                  * the session once had a controlling terminal. (for
904                  * logging and informational purposes)
905                  */
906                 SESS_LOCK(sp);
907                 ttyvp = sp->s_ttyvp;
908                 tp = sp->s_ttyp;
909                 sp->s_ttyvp = NULL;
910                 sp->s_ttydp = NULL;
911                 sp->s_leader = NULL;
912                 SESS_UNLOCK(sp);
913
914                 /*
915                  * Signal foreground pgrp and revoke access to
916                  * controlling terminal if it has not been revoked
917                  * already.
918                  *
919                  * Because the TTY may have been revoked in the mean
920                  * time and could already have a new session associated
921                  * with it, make sure we don't send a SIGHUP to a
922                  * foreground process group that does not belong to this
923                  * session.
924                  */
925
926                 if (tp != NULL) {
927                         tty_lock(tp);
928                         if (tp->t_session == sp)
929                                 tty_signal_pgrp(tp, SIGHUP);
930                         tty_unlock(tp);
931                 }
932
933                 if (ttyvp != NULL) {
934                         sx_xunlock(&proctree_lock);
935                         if (vn_lock(ttyvp, LK_EXCLUSIVE) == 0) {
936                                 VOP_REVOKE(ttyvp, REVOKEALL);
937                                 VOP_UNLOCK(ttyvp);
938                         }
939                         devfs_ctty_unref(ttyvp);
940                         sx_xlock(&proctree_lock);
941                 }
942         }
943         fixjobc_kill(p);
944 }
945
946 /*
947  * A process group has become orphaned;
948  * if there are any stopped processes in the group,
949  * hang-up all process in that group.
950  */
951 static void
952 orphanpg(struct pgrp *pg)
953 {
954         struct proc *p;
955
956         PGRP_LOCK_ASSERT(pg, MA_OWNED);
957
958         LIST_FOREACH(p, &pg->pg_members, p_pglist) {
959                 PROC_LOCK(p);
960                 if (P_SHOULDSTOP(p) == P_STOPPED_SIG) {
961                         PROC_UNLOCK(p);
962                         LIST_FOREACH(p, &pg->pg_members, p_pglist) {
963                                 PROC_LOCK(p);
964                                 kern_psignal(p, SIGHUP);
965                                 kern_psignal(p, SIGCONT);
966                                 PROC_UNLOCK(p);
967                         }
968                         return;
969                 }
970                 PROC_UNLOCK(p);
971         }
972 }
973
974 void
975 sess_hold(struct session *s)
976 {
977
978         refcount_acquire(&s->s_count);
979 }
980
981 void
982 sess_release(struct session *s)
983 {
984
985         if (refcount_release(&s->s_count)) {
986                 if (s->s_ttyp != NULL) {
987                         tty_lock(s->s_ttyp);
988                         tty_rel_sess(s->s_ttyp, s);
989                 }
990                 proc_id_clear(PROC_ID_SESSION, s->s_sid);
991                 mtx_destroy(&s->s_mtx);
992                 free(s, M_SESSION);
993         }
994 }
995
996 #ifdef DDB
997
998 static void
999 db_print_pgrp_one(struct pgrp *pgrp, struct proc *p)
1000 {
1001         db_printf(
1002             "    pid %d at %p pr %d pgrp %p e %d jc %d\n",
1003             p->p_pid, p, p->p_pptr == NULL ? -1 : p->p_pptr->p_pid,
1004             p->p_pgrp, (p->p_treeflag & P_TREE_GRPEXITED) != 0,
1005             p->p_pptr == NULL ? 0 : isjobproc(p->p_pptr, pgrp));
1006 }
1007
1008 DB_SHOW_COMMAND(pgrpdump, pgrpdump)
1009 {
1010         struct pgrp *pgrp;
1011         struct proc *p;
1012         int i;
1013
1014         for (i = 0; i <= pgrphash; i++) {
1015                 if (!LIST_EMPTY(&pgrphashtbl[i])) {
1016                         db_printf("indx %d\n", i);
1017                         LIST_FOREACH(pgrp, &pgrphashtbl[i], pg_hash) {
1018                                 db_printf(
1019                         "  pgrp %p, pgid %d, sess %p, sesscnt %d, mem %p\n",
1020                                     pgrp, (int)pgrp->pg_id, pgrp->pg_session,
1021                                     pgrp->pg_session->s_count,
1022                                     LIST_FIRST(&pgrp->pg_members));
1023                                 LIST_FOREACH(p, &pgrp->pg_members, p_pglist)
1024                                         db_print_pgrp_one(pgrp, p);
1025                         }
1026                 }
1027         }
1028 }
1029 #endif /* DDB */
1030
1031 /*
1032  * Calculate the kinfo_proc members which contain process-wide
1033  * informations.
1034  * Must be called with the target process locked.
1035  */
1036 static void
1037 fill_kinfo_aggregate(struct proc *p, struct kinfo_proc *kp)
1038 {
1039         struct thread *td;
1040
1041         PROC_LOCK_ASSERT(p, MA_OWNED);
1042
1043         kp->ki_estcpu = 0;
1044         kp->ki_pctcpu = 0;
1045         FOREACH_THREAD_IN_PROC(p, td) {
1046                 thread_lock(td);
1047                 kp->ki_pctcpu += sched_pctcpu(td);
1048                 kp->ki_estcpu += sched_estcpu(td);
1049                 thread_unlock(td);
1050         }
1051 }
1052
1053 /*
1054  * Clear kinfo_proc and fill in any information that is common
1055  * to all threads in the process.
1056  * Must be called with the target process locked.
1057  */
1058 static void
1059 fill_kinfo_proc_only(struct proc *p, struct kinfo_proc *kp)
1060 {
1061         struct thread *td0;
1062         struct tty *tp;
1063         struct session *sp;
1064         struct ucred *cred;
1065         struct sigacts *ps;
1066         struct timeval boottime;
1067
1068         PROC_LOCK_ASSERT(p, MA_OWNED);
1069         bzero(kp, sizeof(*kp));
1070
1071         kp->ki_structsize = sizeof(*kp);
1072         kp->ki_paddr = p;
1073         kp->ki_addr =/* p->p_addr; */0; /* XXX */
1074         kp->ki_args = p->p_args;
1075         kp->ki_textvp = p->p_textvp;
1076 #ifdef KTRACE
1077         kp->ki_tracep = p->p_tracevp;
1078         kp->ki_traceflag = p->p_traceflag;
1079 #endif
1080         kp->ki_fd = p->p_fd;
1081         kp->ki_vmspace = p->p_vmspace;
1082         kp->ki_flag = p->p_flag;
1083         kp->ki_flag2 = p->p_flag2;
1084         cred = p->p_ucred;
1085         if (cred) {
1086                 kp->ki_uid = cred->cr_uid;
1087                 kp->ki_ruid = cred->cr_ruid;
1088                 kp->ki_svuid = cred->cr_svuid;
1089                 kp->ki_cr_flags = 0;
1090                 if (cred->cr_flags & CRED_FLAG_CAPMODE)
1091                         kp->ki_cr_flags |= KI_CRF_CAPABILITY_MODE;
1092                 /* XXX bde doesn't like KI_NGROUPS */
1093                 if (cred->cr_ngroups > KI_NGROUPS) {
1094                         kp->ki_ngroups = KI_NGROUPS;
1095                         kp->ki_cr_flags |= KI_CRF_GRP_OVERFLOW;
1096                 } else
1097                         kp->ki_ngroups = cred->cr_ngroups;
1098                 bcopy(cred->cr_groups, kp->ki_groups,
1099                     kp->ki_ngroups * sizeof(gid_t));
1100                 kp->ki_rgid = cred->cr_rgid;
1101                 kp->ki_svgid = cred->cr_svgid;
1102                 /* If jailed(cred), emulate the old P_JAILED flag. */
1103                 if (jailed(cred)) {
1104                         kp->ki_flag |= P_JAILED;
1105                         /* If inside the jail, use 0 as a jail ID. */
1106                         if (cred->cr_prison != curthread->td_ucred->cr_prison)
1107                                 kp->ki_jid = cred->cr_prison->pr_id;
1108                 }
1109                 strlcpy(kp->ki_loginclass, cred->cr_loginclass->lc_name,
1110                     sizeof(kp->ki_loginclass));
1111         }
1112         ps = p->p_sigacts;
1113         if (ps) {
1114                 mtx_lock(&ps->ps_mtx);
1115                 kp->ki_sigignore = ps->ps_sigignore;
1116                 kp->ki_sigcatch = ps->ps_sigcatch;
1117                 mtx_unlock(&ps->ps_mtx);
1118         }
1119         if (p->p_state != PRS_NEW &&
1120             p->p_state != PRS_ZOMBIE &&
1121             p->p_vmspace != NULL) {
1122                 struct vmspace *vm = p->p_vmspace;
1123
1124                 kp->ki_size = vm->vm_map.size;
1125                 kp->ki_rssize = vmspace_resident_count(vm); /*XXX*/
1126                 FOREACH_THREAD_IN_PROC(p, td0) {
1127                         if (!TD_IS_SWAPPED(td0))
1128                                 kp->ki_rssize += td0->td_kstack_pages;
1129                 }
1130                 kp->ki_swrss = vm->vm_swrss;
1131                 kp->ki_tsize = vm->vm_tsize;
1132                 kp->ki_dsize = vm->vm_dsize;
1133                 kp->ki_ssize = vm->vm_ssize;
1134         } else if (p->p_state == PRS_ZOMBIE)
1135                 kp->ki_stat = SZOMB;
1136         if (kp->ki_flag & P_INMEM)
1137                 kp->ki_sflag = PS_INMEM;
1138         else
1139                 kp->ki_sflag = 0;
1140         /* Calculate legacy swtime as seconds since 'swtick'. */
1141         kp->ki_swtime = (ticks - p->p_swtick) / hz;
1142         kp->ki_pid = p->p_pid;
1143         kp->ki_nice = p->p_nice;
1144         kp->ki_fibnum = p->p_fibnum;
1145         kp->ki_start = p->p_stats->p_start;
1146         getboottime(&boottime);
1147         timevaladd(&kp->ki_start, &boottime);
1148         PROC_STATLOCK(p);
1149         rufetch(p, &kp->ki_rusage);
1150         kp->ki_runtime = cputick2usec(p->p_rux.rux_runtime);
1151         calcru(p, &kp->ki_rusage.ru_utime, &kp->ki_rusage.ru_stime);
1152         PROC_STATUNLOCK(p);
1153         calccru(p, &kp->ki_childutime, &kp->ki_childstime);
1154         /* Some callers want child times in a single value. */
1155         kp->ki_childtime = kp->ki_childstime;
1156         timevaladd(&kp->ki_childtime, &kp->ki_childutime);
1157
1158         FOREACH_THREAD_IN_PROC(p, td0)
1159                 kp->ki_cow += td0->td_cow;
1160
1161         tp = NULL;
1162         if (p->p_pgrp) {
1163                 kp->ki_pgid = p->p_pgrp->pg_id;
1164                 kp->ki_jobc = p->p_pgrp->pg_jobc;
1165                 sp = p->p_pgrp->pg_session;
1166
1167                 if (sp != NULL) {
1168                         kp->ki_sid = sp->s_sid;
1169                         SESS_LOCK(sp);
1170                         strlcpy(kp->ki_login, sp->s_login,
1171                             sizeof(kp->ki_login));
1172                         if (sp->s_ttyvp)
1173                                 kp->ki_kiflag |= KI_CTTY;
1174                         if (SESS_LEADER(p))
1175                                 kp->ki_kiflag |= KI_SLEADER;
1176                         /* XXX proctree_lock */
1177                         tp = sp->s_ttyp;
1178                         SESS_UNLOCK(sp);
1179                 }
1180         }
1181         if ((p->p_flag & P_CONTROLT) && tp != NULL) {
1182                 kp->ki_tdev = tty_udev(tp);
1183                 kp->ki_tdev_freebsd11 = kp->ki_tdev; /* truncate */
1184                 kp->ki_tpgid = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
1185                 if (tp->t_session)
1186                         kp->ki_tsid = tp->t_session->s_sid;
1187         } else {
1188                 kp->ki_tdev = NODEV;
1189                 kp->ki_tdev_freebsd11 = kp->ki_tdev; /* truncate */
1190         }
1191         if (p->p_comm[0] != '\0')
1192                 strlcpy(kp->ki_comm, p->p_comm, sizeof(kp->ki_comm));
1193         if (p->p_sysent && p->p_sysent->sv_name != NULL &&
1194             p->p_sysent->sv_name[0] != '\0')
1195                 strlcpy(kp->ki_emul, p->p_sysent->sv_name, sizeof(kp->ki_emul));
1196         kp->ki_siglist = p->p_siglist;
1197         kp->ki_xstat = KW_EXITCODE(p->p_xexit, p->p_xsig);
1198         kp->ki_acflag = p->p_acflag;
1199         kp->ki_lock = p->p_lock;
1200         if (p->p_pptr) {
1201                 kp->ki_ppid = p->p_oppid;
1202                 if (p->p_flag & P_TRACED)
1203                         kp->ki_tracer = p->p_pptr->p_pid;
1204         }
1205 }
1206
1207 /*
1208  * Fill in information that is thread specific.  Must be called with
1209  * target process locked.  If 'preferthread' is set, overwrite certain
1210  * process-related fields that are maintained for both threads and
1211  * processes.
1212  */
1213 static void
1214 fill_kinfo_thread(struct thread *td, struct kinfo_proc *kp, int preferthread)
1215 {
1216         struct proc *p;
1217
1218         p = td->td_proc;
1219         kp->ki_tdaddr = td;
1220         PROC_LOCK_ASSERT(p, MA_OWNED);
1221
1222         if (preferthread)
1223                 PROC_STATLOCK(p);
1224         thread_lock(td);
1225         if (td->td_wmesg != NULL)
1226                 strlcpy(kp->ki_wmesg, td->td_wmesg, sizeof(kp->ki_wmesg));
1227         else
1228                 bzero(kp->ki_wmesg, sizeof(kp->ki_wmesg));
1229         if (strlcpy(kp->ki_tdname, td->td_name, sizeof(kp->ki_tdname)) >=
1230             sizeof(kp->ki_tdname)) {
1231                 strlcpy(kp->ki_moretdname,
1232                     td->td_name + sizeof(kp->ki_tdname) - 1,
1233                     sizeof(kp->ki_moretdname));
1234         } else {
1235                 bzero(kp->ki_moretdname, sizeof(kp->ki_moretdname));
1236         }
1237         if (TD_ON_LOCK(td)) {
1238                 kp->ki_kiflag |= KI_LOCKBLOCK;
1239                 strlcpy(kp->ki_lockname, td->td_lockname,
1240                     sizeof(kp->ki_lockname));
1241         } else {
1242                 kp->ki_kiflag &= ~KI_LOCKBLOCK;
1243                 bzero(kp->ki_lockname, sizeof(kp->ki_lockname));
1244         }
1245
1246         if (p->p_state == PRS_NORMAL) { /* approximate. */
1247                 if (TD_ON_RUNQ(td) ||
1248                     TD_CAN_RUN(td) ||
1249                     TD_IS_RUNNING(td)) {
1250                         kp->ki_stat = SRUN;
1251                 } else if (P_SHOULDSTOP(p)) {
1252                         kp->ki_stat = SSTOP;
1253                 } else if (TD_IS_SLEEPING(td)) {
1254                         kp->ki_stat = SSLEEP;
1255                 } else if (TD_ON_LOCK(td)) {
1256                         kp->ki_stat = SLOCK;
1257                 } else {
1258                         kp->ki_stat = SWAIT;
1259                 }
1260         } else if (p->p_state == PRS_ZOMBIE) {
1261                 kp->ki_stat = SZOMB;
1262         } else {
1263                 kp->ki_stat = SIDL;
1264         }
1265
1266         /* Things in the thread */
1267         kp->ki_wchan = td->td_wchan;
1268         kp->ki_pri.pri_level = td->td_priority;
1269         kp->ki_pri.pri_native = td->td_base_pri;
1270
1271         /*
1272          * Note: legacy fields; clamp at the old NOCPU value and/or
1273          * the maximum u_char CPU value.
1274          */
1275         if (td->td_lastcpu == NOCPU)
1276                 kp->ki_lastcpu_old = NOCPU_OLD;
1277         else if (td->td_lastcpu > MAXCPU_OLD)
1278                 kp->ki_lastcpu_old = MAXCPU_OLD;
1279         else
1280                 kp->ki_lastcpu_old = td->td_lastcpu;
1281
1282         if (td->td_oncpu == NOCPU)
1283                 kp->ki_oncpu_old = NOCPU_OLD;
1284         else if (td->td_oncpu > MAXCPU_OLD)
1285                 kp->ki_oncpu_old = MAXCPU_OLD;
1286         else
1287                 kp->ki_oncpu_old = td->td_oncpu;
1288
1289         kp->ki_lastcpu = td->td_lastcpu;
1290         kp->ki_oncpu = td->td_oncpu;
1291         kp->ki_tdflags = td->td_flags;
1292         kp->ki_tid = td->td_tid;
1293         kp->ki_numthreads = p->p_numthreads;
1294         kp->ki_pcb = td->td_pcb;
1295         kp->ki_kstack = (void *)td->td_kstack;
1296         kp->ki_slptime = (ticks - td->td_slptick) / hz;
1297         kp->ki_pri.pri_class = td->td_pri_class;
1298         kp->ki_pri.pri_user = td->td_user_pri;
1299
1300         if (preferthread) {
1301                 rufetchtd(td, &kp->ki_rusage);
1302                 kp->ki_runtime = cputick2usec(td->td_rux.rux_runtime);
1303                 kp->ki_pctcpu = sched_pctcpu(td);
1304                 kp->ki_estcpu = sched_estcpu(td);
1305                 kp->ki_cow = td->td_cow;
1306         }
1307
1308         /* We can't get this anymore but ps etc never used it anyway. */
1309         kp->ki_rqindex = 0;
1310
1311         if (preferthread)
1312                 kp->ki_siglist = td->td_siglist;
1313         kp->ki_sigmask = td->td_sigmask;
1314         thread_unlock(td);
1315         if (preferthread)
1316                 PROC_STATUNLOCK(p);
1317 }
1318
1319 /*
1320  * Fill in a kinfo_proc structure for the specified process.
1321  * Must be called with the target process locked.
1322  */
1323 void
1324 fill_kinfo_proc(struct proc *p, struct kinfo_proc *kp)
1325 {
1326
1327         MPASS(FIRST_THREAD_IN_PROC(p) != NULL);
1328
1329         fill_kinfo_proc_only(p, kp);
1330         fill_kinfo_thread(FIRST_THREAD_IN_PROC(p), kp, 0);
1331         fill_kinfo_aggregate(p, kp);
1332 }
1333
1334 struct pstats *
1335 pstats_alloc(void)
1336 {
1337
1338         return (malloc(sizeof(struct pstats), M_SUBPROC, M_ZERO|M_WAITOK));
1339 }
1340
1341 /*
1342  * Copy parts of p_stats; zero the rest of p_stats (statistics).
1343  */
1344 void
1345 pstats_fork(struct pstats *src, struct pstats *dst)
1346 {
1347
1348         bzero(&dst->pstat_startzero,
1349             __rangeof(struct pstats, pstat_startzero, pstat_endzero));
1350         bcopy(&src->pstat_startcopy, &dst->pstat_startcopy,
1351             __rangeof(struct pstats, pstat_startcopy, pstat_endcopy));
1352 }
1353
1354 void
1355 pstats_free(struct pstats *ps)
1356 {
1357
1358         free(ps, M_SUBPROC);
1359 }
1360
1361 #ifdef COMPAT_FREEBSD32
1362
1363 /*
1364  * This function is typically used to copy out the kernel address, so
1365  * it can be replaced by assignment of zero.
1366  */
1367 static inline uint32_t
1368 ptr32_trim(const void *ptr)
1369 {
1370         uintptr_t uptr;
1371
1372         uptr = (uintptr_t)ptr;
1373         return ((uptr > UINT_MAX) ? 0 : uptr);
1374 }
1375
1376 #define PTRTRIM_CP(src,dst,fld) \
1377         do { (dst).fld = ptr32_trim((src).fld); } while (0)
1378
1379 static void
1380 freebsd32_kinfo_proc_out(const struct kinfo_proc *ki, struct kinfo_proc32 *ki32)
1381 {
1382         int i;
1383
1384         bzero(ki32, sizeof(struct kinfo_proc32));
1385         ki32->ki_structsize = sizeof(struct kinfo_proc32);
1386         CP(*ki, *ki32, ki_layout);
1387         PTRTRIM_CP(*ki, *ki32, ki_args);
1388         PTRTRIM_CP(*ki, *ki32, ki_paddr);
1389         PTRTRIM_CP(*ki, *ki32, ki_addr);
1390         PTRTRIM_CP(*ki, *ki32, ki_tracep);
1391         PTRTRIM_CP(*ki, *ki32, ki_textvp);
1392         PTRTRIM_CP(*ki, *ki32, ki_fd);
1393         PTRTRIM_CP(*ki, *ki32, ki_vmspace);
1394         PTRTRIM_CP(*ki, *ki32, ki_wchan);
1395         CP(*ki, *ki32, ki_pid);
1396         CP(*ki, *ki32, ki_ppid);
1397         CP(*ki, *ki32, ki_pgid);
1398         CP(*ki, *ki32, ki_tpgid);
1399         CP(*ki, *ki32, ki_sid);
1400         CP(*ki, *ki32, ki_tsid);
1401         CP(*ki, *ki32, ki_jobc);
1402         CP(*ki, *ki32, ki_tdev);
1403         CP(*ki, *ki32, ki_tdev_freebsd11);
1404         CP(*ki, *ki32, ki_siglist);
1405         CP(*ki, *ki32, ki_sigmask);
1406         CP(*ki, *ki32, ki_sigignore);
1407         CP(*ki, *ki32, ki_sigcatch);
1408         CP(*ki, *ki32, ki_uid);
1409         CP(*ki, *ki32, ki_ruid);
1410         CP(*ki, *ki32, ki_svuid);
1411         CP(*ki, *ki32, ki_rgid);
1412         CP(*ki, *ki32, ki_svgid);
1413         CP(*ki, *ki32, ki_ngroups);
1414         for (i = 0; i < KI_NGROUPS; i++)
1415                 CP(*ki, *ki32, ki_groups[i]);
1416         CP(*ki, *ki32, ki_size);
1417         CP(*ki, *ki32, ki_rssize);
1418         CP(*ki, *ki32, ki_swrss);
1419         CP(*ki, *ki32, ki_tsize);
1420         CP(*ki, *ki32, ki_dsize);
1421         CP(*ki, *ki32, ki_ssize);
1422         CP(*ki, *ki32, ki_xstat);
1423         CP(*ki, *ki32, ki_acflag);
1424         CP(*ki, *ki32, ki_pctcpu);
1425         CP(*ki, *ki32, ki_estcpu);
1426         CP(*ki, *ki32, ki_slptime);
1427         CP(*ki, *ki32, ki_swtime);
1428         CP(*ki, *ki32, ki_cow);
1429         CP(*ki, *ki32, ki_runtime);
1430         TV_CP(*ki, *ki32, ki_start);
1431         TV_CP(*ki, *ki32, ki_childtime);
1432         CP(*ki, *ki32, ki_flag);
1433         CP(*ki, *ki32, ki_kiflag);
1434         CP(*ki, *ki32, ki_traceflag);
1435         CP(*ki, *ki32, ki_stat);
1436         CP(*ki, *ki32, ki_nice);
1437         CP(*ki, *ki32, ki_lock);
1438         CP(*ki, *ki32, ki_rqindex);
1439         CP(*ki, *ki32, ki_oncpu);
1440         CP(*ki, *ki32, ki_lastcpu);
1441
1442         /* XXX TODO: wrap cpu value as appropriate */
1443         CP(*ki, *ki32, ki_oncpu_old);
1444         CP(*ki, *ki32, ki_lastcpu_old);
1445
1446         bcopy(ki->ki_tdname, ki32->ki_tdname, TDNAMLEN + 1);
1447         bcopy(ki->ki_wmesg, ki32->ki_wmesg, WMESGLEN + 1);
1448         bcopy(ki->ki_login, ki32->ki_login, LOGNAMELEN + 1);
1449         bcopy(ki->ki_lockname, ki32->ki_lockname, LOCKNAMELEN + 1);
1450         bcopy(ki->ki_comm, ki32->ki_comm, COMMLEN + 1);
1451         bcopy(ki->ki_emul, ki32->ki_emul, KI_EMULNAMELEN + 1);
1452         bcopy(ki->ki_loginclass, ki32->ki_loginclass, LOGINCLASSLEN + 1);
1453         bcopy(ki->ki_moretdname, ki32->ki_moretdname, MAXCOMLEN - TDNAMLEN + 1);
1454         CP(*ki, *ki32, ki_tracer);
1455         CP(*ki, *ki32, ki_flag2);
1456         CP(*ki, *ki32, ki_fibnum);
1457         CP(*ki, *ki32, ki_cr_flags);
1458         CP(*ki, *ki32, ki_jid);
1459         CP(*ki, *ki32, ki_numthreads);
1460         CP(*ki, *ki32, ki_tid);
1461         CP(*ki, *ki32, ki_pri);
1462         freebsd32_rusage_out(&ki->ki_rusage, &ki32->ki_rusage);
1463         freebsd32_rusage_out(&ki->ki_rusage_ch, &ki32->ki_rusage_ch);
1464         PTRTRIM_CP(*ki, *ki32, ki_pcb);
1465         PTRTRIM_CP(*ki, *ki32, ki_kstack);
1466         PTRTRIM_CP(*ki, *ki32, ki_udata);
1467         PTRTRIM_CP(*ki, *ki32, ki_tdaddr);
1468         CP(*ki, *ki32, ki_sflag);
1469         CP(*ki, *ki32, ki_tdflags);
1470 }
1471 #endif
1472
1473 static ssize_t
1474 kern_proc_out_size(struct proc *p, int flags)
1475 {
1476         ssize_t size = 0;
1477
1478         PROC_LOCK_ASSERT(p, MA_OWNED);
1479
1480         if ((flags & KERN_PROC_NOTHREADS) != 0) {
1481 #ifdef COMPAT_FREEBSD32
1482                 if ((flags & KERN_PROC_MASK32) != 0) {
1483                         size += sizeof(struct kinfo_proc32);
1484                 } else
1485 #endif
1486                         size += sizeof(struct kinfo_proc);
1487         } else {
1488 #ifdef COMPAT_FREEBSD32
1489                 if ((flags & KERN_PROC_MASK32) != 0)
1490                         size += sizeof(struct kinfo_proc32) * p->p_numthreads;
1491                 else
1492 #endif
1493                         size += sizeof(struct kinfo_proc) * p->p_numthreads;
1494         }
1495         PROC_UNLOCK(p);
1496         return (size);
1497 }
1498
1499 int
1500 kern_proc_out(struct proc *p, struct sbuf *sb, int flags)
1501 {
1502         struct thread *td;
1503         struct kinfo_proc ki;
1504 #ifdef COMPAT_FREEBSD32
1505         struct kinfo_proc32 ki32;
1506 #endif
1507         int error;
1508
1509         PROC_LOCK_ASSERT(p, MA_OWNED);
1510         MPASS(FIRST_THREAD_IN_PROC(p) != NULL);
1511
1512         error = 0;
1513         fill_kinfo_proc(p, &ki);
1514         if ((flags & KERN_PROC_NOTHREADS) != 0) {
1515 #ifdef COMPAT_FREEBSD32
1516                 if ((flags & KERN_PROC_MASK32) != 0) {
1517                         freebsd32_kinfo_proc_out(&ki, &ki32);
1518                         if (sbuf_bcat(sb, &ki32, sizeof(ki32)) != 0)
1519                                 error = ENOMEM;
1520                 } else
1521 #endif
1522                         if (sbuf_bcat(sb, &ki, sizeof(ki)) != 0)
1523                                 error = ENOMEM;
1524         } else {
1525                 FOREACH_THREAD_IN_PROC(p, td) {
1526                         fill_kinfo_thread(td, &ki, 1);
1527 #ifdef COMPAT_FREEBSD32
1528                         if ((flags & KERN_PROC_MASK32) != 0) {
1529                                 freebsd32_kinfo_proc_out(&ki, &ki32);
1530                                 if (sbuf_bcat(sb, &ki32, sizeof(ki32)) != 0)
1531                                         error = ENOMEM;
1532                         } else
1533 #endif
1534                                 if (sbuf_bcat(sb, &ki, sizeof(ki)) != 0)
1535                                         error = ENOMEM;
1536                         if (error != 0)
1537                                 break;
1538                 }
1539         }
1540         PROC_UNLOCK(p);
1541         return (error);
1542 }
1543
1544 static int
1545 sysctl_out_proc(struct proc *p, struct sysctl_req *req, int flags)
1546 {
1547         struct sbuf sb;
1548         struct kinfo_proc ki;
1549         int error, error2;
1550
1551         if (req->oldptr == NULL)
1552                 return (SYSCTL_OUT(req, 0, kern_proc_out_size(p, flags)));
1553
1554         sbuf_new_for_sysctl(&sb, (char *)&ki, sizeof(ki), req);
1555         sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
1556         error = kern_proc_out(p, &sb, flags);
1557         error2 = sbuf_finish(&sb);
1558         sbuf_delete(&sb);
1559         if (error != 0)
1560                 return (error);
1561         else if (error2 != 0)
1562                 return (error2);
1563         return (0);
1564 }
1565
1566 int
1567 proc_iterate(int (*cb)(struct proc *, void *), void *cbarg)
1568 {
1569         struct proc *p;
1570         int error, i, j;
1571
1572         for (i = 0; i < pidhashlock + 1; i++) {
1573                 sx_slock(&pidhashtbl_lock[i]);
1574                 for (j = i; j <= pidhash; j += pidhashlock + 1) {
1575                         LIST_FOREACH(p, &pidhashtbl[j], p_hash) {
1576                                 if (p->p_state == PRS_NEW)
1577                                         continue;
1578                                 error = cb(p, cbarg);
1579                                 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1580                                 if (error != 0) {
1581                                         sx_sunlock(&pidhashtbl_lock[i]);
1582                                         return (error);
1583                                 }
1584                         }
1585                 }
1586                 sx_sunlock(&pidhashtbl_lock[i]);
1587         }
1588         return (0);
1589 }
1590
1591 struct kern_proc_out_args {
1592         struct sysctl_req *req;
1593         int flags;
1594         int oid_number;
1595         int *name;
1596 };
1597
1598 static int
1599 sysctl_kern_proc_iterate(struct proc *p, void *origarg)
1600 {
1601         struct kern_proc_out_args *arg = origarg;
1602         int *name = arg->name;
1603         int oid_number = arg->oid_number;
1604         int flags = arg->flags;
1605         struct sysctl_req *req = arg->req;
1606         int error = 0;
1607
1608         PROC_LOCK(p);
1609
1610         KASSERT(p->p_ucred != NULL,
1611             ("process credential is NULL for non-NEW proc"));
1612         /*
1613          * Show a user only appropriate processes.
1614          */
1615         if (p_cansee(curthread, p))
1616                 goto skip;
1617         /*
1618          * TODO - make more efficient (see notes below).
1619          * do by session.
1620          */
1621         switch (oid_number) {
1622         case KERN_PROC_GID:
1623                 if (p->p_ucred->cr_gid != (gid_t)name[0])
1624                         goto skip;
1625                 break;
1626
1627         case KERN_PROC_PGRP:
1628                 /* could do this by traversing pgrp */
1629                 if (p->p_pgrp == NULL ||
1630                     p->p_pgrp->pg_id != (pid_t)name[0])
1631                         goto skip;
1632                 break;
1633
1634         case KERN_PROC_RGID:
1635                 if (p->p_ucred->cr_rgid != (gid_t)name[0])
1636                         goto skip;
1637                 break;
1638
1639         case KERN_PROC_SESSION:
1640                 if (p->p_session == NULL ||
1641                     p->p_session->s_sid != (pid_t)name[0])
1642                         goto skip;
1643                 break;
1644
1645         case KERN_PROC_TTY:
1646                 if ((p->p_flag & P_CONTROLT) == 0 ||
1647                     p->p_session == NULL)
1648                         goto skip;
1649                 /* XXX proctree_lock */
1650                 SESS_LOCK(p->p_session);
1651                 if (p->p_session->s_ttyp == NULL ||
1652                     tty_udev(p->p_session->s_ttyp) !=
1653                     (dev_t)name[0]) {
1654                         SESS_UNLOCK(p->p_session);
1655                         goto skip;
1656                 }
1657                 SESS_UNLOCK(p->p_session);
1658                 break;
1659
1660         case KERN_PROC_UID:
1661                 if (p->p_ucred->cr_uid != (uid_t)name[0])
1662                         goto skip;
1663                 break;
1664
1665         case KERN_PROC_RUID:
1666                 if (p->p_ucred->cr_ruid != (uid_t)name[0])
1667                         goto skip;
1668                 break;
1669
1670         case KERN_PROC_PROC:
1671                 break;
1672
1673         default:
1674                 break;
1675         }
1676         error = sysctl_out_proc(p, req, flags);
1677         PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1678         return (error);
1679 skip:
1680         PROC_UNLOCK(p);
1681         return (0);
1682 }
1683
1684 static int
1685 sysctl_kern_proc(SYSCTL_HANDLER_ARGS)
1686 {
1687         struct kern_proc_out_args iterarg;
1688         int *name = (int *)arg1;
1689         u_int namelen = arg2;
1690         struct proc *p;
1691         int flags, oid_number;
1692         int error = 0;
1693
1694         oid_number = oidp->oid_number;
1695         if (oid_number != KERN_PROC_ALL &&
1696             (oid_number & KERN_PROC_INC_THREAD) == 0)
1697                 flags = KERN_PROC_NOTHREADS;
1698         else {
1699                 flags = 0;
1700                 oid_number &= ~KERN_PROC_INC_THREAD;
1701         }
1702 #ifdef COMPAT_FREEBSD32
1703         if (req->flags & SCTL_MASK32)
1704                 flags |= KERN_PROC_MASK32;
1705 #endif
1706         if (oid_number == KERN_PROC_PID) {
1707                 if (namelen != 1)
1708                         return (EINVAL);
1709                 error = sysctl_wire_old_buffer(req, 0);
1710                 if (error)
1711                         return (error);
1712                 error = pget((pid_t)name[0], PGET_CANSEE, &p);
1713                 if (error == 0)
1714                         error = sysctl_out_proc(p, req, flags);
1715                 return (error);
1716         }
1717
1718         switch (oid_number) {
1719         case KERN_PROC_ALL:
1720                 if (namelen != 0)
1721                         return (EINVAL);
1722                 break;
1723         case KERN_PROC_PROC:
1724                 if (namelen != 0 && namelen != 1)
1725                         return (EINVAL);
1726                 break;
1727         default:
1728                 if (namelen != 1)
1729                         return (EINVAL);
1730                 break;
1731         }
1732
1733         if (req->oldptr == NULL) {
1734                 /* overestimate by 5 procs */
1735                 error = SYSCTL_OUT(req, 0, sizeof (struct kinfo_proc) * 5);
1736                 if (error)
1737                         return (error);
1738         } else {
1739                 error = sysctl_wire_old_buffer(req, 0);
1740                 if (error != 0)
1741                         return (error);
1742         }
1743         iterarg.flags = flags;
1744         iterarg.oid_number = oid_number;
1745         iterarg.req = req;
1746         iterarg.name = name;
1747         error = proc_iterate(sysctl_kern_proc_iterate, &iterarg);
1748         return (error);
1749 }
1750
1751 struct pargs *
1752 pargs_alloc(int len)
1753 {
1754         struct pargs *pa;
1755
1756         pa = malloc(sizeof(struct pargs) + len, M_PARGS,
1757                 M_WAITOK);
1758         refcount_init(&pa->ar_ref, 1);
1759         pa->ar_length = len;
1760         return (pa);
1761 }
1762
1763 static void
1764 pargs_free(struct pargs *pa)
1765 {
1766
1767         free(pa, M_PARGS);
1768 }
1769
1770 void
1771 pargs_hold(struct pargs *pa)
1772 {
1773
1774         if (pa == NULL)
1775                 return;
1776         refcount_acquire(&pa->ar_ref);
1777 }
1778
1779 void
1780 pargs_drop(struct pargs *pa)
1781 {
1782
1783         if (pa == NULL)
1784                 return;
1785         if (refcount_release(&pa->ar_ref))
1786                 pargs_free(pa);
1787 }
1788
1789 static int
1790 proc_read_string(struct thread *td, struct proc *p, const char *sptr, char *buf,
1791     size_t len)
1792 {
1793         ssize_t n;
1794
1795         /*
1796          * This may return a short read if the string is shorter than the chunk
1797          * and is aligned at the end of the page, and the following page is not
1798          * mapped.
1799          */
1800         n = proc_readmem(td, p, (vm_offset_t)sptr, buf, len);
1801         if (n <= 0)
1802                 return (ENOMEM);
1803         return (0);
1804 }
1805
1806 #define PROC_AUXV_MAX   256     /* Safety limit on auxv size. */
1807
1808 enum proc_vector_type {
1809         PROC_ARG,
1810         PROC_ENV,
1811         PROC_AUX,
1812 };
1813
1814 #ifdef COMPAT_FREEBSD32
1815 static int
1816 get_proc_vector32(struct thread *td, struct proc *p, char ***proc_vectorp,
1817     size_t *vsizep, enum proc_vector_type type)
1818 {
1819         struct freebsd32_ps_strings pss;
1820         Elf32_Auxinfo aux;
1821         vm_offset_t vptr, ptr;
1822         uint32_t *proc_vector32;
1823         char **proc_vector;
1824         size_t vsize, size;
1825         int i, error;
1826
1827         error = 0;
1828         if (proc_readmem(td, p, (vm_offset_t)p->p_sysent->sv_psstrings, &pss,
1829             sizeof(pss)) != sizeof(pss))
1830                 return (ENOMEM);
1831         switch (type) {
1832         case PROC_ARG:
1833                 vptr = (vm_offset_t)PTRIN(pss.ps_argvstr);
1834                 vsize = pss.ps_nargvstr;
1835                 if (vsize > ARG_MAX)
1836                         return (ENOEXEC);
1837                 size = vsize * sizeof(int32_t);
1838                 break;
1839         case PROC_ENV:
1840                 vptr = (vm_offset_t)PTRIN(pss.ps_envstr);
1841                 vsize = pss.ps_nenvstr;
1842                 if (vsize > ARG_MAX)
1843                         return (ENOEXEC);
1844                 size = vsize * sizeof(int32_t);
1845                 break;
1846         case PROC_AUX:
1847                 vptr = (vm_offset_t)PTRIN(pss.ps_envstr) +
1848                     (pss.ps_nenvstr + 1) * sizeof(int32_t);
1849                 if (vptr % 4 != 0)
1850                         return (ENOEXEC);
1851                 for (ptr = vptr, i = 0; i < PROC_AUXV_MAX; i++) {
1852                         if (proc_readmem(td, p, ptr, &aux, sizeof(aux)) !=
1853                             sizeof(aux))
1854                                 return (ENOMEM);
1855                         if (aux.a_type == AT_NULL)
1856                                 break;
1857                         ptr += sizeof(aux);
1858                 }
1859                 if (aux.a_type != AT_NULL)
1860                         return (ENOEXEC);
1861                 vsize = i + 1;
1862                 size = vsize * sizeof(aux);
1863                 break;
1864         default:
1865                 KASSERT(0, ("Wrong proc vector type: %d", type));
1866                 return (EINVAL);
1867         }
1868         proc_vector32 = malloc(size, M_TEMP, M_WAITOK);
1869         if (proc_readmem(td, p, vptr, proc_vector32, size) != size) {
1870                 error = ENOMEM;
1871                 goto done;
1872         }
1873         if (type == PROC_AUX) {
1874                 *proc_vectorp = (char **)proc_vector32;
1875                 *vsizep = vsize;
1876                 return (0);
1877         }
1878         proc_vector = malloc(vsize * sizeof(char *), M_TEMP, M_WAITOK);
1879         for (i = 0; i < (int)vsize; i++)
1880                 proc_vector[i] = PTRIN(proc_vector32[i]);
1881         *proc_vectorp = proc_vector;
1882         *vsizep = vsize;
1883 done:
1884         free(proc_vector32, M_TEMP);
1885         return (error);
1886 }
1887 #endif
1888
1889 static int
1890 get_proc_vector(struct thread *td, struct proc *p, char ***proc_vectorp,
1891     size_t *vsizep, enum proc_vector_type type)
1892 {
1893         struct ps_strings pss;
1894         Elf_Auxinfo aux;
1895         vm_offset_t vptr, ptr;
1896         char **proc_vector;
1897         size_t vsize, size;
1898         int i;
1899
1900 #ifdef COMPAT_FREEBSD32
1901         if (SV_PROC_FLAG(p, SV_ILP32) != 0)
1902                 return (get_proc_vector32(td, p, proc_vectorp, vsizep, type));
1903 #endif
1904         if (proc_readmem(td, p, (vm_offset_t)p->p_sysent->sv_psstrings, &pss,
1905             sizeof(pss)) != sizeof(pss))
1906                 return (ENOMEM);
1907         switch (type) {
1908         case PROC_ARG:
1909                 vptr = (vm_offset_t)pss.ps_argvstr;
1910                 vsize = pss.ps_nargvstr;
1911                 if (vsize > ARG_MAX)
1912                         return (ENOEXEC);
1913                 size = vsize * sizeof(char *);
1914                 break;
1915         case PROC_ENV:
1916                 vptr = (vm_offset_t)pss.ps_envstr;
1917                 vsize = pss.ps_nenvstr;
1918                 if (vsize > ARG_MAX)
1919                         return (ENOEXEC);
1920                 size = vsize * sizeof(char *);
1921                 break;
1922         case PROC_AUX:
1923                 /*
1924                  * The aux array is just above env array on the stack. Check
1925                  * that the address is naturally aligned.
1926                  */
1927                 vptr = (vm_offset_t)pss.ps_envstr + (pss.ps_nenvstr + 1)
1928                     * sizeof(char *);
1929 #if __ELF_WORD_SIZE == 64
1930                 if (vptr % sizeof(uint64_t) != 0)
1931 #else
1932                 if (vptr % sizeof(uint32_t) != 0)
1933 #endif
1934                         return (ENOEXEC);
1935                 /*
1936                  * We count the array size reading the aux vectors from the
1937                  * stack until AT_NULL vector is returned.  So (to keep the code
1938                  * simple) we read the process stack twice: the first time here
1939                  * to find the size and the second time when copying the vectors
1940                  * to the allocated proc_vector.
1941                  */
1942                 for (ptr = vptr, i = 0; i < PROC_AUXV_MAX; i++) {
1943                         if (proc_readmem(td, p, ptr, &aux, sizeof(aux)) !=
1944                             sizeof(aux))
1945                                 return (ENOMEM);
1946                         if (aux.a_type == AT_NULL)
1947                                 break;
1948                         ptr += sizeof(aux);
1949                 }
1950                 /*
1951                  * If the PROC_AUXV_MAX entries are iterated over, and we have
1952                  * not reached AT_NULL, it is most likely we are reading wrong
1953                  * data: either the process doesn't have auxv array or data has
1954                  * been modified. Return the error in this case.
1955                  */
1956                 if (aux.a_type != AT_NULL)
1957                         return (ENOEXEC);
1958                 vsize = i + 1;
1959                 size = vsize * sizeof(aux);
1960                 break;
1961         default:
1962                 KASSERT(0, ("Wrong proc vector type: %d", type));
1963                 return (EINVAL); /* In case we are built without INVARIANTS. */
1964         }
1965         proc_vector = malloc(size, M_TEMP, M_WAITOK);
1966         if (proc_readmem(td, p, vptr, proc_vector, size) != size) {
1967                 free(proc_vector, M_TEMP);
1968                 return (ENOMEM);
1969         }
1970         *proc_vectorp = proc_vector;
1971         *vsizep = vsize;
1972
1973         return (0);
1974 }
1975
1976 #define GET_PS_STRINGS_CHUNK_SZ 256     /* Chunk size (bytes) for ps_strings operations. */
1977
1978 static int
1979 get_ps_strings(struct thread *td, struct proc *p, struct sbuf *sb,
1980     enum proc_vector_type type)
1981 {
1982         size_t done, len, nchr, vsize;
1983         int error, i;
1984         char **proc_vector, *sptr;
1985         char pss_string[GET_PS_STRINGS_CHUNK_SZ];
1986
1987         PROC_ASSERT_HELD(p);
1988
1989         /*
1990          * We are not going to read more than 2 * (PATH_MAX + ARG_MAX) bytes.
1991          */
1992         nchr = 2 * (PATH_MAX + ARG_MAX);
1993
1994         error = get_proc_vector(td, p, &proc_vector, &vsize, type);
1995         if (error != 0)
1996                 return (error);
1997         for (done = 0, i = 0; i < (int)vsize && done < nchr; i++) {
1998                 /*
1999                  * The program may have scribbled into its argv array, e.g. to
2000                  * remove some arguments.  If that has happened, break out
2001                  * before trying to read from NULL.
2002                  */
2003                 if (proc_vector[i] == NULL)
2004                         break;
2005                 for (sptr = proc_vector[i]; ; sptr += GET_PS_STRINGS_CHUNK_SZ) {
2006                         error = proc_read_string(td, p, sptr, pss_string,
2007                             sizeof(pss_string));
2008                         if (error != 0)
2009                                 goto done;
2010                         len = strnlen(pss_string, GET_PS_STRINGS_CHUNK_SZ);
2011                         if (done + len >= nchr)
2012                                 len = nchr - done - 1;
2013                         sbuf_bcat(sb, pss_string, len);
2014                         if (len != GET_PS_STRINGS_CHUNK_SZ)
2015                                 break;
2016                         done += GET_PS_STRINGS_CHUNK_SZ;
2017                 }
2018                 sbuf_bcat(sb, "", 1);
2019                 done += len + 1;
2020         }
2021 done:
2022         free(proc_vector, M_TEMP);
2023         return (error);
2024 }
2025
2026 int
2027 proc_getargv(struct thread *td, struct proc *p, struct sbuf *sb)
2028 {
2029
2030         return (get_ps_strings(curthread, p, sb, PROC_ARG));
2031 }
2032
2033 int
2034 proc_getenvv(struct thread *td, struct proc *p, struct sbuf *sb)
2035 {
2036
2037         return (get_ps_strings(curthread, p, sb, PROC_ENV));
2038 }
2039
2040 int
2041 proc_getauxv(struct thread *td, struct proc *p, struct sbuf *sb)
2042 {
2043         size_t vsize, size;
2044         char **auxv;
2045         int error;
2046
2047         error = get_proc_vector(td, p, &auxv, &vsize, PROC_AUX);
2048         if (error == 0) {
2049 #ifdef COMPAT_FREEBSD32
2050                 if (SV_PROC_FLAG(p, SV_ILP32) != 0)
2051                         size = vsize * sizeof(Elf32_Auxinfo);
2052                 else
2053 #endif
2054                         size = vsize * sizeof(Elf_Auxinfo);
2055                 if (sbuf_bcat(sb, auxv, size) != 0)
2056                         error = ENOMEM;
2057                 free(auxv, M_TEMP);
2058         }
2059         return (error);
2060 }
2061
2062 /*
2063  * This sysctl allows a process to retrieve the argument list or process
2064  * title for another process without groping around in the address space
2065  * of the other process.  It also allow a process to set its own "process 
2066  * title to a string of its own choice.
2067  */
2068 static int
2069 sysctl_kern_proc_args(SYSCTL_HANDLER_ARGS)
2070 {
2071         int *name = (int *)arg1;
2072         u_int namelen = arg2;
2073         struct pargs *newpa, *pa;
2074         struct proc *p;
2075         struct sbuf sb;
2076         int flags, error = 0, error2;
2077         pid_t pid;
2078
2079         if (namelen != 1)
2080                 return (EINVAL);
2081
2082         pid = (pid_t)name[0];
2083         /*
2084          * If the query is for this process and it is single-threaded, there
2085          * is nobody to modify pargs, thus we can just read.
2086          */
2087         p = curproc;
2088         if (pid == p->p_pid && p->p_numthreads == 1 && req->newptr == NULL &&
2089             (pa = p->p_args) != NULL)
2090                 return (SYSCTL_OUT(req, pa->ar_args, pa->ar_length));
2091
2092         flags = PGET_CANSEE;
2093         if (req->newptr != NULL)
2094                 flags |= PGET_ISCURRENT;
2095         error = pget(pid, flags, &p);
2096         if (error)
2097                 return (error);
2098
2099         pa = p->p_args;
2100         if (pa != NULL) {
2101                 pargs_hold(pa);
2102                 PROC_UNLOCK(p);
2103                 error = SYSCTL_OUT(req, pa->ar_args, pa->ar_length);
2104                 pargs_drop(pa);
2105         } else if ((p->p_flag & (P_WEXIT | P_SYSTEM)) == 0) {
2106                 _PHOLD(p);
2107                 PROC_UNLOCK(p);
2108                 sbuf_new_for_sysctl(&sb, NULL, GET_PS_STRINGS_CHUNK_SZ, req);
2109                 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
2110                 error = proc_getargv(curthread, p, &sb);
2111                 error2 = sbuf_finish(&sb);
2112                 PRELE(p);
2113                 sbuf_delete(&sb);
2114                 if (error == 0 && error2 != 0)
2115                         error = error2;
2116         } else {
2117                 PROC_UNLOCK(p);
2118         }
2119         if (error != 0 || req->newptr == NULL)
2120                 return (error);
2121
2122         if (req->newlen > ps_arg_cache_limit - sizeof(struct pargs))
2123                 return (ENOMEM);
2124
2125         if (req->newlen == 0) {
2126                 /*
2127                  * Clear the argument pointer, so that we'll fetch arguments
2128                  * with proc_getargv() until further notice.
2129                  */
2130                 newpa = NULL;
2131         } else {
2132                 newpa = pargs_alloc(req->newlen);
2133                 error = SYSCTL_IN(req, newpa->ar_args, req->newlen);
2134                 if (error != 0) {
2135                         pargs_free(newpa);
2136                         return (error);
2137                 }
2138         }
2139         PROC_LOCK(p);
2140         pa = p->p_args;
2141         p->p_args = newpa;
2142         PROC_UNLOCK(p);
2143         pargs_drop(pa);
2144         return (0);
2145 }
2146
2147 /*
2148  * This sysctl allows a process to retrieve environment of another process.
2149  */
2150 static int
2151 sysctl_kern_proc_env(SYSCTL_HANDLER_ARGS)
2152 {
2153         int *name = (int *)arg1;
2154         u_int namelen = arg2;
2155         struct proc *p;
2156         struct sbuf sb;
2157         int error, error2;
2158
2159         if (namelen != 1)
2160                 return (EINVAL);
2161
2162         error = pget((pid_t)name[0], PGET_WANTREAD, &p);
2163         if (error != 0)
2164                 return (error);
2165         if ((p->p_flag & P_SYSTEM) != 0) {
2166                 PRELE(p);
2167                 return (0);
2168         }
2169
2170         sbuf_new_for_sysctl(&sb, NULL, GET_PS_STRINGS_CHUNK_SZ, req);
2171         sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
2172         error = proc_getenvv(curthread, p, &sb);
2173         error2 = sbuf_finish(&sb);
2174         PRELE(p);
2175         sbuf_delete(&sb);
2176         return (error != 0 ? error : error2);
2177 }
2178
2179 /*
2180  * This sysctl allows a process to retrieve ELF auxiliary vector of
2181  * another process.
2182  */
2183 static int
2184 sysctl_kern_proc_auxv(SYSCTL_HANDLER_ARGS)
2185 {
2186         int *name = (int *)arg1;
2187         u_int namelen = arg2;
2188         struct proc *p;
2189         struct sbuf sb;
2190         int error, error2;
2191
2192         if (namelen != 1)
2193                 return (EINVAL);
2194
2195         error = pget((pid_t)name[0], PGET_WANTREAD, &p);
2196         if (error != 0)
2197                 return (error);
2198         if ((p->p_flag & P_SYSTEM) != 0) {
2199                 PRELE(p);
2200                 return (0);
2201         }
2202         sbuf_new_for_sysctl(&sb, NULL, GET_PS_STRINGS_CHUNK_SZ, req);
2203         sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
2204         error = proc_getauxv(curthread, p, &sb);
2205         error2 = sbuf_finish(&sb);
2206         PRELE(p);
2207         sbuf_delete(&sb);
2208         return (error != 0 ? error : error2);
2209 }
2210
2211 /*
2212  * This sysctl allows a process to retrieve the path of the executable for
2213  * itself or another process.
2214  */
2215 static int
2216 sysctl_kern_proc_pathname(SYSCTL_HANDLER_ARGS)
2217 {
2218         pid_t *pidp = (pid_t *)arg1;
2219         unsigned int arglen = arg2;
2220         struct proc *p;
2221         struct vnode *vp;
2222         char *retbuf, *freebuf;
2223         int error;
2224
2225         if (arglen != 1)
2226                 return (EINVAL);
2227         if (*pidp == -1) {      /* -1 means this process */
2228                 p = req->td->td_proc;
2229         } else {
2230                 error = pget(*pidp, PGET_CANSEE, &p);
2231                 if (error != 0)
2232                         return (error);
2233         }
2234
2235         vp = p->p_textvp;
2236         if (vp == NULL) {
2237                 if (*pidp != -1)
2238                         PROC_UNLOCK(p);
2239                 return (0);
2240         }
2241         vref(vp);
2242         if (*pidp != -1)
2243                 PROC_UNLOCK(p);
2244         error = vn_fullpath(vp, &retbuf, &freebuf);
2245         vrele(vp);
2246         if (error)
2247                 return (error);
2248         error = SYSCTL_OUT(req, retbuf, strlen(retbuf) + 1);
2249         free(freebuf, M_TEMP);
2250         return (error);
2251 }
2252
2253 static int
2254 sysctl_kern_proc_sv_name(SYSCTL_HANDLER_ARGS)
2255 {
2256         struct proc *p;
2257         char *sv_name;
2258         int *name;
2259         int namelen;
2260         int error;
2261
2262         namelen = arg2;
2263         if (namelen != 1)
2264                 return (EINVAL);
2265
2266         name = (int *)arg1;
2267         error = pget((pid_t)name[0], PGET_CANSEE, &p);
2268         if (error != 0)
2269                 return (error);
2270         sv_name = p->p_sysent->sv_name;
2271         PROC_UNLOCK(p);
2272         return (sysctl_handle_string(oidp, sv_name, 0, req));
2273 }
2274
2275 #ifdef KINFO_OVMENTRY_SIZE
2276 CTASSERT(sizeof(struct kinfo_ovmentry) == KINFO_OVMENTRY_SIZE);
2277 #endif
2278
2279 #ifdef COMPAT_FREEBSD7
2280 static int
2281 sysctl_kern_proc_ovmmap(SYSCTL_HANDLER_ARGS)
2282 {
2283         vm_map_entry_t entry, tmp_entry;
2284         unsigned int last_timestamp;
2285         char *fullpath, *freepath;
2286         struct kinfo_ovmentry *kve;
2287         struct vattr va;
2288         struct ucred *cred;
2289         int error, *name;
2290         struct vnode *vp;
2291         struct proc *p;
2292         vm_map_t map;
2293         struct vmspace *vm;
2294
2295         name = (int *)arg1;
2296         error = pget((pid_t)name[0], PGET_WANTREAD, &p);
2297         if (error != 0)
2298                 return (error);
2299         vm = vmspace_acquire_ref(p);
2300         if (vm == NULL) {
2301                 PRELE(p);
2302                 return (ESRCH);
2303         }
2304         kve = malloc(sizeof(*kve), M_TEMP, M_WAITOK);
2305
2306         map = &vm->vm_map;
2307         vm_map_lock_read(map);
2308         VM_MAP_ENTRY_FOREACH(entry, map) {
2309                 vm_object_t obj, tobj, lobj;
2310                 vm_offset_t addr;
2311
2312                 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
2313                         continue;
2314
2315                 bzero(kve, sizeof(*kve));
2316                 kve->kve_structsize = sizeof(*kve);
2317
2318                 kve->kve_private_resident = 0;
2319                 obj = entry->object.vm_object;
2320                 if (obj != NULL) {
2321                         VM_OBJECT_RLOCK(obj);
2322                         if (obj->shadow_count == 1)
2323                                 kve->kve_private_resident =
2324                                     obj->resident_page_count;
2325                 }
2326                 kve->kve_resident = 0;
2327                 addr = entry->start;
2328                 while (addr < entry->end) {
2329                         if (pmap_extract(map->pmap, addr))
2330                                 kve->kve_resident++;
2331                         addr += PAGE_SIZE;
2332                 }
2333
2334                 for (lobj = tobj = obj; tobj; tobj = tobj->backing_object) {
2335                         if (tobj != obj) {
2336                                 VM_OBJECT_RLOCK(tobj);
2337                                 kve->kve_offset += tobj->backing_object_offset;
2338                         }
2339                         if (lobj != obj)
2340                                 VM_OBJECT_RUNLOCK(lobj);
2341                         lobj = tobj;
2342                 }
2343
2344                 kve->kve_start = (void*)entry->start;
2345                 kve->kve_end = (void*)entry->end;
2346                 kve->kve_offset += (off_t)entry->offset;
2347
2348                 if (entry->protection & VM_PROT_READ)
2349                         kve->kve_protection |= KVME_PROT_READ;
2350                 if (entry->protection & VM_PROT_WRITE)
2351                         kve->kve_protection |= KVME_PROT_WRITE;
2352                 if (entry->protection & VM_PROT_EXECUTE)
2353                         kve->kve_protection |= KVME_PROT_EXEC;
2354
2355                 if (entry->eflags & MAP_ENTRY_COW)
2356                         kve->kve_flags |= KVME_FLAG_COW;
2357                 if (entry->eflags & MAP_ENTRY_NEEDS_COPY)
2358                         kve->kve_flags |= KVME_FLAG_NEEDS_COPY;
2359                 if (entry->eflags & MAP_ENTRY_NOCOREDUMP)
2360                         kve->kve_flags |= KVME_FLAG_NOCOREDUMP;
2361
2362                 last_timestamp = map->timestamp;
2363                 vm_map_unlock_read(map);
2364
2365                 kve->kve_fileid = 0;
2366                 kve->kve_fsid = 0;
2367                 freepath = NULL;
2368                 fullpath = "";
2369                 if (lobj) {
2370                         kve->kve_type = vm_object_kvme_type(lobj, &vp);
2371                         if (kve->kve_type == KVME_TYPE_MGTDEVICE)
2372                                 kve->kve_type = KVME_TYPE_UNKNOWN;
2373                         if (vp != NULL)
2374                                 vref(vp);
2375                         if (lobj != obj)
2376                                 VM_OBJECT_RUNLOCK(lobj);
2377
2378                         kve->kve_ref_count = obj->ref_count;
2379                         kve->kve_shadow_count = obj->shadow_count;
2380                         VM_OBJECT_RUNLOCK(obj);
2381                         if (vp != NULL) {
2382                                 vn_fullpath(vp, &fullpath, &freepath);
2383                                 cred = curthread->td_ucred;
2384                                 vn_lock(vp, LK_SHARED | LK_RETRY);
2385                                 if (VOP_GETATTR(vp, &va, cred) == 0) {
2386                                         kve->kve_fileid = va.va_fileid;
2387                                         /* truncate */
2388                                         kve->kve_fsid = va.va_fsid;
2389                                 }
2390                                 vput(vp);
2391                         }
2392                 } else {
2393                         kve->kve_type = KVME_TYPE_NONE;
2394                         kve->kve_ref_count = 0;
2395                         kve->kve_shadow_count = 0;
2396                 }
2397
2398                 strlcpy(kve->kve_path, fullpath, sizeof(kve->kve_path));
2399                 if (freepath != NULL)
2400                         free(freepath, M_TEMP);
2401
2402                 error = SYSCTL_OUT(req, kve, sizeof(*kve));
2403                 vm_map_lock_read(map);
2404                 if (error)
2405                         break;
2406                 if (last_timestamp != map->timestamp) {
2407                         vm_map_lookup_entry(map, addr - 1, &tmp_entry);
2408                         entry = tmp_entry;
2409                 }
2410         }
2411         vm_map_unlock_read(map);
2412         vmspace_free(vm);
2413         PRELE(p);
2414         free(kve, M_TEMP);
2415         return (error);
2416 }
2417 #endif  /* COMPAT_FREEBSD7 */
2418
2419 #ifdef KINFO_VMENTRY_SIZE
2420 CTASSERT(sizeof(struct kinfo_vmentry) == KINFO_VMENTRY_SIZE);
2421 #endif
2422
2423 void
2424 kern_proc_vmmap_resident(vm_map_t map, vm_map_entry_t entry,
2425     int *resident_count, bool *super)
2426 {
2427         vm_object_t obj, tobj;
2428         vm_page_t m, m_adv;
2429         vm_offset_t addr;
2430         vm_paddr_t pa;
2431         vm_pindex_t pi, pi_adv, pindex;
2432
2433         *super = false;
2434         *resident_count = 0;
2435         if (vmmap_skip_res_cnt)
2436                 return;
2437
2438         pa = 0;
2439         obj = entry->object.vm_object;
2440         addr = entry->start;
2441         m_adv = NULL;
2442         pi = OFF_TO_IDX(entry->offset);
2443         for (; addr < entry->end; addr += IDX_TO_OFF(pi_adv), pi += pi_adv) {
2444                 if (m_adv != NULL) {
2445                         m = m_adv;
2446                 } else {
2447                         pi_adv = atop(entry->end - addr);
2448                         pindex = pi;
2449                         for (tobj = obj;; tobj = tobj->backing_object) {
2450                                 m = vm_page_find_least(tobj, pindex);
2451                                 if (m != NULL) {
2452                                         if (m->pindex == pindex)
2453                                                 break;
2454                                         if (pi_adv > m->pindex - pindex) {
2455                                                 pi_adv = m->pindex - pindex;
2456                                                 m_adv = m;
2457                                         }
2458                                 }
2459                                 if (tobj->backing_object == NULL)
2460                                         goto next;
2461                                 pindex += OFF_TO_IDX(tobj->
2462                                     backing_object_offset);
2463                         }
2464                 }
2465                 m_adv = NULL;
2466                 if (m->psind != 0 && addr + pagesizes[1] <= entry->end &&
2467                     (addr & (pagesizes[1] - 1)) == 0 &&
2468                     (pmap_mincore(map->pmap, addr, &pa) & MINCORE_SUPER) != 0) {
2469                         *super = true;
2470                         pi_adv = atop(pagesizes[1]);
2471                 } else {
2472                         /*
2473                          * We do not test the found page on validity.
2474                          * Either the page is busy and being paged in,
2475                          * or it was invalidated.  The first case
2476                          * should be counted as resident, the second
2477                          * is not so clear; we do account both.
2478                          */
2479                         pi_adv = 1;
2480                 }
2481                 *resident_count += pi_adv;
2482 next:;
2483         }
2484 }
2485
2486 /*
2487  * Must be called with the process locked and will return unlocked.
2488  */
2489 int
2490 kern_proc_vmmap_out(struct proc *p, struct sbuf *sb, ssize_t maxlen, int flags)
2491 {
2492         vm_map_entry_t entry, tmp_entry;
2493         struct vattr va;
2494         vm_map_t map;
2495         vm_object_t obj, tobj, lobj;
2496         char *fullpath, *freepath;
2497         struct kinfo_vmentry *kve;
2498         struct ucred *cred;
2499         struct vnode *vp;
2500         struct vmspace *vm;
2501         vm_offset_t addr;
2502         unsigned int last_timestamp;
2503         int error;
2504         bool super;
2505
2506         PROC_LOCK_ASSERT(p, MA_OWNED);
2507
2508         _PHOLD(p);
2509         PROC_UNLOCK(p);
2510         vm = vmspace_acquire_ref(p);
2511         if (vm == NULL) {
2512                 PRELE(p);
2513                 return (ESRCH);
2514         }
2515         kve = malloc(sizeof(*kve), M_TEMP, M_WAITOK | M_ZERO);
2516
2517         error = 0;
2518         map = &vm->vm_map;
2519         vm_map_lock_read(map);
2520         VM_MAP_ENTRY_FOREACH(entry, map) {
2521                 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
2522                         continue;
2523
2524                 addr = entry->end;
2525                 bzero(kve, sizeof(*kve));
2526                 obj = entry->object.vm_object;
2527                 if (obj != NULL) {
2528                         for (tobj = obj; tobj != NULL;
2529                             tobj = tobj->backing_object) {
2530                                 VM_OBJECT_RLOCK(tobj);
2531                                 kve->kve_offset += tobj->backing_object_offset;
2532                                 lobj = tobj;
2533                         }
2534                         if (obj->backing_object == NULL)
2535                                 kve->kve_private_resident =
2536                                     obj->resident_page_count;
2537                         kern_proc_vmmap_resident(map, entry,
2538                             &kve->kve_resident, &super);
2539                         if (super)
2540                                 kve->kve_flags |= KVME_FLAG_SUPER;
2541                         for (tobj = obj; tobj != NULL;
2542                             tobj = tobj->backing_object) {
2543                                 if (tobj != obj && tobj != lobj)
2544                                         VM_OBJECT_RUNLOCK(tobj);
2545                         }
2546                 } else {
2547                         lobj = NULL;
2548                 }
2549
2550                 kve->kve_start = entry->start;
2551                 kve->kve_end = entry->end;
2552                 kve->kve_offset += entry->offset;
2553
2554                 if (entry->protection & VM_PROT_READ)
2555                         kve->kve_protection |= KVME_PROT_READ;
2556                 if (entry->protection & VM_PROT_WRITE)
2557                         kve->kve_protection |= KVME_PROT_WRITE;
2558                 if (entry->protection & VM_PROT_EXECUTE)
2559                         kve->kve_protection |= KVME_PROT_EXEC;
2560
2561                 if (entry->eflags & MAP_ENTRY_COW)
2562                         kve->kve_flags |= KVME_FLAG_COW;
2563                 if (entry->eflags & MAP_ENTRY_NEEDS_COPY)
2564                         kve->kve_flags |= KVME_FLAG_NEEDS_COPY;
2565                 if (entry->eflags & MAP_ENTRY_NOCOREDUMP)
2566                         kve->kve_flags |= KVME_FLAG_NOCOREDUMP;
2567                 if (entry->eflags & MAP_ENTRY_GROWS_UP)
2568                         kve->kve_flags |= KVME_FLAG_GROWS_UP;
2569                 if (entry->eflags & MAP_ENTRY_GROWS_DOWN)
2570                         kve->kve_flags |= KVME_FLAG_GROWS_DOWN;
2571                 if (entry->eflags & MAP_ENTRY_USER_WIRED)
2572                         kve->kve_flags |= KVME_FLAG_USER_WIRED;
2573
2574                 last_timestamp = map->timestamp;
2575                 vm_map_unlock_read(map);
2576
2577                 freepath = NULL;
2578                 fullpath = "";
2579                 if (lobj != NULL) {
2580                         kve->kve_type = vm_object_kvme_type(lobj, &vp);
2581                         if (vp != NULL)
2582                                 vref(vp);
2583                         if (lobj != obj)
2584                                 VM_OBJECT_RUNLOCK(lobj);
2585
2586                         kve->kve_ref_count = obj->ref_count;
2587                         kve->kve_shadow_count = obj->shadow_count;
2588                         VM_OBJECT_RUNLOCK(obj);
2589                         if (vp != NULL) {
2590                                 vn_fullpath(vp, &fullpath, &freepath);
2591                                 kve->kve_vn_type = vntype_to_kinfo(vp->v_type);
2592                                 cred = curthread->td_ucred;
2593                                 vn_lock(vp, LK_SHARED | LK_RETRY);
2594                                 if (VOP_GETATTR(vp, &va, cred) == 0) {
2595                                         kve->kve_vn_fileid = va.va_fileid;
2596                                         kve->kve_vn_fsid = va.va_fsid;
2597                                         kve->kve_vn_fsid_freebsd11 =
2598                                             kve->kve_vn_fsid; /* truncate */
2599                                         kve->kve_vn_mode =
2600                                             MAKEIMODE(va.va_type, va.va_mode);
2601                                         kve->kve_vn_size = va.va_size;
2602                                         kve->kve_vn_rdev = va.va_rdev;
2603                                         kve->kve_vn_rdev_freebsd11 =
2604                                             kve->kve_vn_rdev; /* truncate */
2605                                         kve->kve_status = KF_ATTR_VALID;
2606                                 }
2607                                 vput(vp);
2608                         }
2609                 } else {
2610                         kve->kve_type = KVME_TYPE_NONE;
2611                         kve->kve_ref_count = 0;
2612                         kve->kve_shadow_count = 0;
2613                 }
2614
2615                 strlcpy(kve->kve_path, fullpath, sizeof(kve->kve_path));
2616                 if (freepath != NULL)
2617                         free(freepath, M_TEMP);
2618
2619                 /* Pack record size down */
2620                 if ((flags & KERN_VMMAP_PACK_KINFO) != 0)
2621                         kve->kve_structsize =
2622                             offsetof(struct kinfo_vmentry, kve_path) +
2623                             strlen(kve->kve_path) + 1;
2624                 else
2625                         kve->kve_structsize = sizeof(*kve);
2626                 kve->kve_structsize = roundup(kve->kve_structsize,
2627                     sizeof(uint64_t));
2628
2629                 /* Halt filling and truncate rather than exceeding maxlen */
2630                 if (maxlen != -1 && maxlen < kve->kve_structsize) {
2631                         error = 0;
2632                         vm_map_lock_read(map);
2633                         break;
2634                 } else if (maxlen != -1)
2635                         maxlen -= kve->kve_structsize;
2636
2637                 if (sbuf_bcat(sb, kve, kve->kve_structsize) != 0)
2638                         error = ENOMEM;
2639                 vm_map_lock_read(map);
2640                 if (error != 0)
2641                         break;
2642                 if (last_timestamp != map->timestamp) {
2643                         vm_map_lookup_entry(map, addr - 1, &tmp_entry);
2644                         entry = tmp_entry;
2645                 }
2646         }
2647         vm_map_unlock_read(map);
2648         vmspace_free(vm);
2649         PRELE(p);
2650         free(kve, M_TEMP);
2651         return (error);
2652 }
2653
2654 static int
2655 sysctl_kern_proc_vmmap(SYSCTL_HANDLER_ARGS)
2656 {
2657         struct proc *p;
2658         struct sbuf sb;
2659         int error, error2, *name;
2660
2661         name = (int *)arg1;
2662         sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_vmentry), req);
2663         sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
2664         error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
2665         if (error != 0) {
2666                 sbuf_delete(&sb);
2667                 return (error);
2668         }
2669         error = kern_proc_vmmap_out(p, &sb, -1, KERN_VMMAP_PACK_KINFO);
2670         error2 = sbuf_finish(&sb);
2671         sbuf_delete(&sb);
2672         return (error != 0 ? error : error2);
2673 }
2674
2675 #if defined(STACK) || defined(DDB)
2676 static int
2677 sysctl_kern_proc_kstack(SYSCTL_HANDLER_ARGS)
2678 {
2679         struct kinfo_kstack *kkstp;
2680         int error, i, *name, numthreads;
2681         lwpid_t *lwpidarray;
2682         struct thread *td;
2683         struct stack *st;
2684         struct sbuf sb;
2685         struct proc *p;
2686
2687         name = (int *)arg1;
2688         error = pget((pid_t)name[0], PGET_NOTINEXEC | PGET_WANTREAD, &p);
2689         if (error != 0)
2690                 return (error);
2691
2692         kkstp = malloc(sizeof(*kkstp), M_TEMP, M_WAITOK);
2693         st = stack_create(M_WAITOK);
2694
2695         lwpidarray = NULL;
2696         PROC_LOCK(p);
2697         do {
2698                 if (lwpidarray != NULL) {
2699                         free(lwpidarray, M_TEMP);
2700                         lwpidarray = NULL;
2701                 }
2702                 numthreads = p->p_numthreads;
2703                 PROC_UNLOCK(p);
2704                 lwpidarray = malloc(sizeof(*lwpidarray) * numthreads, M_TEMP,
2705                     M_WAITOK | M_ZERO);
2706                 PROC_LOCK(p);
2707         } while (numthreads < p->p_numthreads);
2708
2709         /*
2710          * XXXRW: During the below loop, execve(2) and countless other sorts
2711          * of changes could have taken place.  Should we check to see if the
2712          * vmspace has been replaced, or the like, in order to prevent
2713          * giving a snapshot that spans, say, execve(2), with some threads
2714          * before and some after?  Among other things, the credentials could
2715          * have changed, in which case the right to extract debug info might
2716          * no longer be assured.
2717          */
2718         i = 0;
2719         FOREACH_THREAD_IN_PROC(p, td) {
2720                 KASSERT(i < numthreads,
2721                     ("sysctl_kern_proc_kstack: numthreads"));
2722                 lwpidarray[i] = td->td_tid;
2723                 i++;
2724         }
2725         numthreads = i;
2726         for (i = 0; i < numthreads; i++) {
2727                 td = thread_find(p, lwpidarray[i]);
2728                 if (td == NULL) {
2729                         continue;
2730                 }
2731                 bzero(kkstp, sizeof(*kkstp));
2732                 (void)sbuf_new(&sb, kkstp->kkst_trace,
2733                     sizeof(kkstp->kkst_trace), SBUF_FIXEDLEN);
2734                 thread_lock(td);
2735                 kkstp->kkst_tid = td->td_tid;
2736                 if (TD_IS_SWAPPED(td))
2737                         kkstp->kkst_state = KKST_STATE_SWAPPED;
2738                 else if (stack_save_td(st, td) == 0)
2739                         kkstp->kkst_state = KKST_STATE_STACKOK;
2740                 else
2741                         kkstp->kkst_state = KKST_STATE_RUNNING;
2742                 thread_unlock(td);
2743                 PROC_UNLOCK(p);
2744                 stack_sbuf_print(&sb, st);
2745                 sbuf_finish(&sb);
2746                 sbuf_delete(&sb);
2747                 error = SYSCTL_OUT(req, kkstp, sizeof(*kkstp));
2748                 PROC_LOCK(p);
2749                 if (error)
2750                         break;
2751         }
2752         _PRELE(p);
2753         PROC_UNLOCK(p);
2754         if (lwpidarray != NULL)
2755                 free(lwpidarray, M_TEMP);
2756         stack_destroy(st);
2757         free(kkstp, M_TEMP);
2758         return (error);
2759 }
2760 #endif
2761
2762 /*
2763  * This sysctl allows a process to retrieve the full list of groups from
2764  * itself or another process.
2765  */
2766 static int
2767 sysctl_kern_proc_groups(SYSCTL_HANDLER_ARGS)
2768 {
2769         pid_t *pidp = (pid_t *)arg1;
2770         unsigned int arglen = arg2;
2771         struct proc *p;
2772         struct ucred *cred;
2773         int error;
2774
2775         if (arglen != 1)
2776                 return (EINVAL);
2777         if (*pidp == -1) {      /* -1 means this process */
2778                 p = req->td->td_proc;
2779                 PROC_LOCK(p);
2780         } else {
2781                 error = pget(*pidp, PGET_CANSEE, &p);
2782                 if (error != 0)
2783                         return (error);
2784         }
2785
2786         cred = crhold(p->p_ucred);
2787         PROC_UNLOCK(p);
2788
2789         error = SYSCTL_OUT(req, cred->cr_groups,
2790             cred->cr_ngroups * sizeof(gid_t));
2791         crfree(cred);
2792         return (error);
2793 }
2794
2795 /*
2796  * This sysctl allows a process to retrieve or/and set the resource limit for
2797  * another process.
2798  */
2799 static int
2800 sysctl_kern_proc_rlimit(SYSCTL_HANDLER_ARGS)
2801 {
2802         int *name = (int *)arg1;
2803         u_int namelen = arg2;
2804         struct rlimit rlim;
2805         struct proc *p;
2806         u_int which;
2807         int flags, error;
2808
2809         if (namelen != 2)
2810                 return (EINVAL);
2811
2812         which = (u_int)name[1];
2813         if (which >= RLIM_NLIMITS)
2814                 return (EINVAL);
2815
2816         if (req->newptr != NULL && req->newlen != sizeof(rlim))
2817                 return (EINVAL);
2818
2819         flags = PGET_HOLD | PGET_NOTWEXIT;
2820         if (req->newptr != NULL)
2821                 flags |= PGET_CANDEBUG;
2822         else
2823                 flags |= PGET_CANSEE;
2824         error = pget((pid_t)name[0], flags, &p);
2825         if (error != 0)
2826                 return (error);
2827
2828         /*
2829          * Retrieve limit.
2830          */
2831         if (req->oldptr != NULL) {
2832                 PROC_LOCK(p);
2833                 lim_rlimit_proc(p, which, &rlim);
2834                 PROC_UNLOCK(p);
2835         }
2836         error = SYSCTL_OUT(req, &rlim, sizeof(rlim));
2837         if (error != 0)
2838                 goto errout;
2839
2840         /*
2841          * Set limit.
2842          */
2843         if (req->newptr != NULL) {
2844                 error = SYSCTL_IN(req, &rlim, sizeof(rlim));
2845                 if (error == 0)
2846                         error = kern_proc_setrlimit(curthread, p, which, &rlim);
2847         }
2848
2849 errout:
2850         PRELE(p);
2851         return (error);
2852 }
2853
2854 /*
2855  * This sysctl allows a process to retrieve ps_strings structure location of
2856  * another process.
2857  */
2858 static int
2859 sysctl_kern_proc_ps_strings(SYSCTL_HANDLER_ARGS)
2860 {
2861         int *name = (int *)arg1;
2862         u_int namelen = arg2;
2863         struct proc *p;
2864         vm_offset_t ps_strings;
2865         int error;
2866 #ifdef COMPAT_FREEBSD32
2867         uint32_t ps_strings32;
2868 #endif
2869
2870         if (namelen != 1)
2871                 return (EINVAL);
2872
2873         error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
2874         if (error != 0)
2875                 return (error);
2876 #ifdef COMPAT_FREEBSD32
2877         if ((req->flags & SCTL_MASK32) != 0) {
2878                 /*
2879                  * We return 0 if the 32 bit emulation request is for a 64 bit
2880                  * process.
2881                  */
2882                 ps_strings32 = SV_PROC_FLAG(p, SV_ILP32) != 0 ?
2883                     PTROUT(p->p_sysent->sv_psstrings) : 0;
2884                 PROC_UNLOCK(p);
2885                 error = SYSCTL_OUT(req, &ps_strings32, sizeof(ps_strings32));
2886                 return (error);
2887         }
2888 #endif
2889         ps_strings = p->p_sysent->sv_psstrings;
2890         PROC_UNLOCK(p);
2891         error = SYSCTL_OUT(req, &ps_strings, sizeof(ps_strings));
2892         return (error);
2893 }
2894
2895 /*
2896  * This sysctl allows a process to retrieve umask of another process.
2897  */
2898 static int
2899 sysctl_kern_proc_umask(SYSCTL_HANDLER_ARGS)
2900 {
2901         int *name = (int *)arg1;
2902         u_int namelen = arg2;
2903         struct proc *p;
2904         int error;
2905         u_short fd_cmask;
2906         pid_t pid;
2907
2908         if (namelen != 1)
2909                 return (EINVAL);
2910
2911         pid = (pid_t)name[0];
2912         p = curproc;
2913         if (pid == p->p_pid || pid == 0) {
2914                 fd_cmask = p->p_fd->fd_cmask;
2915                 goto out;
2916         }
2917
2918         error = pget(pid, PGET_WANTREAD, &p);
2919         if (error != 0)
2920                 return (error);
2921
2922         fd_cmask = p->p_fd->fd_cmask;
2923         PRELE(p);
2924 out:
2925         error = SYSCTL_OUT(req, &fd_cmask, sizeof(fd_cmask));
2926         return (error);
2927 }
2928
2929 /*
2930  * This sysctl allows a process to set and retrieve binary osreldate of
2931  * another process.
2932  */
2933 static int
2934 sysctl_kern_proc_osrel(SYSCTL_HANDLER_ARGS)
2935 {
2936         int *name = (int *)arg1;
2937         u_int namelen = arg2;
2938         struct proc *p;
2939         int flags, error, osrel;
2940
2941         if (namelen != 1)
2942                 return (EINVAL);
2943
2944         if (req->newptr != NULL && req->newlen != sizeof(osrel))
2945                 return (EINVAL);
2946
2947         flags = PGET_HOLD | PGET_NOTWEXIT;
2948         if (req->newptr != NULL)
2949                 flags |= PGET_CANDEBUG;
2950         else
2951                 flags |= PGET_CANSEE;
2952         error = pget((pid_t)name[0], flags, &p);
2953         if (error != 0)
2954                 return (error);
2955
2956         error = SYSCTL_OUT(req, &p->p_osrel, sizeof(p->p_osrel));
2957         if (error != 0)
2958                 goto errout;
2959
2960         if (req->newptr != NULL) {
2961                 error = SYSCTL_IN(req, &osrel, sizeof(osrel));
2962                 if (error != 0)
2963                         goto errout;
2964                 if (osrel < 0) {
2965                         error = EINVAL;
2966                         goto errout;
2967                 }
2968                 p->p_osrel = osrel;
2969         }
2970 errout:
2971         PRELE(p);
2972         return (error);
2973 }
2974
2975 static int
2976 sysctl_kern_proc_sigtramp(SYSCTL_HANDLER_ARGS)
2977 {
2978         int *name = (int *)arg1;
2979         u_int namelen = arg2;
2980         struct proc *p;
2981         struct kinfo_sigtramp kst;
2982         const struct sysentvec *sv;
2983         int error;
2984 #ifdef COMPAT_FREEBSD32
2985         struct kinfo_sigtramp32 kst32;
2986 #endif
2987
2988         if (namelen != 1)
2989                 return (EINVAL);
2990
2991         error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
2992         if (error != 0)
2993                 return (error);
2994         sv = p->p_sysent;
2995 #ifdef COMPAT_FREEBSD32
2996         if ((req->flags & SCTL_MASK32) != 0) {
2997                 bzero(&kst32, sizeof(kst32));
2998                 if (SV_PROC_FLAG(p, SV_ILP32)) {
2999                         if (sv->sv_sigcode_base != 0) {
3000                                 kst32.ksigtramp_start = sv->sv_sigcode_base;
3001                                 kst32.ksigtramp_end = sv->sv_sigcode_base +
3002                                     *sv->sv_szsigcode;
3003                         } else {
3004                                 kst32.ksigtramp_start = sv->sv_psstrings -
3005                                     *sv->sv_szsigcode;
3006                                 kst32.ksigtramp_end = sv->sv_psstrings;
3007                         }
3008                 }
3009                 PROC_UNLOCK(p);
3010                 error = SYSCTL_OUT(req, &kst32, sizeof(kst32));
3011                 return (error);
3012         }
3013 #endif
3014         bzero(&kst, sizeof(kst));
3015         if (sv->sv_sigcode_base != 0) {
3016                 kst.ksigtramp_start = (char *)sv->sv_sigcode_base;
3017                 kst.ksigtramp_end = (char *)sv->sv_sigcode_base +
3018                     *sv->sv_szsigcode;
3019         } else {
3020                 kst.ksigtramp_start = (char *)sv->sv_psstrings -
3021                     *sv->sv_szsigcode;
3022                 kst.ksigtramp_end = (char *)sv->sv_psstrings;
3023         }
3024         PROC_UNLOCK(p);
3025         error = SYSCTL_OUT(req, &kst, sizeof(kst));
3026         return (error);
3027 }
3028
3029 static int
3030 sysctl_kern_proc_sigfastblk(SYSCTL_HANDLER_ARGS)
3031 {
3032         int *name = (int *)arg1;
3033         u_int namelen = arg2;
3034         pid_t pid;
3035         struct proc *p;
3036         struct thread *td1;
3037         uintptr_t addr;
3038 #ifdef COMPAT_FREEBSD32
3039         uint32_t addr32;
3040 #endif
3041         int error;
3042
3043         if (namelen != 1 || req->newptr != NULL)
3044                 return (EINVAL);
3045
3046         pid = (pid_t)name[0];
3047         error = pget(pid, PGET_HOLD | PGET_NOTWEXIT | PGET_CANDEBUG, &p);
3048         if (error != 0)
3049                 return (error);
3050
3051         PROC_LOCK(p);
3052 #ifdef COMPAT_FREEBSD32
3053         if (SV_CURPROC_FLAG(SV_ILP32)) {
3054                 if (!SV_PROC_FLAG(p, SV_ILP32)) {
3055                         error = EINVAL;
3056                         goto errlocked;
3057                 }
3058         }
3059 #endif
3060         if (pid <= PID_MAX) {
3061                 td1 = FIRST_THREAD_IN_PROC(p);
3062         } else {
3063                 FOREACH_THREAD_IN_PROC(p, td1) {
3064                         if (td1->td_tid == pid)
3065                                 break;
3066                 }
3067         }
3068         if (td1 == NULL) {
3069                 error = ESRCH;
3070                 goto errlocked;
3071         }
3072         /*
3073          * The access to the private thread flags.  It is fine as far
3074          * as no out-of-thin-air values are read from td_pflags, and
3075          * usermode read of the td_sigblock_ptr is racy inherently,
3076          * since target process might have already changed it
3077          * meantime.
3078          */
3079         if ((td1->td_pflags & TDP_SIGFASTBLOCK) != 0)
3080                 addr = (uintptr_t)td1->td_sigblock_ptr;
3081         else
3082                 error = ENOTTY;
3083
3084 errlocked:
3085         _PRELE(p);
3086         PROC_UNLOCK(p);
3087         if (error != 0)
3088                 return (error);
3089
3090 #ifdef COMPAT_FREEBSD32
3091         if (SV_CURPROC_FLAG(SV_ILP32)) {
3092                 addr32 = addr;
3093                 error = SYSCTL_OUT(req, &addr32, sizeof(addr32));
3094         } else
3095 #endif
3096                 error = SYSCTL_OUT(req, &addr, sizeof(addr));
3097         return (error);
3098 }
3099
3100 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD | CTLFLAG_MPSAFE,  0,
3101     "Process table");
3102
3103 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all, CTLFLAG_RD|CTLTYPE_STRUCT|
3104         CTLFLAG_MPSAFE, 0, 0, sysctl_kern_proc, "S,proc",
3105         "Return entire process table");
3106
3107 static SYSCTL_NODE(_kern_proc, KERN_PROC_GID, gid, CTLFLAG_RD | CTLFLAG_MPSAFE,
3108         sysctl_kern_proc, "Process table");
3109
3110 static SYSCTL_NODE(_kern_proc, KERN_PROC_PGRP, pgrp, CTLFLAG_RD | CTLFLAG_MPSAFE,
3111         sysctl_kern_proc, "Process table");
3112
3113 static SYSCTL_NODE(_kern_proc, KERN_PROC_RGID, rgid, CTLFLAG_RD | CTLFLAG_MPSAFE,
3114         sysctl_kern_proc, "Process table");
3115
3116 static SYSCTL_NODE(_kern_proc, KERN_PROC_SESSION, sid, CTLFLAG_RD |
3117         CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3118
3119 static SYSCTL_NODE(_kern_proc, KERN_PROC_TTY, tty, CTLFLAG_RD | CTLFLAG_MPSAFE,
3120         sysctl_kern_proc, "Process table");
3121
3122 static SYSCTL_NODE(_kern_proc, KERN_PROC_UID, uid, CTLFLAG_RD | CTLFLAG_MPSAFE,
3123         sysctl_kern_proc, "Process table");
3124
3125 static SYSCTL_NODE(_kern_proc, KERN_PROC_RUID, ruid, CTLFLAG_RD | CTLFLAG_MPSAFE,
3126         sysctl_kern_proc, "Process table");
3127
3128 static SYSCTL_NODE(_kern_proc, KERN_PROC_PID, pid, CTLFLAG_RD | CTLFLAG_MPSAFE,
3129         sysctl_kern_proc, "Process table");
3130
3131 static SYSCTL_NODE(_kern_proc, KERN_PROC_PROC, proc, CTLFLAG_RD | CTLFLAG_MPSAFE,
3132         sysctl_kern_proc, "Return process table, no threads");
3133
3134 static SYSCTL_NODE(_kern_proc, KERN_PROC_ARGS, args,
3135         CTLFLAG_RW | CTLFLAG_CAPWR | CTLFLAG_ANYBODY | CTLFLAG_MPSAFE,
3136         sysctl_kern_proc_args, "Process argument list");
3137
3138 static SYSCTL_NODE(_kern_proc, KERN_PROC_ENV, env, CTLFLAG_RD | CTLFLAG_MPSAFE,
3139         sysctl_kern_proc_env, "Process environment");
3140
3141 static SYSCTL_NODE(_kern_proc, KERN_PROC_AUXV, auxv, CTLFLAG_RD |
3142         CTLFLAG_MPSAFE, sysctl_kern_proc_auxv, "Process ELF auxiliary vector");
3143
3144 static SYSCTL_NODE(_kern_proc, KERN_PROC_PATHNAME, pathname, CTLFLAG_RD |
3145         CTLFLAG_MPSAFE, sysctl_kern_proc_pathname, "Process executable path");
3146
3147 static SYSCTL_NODE(_kern_proc, KERN_PROC_SV_NAME, sv_name, CTLFLAG_RD |
3148         CTLFLAG_MPSAFE, sysctl_kern_proc_sv_name,
3149         "Process syscall vector name (ABI type)");
3150
3151 static SYSCTL_NODE(_kern_proc, (KERN_PROC_GID | KERN_PROC_INC_THREAD), gid_td,
3152         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3153
3154 static SYSCTL_NODE(_kern_proc, (KERN_PROC_PGRP | KERN_PROC_INC_THREAD), pgrp_td,
3155         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3156
3157 static SYSCTL_NODE(_kern_proc, (KERN_PROC_RGID | KERN_PROC_INC_THREAD), rgid_td,
3158         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3159
3160 static SYSCTL_NODE(_kern_proc, (KERN_PROC_SESSION | KERN_PROC_INC_THREAD),
3161         sid_td, CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3162
3163 static SYSCTL_NODE(_kern_proc, (KERN_PROC_TTY | KERN_PROC_INC_THREAD), tty_td,
3164         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3165
3166 static SYSCTL_NODE(_kern_proc, (KERN_PROC_UID | KERN_PROC_INC_THREAD), uid_td,
3167         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3168
3169 static SYSCTL_NODE(_kern_proc, (KERN_PROC_RUID | KERN_PROC_INC_THREAD), ruid_td,
3170         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3171
3172 static SYSCTL_NODE(_kern_proc, (KERN_PROC_PID | KERN_PROC_INC_THREAD), pid_td,
3173         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3174
3175 static SYSCTL_NODE(_kern_proc, (KERN_PROC_PROC | KERN_PROC_INC_THREAD), proc_td,
3176         CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc,
3177         "Return process table, no threads");
3178
3179 #ifdef COMPAT_FREEBSD7
3180 static SYSCTL_NODE(_kern_proc, KERN_PROC_OVMMAP, ovmmap, CTLFLAG_RD |
3181         CTLFLAG_MPSAFE, sysctl_kern_proc_ovmmap, "Old Process vm map entries");
3182 #endif
3183
3184 static SYSCTL_NODE(_kern_proc, KERN_PROC_VMMAP, vmmap, CTLFLAG_RD |
3185         CTLFLAG_MPSAFE, sysctl_kern_proc_vmmap, "Process vm map entries");
3186
3187 #if defined(STACK) || defined(DDB)
3188 static SYSCTL_NODE(_kern_proc, KERN_PROC_KSTACK, kstack, CTLFLAG_RD |
3189         CTLFLAG_MPSAFE, sysctl_kern_proc_kstack, "Process kernel stacks");
3190 #endif
3191
3192 static SYSCTL_NODE(_kern_proc, KERN_PROC_GROUPS, groups, CTLFLAG_RD |
3193         CTLFLAG_MPSAFE, sysctl_kern_proc_groups, "Process groups");
3194
3195 static SYSCTL_NODE(_kern_proc, KERN_PROC_RLIMIT, rlimit, CTLFLAG_RW |
3196         CTLFLAG_ANYBODY | CTLFLAG_MPSAFE, sysctl_kern_proc_rlimit,
3197         "Process resource limits");
3198
3199 static SYSCTL_NODE(_kern_proc, KERN_PROC_PS_STRINGS, ps_strings, CTLFLAG_RD |
3200         CTLFLAG_MPSAFE, sysctl_kern_proc_ps_strings,
3201         "Process ps_strings location");
3202
3203 static SYSCTL_NODE(_kern_proc, KERN_PROC_UMASK, umask, CTLFLAG_RD |
3204         CTLFLAG_MPSAFE, sysctl_kern_proc_umask, "Process umask");
3205
3206 static SYSCTL_NODE(_kern_proc, KERN_PROC_OSREL, osrel, CTLFLAG_RW |
3207         CTLFLAG_ANYBODY | CTLFLAG_MPSAFE, sysctl_kern_proc_osrel,
3208         "Process binary osreldate");
3209
3210 static SYSCTL_NODE(_kern_proc, KERN_PROC_SIGTRAMP, sigtramp, CTLFLAG_RD |
3211         CTLFLAG_MPSAFE, sysctl_kern_proc_sigtramp,
3212         "Process signal trampoline location");
3213
3214 static SYSCTL_NODE(_kern_proc, KERN_PROC_SIGFASTBLK, sigfastblk, CTLFLAG_RD |
3215         CTLFLAG_ANYBODY | CTLFLAG_MPSAFE, sysctl_kern_proc_sigfastblk,
3216         "Thread sigfastblock address");
3217
3218 int allproc_gen;
3219
3220 /*
3221  * stop_all_proc() purpose is to stop all process which have usermode,
3222  * except current process for obvious reasons.  This makes it somewhat
3223  * unreliable when invoked from multithreaded process.  The service
3224  * must not be user-callable anyway.
3225  */
3226 void
3227 stop_all_proc(void)
3228 {
3229         struct proc *cp, *p;
3230         int r, gen;
3231         bool restart, seen_stopped, seen_exiting, stopped_some;
3232
3233         cp = curproc;
3234 allproc_loop:
3235         sx_xlock(&allproc_lock);
3236         gen = allproc_gen;
3237         seen_exiting = seen_stopped = stopped_some = restart = false;
3238         LIST_REMOVE(cp, p_list);
3239         LIST_INSERT_HEAD(&allproc, cp, p_list);
3240         for (;;) {
3241                 p = LIST_NEXT(cp, p_list);
3242                 if (p == NULL)
3243                         break;
3244                 LIST_REMOVE(cp, p_list);
3245                 LIST_INSERT_AFTER(p, cp, p_list);
3246                 PROC_LOCK(p);
3247                 if ((p->p_flag & (P_KPROC | P_SYSTEM | P_TOTAL_STOP)) != 0) {
3248                         PROC_UNLOCK(p);
3249                         continue;
3250                 }
3251                 if ((p->p_flag & P_WEXIT) != 0) {
3252                         seen_exiting = true;
3253                         PROC_UNLOCK(p);
3254                         continue;
3255                 }
3256                 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
3257                         /*
3258                          * Stopped processes are tolerated when there
3259                          * are no other processes which might continue
3260                          * them.  P_STOPPED_SINGLE but not
3261                          * P_TOTAL_STOP process still has at least one
3262                          * thread running.
3263                          */
3264                         seen_stopped = true;
3265                         PROC_UNLOCK(p);
3266                         continue;
3267                 }
3268                 sx_xunlock(&allproc_lock);
3269                 _PHOLD(p);
3270                 r = thread_single(p, SINGLE_ALLPROC);
3271                 if (r != 0)
3272                         restart = true;
3273                 else
3274                         stopped_some = true;
3275                 _PRELE(p);
3276                 PROC_UNLOCK(p);
3277                 sx_xlock(&allproc_lock);
3278         }
3279         /* Catch forked children we did not see in iteration. */
3280         if (gen != allproc_gen)
3281                 restart = true;
3282         sx_xunlock(&allproc_lock);
3283         if (restart || stopped_some || seen_exiting || seen_stopped) {
3284                 kern_yield(PRI_USER);
3285                 goto allproc_loop;
3286         }
3287 }
3288
3289 void
3290 resume_all_proc(void)
3291 {
3292         struct proc *cp, *p;
3293
3294         cp = curproc;
3295         sx_xlock(&allproc_lock);
3296 again:
3297         LIST_REMOVE(cp, p_list);
3298         LIST_INSERT_HEAD(&allproc, cp, p_list);
3299         for (;;) {
3300                 p = LIST_NEXT(cp, p_list);
3301                 if (p == NULL)
3302                         break;
3303                 LIST_REMOVE(cp, p_list);
3304                 LIST_INSERT_AFTER(p, cp, p_list);
3305                 PROC_LOCK(p);
3306                 if ((p->p_flag & P_TOTAL_STOP) != 0) {
3307                         sx_xunlock(&allproc_lock);
3308                         _PHOLD(p);
3309                         thread_single_end(p, SINGLE_ALLPROC);
3310                         _PRELE(p);
3311                         PROC_UNLOCK(p);
3312                         sx_xlock(&allproc_lock);
3313                 } else {
3314                         PROC_UNLOCK(p);
3315                 }
3316         }
3317         /*  Did the loop above missed any stopped process ? */
3318         FOREACH_PROC_IN_SYSTEM(p) {
3319                 /* No need for proc lock. */
3320                 if ((p->p_flag & P_TOTAL_STOP) != 0)
3321                         goto again;
3322         }
3323         sx_xunlock(&allproc_lock);
3324 }
3325
3326 /* #define      TOTAL_STOP_DEBUG        1 */
3327 #ifdef TOTAL_STOP_DEBUG
3328 volatile static int ap_resume;
3329 #include <sys/mount.h>
3330
3331 static int
3332 sysctl_debug_stop_all_proc(SYSCTL_HANDLER_ARGS)
3333 {
3334         int error, val;
3335
3336         val = 0;
3337         ap_resume = 0;
3338         error = sysctl_handle_int(oidp, &val, 0, req);
3339         if (error != 0 || req->newptr == NULL)
3340                 return (error);
3341         if (val != 0) {
3342                 stop_all_proc();
3343                 syncer_suspend();
3344                 while (ap_resume == 0)
3345                         ;
3346                 syncer_resume();
3347                 resume_all_proc();
3348         }
3349         return (0);
3350 }
3351
3352 SYSCTL_PROC(_debug, OID_AUTO, stop_all_proc, CTLTYPE_INT | CTLFLAG_RW |
3353     CTLFLAG_MPSAFE, __DEVOLATILE(int *, &ap_resume), 0,
3354     sysctl_debug_stop_all_proc, "I",
3355     "");
3356 #endif