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