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