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