Home | History | Annotate | Line # | Download | only in kern
kern_proc.c revision 1.277
      1 /*	$NetBSD: kern_proc.c,v 1.277 2025/03/16 15:51:34 riastradh Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2006, 2007, 2008, 2020, 2023
      5  *     The NetBSD Foundation, Inc.
      6  * All rights reserved.
      7  *
      8  * This code is derived from software contributed to The NetBSD Foundation
      9  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
     10  * NASA Ames Research Center, and by Andrew Doran.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     31  * POSSIBILITY OF SUCH DAMAGE.
     32  */
     33 
     34 /*
     35  * Copyright (c) 1982, 1986, 1989, 1991, 1993
     36  *	The Regents of the University of California.  All rights reserved.
     37  *
     38  * Redistribution and use in source and binary forms, with or without
     39  * modification, are permitted provided that the following conditions
     40  * are met:
     41  * 1. Redistributions of source code must retain the above copyright
     42  *    notice, this list of conditions and the following disclaimer.
     43  * 2. Redistributions in binary form must reproduce the above copyright
     44  *    notice, this list of conditions and the following disclaimer in the
     45  *    documentation and/or other materials provided with the distribution.
     46  * 3. Neither the name of the University nor the names of its contributors
     47  *    may be used to endorse or promote products derived from this software
     48  *    without specific prior written permission.
     49  *
     50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     60  * SUCH DAMAGE.
     61  *
     62  *	@(#)kern_proc.c	8.7 (Berkeley) 2/14/95
     63  */
     64 
     65 #include <sys/cdefs.h>
     66 __KERNEL_RCSID(0, "$NetBSD: kern_proc.c,v 1.277 2025/03/16 15:51:34 riastradh Exp $");
     67 
     68 #ifdef _KERNEL_OPT
     69 #include "opt_kstack.h"
     70 #include "opt_maxuprc.h"
     71 #include "opt_dtrace.h"
     72 #include "opt_compat_netbsd32.h"
     73 #include "opt_kaslr.h"
     74 #endif
     75 
     76 #if defined(__HAVE_COMPAT_NETBSD32) && !defined(COMPAT_NETBSD32) \
     77     && !defined(_RUMPKERNEL)
     78 #define COMPAT_NETBSD32
     79 #endif
     80 
     81 #include <sys/param.h>
     82 #include <sys/types.h>
     83 
     84 #include <sys/acct.h>
     85 #include <sys/atomic.h>
     86 #include <sys/buf.h>
     87 #include <sys/compat_stub.h>
     88 #include <sys/cpu.h>
     89 #include <sys/dtrace_bsd.h>
     90 #include <sys/exec.h>
     91 #include <sys/file.h>
     92 #include <sys/filedesc.h>
     93 #include <sys/futex.h>
     94 #include <sys/ioctl.h>
     95 #include <sys/kauth.h>
     96 #include <sys/kernel.h>
     97 #include <sys/kmem.h>
     98 #include <sys/namei.h>
     99 #include <sys/pool.h>
    100 #include <sys/proc.h>
    101 #include <sys/pserialize.h>
    102 #include <sys/pset.h>
    103 #include <sys/ras.h>
    104 #include <sys/resourcevar.h>
    105 #include <sys/signalvar.h>
    106 #include <sys/sleepq.h>
    107 #include <sys/syscall_stats.h>
    108 #include <sys/sysctl.h>
    109 #include <sys/systm.h>
    110 #include <sys/tty.h>
    111 #include <sys/uio.h>
    112 #include <sys/wait.h>
    113 #include <ufs/ufs/quota.h>
    114 
    115 #include <uvm/uvm_extern.h>
    116 
    117 /*
    118  * Process lists.
    119  */
    120 
    121 struct proclist		allproc		__cacheline_aligned;
    122 struct proclist		zombproc	__cacheline_aligned;
    123 
    124 kmutex_t		proc_lock	__cacheline_aligned;
    125 static pserialize_t	proc_psz;
    126 
    127 /*
    128  * pid to lwp/proc lookup is done by indexing the pid_table array.
    129  * Since pid numbers are only allocated when an empty slot
    130  * has been found, there is no need to search any lists ever.
    131  * (an orphaned pgrp will lock the slot, a session will lock
    132  * the pgrp with the same number.)
    133  * If the table is too small it is reallocated with twice the
    134  * previous size and the entries 'unzipped' into the two halves.
    135  * A linked list of free entries is passed through the pt_lwp
    136  * field of 'free' items - set odd to be an invalid ptr.  Two
    137  * additional bits are also used to indicate if the slot is
    138  * currently occupied by a proc or lwp, and if the PID is
    139  * hidden from certain kinds of lookups.  We thus require a
    140  * minimum alignment for proc and lwp structures (LWPs are
    141  * at least 32-byte aligned).
    142  */
    143 
    144 struct pid_table {
    145 	uintptr_t	pt_slot;
    146 	struct pgrp	*pt_pgrp;
    147 	pid_t		pt_pid;
    148 };
    149 
    150 #define	PT_F_FREE		((uintptr_t)__BIT(0))
    151 #define	PT_F_LWP		0	/* pseudo-flag */
    152 #define	PT_F_PROC		((uintptr_t)__BIT(1))
    153 
    154 #define	PT_F_TYPEBITS		(PT_F_FREE|PT_F_PROC)
    155 #define	PT_F_ALLBITS		(PT_F_FREE|PT_F_PROC)
    156 
    157 #define	PT_VALID(s)		(((s) & PT_F_FREE) == 0)
    158 #define	PT_RESERVED(s)		((s) == 0)
    159 #define	PT_NEXT(s)		((u_int)(s) >> 1)
    160 #define	PT_SET_FREE(pid)	(((pid) << 1) | PT_F_FREE)
    161 #define	PT_SET_LWP(l)		((uintptr_t)(l))
    162 #define	PT_SET_PROC(p)		(((uintptr_t)(p)) | PT_F_PROC)
    163 #define	PT_SET_RESERVED		0
    164 #define	PT_GET_LWP(s)		((struct lwp *)((s) & ~PT_F_ALLBITS))
    165 #define	PT_GET_PROC(s)		((struct proc *)((s) & ~PT_F_ALLBITS))
    166 #define	PT_GET_TYPE(s)		((s) & PT_F_TYPEBITS)
    167 #define	PT_IS_LWP(s)		(PT_GET_TYPE(s) == PT_F_LWP && (s) != 0)
    168 #define	PT_IS_PROC(s)		(PT_GET_TYPE(s) == PT_F_PROC)
    169 
    170 #define	MIN_PROC_ALIGNMENT	(PT_F_ALLBITS + 1)
    171 
    172 /*
    173  * Table of process IDs (PIDs).
    174  */
    175 static struct pid_table *pid_table	__read_mostly;
    176 
    177 #define	INITIAL_PID_TABLE_SIZE		(1 << 5)
    178 
    179 /* Table mask, threshold for growing and number of allocated PIDs. */
    180 static u_int		pid_tbl_mask	__read_mostly;
    181 static u_int		pid_alloc_lim	__read_mostly;
    182 static u_int		pid_alloc_cnt	__cacheline_aligned;
    183 
    184 /* Next free, last free and maximum PIDs. */
    185 static u_int		next_free_pt	__cacheline_aligned;
    186 static u_int		last_free_pt	__cacheline_aligned;
    187 static pid_t		pid_max		__read_mostly;
    188 
    189 /* Components of the first process -- never freed. */
    190 
    191 struct session session0 = {
    192 	.s_count = 1,
    193 	.s_sid = 0,
    194 };
    195 struct pgrp pgrp0 = {
    196 	.pg_members = LIST_HEAD_INITIALIZER(&pgrp0.pg_members),
    197 	.pg_session = &session0,
    198 };
    199 filedesc_t filedesc0;
    200 struct cwdinfo cwdi0 = {
    201 	.cwdi_cmask = CMASK,
    202 	.cwdi_refcnt = 1,
    203 };
    204 struct plimit limit0;
    205 struct pstats pstat0;
    206 struct vmspace vmspace0;
    207 struct sigacts sigacts0;
    208 struct proc proc0 = {
    209 	.p_lwps = LIST_HEAD_INITIALIZER(&proc0.p_lwps),
    210 	.p_sigwaiters = LIST_HEAD_INITIALIZER(&proc0.p_sigwaiters),
    211 	.p_nlwps = 1,
    212 	.p_nrlwps = 1,
    213 	.p_pgrp = &pgrp0,
    214 	.p_comm = "system",
    215 	/*
    216 	 * Set P_NOCLDWAIT so that kernel threads are reparented to init(8)
    217 	 * when they exit.  init(8) can easily wait them out for us.
    218 	 */
    219 	.p_flag = PK_SYSTEM | PK_NOCLDWAIT,
    220 	.p_stat = SACTIVE,
    221 	.p_nice = NZERO,
    222 	.p_emul = &emul_netbsd,
    223 	.p_cwdi = &cwdi0,
    224 	.p_limit = &limit0,
    225 	.p_fd = &filedesc0,
    226 	.p_vmspace = &vmspace0,
    227 	.p_stats = &pstat0,
    228 	.p_sigacts = &sigacts0,
    229 #ifdef PROC0_MD_INITIALIZERS
    230 	PROC0_MD_INITIALIZERS
    231 #endif
    232 };
    233 kauth_cred_t cred0;
    234 
    235 static const int	nofile	= NOFILE;
    236 static const int	maxuprc	= MAXUPRC;
    237 
    238 static int sysctl_doeproc(SYSCTLFN_PROTO);
    239 static int sysctl_kern_proc_args(SYSCTLFN_PROTO);
    240 static int sysctl_security_expose_address(SYSCTLFN_PROTO);
    241 
    242 #ifdef KASLR
    243 static int kern_expose_address = 0;
    244 #else
    245 static int kern_expose_address = 1;
    246 #endif
    247 /*
    248  * The process list descriptors, used during pid allocation and
    249  * by sysctl.  No locking on this data structure is needed since
    250  * it is completely static.
    251  */
    252 const struct proclist_desc proclists[] = {
    253 	{ &allproc	},
    254 	{ &zombproc	},
    255 	{ NULL		},
    256 };
    257 
    258 static struct pgrp *	pg_remove(pid_t);
    259 static void		pg_delete(pid_t);
    260 static void		orphanpg(struct pgrp *);
    261 
    262 static specificdata_domain_t proc_specificdata_domain;
    263 
    264 static pool_cache_t proc_cache;
    265 
    266 static kauth_listener_t proc_listener;
    267 
    268 static void fill_proc(const struct proc *, struct proc *, bool);
    269 static int fill_pathname(struct lwp *, pid_t, void *, size_t *);
    270 static int fill_cwd(struct lwp *, pid_t, void *, size_t *);
    271 
    272 static int
    273 proc_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
    274     void *arg0, void *arg1, void *arg2, void *arg3)
    275 {
    276 	struct proc *p;
    277 	int result;
    278 
    279 	result = KAUTH_RESULT_DEFER;
    280 	p = arg0;
    281 
    282 	switch (action) {
    283 	case KAUTH_PROCESS_CANSEE: {
    284 		enum kauth_process_req req;
    285 
    286 		req = (enum kauth_process_req)(uintptr_t)arg1;
    287 
    288 		switch (req) {
    289 		case KAUTH_REQ_PROCESS_CANSEE_ARGS:
    290 		case KAUTH_REQ_PROCESS_CANSEE_ENTRY:
    291 		case KAUTH_REQ_PROCESS_CANSEE_OPENFILES:
    292 		case KAUTH_REQ_PROCESS_CANSEE_EPROC:
    293 			result = KAUTH_RESULT_ALLOW;
    294 			break;
    295 
    296 		case KAUTH_REQ_PROCESS_CANSEE_ENV:
    297 			if (kauth_cred_getuid(cred) !=
    298 			    kauth_cred_getuid(p->p_cred) ||
    299 			    kauth_cred_getuid(cred) !=
    300 			    kauth_cred_getsvuid(p->p_cred))
    301 				break;
    302 
    303 			result = KAUTH_RESULT_ALLOW;
    304 
    305 			break;
    306 
    307 		case KAUTH_REQ_PROCESS_CANSEE_KPTR:
    308 			if (!kern_expose_address)
    309 				break;
    310 
    311 			if (kern_expose_address == 1 && !(p->p_flag & PK_KMEM))
    312 				break;
    313 
    314 			result = KAUTH_RESULT_ALLOW;
    315 
    316 			break;
    317 
    318 		default:
    319 			break;
    320 		}
    321 
    322 		break;
    323 		}
    324 
    325 	case KAUTH_PROCESS_FORK: {
    326 		int lnprocs = (int)(unsigned long)arg2;
    327 
    328 		/*
    329 		 * Don't allow a nonprivileged user to use the last few
    330 		 * processes. The variable lnprocs is the current number of
    331 		 * processes, maxproc is the limit.
    332 		 */
    333 		if (__predict_false((lnprocs >= maxproc - 5)))
    334 			break;
    335 
    336 		result = KAUTH_RESULT_ALLOW;
    337 
    338 		break;
    339 		}
    340 
    341 	case KAUTH_PROCESS_CORENAME:
    342 	case KAUTH_PROCESS_STOPFLAG:
    343 		if (proc_uidmatch(cred, p->p_cred) == 0)
    344 			result = KAUTH_RESULT_ALLOW;
    345 
    346 		break;
    347 
    348 	default:
    349 		break;
    350 	}
    351 
    352 	return result;
    353 }
    354 
    355 static int
    356 proc_ctor(void *arg __unused, void *obj, int flags __unused)
    357 {
    358 	struct proc *p = obj;
    359 
    360 	memset(p, 0, sizeof(*p));
    361 	klist_init(&p->p_klist);
    362 
    363 	/*
    364 	 * There is no need for a proc_dtor() to do a klist_fini(),
    365 	 * since knote_proc_exit() ensures that p->p_klist is empty
    366 	 * when a process exits.
    367 	 */
    368 
    369 	return 0;
    370 }
    371 
    372 static pid_t proc_alloc_pid_slot(struct proc *, uintptr_t);
    373 
    374 /*
    375  * Initialize global process hashing structures.
    376  */
    377 void
    378 procinit(void)
    379 {
    380 	const struct proclist_desc *pd;
    381 	u_int i;
    382 #define	LINK_EMPTY ((PID_MAX + INITIAL_PID_TABLE_SIZE) & ~(INITIAL_PID_TABLE_SIZE - 1))
    383 
    384 	for (pd = proclists; pd->pd_list != NULL; pd++)
    385 		LIST_INIT(pd->pd_list);
    386 
    387 	mutex_init(&proc_lock, MUTEX_DEFAULT, IPL_NONE);
    388 
    389 	proc_psz = pserialize_create();
    390 
    391 	pid_table = kmem_alloc(INITIAL_PID_TABLE_SIZE
    392 	    * sizeof(struct pid_table), KM_SLEEP);
    393 	pid_tbl_mask = INITIAL_PID_TABLE_SIZE - 1;
    394 	pid_max = PID_MAX;
    395 
    396 	/* Set free list running through table...
    397 	   Preset 'use count' above PID_MAX so we allocate pid 1 next. */
    398 	for (i = 0; i <= pid_tbl_mask; i++) {
    399 		pid_table[i].pt_slot = PT_SET_FREE(LINK_EMPTY + i + 1);
    400 		pid_table[i].pt_pgrp = 0;
    401 		pid_table[i].pt_pid = 0;
    402 	}
    403 	/* slot 0 is just grabbed */
    404 	next_free_pt = 1;
    405 	/* Need to fix last entry. */
    406 	last_free_pt = pid_tbl_mask;
    407 	pid_table[last_free_pt].pt_slot = PT_SET_FREE(LINK_EMPTY);
    408 	/* point at which we grow table - to avoid reusing pids too often */
    409 	pid_alloc_lim = pid_tbl_mask - 1;
    410 #undef LINK_EMPTY
    411 
    412 	/* Reserve PID 1 for init(8). */	/* XXX slightly gross */
    413 	mutex_enter(&proc_lock);
    414 	if (proc_alloc_pid_slot(&proc0, PT_SET_RESERVED) != 1)
    415 		panic("failed to reserve PID 1 for init(8)");
    416 	mutex_exit(&proc_lock);
    417 
    418 	proc_specificdata_domain = specificdata_domain_create();
    419 	KASSERT(proc_specificdata_domain != NULL);
    420 
    421 	size_t proc_alignment = coherency_unit;
    422 	if (proc_alignment < MIN_PROC_ALIGNMENT)
    423 		proc_alignment = MIN_PROC_ALIGNMENT;
    424 
    425 	proc_cache = pool_cache_init(sizeof(struct proc), proc_alignment, 0, 0,
    426 	    "procpl", NULL, IPL_NONE, proc_ctor, NULL, NULL);
    427 
    428 	proc_listener = kauth_listen_scope(KAUTH_SCOPE_PROCESS,
    429 	    proc_listener_cb, NULL);
    430 }
    431 
    432 void
    433 procinit_sysctl(void)
    434 {
    435 	static struct sysctllog *clog;
    436 
    437 	sysctl_createv(&clog, 0, NULL, NULL,
    438 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    439 		       CTLTYPE_INT, "expose_address",
    440 		       SYSCTL_DESCR("Enable exposing kernel addresses"),
    441 		       sysctl_security_expose_address, 0,
    442 		       &kern_expose_address, 0, CTL_KERN, CTL_CREATE, CTL_EOL);
    443 	sysctl_createv(&clog, 0, NULL, NULL,
    444 		       CTLFLAG_PERMANENT,
    445 		       CTLTYPE_NODE, "proc",
    446 		       SYSCTL_DESCR("System-wide process information"),
    447 		       sysctl_doeproc, 0, NULL, 0,
    448 		       CTL_KERN, KERN_PROC, CTL_EOL);
    449 	sysctl_createv(&clog, 0, NULL, NULL,
    450 		       CTLFLAG_PERMANENT,
    451 		       CTLTYPE_NODE, "proc2",
    452 		       SYSCTL_DESCR("Machine-independent process information"),
    453 		       sysctl_doeproc, 0, NULL, 0,
    454 		       CTL_KERN, KERN_PROC2, CTL_EOL);
    455 	sysctl_createv(&clog, 0, NULL, NULL,
    456 		       CTLFLAG_PERMANENT,
    457 		       CTLTYPE_NODE, "proc_args",
    458 		       SYSCTL_DESCR("Process argument information"),
    459 		       sysctl_kern_proc_args, 0, NULL, 0,
    460 		       CTL_KERN, KERN_PROC_ARGS, CTL_EOL);
    461 
    462 	/*
    463 	  "nodes" under these:
    464 
    465 	  KERN_PROC_ALL
    466 	  KERN_PROC_PID pid
    467 	  KERN_PROC_PGRP pgrp
    468 	  KERN_PROC_SESSION sess
    469 	  KERN_PROC_TTY tty
    470 	  KERN_PROC_UID uid
    471 	  KERN_PROC_RUID uid
    472 	  KERN_PROC_GID gid
    473 	  KERN_PROC_RGID gid
    474 
    475 	  all in all, probably not worth the effort...
    476 	*/
    477 }
    478 
    479 /*
    480  * Initialize process 0.
    481  */
    482 void
    483 proc0_init(void)
    484 {
    485 	struct proc *p;
    486 	struct pgrp *pg;
    487 	struct rlimit *rlim;
    488 	rlim_t lim;
    489 	int i;
    490 
    491 	p = &proc0;
    492 	pg = &pgrp0;
    493 
    494 	mutex_init(&p->p_stmutex, MUTEX_DEFAULT, IPL_HIGH);
    495 	mutex_init(&p->p_auxlock, MUTEX_DEFAULT, IPL_NONE);
    496 	p->p_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
    497 
    498 	rw_init(&p->p_reflock);
    499 	cv_init(&p->p_waitcv, "wait");
    500 	cv_init(&p->p_lwpcv, "lwpwait");
    501 
    502 	LIST_INSERT_HEAD(&p->p_lwps, &lwp0, l_sibling);
    503 
    504 	KASSERT(lwp0.l_lid == 0);
    505 	pid_table[lwp0.l_lid].pt_slot = PT_SET_LWP(&lwp0);
    506 	LIST_INSERT_HEAD(&allproc, p, p_list);
    507 
    508 	pid_table[lwp0.l_lid].pt_pgrp = pg;
    509 	LIST_INSERT_HEAD(&pg->pg_members, p, p_pglist);
    510 
    511 #ifdef __HAVE_SYSCALL_INTERN
    512 	(*p->p_emul->e_syscall_intern)(p);
    513 #endif
    514 
    515 	/* Create credentials. */
    516 	cred0 = kauth_cred_alloc();
    517 	p->p_cred = cred0;
    518 
    519 	/* Create the CWD info. */
    520 	rw_init(&cwdi0.cwdi_lock);
    521 
    522 	/* Create the limits structures. */
    523 	mutex_init(&limit0.pl_lock, MUTEX_DEFAULT, IPL_NONE);
    524 
    525 	rlim = limit0.pl_rlimit;
    526 	for (i = 0; i < __arraycount(limit0.pl_rlimit); i++) {
    527 		rlim[i].rlim_cur = RLIM_INFINITY;
    528 		rlim[i].rlim_max = RLIM_INFINITY;
    529 	}
    530 
    531 	rlim[RLIMIT_NOFILE].rlim_max = maxfiles;
    532 	rlim[RLIMIT_NOFILE].rlim_cur = maxfiles < nofile ? maxfiles : nofile;
    533 
    534 	rlim[RLIMIT_NPROC].rlim_max = maxproc;
    535 	rlim[RLIMIT_NPROC].rlim_cur = maxproc < maxuprc ? maxproc : maxuprc;
    536 
    537 	lim = MIN(VM_MAXUSER_ADDRESS, ctob((rlim_t)uvm_availmem(false)));
    538 	rlim[RLIMIT_RSS].rlim_max = lim;
    539 	rlim[RLIMIT_MEMLOCK].rlim_max = lim;
    540 	rlim[RLIMIT_MEMLOCK].rlim_cur = lim / 3;
    541 
    542 	rlim[RLIMIT_NTHR].rlim_max = maxlwp;
    543 	rlim[RLIMIT_NTHR].rlim_cur = maxlwp / 2;
    544 
    545 	/* Note that default core name has zero length. */
    546 	limit0.pl_corename = defcorename;
    547 	limit0.pl_cnlen = 0;
    548 	limit0.pl_refcnt = 1;
    549 	limit0.pl_writeable = false;
    550 	limit0.pl_sv_limit = NULL;
    551 
    552 	/* Configure virtual memory system, set vm rlimits. */
    553 	uvm_init_limits(p);
    554 
    555 	/* Initialize file descriptor table for proc0. */
    556 	fd_init(&filedesc0);
    557 
    558 	/*
    559 	 * Initialize proc0's vmspace, which uses the kernel pmap.
    560 	 * All kernel processes (which never have user space mappings)
    561 	 * share proc0's vmspace, and thus, the kernel pmap.
    562 	 */
    563 	uvmspace_init(&vmspace0, pmap_kernel(), round_page(VM_MIN_ADDRESS),
    564 	    trunc_page(VM_MAXUSER_ADDRESS),
    565 #ifdef __USE_TOPDOWN_VM
    566 	    true
    567 #else
    568 	    false
    569 #endif
    570 	    );
    571 
    572 	/* Initialize signal state for proc0. XXX IPL_SCHED */
    573 	mutex_init(&p->p_sigacts->sa_mutex, MUTEX_DEFAULT, IPL_SCHED);
    574 	siginit(p);
    575 
    576 	proc_initspecific(p);
    577 	kdtrace_proc_ctor(NULL, p);
    578 }
    579 
    580 /*
    581  * Session reference counting.
    582  */
    583 
    584 void
    585 proc_sesshold(struct session *ss)
    586 {
    587 
    588 	KASSERT(mutex_owned(&proc_lock));
    589 	ss->s_count++;
    590 }
    591 
    592 void
    593 proc_sessrele(struct session *ss)
    594 {
    595 	struct pgrp *pg;
    596 
    597 	KASSERT(mutex_owned(&proc_lock));
    598 	KASSERT(ss->s_count > 0);
    599 
    600 	/*
    601 	 * We keep the pgrp with the same id as the session in order to
    602 	 * stop a process being given the same pid.  Since the pgrp holds
    603 	 * a reference to the session, it must be a 'zombie' pgrp by now.
    604 	 */
    605 	if (--ss->s_count == 0) {
    606 		pg = pg_remove(ss->s_sid);
    607 	} else {
    608 		pg = NULL;
    609 		ss = NULL;
    610 	}
    611 
    612 	mutex_exit(&proc_lock);
    613 
    614 	if (pg)
    615 		kmem_free(pg, sizeof(struct pgrp));
    616 	if (ss)
    617 		kmem_free(ss, sizeof(struct session));
    618 }
    619 
    620 /*
    621  * Check that the specified process group is in the session of the
    622  * specified process.
    623  * Treats -ve ids as process ids.
    624  * Used to validate TIOCSPGRP requests.
    625  */
    626 int
    627 pgid_in_session(struct proc *p, pid_t pg_id)
    628 {
    629 	struct pgrp *pgrp;
    630 	struct session *session;
    631 	int error;
    632 
    633 	if (pg_id <= INT_MIN)
    634 		return EINVAL;
    635 
    636 	mutex_enter(&proc_lock);
    637 	if (pg_id < 0) {
    638 		struct proc *p1 = proc_find(-pg_id);
    639 		if (p1 == NULL) {
    640 			error = EINVAL;
    641 			goto fail;
    642 		}
    643 		pgrp = p1->p_pgrp;
    644 	} else {
    645 		pgrp = pgrp_find(pg_id);
    646 		if (pgrp == NULL) {
    647 			error = EINVAL;
    648 			goto fail;
    649 		}
    650 	}
    651 	session = pgrp->pg_session;
    652 	error = (session != p->p_pgrp->pg_session) ? EPERM : 0;
    653 fail:
    654 	mutex_exit(&proc_lock);
    655 	return error;
    656 }
    657 
    658 /*
    659  * p_inferior: is p an inferior of q?
    660  */
    661 static inline bool
    662 p_inferior(struct proc *p, struct proc *q)
    663 {
    664 
    665 	KASSERT(mutex_owned(&proc_lock));
    666 
    667 	for (; p != q; p = p->p_pptr)
    668 		if (p->p_pid == 0)
    669 			return false;
    670 	return true;
    671 }
    672 
    673 /*
    674  * proc_find_lwp: locate an lwp in said proc by the ID.
    675  *
    676  * => Must be called with p::p_lock held.
    677  * => LSIDL lwps are not returned because they are only partially
    678  *    constructed while occupying the slot.
    679  * => Callers need to be careful about lwp::l_stat of the returned
    680  *    lwp.
    681  */
    682 struct lwp *
    683 proc_find_lwp(proc_t *p, pid_t pid)
    684 {
    685 	struct pid_table *pt;
    686 	unsigned pt_mask;
    687 	struct lwp *l = NULL;
    688 	uintptr_t slot;
    689 	int s;
    690 
    691 	KASSERT(mutex_owned(p->p_lock));
    692 
    693 	/*
    694 	 * Look in the pid_table.  This is done unlocked inside a
    695 	 * pserialize read section covering pid_table's memory
    696 	 * allocation only, so take care to read things in the correct
    697 	 * order:
    698 	 *
    699 	 * 1. First read the table mask -- this only ever increases, in
    700 	 *    expand_pid_table, so a stale value is safely
    701 	 *    conservative.
    702 	 *
    703 	 * 2. Next read the pid table -- this is always set _before_
    704 	 *    the mask increases, so if we see a new table and stale
    705 	 *    mask, the mask is still valid for the table.
    706 	 */
    707 	s = pserialize_read_enter();
    708 	pt_mask = atomic_load_acquire(&pid_tbl_mask);
    709 	pt = &atomic_load_consume(&pid_table)[pid & pt_mask];
    710 	slot = atomic_load_consume(&pt->pt_slot);
    711 	if (__predict_false(!PT_IS_LWP(slot))) {
    712 		pserialize_read_exit(s);
    713 		return NULL;
    714 	}
    715 
    716 	/*
    717 	 * Check to see if the LWP is from the correct process.  We won't
    718 	 * see entries in pid_table from a prior process that also used "p",
    719 	 * by virtue of the fact that allocating "p" means all prior updates
    720 	 * to dependant data structures are visible to this thread.
    721 	 */
    722 	l = PT_GET_LWP(slot);
    723 	if (__predict_false(atomic_load_relaxed(&l->l_proc) != p)) {
    724 		pserialize_read_exit(s);
    725 		return NULL;
    726 	}
    727 
    728 	/*
    729 	 * We now know that p->p_lock holds this LWP stable.
    730 	 *
    731 	 * If the status is not LSIDL, it means the LWP is intended to be
    732 	 * findable by LID and l_lid cannot change behind us.
    733 	 *
    734 	 * No need to acquire the LWP's lock to check for LSIDL, as
    735 	 * p->p_lock must be held to transition in and out of LSIDL.
    736 	 * Any other observed state of is no particular interest.
    737 	 */
    738 	pserialize_read_exit(s);
    739 	return l->l_stat != LSIDL && l->l_lid == pid ? l : NULL;
    740 }
    741 
    742 /*
    743  * proc_find_lwp_unlocked: locate an lwp in said proc by the ID.
    744  *
    745  * => Called in a pserialize read section with no locks held.
    746  * => LSIDL lwps are not returned because they are only partially
    747  *    constructed while occupying the slot.
    748  * => Callers need to be careful about lwp::l_stat of the returned
    749  *    lwp.
    750  * => If an LWP is found, it's returned locked.
    751  */
    752 struct lwp *
    753 proc_find_lwp_unlocked(proc_t *p, pid_t pid)
    754 {
    755 	struct pid_table *pt;
    756 	unsigned pt_mask;
    757 	struct lwp *l = NULL;
    758 	uintptr_t slot;
    759 
    760 	KASSERT(pserialize_in_read_section());
    761 
    762 	/*
    763 	 * Look in the pid_table.  This is done unlocked inside a
    764 	 * pserialize read section covering pid_table's memory
    765 	 * allocation only, so take care to read things in the correct
    766 	 * order:
    767 	 *
    768 	 * 1. First read the table mask -- this only ever increases, in
    769 	 *    expand_pid_table, so a stale value is safely
    770 	 *    conservative.
    771 	 *
    772 	 * 2. Next read the pid table -- this is always set _before_
    773 	 *    the mask increases, so if we see a new table and stale
    774 	 *    mask, the mask is still valid for the table.
    775 	 */
    776 	pt_mask = atomic_load_acquire(&pid_tbl_mask);
    777 	pt = &atomic_load_consume(&pid_table)[pid & pt_mask];
    778 	slot = atomic_load_consume(&pt->pt_slot);
    779 	if (__predict_false(!PT_IS_LWP(slot))) {
    780 		return NULL;
    781 	}
    782 
    783 	/*
    784 	 * Lock the LWP we found to get it stable.  If it's embryonic or
    785 	 * reaped (LSIDL) then none of the other fields can safely be
    786 	 * checked.
    787 	 */
    788 	l = PT_GET_LWP(slot);
    789 	lwp_lock(l);
    790 	if (__predict_false(l->l_stat == LSIDL)) {
    791 		lwp_unlock(l);
    792 		return NULL;
    793 	}
    794 
    795 	/*
    796 	 * l_proc and l_lid are now known stable because the LWP is not
    797 	 * LSIDL, so check those fields too to make sure we found the
    798 	 * right thing.
    799 	 */
    800 	if (__predict_false(l->l_proc != p || l->l_lid != pid)) {
    801 		lwp_unlock(l);
    802 		return NULL;
    803 	}
    804 
    805 	/* Everything checks out, return it locked. */
    806 	return l;
    807 }
    808 
    809 /*
    810  * proc_find_lwp_acquire_proc: locate an lwp and acquire a lock
    811  * on its containing proc.
    812  *
    813  * => Similar to proc_find_lwp(), but does not require you to have
    814  *    the proc a priori.
    815  * => Also returns proc * to caller, with p::p_lock held.
    816  * => Same caveats apply.
    817  */
    818 struct lwp *
    819 proc_find_lwp_acquire_proc(pid_t pid, struct proc **pp)
    820 {
    821 	struct pid_table *pt;
    822 	struct proc *p = NULL;
    823 	struct lwp *l = NULL;
    824 	uintptr_t slot;
    825 
    826 	KASSERT(pp != NULL);
    827 	mutex_enter(&proc_lock);
    828 	pt = &pid_table[pid & pid_tbl_mask];
    829 
    830 	slot = pt->pt_slot;
    831 	if (__predict_true(PT_IS_LWP(slot) && pt->pt_pid == pid)) {
    832 		l = PT_GET_LWP(slot);
    833 		p = l->l_proc;
    834 		mutex_enter(p->p_lock);
    835 		if (__predict_false(l->l_stat == LSIDL)) {
    836 			mutex_exit(p->p_lock);
    837 			l = NULL;
    838 			p = NULL;
    839 		}
    840 	}
    841 	mutex_exit(&proc_lock);
    842 
    843 	KASSERT(p == NULL || mutex_owned(p->p_lock));
    844 	*pp = p;
    845 	return l;
    846 }
    847 
    848 /*
    849  * proc_find_raw_pid_table_locked: locate a process by the ID.
    850  *
    851  * => Must be called with proc_lock held.
    852  */
    853 static proc_t *
    854 proc_find_raw_pid_table_locked(pid_t pid, bool any_lwpid)
    855 {
    856 	struct pid_table *pt;
    857 	proc_t *p = NULL;
    858 	uintptr_t slot;
    859 
    860 	/* No - used by DDB.  KASSERT(mutex_owned(&proc_lock)); */
    861 	pt = &pid_table[pid & pid_tbl_mask];
    862 
    863 	slot = pt->pt_slot;
    864 	if (__predict_true(PT_IS_LWP(slot) && pt->pt_pid == pid)) {
    865 		/*
    866 		 * When looking up processes, require a direct match
    867 		 * on the PID assigned to the proc, not just one of
    868 		 * its LWPs.
    869 		 *
    870 		 * N.B. We require lwp::l_proc of LSIDL LWPs to be
    871 		 * valid here.
    872 		 */
    873 		p = PT_GET_LWP(slot)->l_proc;
    874 		if (__predict_false(p->p_pid != pid && !any_lwpid))
    875 			p = NULL;
    876 	} else if (PT_IS_PROC(slot) && pt->pt_pid == pid) {
    877 		p = PT_GET_PROC(slot);
    878 	}
    879 	return p;
    880 }
    881 
    882 proc_t *
    883 proc_find_raw(pid_t pid)
    884 {
    885 
    886 	return proc_find_raw_pid_table_locked(pid, false);
    887 }
    888 
    889 static proc_t *
    890 proc_find_internal(pid_t pid, bool any_lwpid)
    891 {
    892 	proc_t *p;
    893 
    894 	KASSERT(mutex_owned(&proc_lock));
    895 
    896 	p = proc_find_raw_pid_table_locked(pid, any_lwpid);
    897 	if (__predict_false(p == NULL)) {
    898 		return NULL;
    899 	}
    900 
    901 	/*
    902 	 * Only allow live processes to be found by PID.
    903 	 * XXX: p_stat might change, since proc unlocked.
    904 	 */
    905 	if (__predict_true(p->p_stat == SACTIVE || p->p_stat == SSTOP)) {
    906 		return p;
    907 	}
    908 	return NULL;
    909 }
    910 
    911 proc_t *
    912 proc_find(pid_t pid)
    913 {
    914 	return proc_find_internal(pid, false);
    915 }
    916 
    917 proc_t *
    918 proc_find_lwpid(pid_t pid)
    919 {
    920 	return proc_find_internal(pid, true);
    921 }
    922 
    923 /*
    924  * pgrp_find: locate a process group by the ID.
    925  *
    926  * => Must be called with proc_lock held.
    927  */
    928 struct pgrp *
    929 pgrp_find(pid_t pgid)
    930 {
    931 	struct pgrp *pg;
    932 
    933 	KASSERT(mutex_owned(&proc_lock));
    934 
    935 	pg = pid_table[pgid & pid_tbl_mask].pt_pgrp;
    936 
    937 	/*
    938 	 * Cannot look up a process group that only exists because the
    939 	 * session has not died yet (traditional).
    940 	 */
    941 	if (pg == NULL || pg->pg_id != pgid || LIST_EMPTY(&pg->pg_members)) {
    942 		return NULL;
    943 	}
    944 	return pg;
    945 }
    946 
    947 static void
    948 expand_pid_table(void)
    949 {
    950 	size_t pt_size, tsz;
    951 	struct pid_table *n_pt, *new_pt;
    952 	uintptr_t slot;
    953 	struct pgrp *pgrp;
    954 	pid_t pid, rpid;
    955 	u_int i;
    956 	uint new_pt_mask;
    957 
    958 	KASSERT(mutex_owned(&proc_lock));
    959 
    960 	/* Unlock the pid_table briefly to allocate memory. */
    961 	pt_size = pid_tbl_mask + 1;
    962 	mutex_exit(&proc_lock);
    963 
    964 	tsz = pt_size * 2 * sizeof(struct pid_table);
    965 	new_pt = kmem_alloc(tsz, KM_SLEEP);
    966 	new_pt_mask = pt_size * 2 - 1;
    967 
    968 	/* XXX For now.  The pratical limit is much lower anyway. */
    969 	KASSERT(new_pt_mask <= FUTEX_TID_MASK);
    970 
    971 	mutex_enter(&proc_lock);
    972 	if (pt_size != pid_tbl_mask + 1) {
    973 		/* Another process beat us to it... */
    974 		mutex_exit(&proc_lock);
    975 		kmem_free(new_pt, tsz);
    976 		goto out;
    977 	}
    978 
    979 	/*
    980 	 * Copy entries from old table into new one.
    981 	 * If 'pid' is 'odd' we need to place in the upper half,
    982 	 * even pid's to the lower half.
    983 	 * Free items stay in the low half so we don't have to
    984 	 * fixup the reference to them.
    985 	 * We stuff free items on the front of the freelist
    986 	 * because we can't write to unmodified entries.
    987 	 * Processing the table backwards maintains a semblance
    988 	 * of issuing pid numbers that increase with time.
    989 	 */
    990 	i = pt_size - 1;
    991 	n_pt = new_pt + i;
    992 	for (; ; i--, n_pt--) {
    993 		slot = pid_table[i].pt_slot;
    994 		pgrp = pid_table[i].pt_pgrp;
    995 		if (!PT_VALID(slot)) {
    996 			/* Up 'use count' so that link is valid */
    997 			pid = (PT_NEXT(slot) + pt_size) & ~pt_size;
    998 			rpid = 0;
    999 			slot = PT_SET_FREE(pid);
   1000 			if (pgrp)
   1001 				pid = pgrp->pg_id;
   1002 		} else {
   1003 			pid = pid_table[i].pt_pid;
   1004 			rpid = pid;
   1005 		}
   1006 
   1007 		/* Save entry in appropriate half of table */
   1008 		n_pt[pid & pt_size].pt_slot = slot;
   1009 		n_pt[pid & pt_size].pt_pgrp = pgrp;
   1010 		n_pt[pid & pt_size].pt_pid = rpid;
   1011 
   1012 		/* Put other piece on start of free list */
   1013 		pid = (pid ^ pt_size) & ~pid_tbl_mask;
   1014 		n_pt[pid & pt_size].pt_slot =
   1015 			PT_SET_FREE((pid & ~pt_size) | next_free_pt);
   1016 		n_pt[pid & pt_size].pt_pgrp = 0;
   1017 		n_pt[pid & pt_size].pt_pid = 0;
   1018 
   1019 		next_free_pt = i | (pid & pt_size);
   1020 		if (i == 0)
   1021 			break;
   1022 	}
   1023 
   1024 	/* Save old table size and switch tables */
   1025 	tsz = pt_size * sizeof(struct pid_table);
   1026 	n_pt = pid_table;
   1027 	atomic_store_release(&pid_table, new_pt);
   1028 	KASSERT(new_pt_mask >= pid_tbl_mask);
   1029 	atomic_store_release(&pid_tbl_mask, new_pt_mask);
   1030 
   1031 	/*
   1032 	 * pid_max starts as PID_MAX (= 30000), once we have 16384
   1033 	 * allocated pids we need it to be larger!
   1034 	 */
   1035 	if (pid_tbl_mask > PID_MAX) {
   1036 		pid_max = pid_tbl_mask * 2 + 1;
   1037 		pid_alloc_lim |= pid_alloc_lim << 1;
   1038 	} else
   1039 		pid_alloc_lim <<= 1;	/* doubles number of free slots... */
   1040 
   1041 	mutex_exit(&proc_lock);
   1042 
   1043 	/*
   1044 	 * Make sure that unlocked access to the old pid_table is complete
   1045 	 * and then free it.
   1046 	 */
   1047 	pserialize_perform(proc_psz);
   1048 	kmem_free(n_pt, tsz);
   1049 
   1050  out:	/* Return with proc_lock held again. */
   1051 	mutex_enter(&proc_lock);
   1052 }
   1053 
   1054 struct proc *
   1055 proc_alloc(void)
   1056 {
   1057 	struct proc *p;
   1058 
   1059 	p = pool_cache_get(proc_cache, PR_WAITOK);
   1060 	p->p_stat = SIDL;			/* protect against others */
   1061 	proc_initspecific(p);
   1062 	kdtrace_proc_ctor(NULL, p);
   1063 
   1064 	/*
   1065 	 * Allocate a placeholder in the pid_table.  When we create the
   1066 	 * first LWP for this process, it will take ownership of the
   1067 	 * slot.
   1068 	 */
   1069 	if (__predict_false(proc_alloc_pid(p) == -1)) {
   1070 		/* Allocating the PID failed; unwind. */
   1071 		proc_finispecific(p);
   1072 		proc_free_mem(p);
   1073 		p = NULL;
   1074 	}
   1075 	return p;
   1076 }
   1077 
   1078 /*
   1079  * proc_alloc_pid_slot: allocate PID and record the occupant so that
   1080  * proc_find_raw() can find it by the PID.
   1081  */
   1082 static pid_t __noinline
   1083 proc_alloc_pid_slot(struct proc *p, uintptr_t slot)
   1084 {
   1085 	struct pid_table *pt;
   1086 	pid_t pid;
   1087 	int nxt;
   1088 
   1089 	KASSERT(mutex_owned(&proc_lock));
   1090 
   1091 	for (;;expand_pid_table()) {
   1092 		if (__predict_false(pid_alloc_cnt >= pid_alloc_lim)) {
   1093 			/* ensure pids cycle through 2000+ values */
   1094 			continue;
   1095 		}
   1096 		/*
   1097 		 * The first user process *must* be given PID 1.
   1098 		 * it has already been reserved for us.  This
   1099 		 * will be coming in from the proc_alloc() call
   1100 		 * above, and the entry will be usurped later when
   1101 		 * the first user LWP is created.
   1102 		 * XXX this is slightly gross.
   1103 		 */
   1104 		if (__predict_false(PT_RESERVED(pid_table[1].pt_slot) &&
   1105 				    p != &proc0)) {
   1106 			KASSERT(PT_IS_PROC(slot));
   1107 			pt = &pid_table[1];
   1108 			pt->pt_slot = slot;
   1109 			return 1;
   1110 		}
   1111 		pt = &pid_table[next_free_pt];
   1112 #ifdef DIAGNOSTIC
   1113 		if (__predict_false(PT_VALID(pt->pt_slot) || pt->pt_pgrp))
   1114 			panic("proc_alloc: slot busy");
   1115 #endif
   1116 		nxt = PT_NEXT(pt->pt_slot);
   1117 		if (nxt & pid_tbl_mask)
   1118 			break;
   1119 		/* Table full - expand (NB last entry not used....) */
   1120 	}
   1121 
   1122 	/* pid is 'saved use count' + 'size' + entry */
   1123 	pid = (nxt & ~pid_tbl_mask) + pid_tbl_mask + 1 + next_free_pt;
   1124 	if ((uint)pid > (uint)pid_max)
   1125 		pid &= pid_tbl_mask;
   1126 	next_free_pt = nxt & pid_tbl_mask;
   1127 
   1128 	/* XXX For now.  The pratical limit is much lower anyway. */
   1129 	KASSERT(pid <= FUTEX_TID_MASK);
   1130 
   1131 	/* Grab table slot */
   1132 	pt->pt_slot = slot;
   1133 
   1134 	KASSERT(pt->pt_pid == 0);
   1135 	pt->pt_pid = pid;
   1136 	pid_alloc_cnt++;
   1137 
   1138 	return pid;
   1139 }
   1140 
   1141 pid_t
   1142 proc_alloc_pid(struct proc *p)
   1143 {
   1144 	pid_t pid;
   1145 
   1146 	KASSERT((((uintptr_t)p) & PT_F_ALLBITS) == 0);
   1147 	KASSERT(p->p_stat == SIDL);
   1148 
   1149 	mutex_enter(&proc_lock);
   1150 	pid = proc_alloc_pid_slot(p, PT_SET_PROC(p));
   1151 	if (pid != -1)
   1152 		p->p_pid = pid;
   1153 	mutex_exit(&proc_lock);
   1154 
   1155 	return pid;
   1156 }
   1157 
   1158 pid_t
   1159 proc_alloc_lwpid(struct proc *p, struct lwp *l)
   1160 {
   1161 	struct pid_table *pt;
   1162 	pid_t pid;
   1163 
   1164 	KASSERT((((uintptr_t)l) & PT_F_ALLBITS) == 0);
   1165 	KASSERT(l->l_proc == p);
   1166 	KASSERT(l->l_stat == LSIDL);
   1167 
   1168 	/*
   1169 	 * For unlocked lookup in proc_find_lwp(), make sure l->l_proc
   1170 	 * is globally visible before the LWP becomes visible via the
   1171 	 * pid_table.
   1172 	 */
   1173 #ifndef __HAVE_ATOMIC_AS_MEMBAR
   1174 	membar_producer();
   1175 #endif
   1176 
   1177 	/*
   1178 	 * If the slot for p->p_pid currently points to the proc,
   1179 	 * then we should usurp this ID for the LWP.  This happens
   1180 	 * at least once per process (for the first LWP), and can
   1181 	 * happen again if the first LWP for a process exits and
   1182 	 * before the process creates another.
   1183 	 */
   1184 	mutex_enter(&proc_lock);
   1185 	pid = p->p_pid;
   1186 	pt = &pid_table[pid & pid_tbl_mask];
   1187 	KASSERT(pt->pt_pid == pid);
   1188 	if (PT_IS_PROC(pt->pt_slot)) {
   1189 		KASSERT(PT_GET_PROC(pt->pt_slot) == p);
   1190 		l->l_lid = pid;
   1191 		pt->pt_slot = PT_SET_LWP(l);
   1192 	} else {
   1193 		/* Need to allocate a new slot. */
   1194 		pid = proc_alloc_pid_slot(p, PT_SET_LWP(l));
   1195 		if (pid != -1)
   1196 			l->l_lid = pid;
   1197 	}
   1198 	mutex_exit(&proc_lock);
   1199 
   1200 	return pid;
   1201 }
   1202 
   1203 static void __noinline
   1204 proc_free_pid_internal(pid_t pid, uintptr_t type __diagused)
   1205 {
   1206 	struct pid_table *pt;
   1207 
   1208 	KASSERT(mutex_owned(&proc_lock));
   1209 
   1210 	pt = &pid_table[pid & pid_tbl_mask];
   1211 
   1212 	KASSERT(PT_GET_TYPE(pt->pt_slot) == type);
   1213 	KASSERT(pt->pt_pid == pid);
   1214 
   1215 	/* save pid use count in slot */
   1216 	pt->pt_slot = PT_SET_FREE(pid & ~pid_tbl_mask);
   1217 	pt->pt_pid = 0;
   1218 
   1219 	if (pt->pt_pgrp == NULL) {
   1220 		/* link last freed entry onto ours */
   1221 		pid &= pid_tbl_mask;
   1222 		pt = &pid_table[last_free_pt];
   1223 		pt->pt_slot = PT_SET_FREE(PT_NEXT(pt->pt_slot) | pid);
   1224 		pt->pt_pid = 0;
   1225 		last_free_pt = pid;
   1226 		pid_alloc_cnt--;
   1227 	}
   1228 }
   1229 
   1230 /*
   1231  * Free a process id - called from proc_free (in kern_exit.c)
   1232  *
   1233  * Called with the proc_lock held.
   1234  */
   1235 void
   1236 proc_free_pid(pid_t pid)
   1237 {
   1238 
   1239 	KASSERT(mutex_owned(&proc_lock));
   1240 	proc_free_pid_internal(pid, PT_F_PROC);
   1241 }
   1242 
   1243 /*
   1244  * Free a process id used by an LWP.  If this was the process's
   1245  * first LWP, we convert the slot to point to the process; the
   1246  * entry will get cleaned up later when the process finishes exiting.
   1247  *
   1248  * If not, then it's the same as proc_free_pid().
   1249  */
   1250 void
   1251 proc_free_lwpid(struct proc *p, pid_t pid)
   1252 {
   1253 
   1254 	KASSERT(mutex_owned(&proc_lock));
   1255 
   1256 	if (__predict_true(p->p_pid == pid)) {
   1257 		struct pid_table *pt;
   1258 
   1259 		pt = &pid_table[pid & pid_tbl_mask];
   1260 
   1261 		KASSERT(pt->pt_pid == pid);
   1262 		KASSERT(PT_IS_LWP(pt->pt_slot));
   1263 		KASSERT(PT_GET_LWP(pt->pt_slot)->l_proc == p);
   1264 
   1265 		pt->pt_slot = PT_SET_PROC(p);
   1266 		return;
   1267 	}
   1268 	proc_free_pid_internal(pid, PT_F_LWP);
   1269 }
   1270 
   1271 void
   1272 proc_free_mem(struct proc *p)
   1273 {
   1274 
   1275 	kdtrace_proc_dtor(NULL, p);
   1276 	pool_cache_put(proc_cache, p);
   1277 }
   1278 
   1279 /*
   1280  * proc_enterpgrp: move p to a new or existing process group (and session).
   1281  *
   1282  * If we are creating a new pgrp, the pgid should equal
   1283  * the calling process' pid.
   1284  * If is only valid to enter a process group that is in the session
   1285  * of the process.
   1286  * Also mksess should only be set if we are creating a process group
   1287  *
   1288  * Only called from sys_setsid, sys_setpgid and posix_spawn/spawn_return.
   1289  */
   1290 int
   1291 proc_enterpgrp(struct proc *curp, pid_t pid, pid_t pgid, bool mksess)
   1292 {
   1293 	struct pgrp *new_pgrp, *pgrp;
   1294 	struct session *sess;
   1295 	struct proc *p;
   1296 	int rval;
   1297 	pid_t pg_id = NO_PGID;
   1298 
   1299 	/* Allocate data areas we might need before doing any validity checks */
   1300 	sess = mksess ? kmem_alloc(sizeof(*sess), KM_SLEEP) : NULL;
   1301 	new_pgrp = kmem_alloc(sizeof(*new_pgrp), KM_SLEEP);
   1302 
   1303 	mutex_enter(&proc_lock);
   1304 	rval = EPERM;	/* most common error (to save typing) */
   1305 
   1306 	/* Check pgrp exists or can be created */
   1307 	pgrp = pid_table[pgid & pid_tbl_mask].pt_pgrp;
   1308 	if (pgrp != NULL && pgrp->pg_id != pgid)
   1309 		goto done;
   1310 
   1311 	/* Can only set another process under restricted circumstances. */
   1312 	if (pid != curp->p_pid) {
   1313 		/* Must exist and be one of our children... */
   1314 		p = proc_find_internal(pid, false);
   1315 		if (p == NULL || !p_inferior(p, curp)) {
   1316 			rval = ESRCH;
   1317 			goto done;
   1318 		}
   1319 		/* ... in the same session... */
   1320 		if (sess != NULL || p->p_session != curp->p_session)
   1321 			goto done;
   1322 		/* ... existing pgid must be in same session ... */
   1323 		if (pgrp != NULL && pgrp->pg_session != p->p_session)
   1324 			goto done;
   1325 		/* ... and not done an exec. */
   1326 		if (p->p_flag & PK_EXEC) {
   1327 			rval = EACCES;
   1328 			goto done;
   1329 		}
   1330 	} else {
   1331 		/* ... setsid() cannot re-enter a pgrp */
   1332 		if (mksess && (curp->p_pgid == curp->p_pid ||
   1333 		    pgrp_find(curp->p_pid)))
   1334 			goto done;
   1335 		p = curp;
   1336 	}
   1337 
   1338 	/* Changing the process group/session of a session
   1339 	   leader is definitely off limits. */
   1340 	if (SESS_LEADER(p)) {
   1341 		if (sess == NULL && p->p_pgrp == pgrp)
   1342 			/* unless it's a definite noop */
   1343 			rval = 0;
   1344 		goto done;
   1345 	}
   1346 
   1347 	/* Can only create a process group with id of process */
   1348 	if (pgrp == NULL && pgid != pid)
   1349 		goto done;
   1350 
   1351 	/* Can only create a session if creating pgrp */
   1352 	if (sess != NULL && pgrp != NULL)
   1353 		goto done;
   1354 
   1355 	/* Check we allocated memory for a pgrp... */
   1356 	if (pgrp == NULL && new_pgrp == NULL)
   1357 		goto done;
   1358 
   1359 	/* Don't attach to 'zombie' pgrp */
   1360 	if (pgrp != NULL && LIST_EMPTY(&pgrp->pg_members))
   1361 		goto done;
   1362 
   1363 	/* Expect to succeed now */
   1364 	rval = 0;
   1365 
   1366 	if (pgrp == p->p_pgrp)
   1367 		/* nothing to do */
   1368 		goto done;
   1369 
   1370 	/* Ok all setup, link up required structures */
   1371 
   1372 	if (pgrp == NULL) {
   1373 		pgrp = new_pgrp;
   1374 		new_pgrp = NULL;
   1375 		if (sess != NULL) {
   1376 			sess->s_sid = p->p_pid;
   1377 			sess->s_leader = p;
   1378 			sess->s_count = 1;
   1379 			sess->s_ttyvp = NULL;
   1380 			sess->s_ttyp = NULL;
   1381 			sess->s_flags = p->p_session->s_flags & ~S_LOGIN_SET;
   1382 			memcpy(sess->s_login, p->p_session->s_login,
   1383 			    sizeof(sess->s_login));
   1384 			p->p_lflag &= ~PL_CONTROLT;
   1385 		} else {
   1386 			sess = p->p_pgrp->pg_session;
   1387 			proc_sesshold(sess);
   1388 		}
   1389 		pgrp->pg_session = sess;
   1390 		sess = NULL;
   1391 
   1392 		pgrp->pg_id = pgid;
   1393 		LIST_INIT(&pgrp->pg_members);
   1394 #ifdef DIAGNOSTIC
   1395 		if (__predict_false(pid_table[pgid & pid_tbl_mask].pt_pgrp))
   1396 			panic("enterpgrp: pgrp table slot in use");
   1397 		if (__predict_false(mksess && p != curp))
   1398 			panic("enterpgrp: mksession and p != curproc");
   1399 #endif
   1400 		pid_table[pgid & pid_tbl_mask].pt_pgrp = pgrp;
   1401 		pgrp->pg_jobc = 0;
   1402 	}
   1403 
   1404 	/*
   1405 	 * Adjust eligibility of affected pgrps to participate in job control.
   1406 	 * Increment eligibility counts before decrementing, otherwise we
   1407 	 * could reach 0 spuriously during the first call.
   1408 	 */
   1409 	fixjobc(p, pgrp, 1);
   1410 	fixjobc(p, p->p_pgrp, 0);
   1411 
   1412 	/* Interlock with ttread(). */
   1413 	mutex_spin_enter(&tty_lock);
   1414 
   1415 	/* Move process to requested group. */
   1416 	LIST_REMOVE(p, p_pglist);
   1417 	if (LIST_EMPTY(&p->p_pgrp->pg_members))
   1418 		/* defer delete until we've dumped the lock */
   1419 		pg_id = p->p_pgrp->pg_id;
   1420 	p->p_pgrp = pgrp;
   1421 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
   1422 
   1423 	/* Done with the swap; we can release the tty mutex. */
   1424 	mutex_spin_exit(&tty_lock);
   1425 
   1426     done:
   1427 	if (pg_id != NO_PGID) {
   1428 		/* Releases proc_lock. */
   1429 		pg_delete(pg_id);
   1430 	} else {
   1431 		mutex_exit(&proc_lock);
   1432 	}
   1433 	if (sess != NULL)
   1434 		kmem_free(sess, sizeof(*sess));
   1435 	if (new_pgrp != NULL)
   1436 		kmem_free(new_pgrp, sizeof(*new_pgrp));
   1437 #ifdef DEBUG_PGRP
   1438 	if (__predict_false(rval))
   1439 		printf("enterpgrp(%d,%d,%d), curproc %d, rval %d\n",
   1440 			pid, pgid, mksess, curp->p_pid, rval);
   1441 #endif
   1442 	return rval;
   1443 }
   1444 
   1445 /*
   1446  * proc_leavepgrp: remove a process from its process group.
   1447  *  => must be called with the proc_lock held, which will be released;
   1448  */
   1449 void
   1450 proc_leavepgrp(struct proc *p)
   1451 {
   1452 	struct pgrp *pgrp;
   1453 
   1454 	KASSERT(mutex_owned(&proc_lock));
   1455 
   1456 	/* Interlock with ttread() */
   1457 	mutex_spin_enter(&tty_lock);
   1458 	pgrp = p->p_pgrp;
   1459 	LIST_REMOVE(p, p_pglist);
   1460 	p->p_pgrp = NULL;
   1461 	mutex_spin_exit(&tty_lock);
   1462 
   1463 	if (LIST_EMPTY(&pgrp->pg_members)) {
   1464 		/* Releases proc_lock. */
   1465 		pg_delete(pgrp->pg_id);
   1466 	} else {
   1467 		mutex_exit(&proc_lock);
   1468 	}
   1469 }
   1470 
   1471 /*
   1472  * pg_remove: remove a process group from the table.
   1473  *  => must be called with the proc_lock held;
   1474  *  => returns process group to free;
   1475  */
   1476 static struct pgrp *
   1477 pg_remove(pid_t pg_id)
   1478 {
   1479 	struct pgrp *pgrp;
   1480 	struct pid_table *pt;
   1481 
   1482 	KASSERT(mutex_owned(&proc_lock));
   1483 
   1484 	pt = &pid_table[pg_id & pid_tbl_mask];
   1485 	pgrp = pt->pt_pgrp;
   1486 
   1487 	KASSERT(pgrp != NULL);
   1488 	KASSERT(pgrp->pg_id == pg_id);
   1489 	KASSERT(LIST_EMPTY(&pgrp->pg_members));
   1490 
   1491 	pt->pt_pgrp = NULL;
   1492 
   1493 	if (!PT_VALID(pt->pt_slot)) {
   1494 		/* Orphaned pgrp, put slot onto free list. */
   1495 		KASSERT((PT_NEXT(pt->pt_slot) & pid_tbl_mask) == 0);
   1496 		pg_id &= pid_tbl_mask;
   1497 		pt = &pid_table[last_free_pt];
   1498 		pt->pt_slot = PT_SET_FREE(PT_NEXT(pt->pt_slot) | pg_id);
   1499 		KASSERT(pt->pt_pid == 0);
   1500 		last_free_pt = pg_id;
   1501 		pid_alloc_cnt--;
   1502 	}
   1503 	return pgrp;
   1504 }
   1505 
   1506 /*
   1507  * pg_delete: delete and free a process group.
   1508  *  => must be called with the proc_lock held, which will be released.
   1509  */
   1510 static void
   1511 pg_delete(pid_t pg_id)
   1512 {
   1513 	struct pgrp *pg;
   1514 	struct tty *ttyp;
   1515 	struct session *ss;
   1516 
   1517 	KASSERT(mutex_owned(&proc_lock));
   1518 
   1519 	pg = pid_table[pg_id & pid_tbl_mask].pt_pgrp;
   1520 	if (pg == NULL || pg->pg_id != pg_id || !LIST_EMPTY(&pg->pg_members)) {
   1521 		mutex_exit(&proc_lock);
   1522 		return;
   1523 	}
   1524 
   1525 	ss = pg->pg_session;
   1526 
   1527 	/* Remove reference (if any) from tty to this process group */
   1528 	mutex_spin_enter(&tty_lock);
   1529 	ttyp = ss->s_ttyp;
   1530 	if (ttyp != NULL && ttyp->t_pgrp == pg) {
   1531 		ttyp->t_pgrp = NULL;
   1532 		KASSERT(ttyp->t_session == ss);
   1533 	}
   1534 	mutex_spin_exit(&tty_lock);
   1535 
   1536 	/*
   1537 	 * The leading process group in a session is freed by proc_sessrele(),
   1538 	 * if last reference.  It will also release the locks.
   1539 	 */
   1540 	pg = (ss->s_sid != pg->pg_id) ? pg_remove(pg_id) : NULL;
   1541 	proc_sessrele(ss);
   1542 
   1543 	if (pg != NULL) {
   1544 		/* Free it, if was not done above. */
   1545 		kmem_free(pg, sizeof(struct pgrp));
   1546 	}
   1547 }
   1548 
   1549 /*
   1550  * Adjust pgrp jobc counters when specified process changes process group.
   1551  * We count the number of processes in each process group that "qualify"
   1552  * the group for terminal job control (those with a parent in a different
   1553  * process group of the same session).  If that count reaches zero, the
   1554  * process group becomes orphaned.  Check both the specified process'
   1555  * process group and that of its children.
   1556  * entering == 0 => p is leaving specified group.
   1557  * entering == 1 => p is entering specified group.
   1558  *
   1559  * Call with proc_lock held.
   1560  */
   1561 void
   1562 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
   1563 {
   1564 	struct pgrp *hispgrp;
   1565 	struct session *mysession = pgrp->pg_session;
   1566 	struct proc *child;
   1567 
   1568 	KASSERT(mutex_owned(&proc_lock));
   1569 
   1570 	/*
   1571 	 * Check p's parent to see whether p qualifies its own process
   1572 	 * group; if so, adjust count for p's process group.
   1573 	 */
   1574 	hispgrp = p->p_pptr->p_pgrp;
   1575 	if (hispgrp != pgrp && hispgrp->pg_session == mysession) {
   1576 		if (entering) {
   1577 			pgrp->pg_jobc++;
   1578 			p->p_lflag &= ~PL_ORPHANPG;
   1579 		} else {
   1580 			/* KASSERT(pgrp->pg_jobc > 0); */
   1581 			if (--pgrp->pg_jobc == 0)
   1582 				orphanpg(pgrp);
   1583 		}
   1584 	}
   1585 
   1586 	/*
   1587 	 * Check this process' children to see whether they qualify
   1588 	 * their process groups; if so, adjust counts for children's
   1589 	 * process groups.
   1590 	 */
   1591 	LIST_FOREACH(child, &p->p_children, p_sibling) {
   1592 		hispgrp = child->p_pgrp;
   1593 		if (hispgrp != pgrp && hispgrp->pg_session == mysession &&
   1594 		    !P_ZOMBIE(child)) {
   1595 			if (entering) {
   1596 				child->p_lflag &= ~PL_ORPHANPG;
   1597 				hispgrp->pg_jobc++;
   1598 			} else {
   1599 				KASSERT(hispgrp->pg_jobc > 0);
   1600 				if (--hispgrp->pg_jobc == 0)
   1601 					orphanpg(hispgrp);
   1602 			}
   1603 		}
   1604 	}
   1605 }
   1606 
   1607 /*
   1608  * A process group has become orphaned;
   1609  * if there are any stopped processes in the group,
   1610  * hang-up all process in that group.
   1611  *
   1612  * Call with proc_lock held.
   1613  */
   1614 static void
   1615 orphanpg(struct pgrp *pg)
   1616 {
   1617 	struct proc *p;
   1618 
   1619 	KASSERT(mutex_owned(&proc_lock));
   1620 
   1621 	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
   1622 		if (p->p_stat == SSTOP) {
   1623 			p->p_lflag |= PL_ORPHANPG;
   1624 			psignal(p, SIGHUP);
   1625 			psignal(p, SIGCONT);
   1626 		}
   1627 	}
   1628 }
   1629 
   1630 #ifdef DDB
   1631 #include <ddb/db_output.h>
   1632 void pidtbl_dump(void);
   1633 void
   1634 pidtbl_dump(void)
   1635 {
   1636 	struct pid_table *pt;
   1637 	struct proc *p;
   1638 	struct pgrp *pgrp;
   1639 	uintptr_t slot;
   1640 	int id;
   1641 
   1642 	db_printf("pid table %p size %x, next %x, last %x\n",
   1643 		pid_table, pid_tbl_mask+1,
   1644 		next_free_pt, last_free_pt);
   1645 	for (pt = pid_table, id = 0; id <= pid_tbl_mask; id++, pt++) {
   1646 		slot = pt->pt_slot;
   1647 		if (!PT_VALID(slot) && !pt->pt_pgrp)
   1648 			continue;
   1649 		if (PT_IS_LWP(slot)) {
   1650 			p = PT_GET_LWP(slot)->l_proc;
   1651 		} else if (PT_IS_PROC(slot)) {
   1652 			p = PT_GET_PROC(slot);
   1653 		} else {
   1654 			p = NULL;
   1655 		}
   1656 		db_printf("  id %x: ", id);
   1657 		if (p != NULL)
   1658 			db_printf("slotpid %d proc %p id %d (0x%x) %s\n",
   1659 				pt->pt_pid, p, p->p_pid, p->p_pid, p->p_comm);
   1660 		else
   1661 			db_printf("next %x use %x\n",
   1662 				PT_NEXT(slot) & pid_tbl_mask,
   1663 				PT_NEXT(slot) & ~pid_tbl_mask);
   1664 		if ((pgrp = pt->pt_pgrp)) {
   1665 			db_printf("\tsession %p, sid %d, count %d, login %s\n",
   1666 			    pgrp->pg_session, pgrp->pg_session->s_sid,
   1667 			    pgrp->pg_session->s_count,
   1668 			    pgrp->pg_session->s_login);
   1669 			db_printf("\tpgrp %p, pg_id %d, pg_jobc %d, members %p\n",
   1670 			    pgrp, pgrp->pg_id, pgrp->pg_jobc,
   1671 			    LIST_FIRST(&pgrp->pg_members));
   1672 			LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
   1673 				db_printf("\t\tpid %d addr %p pgrp %p %s\n",
   1674 				    p->p_pid, p, p->p_pgrp, p->p_comm);
   1675 			}
   1676 		}
   1677 	}
   1678 }
   1679 #endif /* DDB */
   1680 
   1681 #ifdef KSTACK_CHECK_MAGIC
   1682 
   1683 #define	KSTACK_MAGIC	0xdeadbeaf
   1684 
   1685 /* XXX should be per process basis? */
   1686 static int	kstackleftmin = KSTACK_SIZE;
   1687 static int	kstackleftthres = KSTACK_SIZE / 8;
   1688 
   1689 void
   1690 kstack_setup_magic(const struct lwp *l)
   1691 {
   1692 	uint32_t *ip;
   1693 	uint32_t const *end;
   1694 
   1695 	KASSERT(l != NULL);
   1696 	KASSERT(l != &lwp0);
   1697 
   1698 	/*
   1699 	 * fill all the stack with magic number
   1700 	 * so that later modification on it can be detected.
   1701 	 */
   1702 	ip = (uint32_t *)KSTACK_LOWEST_ADDR(l);
   1703 	end = (uint32_t *)((char *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
   1704 	for (; ip < end; ip++) {
   1705 		*ip = KSTACK_MAGIC;
   1706 	}
   1707 }
   1708 
   1709 void
   1710 kstack_check_magic(const struct lwp *l)
   1711 {
   1712 	uint32_t const *ip, *end;
   1713 	int stackleft;
   1714 
   1715 	KASSERT(l != NULL);
   1716 
   1717 	/* don't check proc0 */ /*XXX*/
   1718 	if (l == &lwp0)
   1719 		return;
   1720 
   1721 #ifdef __MACHINE_STACK_GROWS_UP
   1722 	/* stack grows upwards (eg. hppa) */
   1723 	ip = (uint32_t *)((void *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
   1724 	end = (uint32_t *)KSTACK_LOWEST_ADDR(l);
   1725 	for (ip--; ip >= end; ip--)
   1726 		if (*ip != KSTACK_MAGIC)
   1727 			break;
   1728 
   1729 	stackleft = (void *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE - (void *)ip;
   1730 #else /* __MACHINE_STACK_GROWS_UP */
   1731 	/* stack grows downwards (eg. i386) */
   1732 	ip = (uint32_t *)KSTACK_LOWEST_ADDR(l);
   1733 	end = (uint32_t *)((char *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
   1734 	for (; ip < end; ip++)
   1735 		if (*ip != KSTACK_MAGIC)
   1736 			break;
   1737 
   1738 	stackleft = ((const char *)ip) - (const char *)KSTACK_LOWEST_ADDR(l);
   1739 #endif /* __MACHINE_STACK_GROWS_UP */
   1740 
   1741 	if (kstackleftmin > stackleft) {
   1742 		kstackleftmin = stackleft;
   1743 		if (stackleft < kstackleftthres)
   1744 			printf("warning: kernel stack left %d bytes"
   1745 			    "(pid %u:lid %u)\n", stackleft,
   1746 			    (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
   1747 	}
   1748 
   1749 	if (stackleft <= 0) {
   1750 		panic("magic on the top of kernel stack changed for "
   1751 		    "pid %u, lid %u: maybe kernel stack overflow",
   1752 		    (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
   1753 	}
   1754 }
   1755 #endif /* KSTACK_CHECK_MAGIC */
   1756 
   1757 int
   1758 proclist_foreach_call(struct proclist *list,
   1759     int (*callback)(struct proc *, void *arg), void *arg)
   1760 {
   1761 	struct proc marker;
   1762 	struct proc *p;
   1763 	int ret = 0;
   1764 
   1765 	marker.p_flag = PK_MARKER;
   1766 	mutex_enter(&proc_lock);
   1767 	for (p = LIST_FIRST(list); ret == 0 && p != NULL;) {
   1768 		if (p->p_flag & PK_MARKER) {
   1769 			p = LIST_NEXT(p, p_list);
   1770 			continue;
   1771 		}
   1772 		LIST_INSERT_AFTER(p, &marker, p_list);
   1773 		ret = (*callback)(p, arg);
   1774 		KASSERT(mutex_owned(&proc_lock));
   1775 		p = LIST_NEXT(&marker, p_list);
   1776 		LIST_REMOVE(&marker, p_list);
   1777 	}
   1778 	mutex_exit(&proc_lock);
   1779 
   1780 	return ret;
   1781 }
   1782 
   1783 int
   1784 proc_vmspace_getref(struct proc *p, struct vmspace **vm)
   1785 {
   1786 
   1787 	/* XXXCDC: how should locking work here? */
   1788 
   1789 	/* curproc exception is for coredump. */
   1790 
   1791 	if ((p != curproc && (p->p_sflag & PS_WEXIT) != 0) ||
   1792 	    (p->p_vmspace->vm_refcnt < 1)) {
   1793 		return EFAULT;
   1794 	}
   1795 
   1796 	uvmspace_addref(p->p_vmspace);
   1797 	*vm = p->p_vmspace;
   1798 
   1799 	return 0;
   1800 }
   1801 
   1802 /*
   1803  * Acquire a write lock on the process credential.
   1804  */
   1805 void
   1806 proc_crmod_enter(void)
   1807 {
   1808 	struct lwp *l = curlwp;
   1809 	struct proc *p = l->l_proc;
   1810 	kauth_cred_t oc;
   1811 
   1812 	/* Reset what needs to be reset in plimit. */
   1813 	if (p->p_limit->pl_corename != defcorename) {
   1814 		lim_setcorename(p, defcorename, 0);
   1815 	}
   1816 
   1817 	mutex_enter(p->p_lock);
   1818 
   1819 	/* Ensure the LWP cached credentials are up to date. */
   1820 	if ((oc = l->l_cred) != p->p_cred) {
   1821 		l->l_cred = kauth_cred_hold(p->p_cred);
   1822 		kauth_cred_free(oc);
   1823 	}
   1824 }
   1825 
   1826 /*
   1827  * Set in a new process credential, and drop the write lock.  The credential
   1828  * must have a reference already.  Optionally, free a no-longer required
   1829  * credential.
   1830  */
   1831 void
   1832 proc_crmod_leave(kauth_cred_t scred, kauth_cred_t fcred, bool sugid)
   1833 {
   1834 	struct lwp *l = curlwp, *l2;
   1835 	struct proc *p = l->l_proc;
   1836 	kauth_cred_t oc;
   1837 
   1838 	KASSERT(mutex_owned(p->p_lock));
   1839 
   1840 	/* Is there a new credential to set in? */
   1841 	if (scred != NULL) {
   1842 		p->p_cred = scred;
   1843 		LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
   1844 			if (l2 != l) {
   1845 				lwp_lock(l2);
   1846 				l2->l_flag |= LW_CACHECRED;
   1847 				lwp_need_userret(l2);
   1848 				lwp_unlock(l2);
   1849 			}
   1850 		}
   1851 
   1852 		/* Ensure the LWP cached credentials are up to date. */
   1853 		if ((oc = l->l_cred) != scred) {
   1854 			l->l_cred = kauth_cred_hold(scred);
   1855 		}
   1856 	} else
   1857 		oc = NULL;	/* XXXgcc */
   1858 
   1859 	if (sugid) {
   1860 		/*
   1861 		 * Mark process as having changed credentials, stops
   1862 		 * tracing etc.
   1863 		 */
   1864 		p->p_flag |= PK_SUGID;
   1865 	}
   1866 
   1867 	mutex_exit(p->p_lock);
   1868 
   1869 	/* If there is a credential to be released, free it now. */
   1870 	if (fcred != NULL) {
   1871 		KASSERT(scred != NULL);
   1872 		kauth_cred_free(fcred);
   1873 		if (oc != scred)
   1874 			kauth_cred_free(oc);
   1875 	}
   1876 }
   1877 
   1878 /*
   1879  * proc_specific_key_create --
   1880  *	Create a key for subsystem proc-specific data.
   1881  */
   1882 int
   1883 proc_specific_key_create(specificdata_key_t *keyp, specificdata_dtor_t dtor)
   1884 {
   1885 
   1886 	return (specificdata_key_create(proc_specificdata_domain, keyp, dtor));
   1887 }
   1888 
   1889 /*
   1890  * proc_specific_key_delete --
   1891  *	Delete a key for subsystem proc-specific data.
   1892  */
   1893 void
   1894 proc_specific_key_delete(specificdata_key_t key)
   1895 {
   1896 
   1897 	specificdata_key_delete(proc_specificdata_domain, key);
   1898 }
   1899 
   1900 /*
   1901  * proc_initspecific --
   1902  *	Initialize a proc's specificdata container.
   1903  */
   1904 void
   1905 proc_initspecific(struct proc *p)
   1906 {
   1907 	int error __diagused;
   1908 
   1909 	error = specificdata_init(proc_specificdata_domain, &p->p_specdataref);
   1910 	KASSERT(error == 0);
   1911 }
   1912 
   1913 /*
   1914  * proc_finispecific --
   1915  *	Finalize a proc's specificdata container.
   1916  */
   1917 void
   1918 proc_finispecific(struct proc *p)
   1919 {
   1920 
   1921 	specificdata_fini(proc_specificdata_domain, &p->p_specdataref);
   1922 }
   1923 
   1924 /*
   1925  * proc_getspecific --
   1926  *	Return proc-specific data corresponding to the specified key.
   1927  */
   1928 void *
   1929 proc_getspecific(struct proc *p, specificdata_key_t key)
   1930 {
   1931 
   1932 	return (specificdata_getspecific(proc_specificdata_domain,
   1933 					 &p->p_specdataref, key));
   1934 }
   1935 
   1936 /*
   1937  * proc_setspecific --
   1938  *	Set proc-specific data corresponding to the specified key.
   1939  */
   1940 void
   1941 proc_setspecific(struct proc *p, specificdata_key_t key, void *data)
   1942 {
   1943 
   1944 	specificdata_setspecific(proc_specificdata_domain,
   1945 				 &p->p_specdataref, key, data);
   1946 }
   1947 
   1948 int
   1949 proc_uidmatch(kauth_cred_t cred, kauth_cred_t target)
   1950 {
   1951 	int r = 0;
   1952 
   1953 	if (kauth_cred_getuid(cred) != kauth_cred_getuid(target) ||
   1954 	    kauth_cred_getuid(cred) != kauth_cred_getsvuid(target)) {
   1955 		/*
   1956 		 * suid proc of ours or proc not ours
   1957 		 */
   1958 		r = EPERM;
   1959 	} else if (kauth_cred_getgid(target) != kauth_cred_getsvgid(target)) {
   1960 		/*
   1961 		 * sgid proc has sgid back to us temporarily
   1962 		 */
   1963 		r = EPERM;
   1964 	} else {
   1965 		/*
   1966 		 * our rgid must be in target's group list (ie,
   1967 		 * sub-processes started by a sgid process)
   1968 		 */
   1969 		int ismember = 0;
   1970 
   1971 		if (kauth_cred_ismember_gid(cred,
   1972 		    kauth_cred_getgid(target), &ismember) != 0 ||
   1973 		    !ismember)
   1974 			r = EPERM;
   1975 	}
   1976 
   1977 	return (r);
   1978 }
   1979 
   1980 /*
   1981  * sysctl stuff
   1982  */
   1983 
   1984 #define KERN_PROCSLOP	(5 * sizeof(struct kinfo_proc))
   1985 
   1986 static const u_int sysctl_flagmap[] = {
   1987 	PK_ADVLOCK, P_ADVLOCK,
   1988 	PK_EXEC, P_EXEC,
   1989 	PK_NOCLDWAIT, P_NOCLDWAIT,
   1990 	PK_32, P_32,
   1991 	PK_CLDSIGIGN, P_CLDSIGIGN,
   1992 	PK_SUGID, P_SUGID,
   1993 	0
   1994 };
   1995 
   1996 static const u_int sysctl_sflagmap[] = {
   1997 	PS_NOCLDSTOP, P_NOCLDSTOP,
   1998 	PS_WEXIT, P_WEXIT,
   1999 	PS_STOPFORK, P_STOPFORK,
   2000 	PS_STOPEXEC, P_STOPEXEC,
   2001 	PS_STOPEXIT, P_STOPEXIT,
   2002 	0
   2003 };
   2004 
   2005 static const u_int sysctl_slflagmap[] = {
   2006 	PSL_TRACED, P_TRACED,
   2007 	PSL_CHTRACED, P_CHTRACED,
   2008 	PSL_SYSCALL, P_SYSCALL,
   2009 	0
   2010 };
   2011 
   2012 static const u_int sysctl_lflagmap[] = {
   2013 	PL_CONTROLT, P_CONTROLT,
   2014 	PL_PPWAIT, P_PPWAIT,
   2015 	0
   2016 };
   2017 
   2018 static const u_int sysctl_stflagmap[] = {
   2019 	PST_PROFIL, P_PROFIL,
   2020 	0
   2021 
   2022 };
   2023 
   2024 /* used by kern_lwp also */
   2025 const u_int sysctl_lwpflagmap[] = {
   2026 	LW_SINTR, L_SINTR,
   2027 	LW_SYSTEM, L_SYSTEM,
   2028 	0
   2029 };
   2030 
   2031 /*
   2032  * Find the most ``active'' lwp of a process and return it for ps display
   2033  * purposes
   2034  */
   2035 static struct lwp *
   2036 proc_active_lwp(struct proc *p)
   2037 {
   2038 	static const int ostat[] = {
   2039 		0,
   2040 		2,	/* LSIDL */
   2041 		6,	/* LSRUN */
   2042 		5,	/* LSSLEEP */
   2043 		4,	/* LSSTOP */
   2044 		0,	/* LSZOMB */
   2045 		1,	/* LSDEAD */
   2046 		7,	/* LSONPROC */
   2047 		3	/* LSSUSPENDED */
   2048 	};
   2049 
   2050 	struct lwp *l, *lp = NULL;
   2051 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
   2052 		KASSERT(l->l_stat >= 0);
   2053 		KASSERT(l->l_stat < __arraycount(ostat));
   2054 		if (lp == NULL ||
   2055 		    ostat[l->l_stat] > ostat[lp->l_stat] ||
   2056 		    (ostat[l->l_stat] == ostat[lp->l_stat] &&
   2057 		    l->l_cpticks > lp->l_cpticks)) {
   2058 			lp = l;
   2059 			continue;
   2060 		}
   2061 	}
   2062 	return lp;
   2063 }
   2064 
   2065 static int
   2066 sysctl_doeproc(SYSCTLFN_ARGS)
   2067 {
   2068 	union {
   2069 		struct kinfo_proc kproc;
   2070 		struct kinfo_proc2 kproc2;
   2071 	} *kbuf;
   2072 	struct proc *p, *next, *marker;
   2073 	char *where, *dp;
   2074 	int type, op, arg, error;
   2075 	u_int elem_size, kelem_size, elem_count;
   2076 	size_t buflen, needed;
   2077 	bool match, zombie, mmmbrains;
   2078 	const bool allowaddr = get_expose_address(curproc);
   2079 
   2080 	if (namelen == 1 && name[0] == CTL_QUERY)
   2081 		return (sysctl_query(SYSCTLFN_CALL(rnode)));
   2082 
   2083 	dp = where = oldp;
   2084 	buflen = where != NULL ? *oldlenp : 0;
   2085 	error = 0;
   2086 	needed = 0;
   2087 	type = rnode->sysctl_num;
   2088 
   2089 	if (type == KERN_PROC) {
   2090 		if (namelen == 0)
   2091 			return EINVAL;
   2092 		switch (op = name[0]) {
   2093 		case KERN_PROC_ALL:
   2094 			if (namelen != 1)
   2095 				return EINVAL;
   2096 			arg = 0;
   2097 			break;
   2098 		default:
   2099 			if (namelen != 2)
   2100 				return EINVAL;
   2101 			arg = name[1];
   2102 			break;
   2103 		}
   2104 		elem_count = 0;	/* Hush little compiler, don't you cry */
   2105 		kelem_size = elem_size = sizeof(kbuf->kproc);
   2106 	} else {
   2107 		if (namelen != 4)
   2108 			return EINVAL;
   2109 		op = name[0];
   2110 		arg = name[1];
   2111 		elem_size = name[2];
   2112 		elem_count = name[3];
   2113 		kelem_size = sizeof(kbuf->kproc2);
   2114 	}
   2115 
   2116 	sysctl_unlock();
   2117 
   2118 	kbuf = kmem_zalloc(sizeof(*kbuf), KM_SLEEP);
   2119 	marker = kmem_alloc(sizeof(*marker), KM_SLEEP);
   2120 	marker->p_flag = PK_MARKER;
   2121 
   2122 	mutex_enter(&proc_lock);
   2123 	/*
   2124 	 * Start with zombies to prevent reporting processes twice, in case they
   2125 	 * are dying and being moved from the list of alive processes to zombies.
   2126 	 */
   2127 	mmmbrains = true;
   2128 	for (p = LIST_FIRST(&zombproc);; p = next) {
   2129 		if (p == NULL) {
   2130 			if (mmmbrains) {
   2131 				p = LIST_FIRST(&allproc);
   2132 				mmmbrains = false;
   2133 			}
   2134 			if (p == NULL)
   2135 				break;
   2136 		}
   2137 		next = LIST_NEXT(p, p_list);
   2138 		if ((p->p_flag & PK_MARKER) != 0)
   2139 			continue;
   2140 
   2141 		/*
   2142 		 * Skip embryonic processes.
   2143 		 */
   2144 		if (p->p_stat == SIDL)
   2145 			continue;
   2146 
   2147 		mutex_enter(p->p_lock);
   2148 		error = kauth_authorize_process(l->l_cred,
   2149 		    KAUTH_PROCESS_CANSEE, p,
   2150 		    KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_EPROC), NULL, NULL);
   2151 		if (error != 0) {
   2152 			mutex_exit(p->p_lock);
   2153 			continue;
   2154 		}
   2155 
   2156 		/*
   2157 		 * Hande all the operations in one switch on the cost of
   2158 		 * algorithm complexity is on purpose. The win splitting this
   2159 		 * function into several similar copies makes maintenance
   2160 		 * burden, code grow and boost is negligible in practical
   2161 		 * systems.
   2162 		 */
   2163 		switch (op) {
   2164 		case KERN_PROC_PID:
   2165 			match = (p->p_pid == (pid_t)arg);
   2166 			break;
   2167 
   2168 		case KERN_PROC_PGRP:
   2169 			match = (p->p_pgrp->pg_id == (pid_t)arg);
   2170 			break;
   2171 
   2172 		case KERN_PROC_SESSION:
   2173 			match = (p->p_session->s_sid == (pid_t)arg);
   2174 			break;
   2175 
   2176 		case KERN_PROC_TTY:
   2177 			match = true;
   2178 			if (arg == (int) KERN_PROC_TTY_REVOKE) {
   2179 				if ((p->p_lflag & PL_CONTROLT) == 0 ||
   2180 				    p->p_session->s_ttyp == NULL ||
   2181 				    p->p_session->s_ttyvp != NULL) {
   2182 				    	match = false;
   2183 				}
   2184 			} else if ((p->p_lflag & PL_CONTROLT) == 0 ||
   2185 			    p->p_session->s_ttyp == NULL) {
   2186 				if ((dev_t)arg != KERN_PROC_TTY_NODEV) {
   2187 					match = false;
   2188 				}
   2189 			} else if (p->p_session->s_ttyp->t_dev != (dev_t)arg) {
   2190 				match = false;
   2191 			}
   2192 			break;
   2193 
   2194 		case KERN_PROC_UID:
   2195 			match = (kauth_cred_geteuid(p->p_cred) == (uid_t)arg);
   2196 			break;
   2197 
   2198 		case KERN_PROC_RUID:
   2199 			match = (kauth_cred_getuid(p->p_cred) == (uid_t)arg);
   2200 			break;
   2201 
   2202 		case KERN_PROC_GID:
   2203 			match = (kauth_cred_getegid(p->p_cred) == (uid_t)arg);
   2204 			break;
   2205 
   2206 		case KERN_PROC_RGID:
   2207 			match = (kauth_cred_getgid(p->p_cred) == (uid_t)arg);
   2208 			break;
   2209 
   2210 		case KERN_PROC_ALL:
   2211 			match = true;
   2212 			/* allow everything */
   2213 			break;
   2214 
   2215 		default:
   2216 			error = EINVAL;
   2217 			mutex_exit(p->p_lock);
   2218 			goto cleanup;
   2219 		}
   2220 		if (!match) {
   2221 			mutex_exit(p->p_lock);
   2222 			continue;
   2223 		}
   2224 
   2225 		/*
   2226 		 * Grab a hold on the process.
   2227 		 */
   2228 		if (mmmbrains) {
   2229 			zombie = true;
   2230 		} else {
   2231 			zombie = !rw_tryenter(&p->p_reflock, RW_READER);
   2232 		}
   2233 		if (zombie) {
   2234 			LIST_INSERT_AFTER(p, marker, p_list);
   2235 		}
   2236 
   2237 		if (buflen >= elem_size &&
   2238 		    (type == KERN_PROC || elem_count > 0)) {
   2239 			ruspace(p);	/* Update process vm resource use */
   2240 
   2241 			if (type == KERN_PROC) {
   2242 				fill_proc(p, &kbuf->kproc.kp_proc, allowaddr);
   2243 				fill_eproc(p, &kbuf->kproc.kp_eproc, zombie,
   2244 				    allowaddr);
   2245 			} else {
   2246 				fill_kproc2(p, &kbuf->kproc2, zombie,
   2247 				    allowaddr);
   2248 				elem_count--;
   2249 			}
   2250 			mutex_exit(p->p_lock);
   2251 			mutex_exit(&proc_lock);
   2252 			/*
   2253 			 * Copy out elem_size, but not larger than kelem_size
   2254 			 */
   2255 			error = sysctl_copyout(l, kbuf, dp,
   2256 			    uimin(kelem_size, elem_size));
   2257 			mutex_enter(&proc_lock);
   2258 			if (error) {
   2259 				goto bah;
   2260 			}
   2261 			dp += elem_size;
   2262 			buflen -= elem_size;
   2263 		} else {
   2264 			mutex_exit(p->p_lock);
   2265 		}
   2266 		needed += elem_size;
   2267 
   2268 		/*
   2269 		 * Release reference to process.
   2270 		 */
   2271 	 	if (zombie) {
   2272 			next = LIST_NEXT(marker, p_list);
   2273  			LIST_REMOVE(marker, p_list);
   2274 		} else {
   2275 			rw_exit(&p->p_reflock);
   2276 			next = LIST_NEXT(p, p_list);
   2277 		}
   2278 
   2279 		/*
   2280 		 * Short-circuit break quickly!
   2281 		 */
   2282 		if (op == KERN_PROC_PID)
   2283                 	break;
   2284 	}
   2285 	mutex_exit(&proc_lock);
   2286 
   2287 	if (where != NULL) {
   2288 		*oldlenp = dp - where;
   2289 		if (needed > *oldlenp) {
   2290 			error = ENOMEM;
   2291 			goto out;
   2292 		}
   2293 	} else {
   2294 		needed += KERN_PROCSLOP;
   2295 		*oldlenp = needed;
   2296 	}
   2297 	kmem_free(kbuf, sizeof(*kbuf));
   2298 	kmem_free(marker, sizeof(*marker));
   2299 	sysctl_relock();
   2300 	return 0;
   2301  bah:
   2302  	if (zombie)
   2303  		LIST_REMOVE(marker, p_list);
   2304 	else
   2305 		rw_exit(&p->p_reflock);
   2306  cleanup:
   2307 	mutex_exit(&proc_lock);
   2308  out:
   2309 	kmem_free(kbuf, sizeof(*kbuf));
   2310 	kmem_free(marker, sizeof(*marker));
   2311 	sysctl_relock();
   2312 	return error;
   2313 }
   2314 
   2315 int
   2316 copyin_psstrings(struct proc *p, struct ps_strings *arginfo)
   2317 {
   2318 #if !defined(_RUMPKERNEL)
   2319 	int retval;
   2320 
   2321 	if (p->p_flag & PK_32) {
   2322 		MODULE_HOOK_CALL(kern_proc32_copyin_hook, (p, arginfo),
   2323 		    enosys(), retval);
   2324 		return retval;
   2325 	}
   2326 #endif /* !defined(_RUMPKERNEL) */
   2327 
   2328 	return copyin_proc(p, (void *)p->p_psstrp, arginfo, sizeof(*arginfo));
   2329 }
   2330 
   2331 static int
   2332 copy_procargs_sysctl_cb(void *cookie_, const void *src, size_t off, size_t len)
   2333 {
   2334 	void **cookie = cookie_;
   2335 	struct lwp *l = cookie[0];
   2336 	char *dst = cookie[1];
   2337 
   2338 	return sysctl_copyout(l, src, dst + off, len);
   2339 }
   2340 
   2341 /*
   2342  * sysctl helper routine for kern.proc_args pseudo-subtree.
   2343  */
   2344 static int
   2345 sysctl_kern_proc_args(SYSCTLFN_ARGS)
   2346 {
   2347 	struct ps_strings pss;
   2348 	struct proc *p;
   2349 	pid_t pid;
   2350 	int type, error;
   2351 	void *cookie[2];
   2352 
   2353 	if (namelen == 1 && name[0] == CTL_QUERY)
   2354 		return (sysctl_query(SYSCTLFN_CALL(rnode)));
   2355 
   2356 	if (newp != NULL || namelen != 2)
   2357 		return (EINVAL);
   2358 	pid = name[0];
   2359 	type = name[1];
   2360 
   2361 	switch (type) {
   2362 	case KERN_PROC_PATHNAME:
   2363 		sysctl_unlock();
   2364 		error = fill_pathname(l, pid, oldp, oldlenp);
   2365 		sysctl_relock();
   2366 		return error;
   2367 
   2368 	case KERN_PROC_CWD:
   2369 		sysctl_unlock();
   2370 		error = fill_cwd(l, pid, oldp, oldlenp);
   2371 		sysctl_relock();
   2372 		return error;
   2373 
   2374 	case KERN_PROC_ARGV:
   2375 	case KERN_PROC_NARGV:
   2376 	case KERN_PROC_ENV:
   2377 	case KERN_PROC_NENV:
   2378 		/* ok */
   2379 		break;
   2380 	default:
   2381 		return (EINVAL);
   2382 	}
   2383 
   2384 	sysctl_unlock();
   2385 
   2386 	/* check pid */
   2387 	mutex_enter(&proc_lock);
   2388 	if ((p = proc_find(pid)) == NULL) {
   2389 		error = EINVAL;
   2390 		goto out_locked;
   2391 	}
   2392 	mutex_enter(p->p_lock);
   2393 
   2394 	/* Check permission. */
   2395 	if (type == KERN_PROC_ARGV || type == KERN_PROC_NARGV)
   2396 		error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CANSEE,
   2397 		    p, KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_ARGS), NULL, NULL);
   2398 	else if (type == KERN_PROC_ENV || type == KERN_PROC_NENV)
   2399 		error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CANSEE,
   2400 		    p, KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_ENV), NULL, NULL);
   2401 	else
   2402 		error = EINVAL; /* XXXGCC */
   2403 	if (error) {
   2404 		mutex_exit(p->p_lock);
   2405 		goto out_locked;
   2406 	}
   2407 
   2408 	if (oldp == NULL) {
   2409 		if (type == KERN_PROC_NARGV || type == KERN_PROC_NENV)
   2410 			*oldlenp = sizeof (int);
   2411 		else
   2412 			*oldlenp = ARG_MAX;	/* XXX XXX XXX */
   2413 		error = 0;
   2414 		mutex_exit(p->p_lock);
   2415 		goto out_locked;
   2416 	}
   2417 
   2418 	/*
   2419 	 * Zombies don't have a stack, so we can't read their psstrings.
   2420 	 * System processes also don't have a user stack.
   2421 	 */
   2422 	if (P_ZOMBIE(p) || (p->p_flag & PK_SYSTEM) != 0) {
   2423 		error = EINVAL;
   2424 		mutex_exit(p->p_lock);
   2425 		goto out_locked;
   2426 	}
   2427 
   2428 	error = rw_tryenter(&p->p_reflock, RW_READER) ? 0 : EBUSY;
   2429 	mutex_exit(p->p_lock);
   2430 	if (error) {
   2431 		goto out_locked;
   2432 	}
   2433 	mutex_exit(&proc_lock);
   2434 
   2435 	if (type == KERN_PROC_NARGV || type == KERN_PROC_NENV) {
   2436 		int value;
   2437 		if ((error = copyin_psstrings(p, &pss)) == 0) {
   2438 			if (type == KERN_PROC_NARGV)
   2439 				value = pss.ps_nargvstr;
   2440 			else
   2441 				value = pss.ps_nenvstr;
   2442 			error = sysctl_copyout(l, &value, oldp, sizeof(value));
   2443 			*oldlenp = sizeof(value);
   2444 		}
   2445 	} else {
   2446 		cookie[0] = l;
   2447 		cookie[1] = oldp;
   2448 		error = copy_procargs(p, type, oldlenp,
   2449 		    copy_procargs_sysctl_cb, cookie);
   2450 	}
   2451 	rw_exit(&p->p_reflock);
   2452 	sysctl_relock();
   2453 	return error;
   2454 
   2455 out_locked:
   2456 	mutex_exit(&proc_lock);
   2457 	sysctl_relock();
   2458 	return error;
   2459 }
   2460 
   2461 int
   2462 copy_procargs(struct proc *p, int oid, size_t *limit,
   2463     int (*cb)(void *, const void *, size_t, size_t), void *cookie)
   2464 {
   2465 	struct ps_strings pss;
   2466 	size_t len, i, loaded, entry_len;
   2467 	struct uio auio;
   2468 	struct iovec aiov;
   2469 	int error, argvlen;
   2470 	char *arg;
   2471 	char **argv;
   2472 	vaddr_t user_argv;
   2473 	struct vmspace *vmspace;
   2474 
   2475 	/*
   2476 	 * Allocate a temporary buffer to hold the argument vector and
   2477 	 * the arguments themselve.
   2478 	 */
   2479 	arg = kmem_alloc(PAGE_SIZE, KM_SLEEP);
   2480 	argv = kmem_alloc(PAGE_SIZE, KM_SLEEP);
   2481 
   2482 	/*
   2483 	 * Lock the process down in memory.
   2484 	 */
   2485 	vmspace = p->p_vmspace;
   2486 	uvmspace_addref(vmspace);
   2487 
   2488 	/*
   2489 	 * Read in the ps_strings structure.
   2490 	 */
   2491 	if ((error = copyin_psstrings(p, &pss)) != 0)
   2492 		goto done;
   2493 
   2494 	/*
   2495 	 * Now read the address of the argument vector.
   2496 	 */
   2497 	switch (oid) {
   2498 	case KERN_PROC_ARGV:
   2499 		user_argv = (uintptr_t)pss.ps_argvstr;
   2500 		argvlen = pss.ps_nargvstr;
   2501 		break;
   2502 	case KERN_PROC_ENV:
   2503 		user_argv = (uintptr_t)pss.ps_envstr;
   2504 		argvlen = pss.ps_nenvstr;
   2505 		break;
   2506 	default:
   2507 		error = EINVAL;
   2508 		goto done;
   2509 	}
   2510 
   2511 	if (argvlen < 0) {
   2512 		error = EIO;
   2513 		goto done;
   2514 	}
   2515 
   2516 
   2517 	/*
   2518 	 * Now copy each string.
   2519 	 */
   2520 	len = 0; /* bytes written to user buffer */
   2521 	loaded = 0; /* bytes from argv already processed */
   2522 	i = 0; /* To make compiler happy */
   2523 	entry_len = PROC_PTRSZ(p);
   2524 
   2525 	for (; argvlen; --argvlen) {
   2526 		int finished = 0;
   2527 		vaddr_t base;
   2528 		size_t xlen;
   2529 		int j;
   2530 
   2531 		if (loaded == 0) {
   2532 			size_t rem = entry_len * argvlen;
   2533 			loaded = MIN(rem, PAGE_SIZE);
   2534 			error = copyin_vmspace(vmspace,
   2535 			    (const void *)user_argv, argv, loaded);
   2536 			if (error)
   2537 				break;
   2538 			user_argv += loaded;
   2539 			i = 0;
   2540 		}
   2541 
   2542 #if !defined(_RUMPKERNEL)
   2543 		if (p->p_flag & PK_32)
   2544 			MODULE_HOOK_CALL(kern_proc32_base_hook,
   2545 			    (argv, i++), 0, base);
   2546 		else
   2547 #endif /* !defined(_RUMPKERNEL) */
   2548 			base = (vaddr_t)argv[i++];
   2549 		loaded -= entry_len;
   2550 
   2551 		/*
   2552 		 * The program has messed around with its arguments,
   2553 		 * possibly deleting some, and replacing them with
   2554 		 * NULL's. Treat this as the last argument and not
   2555 		 * a failure.
   2556 		 */
   2557 		if (base == 0)
   2558 			break;
   2559 
   2560 		while (!finished) {
   2561 			xlen = PAGE_SIZE - (base & PAGE_MASK);
   2562 
   2563 			aiov.iov_base = arg;
   2564 			aiov.iov_len = PAGE_SIZE;
   2565 			auio.uio_iov = &aiov;
   2566 			auio.uio_iovcnt = 1;
   2567 			auio.uio_offset = base;
   2568 			auio.uio_resid = xlen;
   2569 			auio.uio_rw = UIO_READ;
   2570 			UIO_SETUP_SYSSPACE(&auio);
   2571 			error = uvm_io(&vmspace->vm_map, &auio, 0);
   2572 			if (error)
   2573 				goto done;
   2574 
   2575 			/* Look for the end of the string */
   2576 			for (j = 0; j < xlen; j++) {
   2577 				if (arg[j] == '\0') {
   2578 					xlen = j + 1;
   2579 					finished = 1;
   2580 					break;
   2581 				}
   2582 			}
   2583 
   2584 			/* Check for user buffer overflow */
   2585 			if (len + xlen > *limit) {
   2586 				finished = 1;
   2587 				if (len > *limit)
   2588 					xlen = 0;
   2589 				else
   2590 					xlen = *limit - len;
   2591 			}
   2592 
   2593 			/* Copyout the page */
   2594 			error = (*cb)(cookie, arg, len, xlen);
   2595 			if (error)
   2596 				goto done;
   2597 
   2598 			len += xlen;
   2599 			base += xlen;
   2600 		}
   2601 	}
   2602 	*limit = len;
   2603 
   2604 done:
   2605 	kmem_free(argv, PAGE_SIZE);
   2606 	kmem_free(arg, PAGE_SIZE);
   2607 	uvmspace_free(vmspace);
   2608 	return error;
   2609 }
   2610 
   2611 /*
   2612  * Fill in a proc structure for the specified process.
   2613  */
   2614 static void
   2615 fill_proc(const struct proc *psrc, struct proc *p, bool allowaddr)
   2616 {
   2617 	COND_SET_STRUCT(p->p_list, psrc->p_list, allowaddr);
   2618 	memset(&p->p_auxlock, 0, sizeof(p->p_auxlock));
   2619 	COND_SET_STRUCT(p->p_lock, psrc->p_lock, allowaddr);
   2620 	memset(&p->p_stmutex, 0, sizeof(p->p_stmutex));
   2621 	memset(&p->p_reflock, 0, sizeof(p->p_reflock));
   2622 	COND_SET_STRUCT(p->p_waitcv, psrc->p_waitcv, allowaddr);
   2623 	COND_SET_STRUCT(p->p_lwpcv, psrc->p_lwpcv, allowaddr);
   2624 	COND_SET_PTR(p->p_cred, psrc->p_cred, allowaddr);
   2625 	COND_SET_PTR(p->p_fd, psrc->p_fd, allowaddr);
   2626 	COND_SET_PTR(p->p_cwdi, psrc->p_cwdi, allowaddr);
   2627 	COND_SET_PTR(p->p_stats, psrc->p_stats, allowaddr);
   2628 	COND_SET_PTR(p->p_limit, psrc->p_limit, allowaddr);
   2629 	COND_SET_PTR(p->p_vmspace, psrc->p_vmspace, allowaddr);
   2630 	COND_SET_PTR(p->p_sigacts, psrc->p_sigacts, allowaddr);
   2631 	COND_SET_PTR(p->p_aio, psrc->p_aio, allowaddr);
   2632 	p->p_mqueue_cnt = psrc->p_mqueue_cnt;
   2633 	memset(&p->p_specdataref, 0, sizeof(p->p_specdataref));
   2634 	p->p_exitsig = psrc->p_exitsig;
   2635 	p->p_flag = psrc->p_flag;
   2636 	p->p_sflag = psrc->p_sflag;
   2637 	p->p_slflag = psrc->p_slflag;
   2638 	p->p_lflag = psrc->p_lflag;
   2639 	p->p_stflag = psrc->p_stflag;
   2640 	p->p_stat = psrc->p_stat;
   2641 	p->p_trace_enabled = psrc->p_trace_enabled;
   2642 	p->p_pid = psrc->p_pid;
   2643 	COND_SET_STRUCT(p->p_pglist, psrc->p_pglist, allowaddr);
   2644 	COND_SET_PTR(p->p_pptr, psrc->p_pptr, allowaddr);
   2645 	COND_SET_STRUCT(p->p_sibling, psrc->p_sibling, allowaddr);
   2646 	COND_SET_STRUCT(p->p_children, psrc->p_children, allowaddr);
   2647 	COND_SET_STRUCT(p->p_lwps, psrc->p_lwps, allowaddr);
   2648 	COND_SET_PTR(p->p_raslist, psrc->p_raslist, allowaddr);
   2649 	p->p_nlwps = psrc->p_nlwps;
   2650 	p->p_nzlwps = psrc->p_nzlwps;
   2651 	p->p_nrlwps = psrc->p_nrlwps;
   2652 	p->p_nlwpwait = psrc->p_nlwpwait;
   2653 	p->p_ndlwps = psrc->p_ndlwps;
   2654 	p->p_nstopchild = psrc->p_nstopchild;
   2655 	p->p_waited = psrc->p_waited;
   2656 	COND_SET_PTR(p->p_zomblwp, psrc->p_zomblwp, allowaddr);
   2657 	COND_SET_PTR(p->p_vforklwp, psrc->p_vforklwp, allowaddr);
   2658 	COND_SET_PTR(p->p_sched_info, psrc->p_sched_info, allowaddr);
   2659 	p->p_estcpu = psrc->p_estcpu;
   2660 	p->p_estcpu_inherited = psrc->p_estcpu_inherited;
   2661 	p->p_forktime = psrc->p_forktime;
   2662 	p->p_pctcpu = psrc->p_pctcpu;
   2663 	COND_SET_PTR(p->p_opptr, psrc->p_opptr, allowaddr);
   2664 	COND_SET_PTR(p->p_timers, psrc->p_timers, allowaddr);
   2665 	p->p_rtime = psrc->p_rtime;
   2666 	p->p_uticks = psrc->p_uticks;
   2667 	p->p_sticks = psrc->p_sticks;
   2668 	p->p_iticks = psrc->p_iticks;
   2669 	p->p_xutime = psrc->p_xutime;
   2670 	p->p_xstime = psrc->p_xstime;
   2671 	p->p_traceflag = psrc->p_traceflag;
   2672 	COND_SET_PTR(p->p_tracep, psrc->p_tracep, allowaddr);
   2673 	COND_SET_PTR(p->p_textvp, psrc->p_textvp, allowaddr);
   2674 	COND_SET_PTR(p->p_emul, psrc->p_emul, allowaddr);
   2675 	COND_SET_PTR(p->p_emuldata, psrc->p_emuldata, allowaddr);
   2676 	COND_SET_CPTR(p->p_execsw, psrc->p_execsw, allowaddr);
   2677 	COND_SET_STRUCT(p->p_klist, psrc->p_klist, allowaddr);
   2678 	COND_SET_STRUCT(p->p_sigwaiters, psrc->p_sigwaiters, allowaddr);
   2679 	COND_SET_STRUCT(p->p_sigpend.sp_info, psrc->p_sigpend.sp_info,
   2680 	    allowaddr);
   2681 	p->p_sigpend.sp_set = psrc->p_sigpend.sp_set;
   2682 	COND_SET_PTR(p->p_lwpctl, psrc->p_lwpctl, allowaddr);
   2683 	p->p_ppid = psrc->p_ppid;
   2684 	p->p_oppid = psrc->p_oppid;
   2685 	COND_SET_PTR(p->p_path, psrc->p_path, allowaddr);
   2686 	p->p_sigctx = psrc->p_sigctx;
   2687 	p->p_nice = psrc->p_nice;
   2688 	memcpy(p->p_comm, psrc->p_comm, sizeof(p->p_comm));
   2689 	COND_SET_PTR(p->p_pgrp, psrc->p_pgrp, allowaddr);
   2690 	COND_SET_VALUE(p->p_psstrp, psrc->p_psstrp, allowaddr);
   2691 	p->p_pax = psrc->p_pax;
   2692 	p->p_xexit = psrc->p_xexit;
   2693 	p->p_xsig = psrc->p_xsig;
   2694 	p->p_acflag = psrc->p_acflag;
   2695 	COND_SET_STRUCT(p->p_md, psrc->p_md, allowaddr);
   2696 	p->p_stackbase = psrc->p_stackbase;
   2697 	COND_SET_PTR(p->p_dtrace, psrc->p_dtrace, allowaddr);
   2698 }
   2699 
   2700 /*
   2701  * Fill in an eproc structure for the specified process.
   2702  */
   2703 void
   2704 fill_eproc(struct proc *p, struct eproc *ep, bool zombie, bool allowaddr)
   2705 {
   2706 	struct tty *tp;
   2707 	struct lwp *l;
   2708 
   2709 	KASSERT(mutex_owned(&proc_lock));
   2710 	KASSERT(mutex_owned(p->p_lock));
   2711 
   2712 	COND_SET_PTR(ep->e_paddr, p, allowaddr);
   2713 	COND_SET_PTR(ep->e_sess, p->p_session, allowaddr);
   2714 	if (p->p_cred) {
   2715 		kauth_cred_topcred(p->p_cred, &ep->e_pcred);
   2716 		kauth_cred_toucred(p->p_cred, &ep->e_ucred);
   2717 	}
   2718 	if (p->p_stat != SIDL && !P_ZOMBIE(p) && !zombie) {
   2719 		struct vmspace *vm = p->p_vmspace;
   2720 
   2721 		ep->e_vm.vm_rssize = vm_resident_count(vm);
   2722 		ep->e_vm.vm_tsize = vm->vm_tsize;
   2723 		ep->e_vm.vm_dsize = vm->vm_dsize;
   2724 		ep->e_vm.vm_ssize = vm->vm_ssize;
   2725 		ep->e_vm.vm_map.size = vm->vm_map.size;
   2726 
   2727 		/* Pick the primary (first) LWP */
   2728 		l = proc_active_lwp(p);
   2729 		KASSERT(l != NULL);
   2730 		lwp_lock(l);
   2731 		if (l->l_wchan)
   2732 			strncpy(ep->e_wmesg, l->l_wmesg, WMESGLEN);
   2733 		lwp_unlock(l);
   2734 	}
   2735 	ep->e_ppid = p->p_ppid;
   2736 	if (p->p_pgrp && p->p_session) {
   2737 		ep->e_pgid = p->p_pgrp->pg_id;
   2738 		ep->e_jobc = p->p_pgrp->pg_jobc;
   2739 		ep->e_sid = p->p_session->s_sid;
   2740 		if ((p->p_lflag & PL_CONTROLT) &&
   2741 		    (tp = p->p_session->s_ttyp)) {
   2742 			ep->e_tdev = tp->t_dev;
   2743 			ep->e_tpgid = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PGID;
   2744 			COND_SET_PTR(ep->e_tsess, tp->t_session, allowaddr);
   2745 		} else
   2746 			ep->e_tdev = (uint32_t)NODEV;
   2747 		ep->e_flag = p->p_session->s_ttyvp ? EPROC_CTTY : 0;
   2748 		if (SESS_LEADER(p))
   2749 			ep->e_flag |= EPROC_SLEADER;
   2750 		strncpy(ep->e_login, p->p_session->s_login, MAXLOGNAME);
   2751 	}
   2752 	ep->e_xsize = ep->e_xrssize = 0;
   2753 	ep->e_xccount = ep->e_xswrss = 0;
   2754 }
   2755 
   2756 /*
   2757  * Fill in a kinfo_proc2 structure for the specified process.
   2758  */
   2759 void
   2760 fill_kproc2(struct proc *p, struct kinfo_proc2 *ki, bool zombie, bool allowaddr)
   2761 {
   2762 	struct tty *tp;
   2763 	struct lwp *l;
   2764 	struct timeval ut, st, rt;
   2765 	sigset_t ss1, ss2;
   2766 	struct rusage ru;
   2767 	struct vmspace *vm;
   2768 
   2769 	KASSERT(mutex_owned(&proc_lock));
   2770 	KASSERT(mutex_owned(p->p_lock));
   2771 
   2772 	sigemptyset(&ss1);
   2773 	sigemptyset(&ss2);
   2774 
   2775 	COND_SET_VALUE(ki->p_paddr, PTRTOUINT64(p), allowaddr);
   2776 	COND_SET_VALUE(ki->p_fd, PTRTOUINT64(p->p_fd), allowaddr);
   2777 	COND_SET_VALUE(ki->p_cwdi, PTRTOUINT64(p->p_cwdi), allowaddr);
   2778 	COND_SET_VALUE(ki->p_stats, PTRTOUINT64(p->p_stats), allowaddr);
   2779 	COND_SET_VALUE(ki->p_limit, PTRTOUINT64(p->p_limit), allowaddr);
   2780 	COND_SET_VALUE(ki->p_vmspace, PTRTOUINT64(p->p_vmspace), allowaddr);
   2781 	COND_SET_VALUE(ki->p_sigacts, PTRTOUINT64(p->p_sigacts), allowaddr);
   2782 	COND_SET_VALUE(ki->p_sess, PTRTOUINT64(p->p_session), allowaddr);
   2783 	ki->p_tsess = 0;	/* may be changed if controlling tty below */
   2784 	COND_SET_VALUE(ki->p_ru, PTRTOUINT64(&p->p_stats->p_ru), allowaddr);
   2785 	ki->p_eflag = 0;
   2786 	ki->p_exitsig = p->p_exitsig;
   2787 	ki->p_flag = L_INMEM;   /* Process never swapped out */
   2788 	ki->p_flag |= sysctl_map_flags(sysctl_flagmap, p->p_flag);
   2789 	ki->p_flag |= sysctl_map_flags(sysctl_sflagmap, p->p_sflag);
   2790 	ki->p_flag |= sysctl_map_flags(sysctl_slflagmap, p->p_slflag);
   2791 	ki->p_flag |= sysctl_map_flags(sysctl_lflagmap, p->p_lflag);
   2792 	ki->p_flag |= sysctl_map_flags(sysctl_stflagmap, p->p_stflag);
   2793 	ki->p_pid = p->p_pid;
   2794 	ki->p_ppid = p->p_ppid;
   2795 	ki->p_uid = kauth_cred_geteuid(p->p_cred);
   2796 	ki->p_ruid = kauth_cred_getuid(p->p_cred);
   2797 	ki->p_gid = kauth_cred_getegid(p->p_cred);
   2798 	ki->p_rgid = kauth_cred_getgid(p->p_cred);
   2799 	ki->p_svuid = kauth_cred_getsvuid(p->p_cred);
   2800 	ki->p_svgid = kauth_cred_getsvgid(p->p_cred);
   2801 	ki->p_ngroups = kauth_cred_ngroups(p->p_cred);
   2802 	kauth_cred_getgroups(p->p_cred, ki->p_groups,
   2803 	    uimin(ki->p_ngroups, sizeof(ki->p_groups) / sizeof(ki->p_groups[0])),
   2804 	    UIO_SYSSPACE);
   2805 
   2806 	ki->p_uticks = p->p_uticks;
   2807 	ki->p_sticks = p->p_sticks;
   2808 	ki->p_iticks = p->p_iticks;
   2809 	ki->p_tpgid = NO_PGID;	/* may be changed if controlling tty below */
   2810 	COND_SET_VALUE(ki->p_tracep, PTRTOUINT64(p->p_tracep), allowaddr);
   2811 	ki->p_traceflag = p->p_traceflag;
   2812 
   2813 	memcpy(&ki->p_sigignore, &p->p_sigctx.ps_sigignore,sizeof(ki_sigset_t));
   2814 	memcpy(&ki->p_sigcatch, &p->p_sigctx.ps_sigcatch, sizeof(ki_sigset_t));
   2815 
   2816 	ki->p_cpticks = 0;
   2817 	ki->p_pctcpu = p->p_pctcpu;
   2818 	ki->p_estcpu = 0;
   2819 	ki->p_stat = p->p_stat; /* Will likely be overridden by LWP status */
   2820 	ki->p_realstat = p->p_stat;
   2821 	ki->p_nice = p->p_nice;
   2822 	ki->p_xstat = P_WAITSTATUS(p);
   2823 	ki->p_acflag = p->p_acflag;
   2824 
   2825 	strncpy(ki->p_comm, p->p_comm,
   2826 	    uimin(sizeof(ki->p_comm), sizeof(p->p_comm)));
   2827 	strncpy(ki->p_ename, p->p_emul->e_name, sizeof(ki->p_ename));
   2828 
   2829 	ki->p_nlwps = p->p_nlwps;
   2830 	ki->p_realflag = ki->p_flag;
   2831 
   2832 	if (p->p_stat != SIDL && !P_ZOMBIE(p) && !zombie) {
   2833 		vm = p->p_vmspace;
   2834 		ki->p_vm_rssize = vm_resident_count(vm);
   2835 		ki->p_vm_tsize = vm->vm_tsize;
   2836 		ki->p_vm_dsize = vm->vm_dsize;
   2837 		ki->p_vm_ssize = vm->vm_ssize;
   2838 		ki->p_vm_vsize = atop(vm->vm_map.size);
   2839 		/*
   2840 		 * Since the stack is initially mapped mostly with
   2841 		 * PROT_NONE and grown as needed, adjust the "mapped size"
   2842 		 * to skip the unused stack portion.
   2843 		 */
   2844 		ki->p_vm_msize =
   2845 		    atop(vm->vm_map.size) - vm->vm_issize + vm->vm_ssize;
   2846 
   2847 		/* Pick the primary (first) LWP */
   2848 		l = proc_active_lwp(p);
   2849 		KASSERT(l != NULL);
   2850 		lwp_lock(l);
   2851 		ki->p_nrlwps = p->p_nrlwps;
   2852 		ki->p_forw = 0;
   2853 		ki->p_back = 0;
   2854 		COND_SET_VALUE(ki->p_addr, PTRTOUINT64(l->l_addr), allowaddr);
   2855 		ki->p_stat = l->l_stat;
   2856 		ki->p_flag |= sysctl_map_flags(sysctl_lwpflagmap, l->l_flag);
   2857 		ki->p_swtime = l->l_swtime;
   2858 		ki->p_slptime = l->l_slptime;
   2859 		if (l->l_stat == LSONPROC)
   2860 			ki->p_schedflags = l->l_cpu->ci_schedstate.spc_flags;
   2861 		else
   2862 			ki->p_schedflags = 0;
   2863 		ki->p_priority = lwp_eprio(l);
   2864 		ki->p_usrpri = l->l_priority;
   2865 		if (l->l_wchan)
   2866 			strncpy(ki->p_wmesg, l->l_wmesg, sizeof(ki->p_wmesg));
   2867 		COND_SET_VALUE(ki->p_wchan, PTRTOUINT64(l->l_wchan), allowaddr);
   2868 		ki->p_cpuid = cpu_index(l->l_cpu);
   2869 		lwp_unlock(l);
   2870 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
   2871 			/* This is hardly correct, but... */
   2872 			sigplusset(&l->l_sigpend.sp_set, &ss1);
   2873 			sigplusset(&l->l_sigmask, &ss2);
   2874 			ki->p_cpticks += l->l_cpticks;
   2875 			ki->p_pctcpu += l->l_pctcpu;
   2876 			ki->p_estcpu += l->l_estcpu;
   2877 		}
   2878 	}
   2879 	sigplusset(&p->p_sigpend.sp_set, &ss1);
   2880 	memcpy(&ki->p_siglist, &ss1, sizeof(ki_sigset_t));
   2881 	memcpy(&ki->p_sigmask, &ss2, sizeof(ki_sigset_t));
   2882 
   2883 	if (p->p_session != NULL) {
   2884 		ki->p_sid = p->p_session->s_sid;
   2885 		ki->p__pgid = p->p_pgrp->pg_id;
   2886 		if (p->p_session->s_ttyvp)
   2887 			ki->p_eflag |= EPROC_CTTY;
   2888 		if (SESS_LEADER(p))
   2889 			ki->p_eflag |= EPROC_SLEADER;
   2890 		strncpy(ki->p_login, p->p_session->s_login,
   2891 		    uimin(sizeof ki->p_login - 1, sizeof p->p_session->s_login));
   2892 		ki->p_jobc = p->p_pgrp->pg_jobc;
   2893 		if ((p->p_lflag & PL_CONTROLT) && (tp = p->p_session->s_ttyp)) {
   2894 			ki->p_tdev = tp->t_dev;
   2895 			ki->p_tpgid = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PGID;
   2896 			COND_SET_VALUE(ki->p_tsess, PTRTOUINT64(tp->t_session),
   2897 			    allowaddr);
   2898 		} else {
   2899 			ki->p_tdev = (int32_t)NODEV;
   2900 		}
   2901 	}
   2902 
   2903 	if (!P_ZOMBIE(p) && !zombie) {
   2904 		ki->p_uvalid = 1;
   2905 		ki->p_ustart_sec = p->p_stats->p_start.tv_sec;
   2906 		ki->p_ustart_usec = p->p_stats->p_start.tv_usec;
   2907 
   2908 		calcru(p, &ut, &st, NULL, &rt);
   2909 		ki->p_rtime_sec = rt.tv_sec;
   2910 		ki->p_rtime_usec = rt.tv_usec;
   2911 		ki->p_uutime_sec = ut.tv_sec;
   2912 		ki->p_uutime_usec = ut.tv_usec;
   2913 		ki->p_ustime_sec = st.tv_sec;
   2914 		ki->p_ustime_usec = st.tv_usec;
   2915 
   2916 		memcpy(&ru, &p->p_stats->p_ru, sizeof(ru));
   2917 		rulwps(p, &ru);
   2918 		ki->p_uru_nvcsw = ru.ru_nvcsw;
   2919 		ki->p_uru_nivcsw = ru.ru_nivcsw;
   2920 		ki->p_uru_maxrss = ru.ru_maxrss;
   2921 		ki->p_uru_ixrss = ru.ru_ixrss;
   2922 		ki->p_uru_idrss = ru.ru_idrss;
   2923 		ki->p_uru_isrss = ru.ru_isrss;
   2924 		ki->p_uru_minflt = ru.ru_minflt;
   2925 		ki->p_uru_majflt = ru.ru_majflt;
   2926 		ki->p_uru_nswap = ru.ru_nswap;
   2927 		ki->p_uru_inblock = ru.ru_inblock;
   2928 		ki->p_uru_oublock = ru.ru_oublock;
   2929 		ki->p_uru_msgsnd = ru.ru_msgsnd;
   2930 		ki->p_uru_msgrcv = ru.ru_msgrcv;
   2931 		ki->p_uru_nsignals = ru.ru_nsignals;
   2932 
   2933 		timeradd(&p->p_stats->p_cru.ru_utime,
   2934 			 &p->p_stats->p_cru.ru_stime, &ut);
   2935 		ki->p_uctime_sec = ut.tv_sec;
   2936 		ki->p_uctime_usec = ut.tv_usec;
   2937 	}
   2938 }
   2939 
   2940 
   2941 int
   2942 proc_find_locked(struct lwp *l, struct proc **p, pid_t pid)
   2943 {
   2944 	int error;
   2945 
   2946 	mutex_enter(&proc_lock);
   2947 	if (pid == -1)
   2948 		*p = l->l_proc;
   2949 	else
   2950 		*p = proc_find(pid);
   2951 
   2952 	if (*p == NULL) {
   2953 		if (pid != -1)
   2954 			mutex_exit(&proc_lock);
   2955 		return ESRCH;
   2956 	}
   2957 	if (pid != -1)
   2958 		mutex_enter((*p)->p_lock);
   2959 	mutex_exit(&proc_lock);
   2960 
   2961 	error = kauth_authorize_process(l->l_cred,
   2962 	    KAUTH_PROCESS_CANSEE, *p,
   2963 	    KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_ENTRY), NULL, NULL);
   2964 	if (error) {
   2965 		if (pid != -1)
   2966 			mutex_exit((*p)->p_lock);
   2967 	}
   2968 	return error;
   2969 }
   2970 
   2971 static int
   2972 fill_pathname(struct lwp *l, pid_t pid, void *oldp, size_t *oldlenp)
   2973 {
   2974 	int error;
   2975 	struct proc *p;
   2976 
   2977 	if ((error = proc_find_locked(l, &p, pid)) != 0)
   2978 		return error;
   2979 
   2980 	if (p->p_path == NULL) {
   2981 		if (pid != -1)
   2982 			mutex_exit(p->p_lock);
   2983 		return ENOENT;
   2984 	}
   2985 
   2986 	size_t len = strlen(p->p_path) + 1;
   2987 	if (oldp != NULL) {
   2988 		size_t copylen = uimin(len, *oldlenp);
   2989 		error = sysctl_copyout(l, p->p_path, oldp, copylen);
   2990 		if (error == 0 && *oldlenp < len)
   2991 			error = ENOSPC;
   2992 	}
   2993 	*oldlenp = len;
   2994 	if (pid != -1)
   2995 		mutex_exit(p->p_lock);
   2996 	return error;
   2997 }
   2998 
   2999 static int
   3000 fill_cwd(struct lwp *l, pid_t pid, void *oldp, size_t *oldlenp)
   3001 {
   3002 	int error;
   3003 	struct proc *p;
   3004 	char *path;
   3005 	char *bp, *bend;
   3006 	struct cwdinfo *cwdi;
   3007 	struct vnode *vp;
   3008 	size_t len, lenused;
   3009 
   3010 	if ((error = proc_find_locked(l, &p, pid)) != 0)
   3011 		return error;
   3012 
   3013 	len = MAXPATHLEN * 4;
   3014 
   3015 	path = kmem_alloc(len, KM_SLEEP);
   3016 
   3017 	bp = &path[len];
   3018 	bend = bp;
   3019 	*(--bp) = '\0';
   3020 
   3021 	cwdi = p->p_cwdi;
   3022 	rw_enter(&cwdi->cwdi_lock, RW_READER);
   3023 	vp = cwdi->cwdi_cdir;
   3024 	error = getcwd_common(vp, NULL, &bp, path, len/2, 0, l);
   3025 	rw_exit(&cwdi->cwdi_lock);
   3026 
   3027 	if (error)
   3028 		goto out;
   3029 
   3030 	lenused = bend - bp;
   3031 
   3032 	if (oldp != NULL) {
   3033 		size_t copylen = uimin(lenused, *oldlenp);
   3034 		error = sysctl_copyout(l, bp, oldp, copylen);
   3035 		if (error == 0 && *oldlenp < lenused)
   3036 			error = ENOSPC;
   3037 	}
   3038 	*oldlenp = lenused;
   3039 out:
   3040 	if (pid != -1)
   3041 		mutex_exit(p->p_lock);
   3042 	kmem_free(path, len);
   3043 	return error;
   3044 }
   3045 
   3046 int
   3047 proc_getauxv(struct proc *p, void **buf, size_t *len)
   3048 {
   3049 	struct ps_strings pss;
   3050 	int error;
   3051 	void *uauxv, *kauxv;
   3052 	size_t size;
   3053 
   3054 	if ((error = copyin_psstrings(p, &pss)) != 0)
   3055 		return error;
   3056 	if (pss.ps_envstr == NULL)
   3057 		return EIO;
   3058 
   3059 	size = p->p_execsw->es_arglen;
   3060 	if (size == 0)
   3061 		return EIO;
   3062 
   3063 	size_t ptrsz = PROC_PTRSZ(p);
   3064 	uauxv = (void *)((char *)pss.ps_envstr + (pss.ps_nenvstr + 1) * ptrsz);
   3065 
   3066 	kauxv = kmem_alloc(size, KM_SLEEP);
   3067 
   3068 	error = copyin_proc(p, uauxv, kauxv, size);
   3069 	if (error) {
   3070 		kmem_free(kauxv, size);
   3071 		return error;
   3072 	}
   3073 
   3074 	*buf = kauxv;
   3075 	*len = size;
   3076 
   3077 	return 0;
   3078 }
   3079 
   3080 
   3081 static int
   3082 sysctl_security_expose_address(SYSCTLFN_ARGS)
   3083 {
   3084 	int expose_address, error;
   3085 	struct sysctlnode node;
   3086 
   3087 	node = *rnode;
   3088 	node.sysctl_data = &expose_address;
   3089 	expose_address = *(int *)rnode->sysctl_data;
   3090 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   3091 	if (error || newp == NULL)
   3092 		return error;
   3093 
   3094 	if (kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_KERNADDR,
   3095 	    0, NULL, NULL, NULL))
   3096 		return EPERM;
   3097 
   3098 	switch (expose_address) {
   3099 	case 0:
   3100 	case 1:
   3101 	case 2:
   3102 		break;
   3103 	default:
   3104 		return EINVAL;
   3105 	}
   3106 
   3107 	*(int *)rnode->sysctl_data = expose_address;
   3108 
   3109 	return 0;
   3110 }
   3111 
   3112 bool
   3113 get_expose_address(struct proc *p)
   3114 {
   3115 	/* allow only if sysctl variable is set or privileged */
   3116 	return kauth_authorize_process(kauth_cred_get(), KAUTH_PROCESS_CANSEE,
   3117 	    p, KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_KPTR), NULL, NULL) == 0;
   3118 }
   3119