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