Home | History | Annotate | Line # | Download | only in kern
kern_proc.c revision 1.141.2.1
      1 /*	$NetBSD: kern_proc.c,v 1.141.2.1 2008/05/10 23:49:04 wrstuden Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2006, 2007, 2008 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.141.2.1 2008/05/10 23:49:04 wrstuden Exp $");
     66 
     67 #include "opt_kstack.h"
     68 #include "opt_maxuprc.h"
     69 #include "opt_multiprocessor.h"
     70 #include "opt_lockdebug.h"
     71 
     72 #include <sys/param.h>
     73 #include <sys/systm.h>
     74 #include <sys/kernel.h>
     75 #include <sys/proc.h>
     76 #include <sys/resourcevar.h>
     77 #include <sys/buf.h>
     78 #include <sys/acct.h>
     79 #include <sys/wait.h>
     80 #include <sys/file.h>
     81 #include <ufs/ufs/quota.h>
     82 #include <sys/uio.h>
     83 #include <sys/malloc.h>
     84 #include <sys/pool.h>
     85 #include <sys/mbuf.h>
     86 #include <sys/ioctl.h>
     87 #include <sys/tty.h>
     88 #include <sys/signalvar.h>
     89 #include <sys/ras.h>
     90 #include <sys/sa.h>
     91 #include <sys/savar.h>
     92 #include <sys/filedesc.h>
     93 #include "sys/syscall_stats.h"
     94 #include <sys/kauth.h>
     95 #include <sys/sleepq.h>
     96 #include <sys/atomic.h>
     97 #include <sys/kmem.h>
     98 
     99 #include <uvm/uvm.h>
    100 #include <uvm/uvm_extern.h>
    101 
    102 /*
    103  * Other process lists
    104  */
    105 
    106 struct proclist allproc;
    107 struct proclist zombproc;	/* resources have been freed */
    108 
    109 kmutex_t	*proc_lock;
    110 
    111 /*
    112  * pid to proc lookup is done by indexing the pid_table array.
    113  * Since pid numbers are only allocated when an empty slot
    114  * has been found, there is no need to search any lists ever.
    115  * (an orphaned pgrp will lock the slot, a session will lock
    116  * the pgrp with the same number.)
    117  * If the table is too small it is reallocated with twice the
    118  * previous size and the entries 'unzipped' into the two halves.
    119  * A linked list of free entries is passed through the pt_proc
    120  * field of 'free' items - set odd to be an invalid ptr.
    121  */
    122 
    123 struct pid_table {
    124 	struct proc	*pt_proc;
    125 	struct pgrp	*pt_pgrp;
    126 };
    127 #if 1	/* strongly typed cast - should be a noop */
    128 static inline uint p2u(struct proc *p) { return (uint)(uintptr_t)p; }
    129 #else
    130 #define p2u(p) ((uint)p)
    131 #endif
    132 #define P_VALID(p) (!(p2u(p) & 1))
    133 #define P_NEXT(p) (p2u(p) >> 1)
    134 #define P_FREE(pid) ((struct proc *)(uintptr_t)((pid) << 1 | 1))
    135 
    136 #define INITIAL_PID_TABLE_SIZE	(1 << 5)
    137 static struct pid_table *pid_table;
    138 static uint pid_tbl_mask = INITIAL_PID_TABLE_SIZE - 1;
    139 static uint pid_alloc_lim;	/* max we allocate before growing table */
    140 static uint pid_alloc_cnt;	/* number of allocated pids */
    141 
    142 /* links through free slots - never empty! */
    143 static uint next_free_pt, last_free_pt;
    144 static pid_t pid_max = PID_MAX;		/* largest value we allocate */
    145 
    146 /* Components of the first process -- never freed. */
    147 
    148 extern const struct emul emul_netbsd;	/* defined in kern_exec.c */
    149 
    150 struct session session0 = {
    151 	.s_count = 1,
    152 	.s_sid = 0,
    153 };
    154 struct pgrp pgrp0 = {
    155 	.pg_members = LIST_HEAD_INITIALIZER(&pgrp0.pg_members),
    156 	.pg_session = &session0,
    157 };
    158 filedesc_t filedesc0;
    159 struct cwdinfo cwdi0 = {
    160 	.cwdi_cmask = CMASK,		/* see cmask below */
    161 	.cwdi_refcnt = 1,
    162 };
    163 struct plimit limit0 = {
    164 	.pl_corename = defcorename,
    165 	.pl_refcnt = 1,
    166 	.pl_rlimit = {
    167 		[0 ... __arraycount(limit0.pl_rlimit) - 1] = {
    168 			.rlim_cur = RLIM_INFINITY,
    169 			.rlim_max = RLIM_INFINITY,
    170 		},
    171 	},
    172 };
    173 struct pstats pstat0;
    174 struct vmspace vmspace0;
    175 struct sigacts sigacts0;
    176 struct turnstile turnstile0;
    177 struct proc proc0 = {
    178 	.p_lwps = LIST_HEAD_INITIALIZER(&proc0.p_lwps),
    179 	.p_sigwaiters = LIST_HEAD_INITIALIZER(&proc0.p_sigwaiters),
    180 	.p_nlwps = 1,
    181 	.p_nrlwps = 1,
    182 	.p_nlwpid = 1,		/* must match lwp0.l_lid */
    183 	.p_pgrp = &pgrp0,
    184 	.p_comm = "system",
    185 	/*
    186 	 * Set P_NOCLDWAIT so that kernel threads are reparented to init(8)
    187 	 * when they exit.  init(8) can easily wait them out for us.
    188 	 */
    189 	.p_flag = PK_SYSTEM | PK_NOCLDWAIT,
    190 	.p_stat = SACTIVE,
    191 	.p_nice = NZERO,
    192 	.p_emul = &emul_netbsd,
    193 	.p_cwdi = &cwdi0,
    194 	.p_limit = &limit0,
    195 	.p_fd = &filedesc0,
    196 	.p_vmspace = &vmspace0,
    197 	.p_stats = &pstat0,
    198 	.p_sigacts = &sigacts0,
    199 };
    200 struct lwp lwp0 __aligned(MIN_LWP_ALIGNMENT) = {
    201 #ifdef LWP0_CPU_INFO
    202 	.l_cpu = LWP0_CPU_INFO,
    203 #endif
    204 	.l_proc = &proc0,
    205 	.l_lid = 1,
    206 	.l_flag = LW_INMEM | LW_SYSTEM,
    207 	.l_stat = LSONPROC,
    208 	.l_ts = &turnstile0,
    209 	.l_syncobj = &sched_syncobj,
    210 	.l_refcnt = 1,
    211 	.l_priority = PRI_USER + NPRI_USER - 1,
    212 	.l_inheritedprio = -1,
    213 	.l_class = SCHED_OTHER,
    214 	.l_pi_lenders = SLIST_HEAD_INITIALIZER(&lwp0.l_pi_lenders),
    215 	.l_name = __UNCONST("swapper"),
    216 };
    217 kauth_cred_t cred0;
    218 
    219 extern struct user *proc0paddr;
    220 
    221 int nofile = NOFILE;
    222 int maxuprc = MAXUPRC;
    223 int cmask = CMASK;
    224 
    225 MALLOC_DEFINE(M_EMULDATA, "emuldata", "Per-process emulation data");
    226 MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
    227 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
    228 
    229 /*
    230  * The process list descriptors, used during pid allocation and
    231  * by sysctl.  No locking on this data structure is needed since
    232  * it is completely static.
    233  */
    234 const struct proclist_desc proclists[] = {
    235 	{ &allproc	},
    236 	{ &zombproc	},
    237 	{ NULL		},
    238 };
    239 
    240 static void orphanpg(struct pgrp *);
    241 static void pg_delete(pid_t);
    242 
    243 static specificdata_domain_t proc_specificdata_domain;
    244 
    245 static pool_cache_t proc_cache;
    246 
    247 /*
    248  * Initialize global process hashing structures.
    249  */
    250 void
    251 procinit(void)
    252 {
    253 	const struct proclist_desc *pd;
    254 	int i;
    255 #define	LINK_EMPTY ((PID_MAX + INITIAL_PID_TABLE_SIZE) & ~(INITIAL_PID_TABLE_SIZE - 1))
    256 
    257 	for (pd = proclists; pd->pd_list != NULL; pd++)
    258 		LIST_INIT(pd->pd_list);
    259 
    260 	proc_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
    261 
    262 	pid_table = malloc(INITIAL_PID_TABLE_SIZE * sizeof *pid_table,
    263 			    M_PROC, M_WAITOK);
    264 	/* Set free list running through table...
    265 	   Preset 'use count' above PID_MAX so we allocate pid 1 next. */
    266 	for (i = 0; i <= pid_tbl_mask; i++) {
    267 		pid_table[i].pt_proc = P_FREE(LINK_EMPTY + i + 1);
    268 		pid_table[i].pt_pgrp = 0;
    269 	}
    270 	/* slot 0 is just grabbed */
    271 	next_free_pt = 1;
    272 	/* Need to fix last entry. */
    273 	last_free_pt = pid_tbl_mask;
    274 	pid_table[last_free_pt].pt_proc = P_FREE(LINK_EMPTY);
    275 	/* point at which we grow table - to avoid reusing pids too often */
    276 	pid_alloc_lim = pid_tbl_mask - 1;
    277 #undef LINK_EMPTY
    278 
    279 	proc_specificdata_domain = specificdata_domain_create();
    280 	KASSERT(proc_specificdata_domain != NULL);
    281 
    282 	proc_cache = pool_cache_init(sizeof(struct proc), 0, 0, 0,
    283 	    "procpl", NULL, IPL_NONE, NULL, NULL, NULL);
    284 }
    285 
    286 /*
    287  * Initialize process 0.
    288  */
    289 void
    290 proc0_init(void)
    291 {
    292 	struct proc *p;
    293 	struct pgrp *pg;
    294 	struct session *sess;
    295 	struct lwp *l;
    296 	rlim_t lim;
    297 
    298 	p = &proc0;
    299 	pg = &pgrp0;
    300 	sess = &session0;
    301 	l = &lwp0;
    302 
    303 	KASSERT(l->l_lid == p->p_nlwpid);
    304 
    305 	mutex_init(&p->p_stmutex, MUTEX_DEFAULT, IPL_HIGH);
    306 	mutex_init(&p->p_auxlock, MUTEX_DEFAULT, IPL_NONE);
    307 	mutex_init(&l->l_swaplock, MUTEX_DEFAULT, IPL_NONE);
    308 	p->p_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
    309 
    310 	rw_init(&p->p_reflock);
    311 	cv_init(&p->p_waitcv, "wait");
    312 	cv_init(&p->p_lwpcv, "lwpwait");
    313 
    314 	LIST_INSERT_HEAD(&p->p_lwps, l, l_sibling);
    315 
    316 	pid_table[0].pt_proc = p;
    317 	LIST_INSERT_HEAD(&allproc, p, p_list);
    318 	LIST_INSERT_HEAD(&alllwp, l, l_list);
    319 
    320 	pid_table[0].pt_pgrp = pg;
    321 	LIST_INSERT_HEAD(&pg->pg_members, p, p_pglist);
    322 
    323 #ifdef __HAVE_SYSCALL_INTERN
    324 	(*p->p_emul->e_syscall_intern)(p);
    325 #endif
    326 
    327 	callout_init(&l->l_timeout_ch, CALLOUT_MPSAFE);
    328 	callout_setfunc(&l->l_timeout_ch, sleepq_timeout, l);
    329 	cv_init(&l->l_sigcv, "sigwait");
    330 
    331 	/* Create credentials. */
    332 	cred0 = kauth_cred_alloc();
    333 	p->p_cred = cred0;
    334 	kauth_cred_hold(cred0);
    335 	l->l_cred = cred0;
    336 
    337 	/* Create the CWD info. */
    338 	rw_init(&cwdi0.cwdi_lock);
    339 
    340 	/* Create the limits structures. */
    341 	mutex_init(&limit0.pl_lock, MUTEX_DEFAULT, IPL_NONE);
    342 
    343 	limit0.pl_rlimit[RLIMIT_NOFILE].rlim_max = maxfiles;
    344 	limit0.pl_rlimit[RLIMIT_NOFILE].rlim_cur =
    345 	    maxfiles < nofile ? maxfiles : nofile;
    346 
    347 	limit0.pl_rlimit[RLIMIT_NPROC].rlim_max = maxproc;
    348 	limit0.pl_rlimit[RLIMIT_NPROC].rlim_cur =
    349 	    maxproc < maxuprc ? maxproc : maxuprc;
    350 
    351 	lim = ptoa(uvmexp.free);
    352 	limit0.pl_rlimit[RLIMIT_RSS].rlim_max = lim;
    353 	limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_max = lim;
    354 	limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_cur = lim / 3;
    355 
    356 	/* Configure virtual memory system, set vm rlimits. */
    357 	uvm_init_limits(p);
    358 
    359 	/* Initialize file descriptor table for proc0. */
    360 	fd_init(&filedesc0);
    361 
    362 	/*
    363 	 * Initialize proc0's vmspace, which uses the kernel pmap.
    364 	 * All kernel processes (which never have user space mappings)
    365 	 * share proc0's vmspace, and thus, the kernel pmap.
    366 	 */
    367 	uvmspace_init(&vmspace0, pmap_kernel(), round_page(VM_MIN_ADDRESS),
    368 	    trunc_page(VM_MAX_ADDRESS));
    369 
    370 	l->l_addr = proc0paddr;				/* XXX */
    371 
    372 	/* Initialize signal state for proc0. XXX IPL_SCHED */
    373 	mutex_init(&p->p_sigacts->sa_mutex, MUTEX_DEFAULT, IPL_SCHED);
    374 	siginit(p);
    375 
    376 	proc_initspecific(p);
    377 	lwp_initspecific(l);
    378 
    379 	SYSCALL_TIME_LWP_INIT(l);
    380 }
    381 
    382 /*
    383  * Check that the specified process group is in the session of the
    384  * specified process.
    385  * Treats -ve ids as process ids.
    386  * Used to validate TIOCSPGRP requests.
    387  */
    388 int
    389 pgid_in_session(struct proc *p, pid_t pg_id)
    390 {
    391 	struct pgrp *pgrp;
    392 	struct session *session;
    393 	int error;
    394 
    395 	mutex_enter(proc_lock);
    396 	if (pg_id < 0) {
    397 		struct proc *p1 = p_find(-pg_id, PFIND_LOCKED | PFIND_UNLOCK_FAIL);
    398 		if (p1 == NULL)
    399 			return EINVAL;
    400 		pgrp = p1->p_pgrp;
    401 	} else {
    402 		pgrp = pg_find(pg_id, PFIND_LOCKED | PFIND_UNLOCK_FAIL);
    403 		if (pgrp == NULL)
    404 			return EINVAL;
    405 	}
    406 	session = pgrp->pg_session;
    407 	if (session != p->p_pgrp->pg_session)
    408 		error = EPERM;
    409 	else
    410 		error = 0;
    411 	mutex_exit(proc_lock);
    412 
    413 	return error;
    414 }
    415 
    416 /*
    417  * Is p an inferior of q?
    418  *
    419  * Call with the proc_lock held.
    420  */
    421 int
    422 inferior(struct proc *p, struct proc *q)
    423 {
    424 
    425 	for (; p != q; p = p->p_pptr)
    426 		if (p->p_pid == 0)
    427 			return 0;
    428 	return 1;
    429 }
    430 
    431 /*
    432  * Locate a process by number
    433  */
    434 struct proc *
    435 p_find(pid_t pid, uint flags)
    436 {
    437 	struct proc *p;
    438 	char stat;
    439 
    440 	if (!(flags & PFIND_LOCKED))
    441 		mutex_enter(proc_lock);
    442 
    443 	p = pid_table[pid & pid_tbl_mask].pt_proc;
    444 
    445 	/* Only allow live processes to be found by pid. */
    446 	/* XXXSMP p_stat */
    447 	if (P_VALID(p) && p->p_pid == pid && ((stat = p->p_stat) == SACTIVE ||
    448 	    stat == SSTOP || ((flags & PFIND_ZOMBIE) &&
    449 	    (stat == SZOMB || stat == SDEAD || stat == SDYING)))) {
    450 		if (flags & PFIND_UNLOCK_OK)
    451 			 mutex_exit(proc_lock);
    452 		return p;
    453 	}
    454 	if (flags & PFIND_UNLOCK_FAIL)
    455 		mutex_exit(proc_lock);
    456 	return NULL;
    457 }
    458 
    459 
    460 /*
    461  * Locate a process group by number
    462  */
    463 struct pgrp *
    464 pg_find(pid_t pgid, uint flags)
    465 {
    466 	struct pgrp *pg;
    467 
    468 	if (!(flags & PFIND_LOCKED))
    469 		mutex_enter(proc_lock);
    470 	pg = pid_table[pgid & pid_tbl_mask].pt_pgrp;
    471 	/*
    472 	 * Can't look up a pgrp that only exists because the session
    473 	 * hasn't died yet (traditional)
    474 	 */
    475 	if (pg == NULL || pg->pg_id != pgid || LIST_EMPTY(&pg->pg_members)) {
    476 		if (flags & PFIND_UNLOCK_FAIL)
    477 			 mutex_exit(proc_lock);
    478 		return NULL;
    479 	}
    480 
    481 	if (flags & PFIND_UNLOCK_OK)
    482 		mutex_exit(proc_lock);
    483 	return pg;
    484 }
    485 
    486 static void
    487 expand_pid_table(void)
    488 {
    489 	uint pt_size = pid_tbl_mask + 1;
    490 	struct pid_table *n_pt, *new_pt;
    491 	struct proc *proc;
    492 	struct pgrp *pgrp;
    493 	int i;
    494 	pid_t pid;
    495 
    496 	new_pt = malloc(pt_size * 2 * sizeof *new_pt, M_PROC, M_WAITOK);
    497 
    498 	mutex_enter(proc_lock);
    499 	if (pt_size != pid_tbl_mask + 1) {
    500 		/* Another process beat us to it... */
    501 		mutex_exit(proc_lock);
    502 		FREE(new_pt, M_PROC);
    503 		return;
    504 	}
    505 
    506 	/*
    507 	 * Copy entries from old table into new one.
    508 	 * If 'pid' is 'odd' we need to place in the upper half,
    509 	 * even pid's to the lower half.
    510 	 * Free items stay in the low half so we don't have to
    511 	 * fixup the reference to them.
    512 	 * We stuff free items on the front of the freelist
    513 	 * because we can't write to unmodified entries.
    514 	 * Processing the table backwards maintains a semblance
    515 	 * of issueing pid numbers that increase with time.
    516 	 */
    517 	i = pt_size - 1;
    518 	n_pt = new_pt + i;
    519 	for (; ; i--, n_pt--) {
    520 		proc = pid_table[i].pt_proc;
    521 		pgrp = pid_table[i].pt_pgrp;
    522 		if (!P_VALID(proc)) {
    523 			/* Up 'use count' so that link is valid */
    524 			pid = (P_NEXT(proc) + pt_size) & ~pt_size;
    525 			proc = P_FREE(pid);
    526 			if (pgrp)
    527 				pid = pgrp->pg_id;
    528 		} else
    529 			pid = proc->p_pid;
    530 
    531 		/* Save entry in appropriate half of table */
    532 		n_pt[pid & pt_size].pt_proc = proc;
    533 		n_pt[pid & pt_size].pt_pgrp = pgrp;
    534 
    535 		/* Put other piece on start of free list */
    536 		pid = (pid ^ pt_size) & ~pid_tbl_mask;
    537 		n_pt[pid & pt_size].pt_proc =
    538 				    P_FREE((pid & ~pt_size) | next_free_pt);
    539 		n_pt[pid & pt_size].pt_pgrp = 0;
    540 		next_free_pt = i | (pid & pt_size);
    541 		if (i == 0)
    542 			break;
    543 	}
    544 
    545 	/* Switch tables */
    546 	n_pt = pid_table;
    547 	pid_table = new_pt;
    548 	pid_tbl_mask = pt_size * 2 - 1;
    549 
    550 	/*
    551 	 * pid_max starts as PID_MAX (= 30000), once we have 16384
    552 	 * allocated pids we need it to be larger!
    553 	 */
    554 	if (pid_tbl_mask > PID_MAX) {
    555 		pid_max = pid_tbl_mask * 2 + 1;
    556 		pid_alloc_lim |= pid_alloc_lim << 1;
    557 	} else
    558 		pid_alloc_lim <<= 1;	/* doubles number of free slots... */
    559 
    560 	mutex_exit(proc_lock);
    561 	FREE(n_pt, M_PROC);
    562 }
    563 
    564 struct proc *
    565 proc_alloc(void)
    566 {
    567 	struct proc *p;
    568 	int nxt;
    569 	pid_t pid;
    570 	struct pid_table *pt;
    571 
    572 	p = pool_cache_get(proc_cache, PR_WAITOK);
    573 	p->p_stat = SIDL;			/* protect against others */
    574 
    575 	proc_initspecific(p);
    576 	/* allocate next free pid */
    577 
    578 	for (;;expand_pid_table()) {
    579 		if (__predict_false(pid_alloc_cnt >= pid_alloc_lim))
    580 			/* ensure pids cycle through 2000+ values */
    581 			continue;
    582 		mutex_enter(proc_lock);
    583 		pt = &pid_table[next_free_pt];
    584 #ifdef DIAGNOSTIC
    585 		if (__predict_false(P_VALID(pt->pt_proc) || pt->pt_pgrp))
    586 			panic("proc_alloc: slot busy");
    587 #endif
    588 		nxt = P_NEXT(pt->pt_proc);
    589 		if (nxt & pid_tbl_mask)
    590 			break;
    591 		/* Table full - expand (NB last entry not used....) */
    592 		mutex_exit(proc_lock);
    593 	}
    594 
    595 	/* pid is 'saved use count' + 'size' + entry */
    596 	pid = (nxt & ~pid_tbl_mask) + pid_tbl_mask + 1 + next_free_pt;
    597 	if ((uint)pid > (uint)pid_max)
    598 		pid &= pid_tbl_mask;
    599 	p->p_pid = pid;
    600 	next_free_pt = nxt & pid_tbl_mask;
    601 
    602 	/* Grab table slot */
    603 	pt->pt_proc = p;
    604 	pid_alloc_cnt++;
    605 
    606 	mutex_exit(proc_lock);
    607 
    608 	return p;
    609 }
    610 
    611 /*
    612  * Free a process id - called from proc_free (in kern_exit.c)
    613  *
    614  * Called with the proc_lock held.
    615  */
    616 void
    617 proc_free_pid(struct proc *p)
    618 {
    619 	pid_t pid = p->p_pid;
    620 	struct pid_table *pt;
    621 
    622 	KASSERT(mutex_owned(proc_lock));
    623 
    624 	pt = &pid_table[pid & pid_tbl_mask];
    625 #ifdef DIAGNOSTIC
    626 	if (__predict_false(pt->pt_proc != p))
    627 		panic("proc_free: pid_table mismatch, pid %x, proc %p",
    628 			pid, p);
    629 #endif
    630 	/* save pid use count in slot */
    631 	pt->pt_proc = P_FREE(pid & ~pid_tbl_mask);
    632 
    633 	if (pt->pt_pgrp == NULL) {
    634 		/* link last freed entry onto ours */
    635 		pid &= pid_tbl_mask;
    636 		pt = &pid_table[last_free_pt];
    637 		pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pid);
    638 		last_free_pt = pid;
    639 		pid_alloc_cnt--;
    640 	}
    641 
    642 	atomic_dec_uint(&nprocs);
    643 }
    644 
    645 void
    646 proc_free_mem(struct proc *p)
    647 {
    648 
    649 	pool_cache_put(proc_cache, p);
    650 }
    651 
    652 /*
    653  * Move p to a new or existing process group (and session)
    654  *
    655  * If we are creating a new pgrp, the pgid should equal
    656  * the calling process' pid.
    657  * If is only valid to enter a process group that is in the session
    658  * of the process.
    659  * Also mksess should only be set if we are creating a process group
    660  *
    661  * Only called from sys_setsid and sys_setpgid.
    662  */
    663 int
    664 enterpgrp(struct proc *curp, pid_t pid, pid_t pgid, int mksess)
    665 {
    666 	struct pgrp *new_pgrp, *pgrp;
    667 	struct session *sess;
    668 	struct proc *p;
    669 	int rval;
    670 	pid_t pg_id = NO_PGID;
    671 
    672 	if (mksess)
    673 		sess = kmem_alloc(sizeof(*sess), KM_SLEEP);
    674 	else
    675 		sess = NULL;
    676 
    677 	/* Allocate data areas we might need before doing any validity checks */
    678 	mutex_enter(proc_lock);		/* Because pid_table might change */
    679 	if (pid_table[pgid & pid_tbl_mask].pt_pgrp == 0) {
    680 		mutex_exit(proc_lock);
    681 		new_pgrp = kmem_alloc(sizeof(*new_pgrp), KM_SLEEP);
    682 		mutex_enter(proc_lock);
    683 	} else
    684 		new_pgrp = NULL;
    685 	rval = EPERM;	/* most common error (to save typing) */
    686 
    687 	/* Check pgrp exists or can be created */
    688 	pgrp = pid_table[pgid & pid_tbl_mask].pt_pgrp;
    689 	if (pgrp != NULL && pgrp->pg_id != pgid)
    690 		goto done;
    691 
    692 	/* Can only set another process under restricted circumstances. */
    693 	if (pid != curp->p_pid) {
    694 		/* must exist and be one of our children... */
    695 		if ((p = p_find(pid, PFIND_LOCKED)) == NULL ||
    696 		    !inferior(p, curp)) {
    697 			rval = ESRCH;
    698 			goto done;
    699 		}
    700 		/* ... in the same session... */
    701 		if (sess != NULL || p->p_session != curp->p_session)
    702 			goto done;
    703 		/* ... existing pgid must be in same session ... */
    704 		if (pgrp != NULL && pgrp->pg_session != p->p_session)
    705 			goto done;
    706 		/* ... and not done an exec. */
    707 		if (p->p_flag & PK_EXEC) {
    708 			rval = EACCES;
    709 			goto done;
    710 		}
    711 	} else {
    712 		/* ... setsid() cannot re-enter a pgrp */
    713 		if (mksess && (curp->p_pgid == curp->p_pid ||
    714 		    pg_find(curp->p_pid, PFIND_LOCKED)))
    715 			goto done;
    716 		p = curp;
    717 	}
    718 
    719 	/* Changing the process group/session of a session
    720 	   leader is definitely off limits. */
    721 	if (SESS_LEADER(p)) {
    722 		if (sess == NULL && p->p_pgrp == pgrp)
    723 			/* unless it's a definite noop */
    724 			rval = 0;
    725 		goto done;
    726 	}
    727 
    728 	/* Can only create a process group with id of process */
    729 	if (pgrp == NULL && pgid != pid)
    730 		goto done;
    731 
    732 	/* Can only create a session if creating pgrp */
    733 	if (sess != NULL && pgrp != NULL)
    734 		goto done;
    735 
    736 	/* Check we allocated memory for a pgrp... */
    737 	if (pgrp == NULL && new_pgrp == NULL)
    738 		goto done;
    739 
    740 	/* Don't attach to 'zombie' pgrp */
    741 	if (pgrp != NULL && LIST_EMPTY(&pgrp->pg_members))
    742 		goto done;
    743 
    744 	/* Expect to succeed now */
    745 	rval = 0;
    746 
    747 	if (pgrp == p->p_pgrp)
    748 		/* nothing to do */
    749 		goto done;
    750 
    751 	/* Ok all setup, link up required structures */
    752 
    753 	if (pgrp == NULL) {
    754 		pgrp = new_pgrp;
    755 		new_pgrp = NULL;
    756 		if (sess != NULL) {
    757 			sess->s_sid = p->p_pid;
    758 			sess->s_leader = p;
    759 			sess->s_count = 1;
    760 			sess->s_ttyvp = NULL;
    761 			sess->s_ttyp = NULL;
    762 			sess->s_flags = p->p_session->s_flags & ~S_LOGIN_SET;
    763 			memcpy(sess->s_login, p->p_session->s_login,
    764 			    sizeof(sess->s_login));
    765 			p->p_lflag &= ~PL_CONTROLT;
    766 		} else {
    767 			sess = p->p_pgrp->pg_session;
    768 			SESSHOLD(sess);
    769 		}
    770 		pgrp->pg_session = sess;
    771 		sess = NULL;
    772 
    773 		pgrp->pg_id = pgid;
    774 		LIST_INIT(&pgrp->pg_members);
    775 #ifdef DIAGNOSTIC
    776 		if (__predict_false(pid_table[pgid & pid_tbl_mask].pt_pgrp))
    777 			panic("enterpgrp: pgrp table slot in use");
    778 		if (__predict_false(mksess && p != curp))
    779 			panic("enterpgrp: mksession and p != curproc");
    780 #endif
    781 		pid_table[pgid & pid_tbl_mask].pt_pgrp = pgrp;
    782 		pgrp->pg_jobc = 0;
    783 	}
    784 
    785 	/*
    786 	 * Adjust eligibility of affected pgrps to participate in job control.
    787 	 * Increment eligibility counts before decrementing, otherwise we
    788 	 * could reach 0 spuriously during the first call.
    789 	 */
    790 	fixjobc(p, pgrp, 1);
    791 	fixjobc(p, p->p_pgrp, 0);
    792 
    793 	/* Interlock with ttread(). */
    794 	mutex_spin_enter(&tty_lock);
    795 
    796 	/* Move process to requested group. */
    797 	LIST_REMOVE(p, p_pglist);
    798 	if (LIST_EMPTY(&p->p_pgrp->pg_members))
    799 		/* defer delete until we've dumped the lock */
    800 		pg_id = p->p_pgrp->pg_id;
    801 	p->p_pgrp = pgrp;
    802 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
    803 
    804 	/* Done with the swap; we can release the tty mutex. */
    805 	mutex_spin_exit(&tty_lock);
    806 
    807     done:
    808 	if (pg_id != NO_PGID)
    809 		pg_delete(pg_id);
    810 	mutex_exit(proc_lock);
    811 	if (sess != NULL)
    812 		kmem_free(sess, sizeof(*sess));
    813 	if (new_pgrp != NULL)
    814 		kmem_free(new_pgrp, sizeof(*new_pgrp));
    815 #ifdef DEBUG_PGRP
    816 	if (__predict_false(rval))
    817 		printf("enterpgrp(%d,%d,%d), curproc %d, rval %d\n",
    818 			pid, pgid, mksess, curp->p_pid, rval);
    819 #endif
    820 	return rval;
    821 }
    822 
    823 /*
    824  * Remove a process from its process group.  Must be called with the
    825  * proc_lock held.
    826  */
    827 void
    828 leavepgrp(struct proc *p)
    829 {
    830 	struct pgrp *pgrp;
    831 
    832 	KASSERT(mutex_owned(proc_lock));
    833 
    834 	/* Interlock with ttread() */
    835 	mutex_spin_enter(&tty_lock);
    836 	pgrp = p->p_pgrp;
    837 	LIST_REMOVE(p, p_pglist);
    838 	p->p_pgrp = NULL;
    839 	mutex_spin_exit(&tty_lock);
    840 
    841 	if (LIST_EMPTY(&pgrp->pg_members))
    842 		pg_delete(pgrp->pg_id);
    843 }
    844 
    845 /*
    846  * Free a process group.  Must be called with the proc_lock held.
    847  */
    848 static void
    849 pg_free(pid_t pg_id)
    850 {
    851 	struct pgrp *pgrp;
    852 	struct pid_table *pt;
    853 
    854 	KASSERT(mutex_owned(proc_lock));
    855 
    856 	pt = &pid_table[pg_id & pid_tbl_mask];
    857 	pgrp = pt->pt_pgrp;
    858 #ifdef DIAGNOSTIC
    859 	if (__predict_false(!pgrp || pgrp->pg_id != pg_id
    860 	    || !LIST_EMPTY(&pgrp->pg_members)))
    861 		panic("pg_free: process group absent or has members");
    862 #endif
    863 	pt->pt_pgrp = 0;
    864 
    865 	if (!P_VALID(pt->pt_proc)) {
    866 		/* orphaned pgrp, put slot onto free list */
    867 #ifdef DIAGNOSTIC
    868 		if (__predict_false(P_NEXT(pt->pt_proc) & pid_tbl_mask))
    869 			panic("pg_free: process slot on free list");
    870 #endif
    871 		pg_id &= pid_tbl_mask;
    872 		pt = &pid_table[last_free_pt];
    873 		pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pg_id);
    874 		last_free_pt = pg_id;
    875 		pid_alloc_cnt--;
    876 	}
    877 	kmem_free(pgrp, sizeof(*pgrp));
    878 }
    879 
    880 /*
    881  * Delete a process group.  Must be called with the proc_lock held.
    882  */
    883 static void
    884 pg_delete(pid_t pg_id)
    885 {
    886 	struct pgrp *pgrp;
    887 	struct tty *ttyp;
    888 	struct session *ss;
    889 	int is_pgrp_leader;
    890 
    891 	KASSERT(mutex_owned(proc_lock));
    892 
    893 	pgrp = pid_table[pg_id & pid_tbl_mask].pt_pgrp;
    894 	if (pgrp == NULL || pgrp->pg_id != pg_id ||
    895 	    !LIST_EMPTY(&pgrp->pg_members))
    896 		return;
    897 
    898 	ss = pgrp->pg_session;
    899 
    900 	/* Remove reference (if any) from tty to this process group */
    901 	mutex_spin_enter(&tty_lock);
    902 	ttyp = ss->s_ttyp;
    903 	if (ttyp != NULL && ttyp->t_pgrp == pgrp) {
    904 		ttyp->t_pgrp = NULL;
    905 #ifdef DIAGNOSTIC
    906 		if (ttyp->t_session != ss)
    907 			panic("pg_delete: wrong session on terminal");
    908 #endif
    909 	}
    910 	mutex_spin_exit(&tty_lock);
    911 
    912 	/*
    913 	 * The leading process group in a session is freed
    914 	 * by sessdelete() if last reference.
    915 	 */
    916 	is_pgrp_leader = (ss->s_sid == pgrp->pg_id);
    917 	SESSRELE(ss);
    918 
    919 	if (is_pgrp_leader)
    920 		return;
    921 
    922 	pg_free(pg_id);
    923 }
    924 
    925 /*
    926  * Delete session - called from SESSRELE when s_count becomes zero.
    927  * Must be called with the proc_lock held.
    928  */
    929 void
    930 sessdelete(struct session *ss)
    931 {
    932 
    933 	KASSERT(mutex_owned(proc_lock));
    934 
    935 	/*
    936 	 * We keep the pgrp with the same id as the session in
    937 	 * order to stop a process being given the same pid.
    938 	 * Since the pgrp holds a reference to the session, it
    939 	 * must be a 'zombie' pgrp by now.
    940 	 */
    941 	pg_free(ss->s_sid);
    942 	kmem_free(ss, sizeof(*ss));
    943 }
    944 
    945 /*
    946  * Adjust pgrp jobc counters when specified process changes process group.
    947  * We count the number of processes in each process group that "qualify"
    948  * the group for terminal job control (those with a parent in a different
    949  * process group of the same session).  If that count reaches zero, the
    950  * process group becomes orphaned.  Check both the specified process'
    951  * process group and that of its children.
    952  * entering == 0 => p is leaving specified group.
    953  * entering == 1 => p is entering specified group.
    954  *
    955  * Call with proc_lock held.
    956  */
    957 void
    958 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
    959 {
    960 	struct pgrp *hispgrp;
    961 	struct session *mysession = pgrp->pg_session;
    962 	struct proc *child;
    963 
    964 	KASSERT(mutex_owned(proc_lock));
    965 
    966 	/*
    967 	 * Check p's parent to see whether p qualifies its own process
    968 	 * group; if so, adjust count for p's process group.
    969 	 */
    970 	hispgrp = p->p_pptr->p_pgrp;
    971 	if (hispgrp != pgrp && hispgrp->pg_session == mysession) {
    972 		if (entering) {
    973 			pgrp->pg_jobc++;
    974 			p->p_lflag &= ~PL_ORPHANPG;
    975 		} else if (--pgrp->pg_jobc == 0)
    976 			orphanpg(pgrp);
    977 	}
    978 
    979 	/*
    980 	 * Check this process' children to see whether they qualify
    981 	 * their process groups; if so, adjust counts for children's
    982 	 * process groups.
    983 	 */
    984 	LIST_FOREACH(child, &p->p_children, p_sibling) {
    985 		hispgrp = child->p_pgrp;
    986 		if (hispgrp != pgrp && hispgrp->pg_session == mysession &&
    987 		    !P_ZOMBIE(child)) {
    988 			if (entering) {
    989 				child->p_lflag &= ~PL_ORPHANPG;
    990 				hispgrp->pg_jobc++;
    991 			} else if (--hispgrp->pg_jobc == 0)
    992 				orphanpg(hispgrp);
    993 		}
    994 	}
    995 }
    996 
    997 /*
    998  * A process group has become orphaned;
    999  * if there are any stopped processes in the group,
   1000  * hang-up all process in that group.
   1001  *
   1002  * Call with proc_lock held.
   1003  */
   1004 static void
   1005 orphanpg(struct pgrp *pg)
   1006 {
   1007 	struct proc *p;
   1008 	int doit;
   1009 
   1010 	KASSERT(mutex_owned(proc_lock));
   1011 
   1012 	doit = 0;
   1013 
   1014 	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
   1015 		if (p->p_stat == SSTOP) {
   1016 			p->p_lflag |= PL_ORPHANPG;
   1017 			psignal(p, SIGHUP);
   1018 			psignal(p, SIGCONT);
   1019 		}
   1020 	}
   1021 }
   1022 
   1023 #ifdef DDB
   1024 #include <ddb/db_output.h>
   1025 void pidtbl_dump(void);
   1026 void
   1027 pidtbl_dump(void)
   1028 {
   1029 	struct pid_table *pt;
   1030 	struct proc *p;
   1031 	struct pgrp *pgrp;
   1032 	int id;
   1033 
   1034 	db_printf("pid table %p size %x, next %x, last %x\n",
   1035 		pid_table, pid_tbl_mask+1,
   1036 		next_free_pt, last_free_pt);
   1037 	for (pt = pid_table, id = 0; id <= pid_tbl_mask; id++, pt++) {
   1038 		p = pt->pt_proc;
   1039 		if (!P_VALID(p) && !pt->pt_pgrp)
   1040 			continue;
   1041 		db_printf("  id %x: ", id);
   1042 		if (P_VALID(p))
   1043 			db_printf("proc %p id %d (0x%x) %s\n",
   1044 				p, p->p_pid, p->p_pid, p->p_comm);
   1045 		else
   1046 			db_printf("next %x use %x\n",
   1047 				P_NEXT(p) & pid_tbl_mask,
   1048 				P_NEXT(p) & ~pid_tbl_mask);
   1049 		if ((pgrp = pt->pt_pgrp)) {
   1050 			db_printf("\tsession %p, sid %d, count %d, login %s\n",
   1051 			    pgrp->pg_session, pgrp->pg_session->s_sid,
   1052 			    pgrp->pg_session->s_count,
   1053 			    pgrp->pg_session->s_login);
   1054 			db_printf("\tpgrp %p, pg_id %d, pg_jobc %d, members %p\n",
   1055 			    pgrp, pgrp->pg_id, pgrp->pg_jobc,
   1056 			    LIST_FIRST(&pgrp->pg_members));
   1057 			LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
   1058 				db_printf("\t\tpid %d addr %p pgrp %p %s\n",
   1059 				    p->p_pid, p, p->p_pgrp, p->p_comm);
   1060 			}
   1061 		}
   1062 	}
   1063 }
   1064 #endif /* DDB */
   1065 
   1066 #ifdef KSTACK_CHECK_MAGIC
   1067 #include <sys/user.h>
   1068 
   1069 #define	KSTACK_MAGIC	0xdeadbeaf
   1070 
   1071 /* XXX should be per process basis? */
   1072 int kstackleftmin = KSTACK_SIZE;
   1073 int kstackleftthres = KSTACK_SIZE / 8; /* warn if remaining stack is
   1074 					  less than this */
   1075 
   1076 void
   1077 kstack_setup_magic(const struct lwp *l)
   1078 {
   1079 	uint32_t *ip;
   1080 	uint32_t const *end;
   1081 
   1082 	KASSERT(l != NULL);
   1083 	KASSERT(l != &lwp0);
   1084 
   1085 	/*
   1086 	 * fill all the stack with magic number
   1087 	 * so that later modification on it can be detected.
   1088 	 */
   1089 	ip = (uint32_t *)KSTACK_LOWEST_ADDR(l);
   1090 	end = (uint32_t *)((char *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
   1091 	for (; ip < end; ip++) {
   1092 		*ip = KSTACK_MAGIC;
   1093 	}
   1094 }
   1095 
   1096 void
   1097 kstack_check_magic(const struct lwp *l)
   1098 {
   1099 	uint32_t const *ip, *end;
   1100 	int stackleft;
   1101 
   1102 	KASSERT(l != NULL);
   1103 
   1104 	/* don't check proc0 */ /*XXX*/
   1105 	if (l == &lwp0)
   1106 		return;
   1107 
   1108 #ifdef __MACHINE_STACK_GROWS_UP
   1109 	/* stack grows upwards (eg. hppa) */
   1110 	ip = (uint32_t *)((void *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
   1111 	end = (uint32_t *)KSTACK_LOWEST_ADDR(l);
   1112 	for (ip--; ip >= end; ip--)
   1113 		if (*ip != KSTACK_MAGIC)
   1114 			break;
   1115 
   1116 	stackleft = (void *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE - (void *)ip;
   1117 #else /* __MACHINE_STACK_GROWS_UP */
   1118 	/* stack grows downwards (eg. i386) */
   1119 	ip = (uint32_t *)KSTACK_LOWEST_ADDR(l);
   1120 	end = (uint32_t *)((char *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
   1121 	for (; ip < end; ip++)
   1122 		if (*ip != KSTACK_MAGIC)
   1123 			break;
   1124 
   1125 	stackleft = ((const char *)ip) - (const char *)KSTACK_LOWEST_ADDR(l);
   1126 #endif /* __MACHINE_STACK_GROWS_UP */
   1127 
   1128 	if (kstackleftmin > stackleft) {
   1129 		kstackleftmin = stackleft;
   1130 		if (stackleft < kstackleftthres)
   1131 			printf("warning: kernel stack left %d bytes"
   1132 			    "(pid %u:lid %u)\n", stackleft,
   1133 			    (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
   1134 	}
   1135 
   1136 	if (stackleft <= 0) {
   1137 		panic("magic on the top of kernel stack changed for "
   1138 		    "pid %u, lid %u: maybe kernel stack overflow",
   1139 		    (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
   1140 	}
   1141 }
   1142 #endif /* KSTACK_CHECK_MAGIC */
   1143 
   1144 int
   1145 proclist_foreach_call(struct proclist *list,
   1146     int (*callback)(struct proc *, void *arg), void *arg)
   1147 {
   1148 	struct proc marker;
   1149 	struct proc *p;
   1150 	struct lwp * const l = curlwp;
   1151 	int ret = 0;
   1152 
   1153 	marker.p_flag = PK_MARKER;
   1154 	uvm_lwp_hold(l);
   1155 	mutex_enter(proc_lock);
   1156 	for (p = LIST_FIRST(list); ret == 0 && p != NULL;) {
   1157 		if (p->p_flag & PK_MARKER) {
   1158 			p = LIST_NEXT(p, p_list);
   1159 			continue;
   1160 		}
   1161 		LIST_INSERT_AFTER(p, &marker, p_list);
   1162 		ret = (*callback)(p, arg);
   1163 		KASSERT(mutex_owned(proc_lock));
   1164 		p = LIST_NEXT(&marker, p_list);
   1165 		LIST_REMOVE(&marker, p_list);
   1166 	}
   1167 	mutex_exit(proc_lock);
   1168 	uvm_lwp_rele(l);
   1169 
   1170 	return ret;
   1171 }
   1172 
   1173 int
   1174 proc_vmspace_getref(struct proc *p, struct vmspace **vm)
   1175 {
   1176 
   1177 	/* XXXCDC: how should locking work here? */
   1178 
   1179 	/* curproc exception is for coredump. */
   1180 
   1181 	if ((p != curproc && (p->p_sflag & PS_WEXIT) != 0) ||
   1182 	    (p->p_vmspace->vm_refcnt < 1)) { /* XXX */
   1183 		return EFAULT;
   1184 	}
   1185 
   1186 	uvmspace_addref(p->p_vmspace);
   1187 	*vm = p->p_vmspace;
   1188 
   1189 	return 0;
   1190 }
   1191 
   1192 /*
   1193  * Acquire a write lock on the process credential.
   1194  */
   1195 void
   1196 proc_crmod_enter(void)
   1197 {
   1198 	struct lwp *l = curlwp;
   1199 	struct proc *p = l->l_proc;
   1200 	struct plimit *lim;
   1201 	kauth_cred_t oc;
   1202 	char *cn;
   1203 
   1204 	/* Reset what needs to be reset in plimit. */
   1205 	if (p->p_limit->pl_corename != defcorename) {
   1206 		lim_privatise(p, false);
   1207 		lim = p->p_limit;
   1208 		mutex_enter(&lim->pl_lock);
   1209 		cn = lim->pl_corename;
   1210 		lim->pl_corename = defcorename;
   1211 		mutex_exit(&lim->pl_lock);
   1212 		if (cn != defcorename)
   1213 			free(cn, M_TEMP);
   1214 	}
   1215 
   1216 	mutex_enter(p->p_lock);
   1217 
   1218 	/* Ensure the LWP cached credentials are up to date. */
   1219 	if ((oc = l->l_cred) != p->p_cred) {
   1220 		kauth_cred_hold(p->p_cred);
   1221 		l->l_cred = p->p_cred;
   1222 		kauth_cred_free(oc);
   1223 	}
   1224 
   1225 }
   1226 
   1227 /*
   1228  * Set in a new process credential, and drop the write lock.  The credential
   1229  * must have a reference already.  Optionally, free a no-longer required
   1230  * credential.  The scheduler also needs to inspect p_cred, so we also
   1231  * briefly acquire the sched state mutex.
   1232  */
   1233 void
   1234 proc_crmod_leave(kauth_cred_t scred, kauth_cred_t fcred, bool sugid)
   1235 {
   1236 	struct lwp *l = curlwp, *l2;
   1237 	struct proc *p = l->l_proc;
   1238 	kauth_cred_t oc;
   1239 
   1240 	KASSERT(mutex_owned(p->p_lock));
   1241 
   1242 	/* Is there a new credential to set in? */
   1243 	if (scred != NULL) {
   1244 		p->p_cred = scred;
   1245 		LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
   1246 			if (l2 != l)
   1247 				l2->l_prflag |= LPR_CRMOD;
   1248 		}
   1249 
   1250 		/* Ensure the LWP cached credentials are up to date. */
   1251 		if ((oc = l->l_cred) != scred) {
   1252 			kauth_cred_hold(scred);
   1253 			l->l_cred = scred;
   1254 		}
   1255 	} else
   1256 		oc = NULL;	/* XXXgcc */
   1257 
   1258 	if (sugid) {
   1259 		/*
   1260 		 * Mark process as having changed credentials, stops
   1261 		 * tracing etc.
   1262 		 */
   1263 		p->p_flag |= PK_SUGID;
   1264 	}
   1265 
   1266 	mutex_exit(p->p_lock);
   1267 
   1268 	/* If there is a credential to be released, free it now. */
   1269 	if (fcred != NULL) {
   1270 		KASSERT(scred != NULL);
   1271 		kauth_cred_free(fcred);
   1272 		if (oc != scred)
   1273 			kauth_cred_free(oc);
   1274 	}
   1275 }
   1276 
   1277 /*
   1278  * proc_specific_key_create --
   1279  *	Create a key for subsystem proc-specific data.
   1280  */
   1281 int
   1282 proc_specific_key_create(specificdata_key_t *keyp, specificdata_dtor_t dtor)
   1283 {
   1284 
   1285 	return (specificdata_key_create(proc_specificdata_domain, keyp, dtor));
   1286 }
   1287 
   1288 /*
   1289  * proc_specific_key_delete --
   1290  *	Delete a key for subsystem proc-specific data.
   1291  */
   1292 void
   1293 proc_specific_key_delete(specificdata_key_t key)
   1294 {
   1295 
   1296 	specificdata_key_delete(proc_specificdata_domain, key);
   1297 }
   1298 
   1299 /*
   1300  * proc_initspecific --
   1301  *	Initialize a proc's specificdata container.
   1302  */
   1303 void
   1304 proc_initspecific(struct proc *p)
   1305 {
   1306 	int error;
   1307 
   1308 	error = specificdata_init(proc_specificdata_domain, &p->p_specdataref);
   1309 	KASSERT(error == 0);
   1310 }
   1311 
   1312 /*
   1313  * proc_finispecific --
   1314  *	Finalize a proc's specificdata container.
   1315  */
   1316 void
   1317 proc_finispecific(struct proc *p)
   1318 {
   1319 
   1320 	specificdata_fini(proc_specificdata_domain, &p->p_specdataref);
   1321 }
   1322 
   1323 /*
   1324  * proc_getspecific --
   1325  *	Return proc-specific data corresponding to the specified key.
   1326  */
   1327 void *
   1328 proc_getspecific(struct proc *p, specificdata_key_t key)
   1329 {
   1330 
   1331 	return (specificdata_getspecific(proc_specificdata_domain,
   1332 					 &p->p_specdataref, key));
   1333 }
   1334 
   1335 /*
   1336  * proc_setspecific --
   1337  *	Set proc-specific data corresponding to the specified key.
   1338  */
   1339 void
   1340 proc_setspecific(struct proc *p, specificdata_key_t key, void *data)
   1341 {
   1342 
   1343 	specificdata_setspecific(proc_specificdata_domain,
   1344 				 &p->p_specdataref, key, data);
   1345 }
   1346