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