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