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