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