Home | History | Annotate | Line # | Download | only in kern
kern_proc.c revision 1.114.2.1
      1 /*	$NetBSD: kern_proc.c,v 1.114.2.1 2007/08/28 18:43:44 matt Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2006, 2007 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  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the NetBSD
     22  *	Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 /*
     41  * Copyright (c) 1982, 1986, 1989, 1991, 1993
     42  *	The Regents of the University of California.  All rights reserved.
     43  *
     44  * Redistribution and use in source and binary forms, with or without
     45  * modification, are permitted provided that the following conditions
     46  * are met:
     47  * 1. Redistributions of source code must retain the above copyright
     48  *    notice, this list of conditions and the following disclaimer.
     49  * 2. Redistributions in binary form must reproduce the above copyright
     50  *    notice, this list of conditions and the following disclaimer in the
     51  *    documentation and/or other materials provided with the distribution.
     52  * 3. Neither the name of the University nor the names of its contributors
     53  *    may be used to endorse or promote products derived from this software
     54  *    without specific prior written permission.
     55  *
     56  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     57  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     58  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     59  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     60  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     61  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     62  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     63  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     64  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     65  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     66  * SUCH DAMAGE.
     67  *
     68  *	@(#)kern_proc.c	8.7 (Berkeley) 2/14/95
     69  */
     70 
     71 #include <sys/cdefs.h>
     72 __KERNEL_RCSID(0, "$NetBSD: kern_proc.c,v 1.114.2.1 2007/08/28 18:43:44 matt Exp $");
     73 
     74 #include "opt_kstack.h"
     75 #include "opt_maxuprc.h"
     76 #include "opt_multiprocessor.h"
     77 #include "opt_lockdebug.h"
     78 
     79 #include <sys/param.h>
     80 #include <sys/systm.h>
     81 #include <sys/kernel.h>
     82 #include <sys/proc.h>
     83 #include <sys/resourcevar.h>
     84 #include <sys/buf.h>
     85 #include <sys/acct.h>
     86 #include <sys/wait.h>
     87 #include <sys/file.h>
     88 #include <ufs/ufs/quota.h>
     89 #include <sys/uio.h>
     90 #include <sys/malloc.h>
     91 #include <sys/pool.h>
     92 #include <sys/mbuf.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 
    102 #include <uvm/uvm.h>
    103 #include <uvm/uvm_extern.h>
    104 
    105 /*
    106  * Other process lists
    107  */
    108 
    109 struct proclist allproc;
    110 struct proclist zombproc;	/* resources have been freed */
    111 
    112 /*
    113  * There are two locks on global process state.
    114  *
    115  * 1. proclist_lock is an adaptive mutex and is used when modifying
    116  * or examining process state from a process context.  It protects
    117  * the internal tables, all of the process lists, and a number of
    118  * members of struct proc.
    119  *
    120  * 2. proclist_mutex is used when allproc must be traversed from an
    121  * interrupt context, or when changing the state of processes.  The
    122  * proclist_lock should always be used in preference.  In some cases,
    123  * both locks need to be held.
    124  *
    125  *	proclist_lock	proclist_mutex	structure
    126  *	--------------- --------------- -----------------
    127  *	x				zombproc
    128  *	x		x		pid_table
    129  *	x				proc::p_pptr
    130  *	x				proc::p_sibling
    131  *	x				proc::p_children
    132  *	x		x		allproc
    133  *	x		x		proc::p_pgrp
    134  *	x		x		proc::p_pglist
    135  *	x		x		proc::p_session
    136  *	x		x		proc::p_list
    137  *			x		alllwp
    138  *			x		lwp::l_list
    139  *
    140  * The lock order for processes and LWPs is approximately as following:
    141  *
    142  * kernel_lock
    143  * -> proclist_lock
    144  *   -> proc::p_mutex
    145  *      -> proclist_mutex
    146  *         -> proc::p_smutex
    147  *           -> proc::p_stmutex
    148  *
    149  * XXX p_smutex can be run at IPL_VM once audio drivers on the x86
    150  * platform are made MP safe.  Currently it blocks interrupts at
    151  * IPL_SCHED and below.
    152  *
    153  * XXX The two process locks (p_smutex + p_mutex), and the two global
    154  * state locks (proclist_lock + proclist_mutex) should be merged
    155  * together.  However, to do so requires interrupts that interrupts
    156  * be run with LWP context.
    157  */
    158 kmutex_t	proclist_lock;
    159 kmutex_t	proclist_mutex;
    160 
    161 /*
    162  * pid to proc lookup is done by indexing the pid_table array.
    163  * Since pid numbers are only allocated when an empty slot
    164  * has been found, there is no need to search any lists ever.
    165  * (an orphaned pgrp will lock the slot, a session will lock
    166  * the pgrp with the same number.)
    167  * If the table is too small it is reallocated with twice the
    168  * previous size and the entries 'unzipped' into the two halves.
    169  * A linked list of free entries is passed through the pt_proc
    170  * field of 'free' items - set odd to be an invalid ptr.
    171  */
    172 
    173 struct pid_table {
    174 	struct proc	*pt_proc;
    175 	struct pgrp	*pt_pgrp;
    176 };
    177 #if 1	/* strongly typed cast - should be a noop */
    178 static inline uint p2u(struct proc *p) { return (uint)(uintptr_t)p; }
    179 #else
    180 #define p2u(p) ((uint)p)
    181 #endif
    182 #define P_VALID(p) (!(p2u(p) & 1))
    183 #define P_NEXT(p) (p2u(p) >> 1)
    184 #define P_FREE(pid) ((struct proc *)(uintptr_t)((pid) << 1 | 1))
    185 
    186 #define INITIAL_PID_TABLE_SIZE	(1 << 5)
    187 static struct pid_table *pid_table;
    188 static uint pid_tbl_mask = INITIAL_PID_TABLE_SIZE - 1;
    189 static uint pid_alloc_lim;	/* max we allocate before growing table */
    190 static uint pid_alloc_cnt;	/* number of allocated pids */
    191 
    192 /* links through free slots - never empty! */
    193 static uint next_free_pt, last_free_pt;
    194 static pid_t pid_max = PID_MAX;		/* largest value we allocate */
    195 
    196 /* Components of the first process -- never freed. */
    197 
    198 extern const struct emul emul_netbsd;	/* defined in kern_exec.c */
    199 
    200 struct session session0 = {
    201 	.s_count = 1,
    202 	.s_sid = 0,
    203 };
    204 struct pgrp pgrp0 = {
    205 	.pg_members = LIST_HEAD_INITIALIZER(&pgrp0.pg_members),
    206 	.pg_session = &session0,
    207 };
    208 struct filedesc0 filedesc0;
    209 struct cwdinfo cwdi0 = {
    210 	.cwdi_cmask = CMASK,		/* see cmask below */
    211 	.cwdi_refcnt = 1,
    212 };
    213 struct plimit limit0 = {
    214 	.pl_corename = defcorename,
    215 	.p_refcnt = 1,
    216 	.pl_rlimit = {
    217 		[0 ... __arraycount(limit0.pl_rlimit) - 1] = {
    218 			.rlim_cur = RLIM_INFINITY,
    219 			.rlim_max = RLIM_INFINITY,
    220 		},
    221 	},
    222 };
    223 struct pstats pstat0;
    224 struct vmspace vmspace0;
    225 struct sigacts sigacts0;
    226 struct turnstile turnstile0;
    227 struct proc proc0 = {
    228 	.p_lwps = LIST_HEAD_INITIALIZER(&proc0.p_lwps),
    229 	.p_sigwaiters = LIST_HEAD_INITIALIZER(&proc0.p_sigwaiters),
    230 	.p_nlwps = 1,
    231 	.p_nrlwps = 1,
    232 	.p_nlwpid = 1,		/* must match lwp.l_lid */
    233 	.p_refcnt = 1,
    234 	.p_pgrp = &pgrp0,
    235 	.p_comm = "system",
    236 	/*
    237 	 * Set P_NOCLDWAIT so that kernel threads are reparented to init(8)
    238 	 * when they exit.  init(8) can easily wait them out for us.
    239 	 */
    240 	.p_flag = PK_SYSTEM | PK_NOCLDWAIT,
    241 	.p_stat = SACTIVE,
    242 	.p_nice = NZERO,
    243 	.p_emul = &emul_netbsd,
    244 	.p_cwdi = &cwdi0,
    245 	.p_limit = &limit0,
    246 	.p_fd = &filedesc0.fd_fd,
    247 	.p_vmspace = &vmspace0,
    248 	.p_stats = &pstat0,
    249 	.p_sigacts = &sigacts0,
    250 };
    251 struct lwp lwp0 __aligned(MIN_LWP_ALIGNMENT) = {
    252 #ifndef LWP0_CPU_INFO
    253 	.l_cpu = LWP0_CPU_INFO,
    254 #endif
    255 	.l_proc = &proc0,
    256 	.l_lid = 1,
    257 	.l_flag = LW_INMEM | LW_SYSTEM,
    258 	.l_stat = LSONPROC,
    259 	.l_ts = &turnstile0,
    260 	.l_syncobj = &sched_syncobj,
    261 	.l_refcnt = 1,
    262 	.l_priority = PRIBIO,
    263 	.l_usrpri = PRIBIO,
    264 	.l_inheritedprio = MAXPRI,
    265 	.l_pi_lenders = SLIST_HEAD_INITIALIZER(&lwp0.l_pi_lenders),
    266 	.l_name = __UNCONST("swapper"),
    267 };
    268 kauth_cred_t cred0;
    269 
    270 extern struct user *proc0paddr;
    271 
    272 int nofile = NOFILE;
    273 int maxuprc = MAXUPRC;
    274 int cmask = CMASK;
    275 
    276 POOL_INIT(proc_pool, sizeof(struct proc), 0, 0, 0, "procpl",
    277     &pool_allocator_nointr, IPL_NONE);
    278 POOL_INIT(pgrp_pool, sizeof(struct pgrp), 0, 0, 0, "pgrppl",
    279     &pool_allocator_nointr, IPL_NONE);
    280 POOL_INIT(plimit_pool, sizeof(struct plimit), 0, 0, 0, "plimitpl",
    281     &pool_allocator_nointr, IPL_NONE);
    282 POOL_INIT(pstats_pool, sizeof(struct pstats), 0, 0, 0, "pstatspl",
    283     &pool_allocator_nointr, IPL_NONE);
    284 POOL_INIT(session_pool, sizeof(struct session), 0, 0, 0, "sessionpl",
    285     &pool_allocator_nointr, IPL_NONE);
    286 
    287 MALLOC_DEFINE(M_EMULDATA, "emuldata", "Per-process emulation data");
    288 MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
    289 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
    290 
    291 /*
    292  * The process list descriptors, used during pid allocation and
    293  * by sysctl.  No locking on this data structure is needed since
    294  * it is completely static.
    295  */
    296 const struct proclist_desc proclists[] = {
    297 	{ &allproc	},
    298 	{ &zombproc	},
    299 	{ NULL		},
    300 };
    301 
    302 static void orphanpg(struct pgrp *);
    303 static void pg_delete(pid_t);
    304 
    305 static specificdata_domain_t proc_specificdata_domain;
    306 
    307 /*
    308  * Initialize global process hashing structures.
    309  */
    310 void
    311 procinit(void)
    312 {
    313 	const struct proclist_desc *pd;
    314 	int i;
    315 #define	LINK_EMPTY ((PID_MAX + INITIAL_PID_TABLE_SIZE) & ~(INITIAL_PID_TABLE_SIZE - 1))
    316 
    317 	for (pd = proclists; pd->pd_list != NULL; pd++)
    318 		LIST_INIT(pd->pd_list);
    319 
    320 	mutex_init(&proclist_lock, MUTEX_DEFAULT, IPL_NONE);
    321 	mutex_init(&proclist_mutex, MUTEX_SPIN, IPL_SCHED);
    322 
    323 	pid_table = malloc(INITIAL_PID_TABLE_SIZE * sizeof *pid_table,
    324 			    M_PROC, M_WAITOK);
    325 	/* Set free list running through table...
    326 	   Preset 'use count' above PID_MAX so we allocate pid 1 next. */
    327 	for (i = 0; i <= pid_tbl_mask; i++) {
    328 		pid_table[i].pt_proc = P_FREE(LINK_EMPTY + i + 1);
    329 		pid_table[i].pt_pgrp = 0;
    330 	}
    331 	/* slot 0 is just grabbed */
    332 	next_free_pt = 1;
    333 	/* Need to fix last entry. */
    334 	last_free_pt = pid_tbl_mask;
    335 	pid_table[last_free_pt].pt_proc = P_FREE(LINK_EMPTY);
    336 	/* point at which we grow table - to avoid reusing pids too often */
    337 	pid_alloc_lim = pid_tbl_mask - 1;
    338 #undef LINK_EMPTY
    339 
    340 	LIST_INIT(&alllwp);
    341 
    342 	uihashtbl =
    343 	    hashinit(maxproc / 16, HASH_LIST, M_PROC, M_WAITOK, &uihash);
    344 
    345 	proc_specificdata_domain = specificdata_domain_create();
    346 	KASSERT(proc_specificdata_domain != NULL);
    347 }
    348 
    349 /*
    350  * Initialize process 0.
    351  */
    352 void
    353 proc0_init(void)
    354 {
    355 	struct proc *p;
    356 	struct pgrp *pg;
    357 	struct session *sess;
    358 	struct lwp *l;
    359 	rlim_t lim;
    360 
    361 	p = &proc0;
    362 	pg = &pgrp0;
    363 	sess = &session0;
    364 	l = &lwp0;
    365 
    366 	/*
    367 	 * XXX p_rasmutex is run at IPL_SCHED, because of lock order
    368 	 * issues (kernel_lock -> p_rasmutex).  Ideally ras_lookup
    369 	 * should operate "lock free".
    370 	 */
    371 	mutex_init(&p->p_smutex, MUTEX_SPIN, IPL_SCHED);
    372 	mutex_init(&p->p_stmutex, MUTEX_SPIN, IPL_HIGH);
    373 	mutex_init(&p->p_rasmutex, MUTEX_SPIN, IPL_SCHED);
    374 	mutex_init(&p->p_mutex, MUTEX_DEFAULT, IPL_NONE);
    375 	mutex_init(&l->l_swaplock, MUTEX_DEFAULT, IPL_NONE);
    376 
    377 	cv_init(&p->p_refcv, "drainref");
    378 	cv_init(&p->p_waitcv, "wait");
    379 	cv_init(&p->p_lwpcv, "lwpwait");
    380 
    381 	LIST_INSERT_HEAD(&p->p_lwps, l, l_sibling);
    382 
    383 	pid_table[0].pt_proc = p;
    384 	LIST_INSERT_HEAD(&allproc, p, p_list);
    385 	LIST_INSERT_HEAD(&alllwp, l, l_list);
    386 
    387 	pid_table[0].pt_pgrp = pg;
    388 	LIST_INSERT_HEAD(&pg->pg_members, p, p_pglist);
    389 
    390 #ifdef __HAVE_SYSCALL_INTERN
    391 	(*p->p_emul->e_syscall_intern)(p);
    392 #endif
    393 
    394 	callout_init(&l->l_tsleep_ch, 0);
    395 	cv_init(&l->l_sigcv, "sigwait");
    396 
    397 	/* Create credentials. */
    398 	cred0 = kauth_cred_alloc();
    399 	p->p_cred = cred0;
    400 	kauth_cred_hold(cred0);
    401 	l->l_cred = cred0;
    402 
    403 	/* Create the CWD info. */
    404 	rw_init(&cwdi0.cwdi_lock);
    405 
    406 	/* Create the limits structures. */
    407 	mutex_init(&limit0.p_lock, MUTEX_DEFAULT, IPL_NONE);
    408 
    409 	limit0.pl_rlimit[RLIMIT_NOFILE].rlim_max = maxfiles;
    410 	limit0.pl_rlimit[RLIMIT_NOFILE].rlim_cur =
    411 	    maxfiles < nofile ? maxfiles : nofile;
    412 
    413 	limit0.pl_rlimit[RLIMIT_NPROC].rlim_max = maxproc;
    414 	limit0.pl_rlimit[RLIMIT_NPROC].rlim_cur =
    415 	    maxproc < maxuprc ? maxproc : maxuprc;
    416 
    417 	lim = ptoa(uvmexp.free);
    418 	limit0.pl_rlimit[RLIMIT_RSS].rlim_max = lim;
    419 	limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_max = lim;
    420 	limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_cur = lim / 3;
    421 
    422 	/* Configure virtual memory system, set vm rlimits. */
    423 	uvm_init_limits(p);
    424 
    425 	/* Initialize file descriptor table for proc0. */
    426 	fdinit1(&filedesc0);
    427 
    428 	/*
    429 	 * Initialize proc0's vmspace, which uses the kernel pmap.
    430 	 * All kernel processes (which never have user space mappings)
    431 	 * share proc0's vmspace, and thus, the kernel pmap.
    432 	 */
    433 	uvmspace_init(&vmspace0, pmap_kernel(), round_page(VM_MIN_ADDRESS),
    434 	    trunc_page(VM_MAX_ADDRESS));
    435 
    436 	l->l_addr = proc0paddr;				/* XXX */
    437 
    438 	/* Initialize signal state for proc0. */
    439 	mutex_init(&p->p_sigacts->sa_mutex, MUTEX_SPIN, IPL_NONE);
    440 	siginit(p);
    441 
    442 	proc_initspecific(p);
    443 	lwp_initspecific(l);
    444 
    445 	SYSCALL_TIME_LWP_INIT(l);
    446 }
    447 
    448 /*
    449  * Check that the specified process group is in the session of the
    450  * specified process.
    451  * Treats -ve ids as process ids.
    452  * Used to validate TIOCSPGRP requests.
    453  */
    454 int
    455 pgid_in_session(struct proc *p, pid_t pg_id)
    456 {
    457 	struct pgrp *pgrp;
    458 	struct session *session;
    459 	int error;
    460 
    461 	mutex_enter(&proclist_lock);
    462 	if (pg_id < 0) {
    463 		struct proc *p1 = p_find(-pg_id, PFIND_LOCKED | PFIND_UNLOCK_FAIL);
    464 		if (p1 == NULL)
    465 			return EINVAL;
    466 		pgrp = p1->p_pgrp;
    467 	} else {
    468 		pgrp = pg_find(pg_id, PFIND_LOCKED | PFIND_UNLOCK_FAIL);
    469 		if (pgrp == NULL)
    470 			return EINVAL;
    471 	}
    472 	session = pgrp->pg_session;
    473 	if (session != p->p_pgrp->pg_session)
    474 		error = EPERM;
    475 	else
    476 		error = 0;
    477 	mutex_exit(&proclist_lock);
    478 
    479 	return error;
    480 }
    481 
    482 /*
    483  * Is p an inferior of q?
    484  *
    485  * Call with the proclist_lock held.
    486  */
    487 int
    488 inferior(struct proc *p, struct proc *q)
    489 {
    490 
    491 	for (; p != q; p = p->p_pptr)
    492 		if (p->p_pid == 0)
    493 			return 0;
    494 	return 1;
    495 }
    496 
    497 /*
    498  * Locate a process by number
    499  */
    500 struct proc *
    501 p_find(pid_t pid, uint flags)
    502 {
    503 	struct proc *p;
    504 	char stat;
    505 
    506 	if (!(flags & PFIND_LOCKED))
    507 		mutex_enter(&proclist_lock);
    508 
    509 	p = pid_table[pid & pid_tbl_mask].pt_proc;
    510 
    511 	/* Only allow live processes to be found by pid. */
    512 	/* XXXSMP p_stat */
    513 	if (P_VALID(p) && p->p_pid == pid && ((stat = p->p_stat) == SACTIVE ||
    514 	    stat == SSTOP || ((flags & PFIND_ZOMBIE) &&
    515 	    (stat == SZOMB || stat == SDEAD || stat == SDYING)))) {
    516 		if (flags & PFIND_UNLOCK_OK)
    517 			 mutex_exit(&proclist_lock);
    518 		return p;
    519 	}
    520 	if (flags & PFIND_UNLOCK_FAIL)
    521 		mutex_exit(&proclist_lock);
    522 	return NULL;
    523 }
    524 
    525 
    526 /*
    527  * Locate a process group by number
    528  */
    529 struct pgrp *
    530 pg_find(pid_t pgid, uint flags)
    531 {
    532 	struct pgrp *pg;
    533 
    534 	if (!(flags & PFIND_LOCKED))
    535 		mutex_enter(&proclist_lock);
    536 	pg = pid_table[pgid & pid_tbl_mask].pt_pgrp;
    537 	/*
    538 	 * Can't look up a pgrp that only exists because the session
    539 	 * hasn't died yet (traditional)
    540 	 */
    541 	if (pg == NULL || pg->pg_id != pgid || LIST_EMPTY(&pg->pg_members)) {
    542 		if (flags & PFIND_UNLOCK_FAIL)
    543 			 mutex_exit(&proclist_lock);
    544 		return NULL;
    545 	}
    546 
    547 	if (flags & PFIND_UNLOCK_OK)
    548 		mutex_exit(&proclist_lock);
    549 	return pg;
    550 }
    551 
    552 static void
    553 expand_pid_table(void)
    554 {
    555 	uint pt_size = pid_tbl_mask + 1;
    556 	struct pid_table *n_pt, *new_pt;
    557 	struct proc *proc;
    558 	struct pgrp *pgrp;
    559 	int i;
    560 	pid_t pid;
    561 
    562 	new_pt = malloc(pt_size * 2 * sizeof *new_pt, M_PROC, M_WAITOK);
    563 
    564 	mutex_enter(&proclist_lock);
    565 	if (pt_size != pid_tbl_mask + 1) {
    566 		/* Another process beat us to it... */
    567 		mutex_exit(&proclist_lock);
    568 		FREE(new_pt, M_PROC);
    569 		return;
    570 	}
    571 
    572 	/*
    573 	 * Copy entries from old table into new one.
    574 	 * If 'pid' is 'odd' we need to place in the upper half,
    575 	 * even pid's to the lower half.
    576 	 * Free items stay in the low half so we don't have to
    577 	 * fixup the reference to them.
    578 	 * We stuff free items on the front of the freelist
    579 	 * because we can't write to unmodified entries.
    580 	 * Processing the table backwards maintains a semblance
    581 	 * of issueing pid numbers that increase with time.
    582 	 */
    583 	i = pt_size - 1;
    584 	n_pt = new_pt + i;
    585 	for (; ; i--, n_pt--) {
    586 		proc = pid_table[i].pt_proc;
    587 		pgrp = pid_table[i].pt_pgrp;
    588 		if (!P_VALID(proc)) {
    589 			/* Up 'use count' so that link is valid */
    590 			pid = (P_NEXT(proc) + pt_size) & ~pt_size;
    591 			proc = P_FREE(pid);
    592 			if (pgrp)
    593 				pid = pgrp->pg_id;
    594 		} else
    595 			pid = proc->p_pid;
    596 
    597 		/* Save entry in appropriate half of table */
    598 		n_pt[pid & pt_size].pt_proc = proc;
    599 		n_pt[pid & pt_size].pt_pgrp = pgrp;
    600 
    601 		/* Put other piece on start of free list */
    602 		pid = (pid ^ pt_size) & ~pid_tbl_mask;
    603 		n_pt[pid & pt_size].pt_proc =
    604 				    P_FREE((pid & ~pt_size) | next_free_pt);
    605 		n_pt[pid & pt_size].pt_pgrp = 0;
    606 		next_free_pt = i | (pid & pt_size);
    607 		if (i == 0)
    608 			break;
    609 	}
    610 
    611 	/* Switch tables */
    612 	mutex_enter(&proclist_mutex);
    613 	n_pt = pid_table;
    614 	pid_table = new_pt;
    615 	mutex_exit(&proclist_mutex);
    616 	pid_tbl_mask = pt_size * 2 - 1;
    617 
    618 	/*
    619 	 * pid_max starts as PID_MAX (= 30000), once we have 16384
    620 	 * allocated pids we need it to be larger!
    621 	 */
    622 	if (pid_tbl_mask > PID_MAX) {
    623 		pid_max = pid_tbl_mask * 2 + 1;
    624 		pid_alloc_lim |= pid_alloc_lim << 1;
    625 	} else
    626 		pid_alloc_lim <<= 1;	/* doubles number of free slots... */
    627 
    628 	mutex_exit(&proclist_lock);
    629 	FREE(n_pt, M_PROC);
    630 }
    631 
    632 struct proc *
    633 proc_alloc(void)
    634 {
    635 	struct proc *p;
    636 	int nxt;
    637 	pid_t pid;
    638 	struct pid_table *pt;
    639 
    640 	p = pool_get(&proc_pool, PR_WAITOK);
    641 	p->p_stat = SIDL;			/* protect against others */
    642 
    643 	proc_initspecific(p);
    644 	/* allocate next free pid */
    645 
    646 	for (;;expand_pid_table()) {
    647 		if (__predict_false(pid_alloc_cnt >= pid_alloc_lim))
    648 			/* ensure pids cycle through 2000+ values */
    649 			continue;
    650 		mutex_enter(&proclist_lock);
    651 		pt = &pid_table[next_free_pt];
    652 #ifdef DIAGNOSTIC
    653 		if (__predict_false(P_VALID(pt->pt_proc) || pt->pt_pgrp))
    654 			panic("proc_alloc: slot busy");
    655 #endif
    656 		nxt = P_NEXT(pt->pt_proc);
    657 		if (nxt & pid_tbl_mask)
    658 			break;
    659 		/* Table full - expand (NB last entry not used....) */
    660 		mutex_exit(&proclist_lock);
    661 	}
    662 
    663 	/* pid is 'saved use count' + 'size' + entry */
    664 	pid = (nxt & ~pid_tbl_mask) + pid_tbl_mask + 1 + next_free_pt;
    665 	if ((uint)pid > (uint)pid_max)
    666 		pid &= pid_tbl_mask;
    667 	p->p_pid = pid;
    668 	next_free_pt = nxt & pid_tbl_mask;
    669 
    670 	/* Grab table slot */
    671 	mutex_enter(&proclist_mutex);
    672 	pt->pt_proc = p;
    673 	mutex_exit(&proclist_mutex);
    674 	pid_alloc_cnt++;
    675 
    676 	mutex_exit(&proclist_lock);
    677 
    678 	return p;
    679 }
    680 
    681 /*
    682  * Free last resources of a process - called from proc_free (in kern_exit.c)
    683  *
    684  * Called with the proclist_lock held, and releases upon exit.
    685  */
    686 void
    687 proc_free_mem(struct proc *p)
    688 {
    689 	pid_t pid = p->p_pid;
    690 	struct pid_table *pt;
    691 
    692 	KASSERT(mutex_owned(&proclist_lock));
    693 
    694 	pt = &pid_table[pid & pid_tbl_mask];
    695 #ifdef DIAGNOSTIC
    696 	if (__predict_false(pt->pt_proc != p))
    697 		panic("proc_free: pid_table mismatch, pid %x, proc %p",
    698 			pid, p);
    699 #endif
    700 	mutex_enter(&proclist_mutex);
    701 	/* save pid use count in slot */
    702 	pt->pt_proc = P_FREE(pid & ~pid_tbl_mask);
    703 
    704 	if (pt->pt_pgrp == NULL) {
    705 		/* link last freed entry onto ours */
    706 		pid &= pid_tbl_mask;
    707 		pt = &pid_table[last_free_pt];
    708 		pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pid);
    709 		last_free_pt = pid;
    710 		pid_alloc_cnt--;
    711 	}
    712 	mutex_exit(&proclist_mutex);
    713 
    714 	nprocs--;
    715 	mutex_exit(&proclist_lock);
    716 
    717 	pool_put(&proc_pool, p);
    718 }
    719 
    720 /*
    721  * Move p to a new or existing process group (and session)
    722  *
    723  * If we are creating a new pgrp, the pgid should equal
    724  * the calling process' pid.
    725  * If is only valid to enter a process group that is in the session
    726  * of the process.
    727  * Also mksess should only be set if we are creating a process group
    728  *
    729  * Only called from sys_setsid, sys_setpgid/sys_setpgrp and the
    730  * SYSV setpgrp support for hpux.
    731  */
    732 int
    733 enterpgrp(struct proc *curp, pid_t pid, pid_t pgid, int mksess)
    734 {
    735 	struct pgrp *new_pgrp, *pgrp;
    736 	struct session *sess;
    737 	struct proc *p;
    738 	int rval;
    739 	pid_t pg_id = NO_PGID;
    740 
    741 	if (mksess)
    742 		sess = pool_get(&session_pool, PR_WAITOK);
    743 	else
    744 		sess = NULL;
    745 
    746 	/* Allocate data areas we might need before doing any validity checks */
    747 	mutex_enter(&proclist_lock);		/* Because pid_table might change */
    748 	if (pid_table[pgid & pid_tbl_mask].pt_pgrp == 0) {
    749 		mutex_exit(&proclist_lock);
    750 		new_pgrp = pool_get(&pgrp_pool, PR_WAITOK);
    751 		mutex_enter(&proclist_lock);
    752 	} else
    753 		new_pgrp = NULL;
    754 	rval = EPERM;	/* most common error (to save typing) */
    755 
    756 	/* Check pgrp exists or can be created */
    757 	pgrp = pid_table[pgid & pid_tbl_mask].pt_pgrp;
    758 	if (pgrp != NULL && pgrp->pg_id != pgid)
    759 		goto done;
    760 
    761 	/* Can only set another process under restricted circumstances. */
    762 	if (pid != curp->p_pid) {
    763 		/* must exist and be one of our children... */
    764 		if ((p = p_find(pid, PFIND_LOCKED)) == NULL ||
    765 		    !inferior(p, curp)) {
    766 			rval = ESRCH;
    767 			goto done;
    768 		}
    769 		/* ... in the same session... */
    770 		if (sess != NULL || p->p_session != curp->p_session)
    771 			goto done;
    772 		/* ... existing pgid must be in same session ... */
    773 		if (pgrp != NULL && pgrp->pg_session != p->p_session)
    774 			goto done;
    775 		/* ... and not done an exec. */
    776 		if (p->p_flag & PK_EXEC) {
    777 			rval = EACCES;
    778 			goto done;
    779 		}
    780 	} else {
    781 		/* ... setsid() cannot re-enter a pgrp */
    782 		if (mksess && (curp->p_pgid == curp->p_pid ||
    783 		    pg_find(curp->p_pid, PFIND_LOCKED)))
    784 			goto done;
    785 		p = curp;
    786 	}
    787 
    788 	/* Changing the process group/session of a session
    789 	   leader is definitely off limits. */
    790 	if (SESS_LEADER(p)) {
    791 		if (sess == NULL && p->p_pgrp == pgrp)
    792 			/* unless it's a definite noop */
    793 			rval = 0;
    794 		goto done;
    795 	}
    796 
    797 	/* Can only create a process group with id of process */
    798 	if (pgrp == NULL && pgid != pid)
    799 		goto done;
    800 
    801 	/* Can only create a session if creating pgrp */
    802 	if (sess != NULL && pgrp != NULL)
    803 		goto done;
    804 
    805 	/* Check we allocated memory for a pgrp... */
    806 	if (pgrp == NULL && new_pgrp == NULL)
    807 		goto done;
    808 
    809 	/* Don't attach to 'zombie' pgrp */
    810 	if (pgrp != NULL && LIST_EMPTY(&pgrp->pg_members))
    811 		goto done;
    812 
    813 	/* Expect to succeed now */
    814 	rval = 0;
    815 
    816 	if (pgrp == p->p_pgrp)
    817 		/* nothing to do */
    818 		goto done;
    819 
    820 	/* Ok all setup, link up required structures */
    821 
    822 	if (pgrp == NULL) {
    823 		pgrp = new_pgrp;
    824 		new_pgrp = 0;
    825 		if (sess != NULL) {
    826 			sess->s_sid = p->p_pid;
    827 			sess->s_leader = p;
    828 			sess->s_count = 1;
    829 			sess->s_ttyvp = NULL;
    830 			sess->s_ttyp = NULL;
    831 			sess->s_flags = p->p_session->s_flags & ~S_LOGIN_SET;
    832 			memcpy(sess->s_login, p->p_session->s_login,
    833 			    sizeof(sess->s_login));
    834 			p->p_lflag &= ~PL_CONTROLT;
    835 		} else {
    836 			sess = p->p_pgrp->pg_session;
    837 			SESSHOLD(sess);
    838 		}
    839 		pgrp->pg_session = sess;
    840 		sess = 0;
    841 
    842 		pgrp->pg_id = pgid;
    843 		LIST_INIT(&pgrp->pg_members);
    844 #ifdef DIAGNOSTIC
    845 		if (__predict_false(pid_table[pgid & pid_tbl_mask].pt_pgrp))
    846 			panic("enterpgrp: pgrp table slot in use");
    847 		if (__predict_false(mksess && p != curp))
    848 			panic("enterpgrp: mksession and p != curproc");
    849 #endif
    850 		mutex_enter(&proclist_mutex);
    851 		pid_table[pgid & pid_tbl_mask].pt_pgrp = pgrp;
    852 		pgrp->pg_jobc = 0;
    853 	} else
    854 		mutex_enter(&proclist_mutex);
    855 
    856 #ifdef notyet
    857 	/*
    858 	 * If there's a controlling terminal for the current session, we
    859 	 * have to interlock with it.  See ttread().
    860 	 */
    861 	if (p->p_session->s_ttyvp != NULL) {
    862 		tp = p->p_session->s_ttyp;
    863 		mutex_enter(&tp->t_mutex);
    864 	} else
    865 		tp = NULL;
    866 #endif
    867 
    868 	/*
    869 	 * Adjust eligibility of affected pgrps to participate in job control.
    870 	 * Increment eligibility counts before decrementing, otherwise we
    871 	 * could reach 0 spuriously during the first call.
    872 	 */
    873 	fixjobc(p, pgrp, 1);
    874 	fixjobc(p, p->p_pgrp, 0);
    875 
    876 	/* Move process to requested group. */
    877 	LIST_REMOVE(p, p_pglist);
    878 	if (LIST_EMPTY(&p->p_pgrp->pg_members))
    879 		/* defer delete until we've dumped the lock */
    880 		pg_id = p->p_pgrp->pg_id;
    881 	p->p_pgrp = pgrp;
    882 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
    883 	mutex_exit(&proclist_mutex);
    884 
    885 #ifdef notyet
    886 	/* Done with the swap; we can release the tty mutex. */
    887 	if (tp != NULL)
    888 		mutex_exit(&tp->t_mutex);
    889 #endif
    890 
    891     done:
    892 	if (pg_id != NO_PGID)
    893 		pg_delete(pg_id);
    894 	mutex_exit(&proclist_lock);
    895 	if (sess != NULL)
    896 		pool_put(&session_pool, sess);
    897 	if (new_pgrp != NULL)
    898 		pool_put(&pgrp_pool, new_pgrp);
    899 #ifdef DEBUG_PGRP
    900 	if (__predict_false(rval))
    901 		printf("enterpgrp(%d,%d,%d), curproc %d, rval %d\n",
    902 			pid, pgid, mksess, curp->p_pid, rval);
    903 #endif
    904 	return rval;
    905 }
    906 
    907 /*
    908  * Remove a process from its process group.  Must be called with the
    909  * proclist_lock held.
    910  */
    911 void
    912 leavepgrp(struct proc *p)
    913 {
    914 	struct pgrp *pgrp;
    915 
    916 	KASSERT(mutex_owned(&proclist_lock));
    917 
    918 	/*
    919 	 * If there's a controlling terminal for the session, we have to
    920 	 * interlock with it.  See ttread().
    921 	 */
    922 	mutex_enter(&proclist_mutex);
    923 #ifdef notyet
    924 	if (p_>p_session->s_ttyvp != NULL) {
    925 		tp = p->p_session->s_ttyp;
    926 		mutex_enter(&tp->t_mutex);
    927 	} else
    928 		tp = NULL;
    929 #endif
    930 
    931 	pgrp = p->p_pgrp;
    932 	LIST_REMOVE(p, p_pglist);
    933 	p->p_pgrp = NULL;
    934 
    935 #ifdef notyet
    936 	if (tp != NULL)
    937 		mutex_exit(&tp->t_mutex);
    938 #endif
    939 	mutex_exit(&proclist_mutex);
    940 
    941 	if (LIST_EMPTY(&pgrp->pg_members))
    942 		pg_delete(pgrp->pg_id);
    943 }
    944 
    945 /*
    946  * Free a process group.  Must be called with the proclist_lock held.
    947  */
    948 static void
    949 pg_free(pid_t pg_id)
    950 {
    951 	struct pgrp *pgrp;
    952 	struct pid_table *pt;
    953 
    954 	KASSERT(mutex_owned(&proclist_lock));
    955 
    956 	pt = &pid_table[pg_id & pid_tbl_mask];
    957 	pgrp = pt->pt_pgrp;
    958 #ifdef DIAGNOSTIC
    959 	if (__predict_false(!pgrp || pgrp->pg_id != pg_id
    960 	    || !LIST_EMPTY(&pgrp->pg_members)))
    961 		panic("pg_free: process group absent or has members");
    962 #endif
    963 	pt->pt_pgrp = 0;
    964 
    965 	if (!P_VALID(pt->pt_proc)) {
    966 		/* orphaned pgrp, put slot onto free list */
    967 #ifdef DIAGNOSTIC
    968 		if (__predict_false(P_NEXT(pt->pt_proc) & pid_tbl_mask))
    969 			panic("pg_free: process slot on free list");
    970 #endif
    971 		mutex_enter(&proclist_mutex);
    972 		pg_id &= pid_tbl_mask;
    973 		pt = &pid_table[last_free_pt];
    974 		pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pg_id);
    975 		mutex_exit(&proclist_mutex);
    976 		last_free_pt = pg_id;
    977 		pid_alloc_cnt--;
    978 	}
    979 	pool_put(&pgrp_pool, pgrp);
    980 }
    981 
    982 /*
    983  * Delete a process group.  Must be called with the proclist_lock held.
    984  */
    985 static void
    986 pg_delete(pid_t pg_id)
    987 {
    988 	struct pgrp *pgrp;
    989 	struct tty *ttyp;
    990 	struct session *ss;
    991 	int is_pgrp_leader;
    992 
    993 	KASSERT(mutex_owned(&proclist_lock));
    994 
    995 	pgrp = pid_table[pg_id & pid_tbl_mask].pt_pgrp;
    996 	if (pgrp == NULL || pgrp->pg_id != pg_id ||
    997 	    !LIST_EMPTY(&pgrp->pg_members))
    998 		return;
    999 
   1000 	ss = pgrp->pg_session;
   1001 
   1002 	/* Remove reference (if any) from tty to this process group */
   1003 	ttyp = ss->s_ttyp;
   1004 	if (ttyp != NULL && ttyp->t_pgrp == pgrp) {
   1005 		ttyp->t_pgrp = NULL;
   1006 #ifdef DIAGNOSTIC
   1007 		if (ttyp->t_session != ss)
   1008 			panic("pg_delete: wrong session on terminal");
   1009 #endif
   1010 	}
   1011 
   1012 	/*
   1013 	 * The leading process group in a session is freed
   1014 	 * by sessdelete() if last reference.
   1015 	 */
   1016 	is_pgrp_leader = (ss->s_sid == pgrp->pg_id);
   1017 	SESSRELE(ss);
   1018 
   1019 	if (is_pgrp_leader)
   1020 		return;
   1021 
   1022 	pg_free(pg_id);
   1023 }
   1024 
   1025 /*
   1026  * Delete session - called from SESSRELE when s_count becomes zero.
   1027  * Must be called with the proclist_lock held.
   1028  */
   1029 void
   1030 sessdelete(struct session *ss)
   1031 {
   1032 
   1033 	KASSERT(mutex_owned(&proclist_lock));
   1034 
   1035 	/*
   1036 	 * We keep the pgrp with the same id as the session in
   1037 	 * order to stop a process being given the same pid.
   1038 	 * Since the pgrp holds a reference to the session, it
   1039 	 * must be a 'zombie' pgrp by now.
   1040 	 */
   1041 	pg_free(ss->s_sid);
   1042 	pool_put(&session_pool, ss);
   1043 }
   1044 
   1045 /*
   1046  * Adjust pgrp jobc counters when specified process changes process group.
   1047  * We count the number of processes in each process group that "qualify"
   1048  * the group for terminal job control (those with a parent in a different
   1049  * process group of the same session).  If that count reaches zero, the
   1050  * process group becomes orphaned.  Check both the specified process'
   1051  * process group and that of its children.
   1052  * entering == 0 => p is leaving specified group.
   1053  * entering == 1 => p is entering specified group.
   1054  *
   1055  * Call with proclist_lock held.
   1056  */
   1057 void
   1058 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
   1059 {
   1060 	struct pgrp *hispgrp;
   1061 	struct session *mysession = pgrp->pg_session;
   1062 	struct proc *child;
   1063 
   1064 	KASSERT(mutex_owned(&proclist_lock));
   1065 	KASSERT(mutex_owned(&proclist_mutex));
   1066 
   1067 	/*
   1068 	 * Check p's parent to see whether p qualifies its own process
   1069 	 * group; if so, adjust count for p's process group.
   1070 	 */
   1071 	hispgrp = p->p_pptr->p_pgrp;
   1072 	if (hispgrp != pgrp && hispgrp->pg_session == mysession) {
   1073 		if (entering) {
   1074 			mutex_enter(&p->p_smutex);
   1075 			p->p_sflag &= ~PS_ORPHANPG;
   1076 			mutex_exit(&p->p_smutex);
   1077 			pgrp->pg_jobc++;
   1078 		} else if (--pgrp->pg_jobc == 0)
   1079 			orphanpg(pgrp);
   1080 	}
   1081 
   1082 	/*
   1083 	 * Check this process' children to see whether they qualify
   1084 	 * their process groups; if so, adjust counts for children's
   1085 	 * process groups.
   1086 	 */
   1087 	LIST_FOREACH(child, &p->p_children, p_sibling) {
   1088 		hispgrp = child->p_pgrp;
   1089 		if (hispgrp != pgrp && hispgrp->pg_session == mysession &&
   1090 		    !P_ZOMBIE(child)) {
   1091 			if (entering) {
   1092 				mutex_enter(&child->p_smutex);
   1093 				child->p_sflag &= ~PS_ORPHANPG;
   1094 				mutex_exit(&child->p_smutex);
   1095 				hispgrp->pg_jobc++;
   1096 			} else if (--hispgrp->pg_jobc == 0)
   1097 				orphanpg(hispgrp);
   1098 		}
   1099 	}
   1100 }
   1101 
   1102 /*
   1103  * A process group has become orphaned;
   1104  * if there are any stopped processes in the group,
   1105  * hang-up all process in that group.
   1106  *
   1107  * Call with proclist_lock held.
   1108  */
   1109 static void
   1110 orphanpg(struct pgrp *pg)
   1111 {
   1112 	struct proc *p;
   1113 	int doit;
   1114 
   1115 	KASSERT(mutex_owned(&proclist_lock));
   1116 	KASSERT(mutex_owned(&proclist_mutex));
   1117 
   1118 	doit = 0;
   1119 
   1120 	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
   1121 		mutex_enter(&p->p_smutex);
   1122 		if (p->p_stat == SSTOP) {
   1123 			doit = 1;
   1124 			p->p_sflag |= PS_ORPHANPG;
   1125 		}
   1126 		mutex_exit(&p->p_smutex);
   1127 	}
   1128 
   1129 	if (doit) {
   1130 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
   1131 			psignal(p, SIGHUP);
   1132 			psignal(p, SIGCONT);
   1133 		}
   1134 	}
   1135 }
   1136 
   1137 #ifdef DDB
   1138 #include <ddb/db_output.h>
   1139 void pidtbl_dump(void);
   1140 void
   1141 pidtbl_dump(void)
   1142 {
   1143 	struct pid_table *pt;
   1144 	struct proc *p;
   1145 	struct pgrp *pgrp;
   1146 	int id;
   1147 
   1148 	db_printf("pid table %p size %x, next %x, last %x\n",
   1149 		pid_table, pid_tbl_mask+1,
   1150 		next_free_pt, last_free_pt);
   1151 	for (pt = pid_table, id = 0; id <= pid_tbl_mask; id++, pt++) {
   1152 		p = pt->pt_proc;
   1153 		if (!P_VALID(p) && !pt->pt_pgrp)
   1154 			continue;
   1155 		db_printf("  id %x: ", id);
   1156 		if (P_VALID(p))
   1157 			db_printf("proc %p id %d (0x%x) %s\n",
   1158 				p, p->p_pid, p->p_pid, p->p_comm);
   1159 		else
   1160 			db_printf("next %x use %x\n",
   1161 				P_NEXT(p) & pid_tbl_mask,
   1162 				P_NEXT(p) & ~pid_tbl_mask);
   1163 		if ((pgrp = pt->pt_pgrp)) {
   1164 			db_printf("\tsession %p, sid %d, count %d, login %s\n",
   1165 			    pgrp->pg_session, pgrp->pg_session->s_sid,
   1166 			    pgrp->pg_session->s_count,
   1167 			    pgrp->pg_session->s_login);
   1168 			db_printf("\tpgrp %p, pg_id %d, pg_jobc %d, members %p\n",
   1169 			    pgrp, pgrp->pg_id, pgrp->pg_jobc,
   1170 			    pgrp->pg_members.lh_first);
   1171 			for (p = pgrp->pg_members.lh_first; p != 0;
   1172 			    p = p->p_pglist.le_next) {
   1173 				db_printf("\t\tpid %d addr %p pgrp %p %s\n",
   1174 				    p->p_pid, p, p->p_pgrp, p->p_comm);
   1175 			}
   1176 		}
   1177 	}
   1178 }
   1179 #endif /* DDB */
   1180 
   1181 #ifdef KSTACK_CHECK_MAGIC
   1182 #include <sys/user.h>
   1183 
   1184 #define	KSTACK_MAGIC	0xdeadbeaf
   1185 
   1186 /* XXX should be per process basis? */
   1187 int kstackleftmin = KSTACK_SIZE;
   1188 int kstackleftthres = KSTACK_SIZE / 8; /* warn if remaining stack is
   1189 					  less than this */
   1190 
   1191 void
   1192 kstack_setup_magic(const struct lwp *l)
   1193 {
   1194 	uint32_t *ip;
   1195 	uint32_t const *end;
   1196 
   1197 	KASSERT(l != NULL);
   1198 	KASSERT(l != &lwp0);
   1199 
   1200 	/*
   1201 	 * fill all the stack with magic number
   1202 	 * so that later modification on it can be detected.
   1203 	 */
   1204 	ip = (uint32_t *)KSTACK_LOWEST_ADDR(l);
   1205 	end = (uint32_t *)((char *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
   1206 	for (; ip < end; ip++) {
   1207 		*ip = KSTACK_MAGIC;
   1208 	}
   1209 }
   1210 
   1211 void
   1212 kstack_check_magic(const struct lwp *l)
   1213 {
   1214 	uint32_t const *ip, *end;
   1215 	int stackleft;
   1216 
   1217 	KASSERT(l != NULL);
   1218 
   1219 	/* don't check proc0 */ /*XXX*/
   1220 	if (l == &lwp0)
   1221 		return;
   1222 
   1223 #ifdef __MACHINE_STACK_GROWS_UP
   1224 	/* stack grows upwards (eg. hppa) */
   1225 	ip = (uint32_t *)((void *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
   1226 	end = (uint32_t *)KSTACK_LOWEST_ADDR(l);
   1227 	for (ip--; ip >= end; ip--)
   1228 		if (*ip != KSTACK_MAGIC)
   1229 			break;
   1230 
   1231 	stackleft = (void *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE - (void *)ip;
   1232 #else /* __MACHINE_STACK_GROWS_UP */
   1233 	/* stack grows downwards (eg. i386) */
   1234 	ip = (uint32_t *)KSTACK_LOWEST_ADDR(l);
   1235 	end = (uint32_t *)((char *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
   1236 	for (; ip < end; ip++)
   1237 		if (*ip != KSTACK_MAGIC)
   1238 			break;
   1239 
   1240 	stackleft = ((const char *)ip) - (const char *)KSTACK_LOWEST_ADDR(l);
   1241 #endif /* __MACHINE_STACK_GROWS_UP */
   1242 
   1243 	if (kstackleftmin > stackleft) {
   1244 		kstackleftmin = stackleft;
   1245 		if (stackleft < kstackleftthres)
   1246 			printf("warning: kernel stack left %d bytes"
   1247 			    "(pid %u:lid %u)\n", stackleft,
   1248 			    (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
   1249 	}
   1250 
   1251 	if (stackleft <= 0) {
   1252 		panic("magic on the top of kernel stack changed for "
   1253 		    "pid %u, lid %u: maybe kernel stack overflow",
   1254 		    (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
   1255 	}
   1256 }
   1257 #endif /* KSTACK_CHECK_MAGIC */
   1258 
   1259 /*
   1260  * XXXSMP this is bust, it grabs a read lock and then messes about
   1261  * with allproc.
   1262  */
   1263 int
   1264 proclist_foreach_call(struct proclist *list,
   1265     int (*callback)(struct proc *, void *arg), void *arg)
   1266 {
   1267 	struct proc marker;
   1268 	struct proc *p;
   1269 	struct lwp * const l = curlwp;
   1270 	int ret = 0;
   1271 
   1272 	marker.p_flag = PK_MARKER;
   1273 	uvm_lwp_hold(l);
   1274 	mutex_enter(&proclist_lock);
   1275 	for (p = LIST_FIRST(list); ret == 0 && p != NULL;) {
   1276 		if (p->p_flag & PK_MARKER) {
   1277 			p = LIST_NEXT(p, p_list);
   1278 			continue;
   1279 		}
   1280 		LIST_INSERT_AFTER(p, &marker, p_list);
   1281 		ret = (*callback)(p, arg);
   1282 		KASSERT(mutex_owned(&proclist_lock));
   1283 		p = LIST_NEXT(&marker, p_list);
   1284 		LIST_REMOVE(&marker, p_list);
   1285 	}
   1286 	mutex_exit(&proclist_lock);
   1287 	uvm_lwp_rele(l);
   1288 
   1289 	return ret;
   1290 }
   1291 
   1292 int
   1293 proc_vmspace_getref(struct proc *p, struct vmspace **vm)
   1294 {
   1295 
   1296 	/* XXXCDC: how should locking work here? */
   1297 
   1298 	/* curproc exception is for coredump. */
   1299 
   1300 	if ((p != curproc && (p->p_sflag & PS_WEXIT) != 0) ||
   1301 	    (p->p_vmspace->vm_refcnt < 1)) { /* XXX */
   1302 		return EFAULT;
   1303 	}
   1304 
   1305 	uvmspace_addref(p->p_vmspace);
   1306 	*vm = p->p_vmspace;
   1307 
   1308 	return 0;
   1309 }
   1310 
   1311 /*
   1312  * Acquire a write lock on the process credential.
   1313  */
   1314 void
   1315 proc_crmod_enter(void)
   1316 {
   1317 	struct lwp *l = curlwp;
   1318 	struct proc *p = l->l_proc;
   1319 	struct plimit *lim;
   1320 	kauth_cred_t oc;
   1321 	char *cn;
   1322 
   1323 	mutex_enter(&p->p_mutex);
   1324 
   1325 	/* Ensure the LWP cached credentials are up to date. */
   1326 	if ((oc = l->l_cred) != p->p_cred) {
   1327 		kauth_cred_hold(p->p_cred);
   1328 		l->l_cred = p->p_cred;
   1329 		kauth_cred_free(oc);
   1330 	}
   1331 
   1332 	/* Reset what needs to be reset in plimit. */
   1333 	lim = p->p_limit;
   1334 	if (lim->pl_corename != defcorename) {
   1335 		if (lim->p_refcnt > 1 &&
   1336 		    (lim->p_lflags & PL_SHAREMOD) == 0) {
   1337 			p->p_limit = limcopy(p);
   1338 			limfree(lim);
   1339 			lim = p->p_limit;
   1340 		}
   1341 		mutex_enter(&lim->p_lock);
   1342 		cn = lim->pl_corename;
   1343 		lim->pl_corename = defcorename;
   1344 		mutex_exit(&lim->p_lock);
   1345 		if (cn != defcorename)
   1346 			free(cn, M_TEMP);
   1347 	}
   1348 }
   1349 
   1350 /*
   1351  * Set in a new process credential, and drop the write lock.  The credential
   1352  * must have a reference already.  Optionally, free a no-longer required
   1353  * credential.  The scheduler also needs to inspect p_cred, so we also
   1354  * briefly acquire the sched state mutex.
   1355  */
   1356 void
   1357 proc_crmod_leave(kauth_cred_t scred, kauth_cred_t fcred, bool sugid)
   1358 {
   1359 	struct lwp *l = curlwp;
   1360 	struct proc *p = l->l_proc;
   1361 	kauth_cred_t oc;
   1362 
   1363 	/* Is there a new credential to set in? */
   1364 	if (scred != NULL) {
   1365 		mutex_enter(&p->p_smutex);
   1366 		p->p_cred = scred;
   1367 		mutex_exit(&p->p_smutex);
   1368 
   1369 		/* Ensure the LWP cached credentials are up to date. */
   1370 		if ((oc = l->l_cred) != scred) {
   1371 			kauth_cred_hold(scred);
   1372 			l->l_cred = scred;
   1373 		}
   1374 	} else
   1375 		oc = NULL;	/* XXXgcc */
   1376 
   1377 	if (sugid) {
   1378 		/*
   1379 		 * Mark process as having changed credentials, stops
   1380 		 * tracing etc.
   1381 		 */
   1382 		p->p_flag |= PK_SUGID;
   1383 	}
   1384 
   1385 	mutex_exit(&p->p_mutex);
   1386 
   1387 	/* If there is a credential to be released, free it now. */
   1388 	if (fcred != NULL) {
   1389 		KASSERT(scred != NULL);
   1390 		kauth_cred_free(fcred);
   1391 		if (oc != scred)
   1392 			kauth_cred_free(oc);
   1393 	}
   1394 }
   1395 
   1396 /*
   1397  * Acquire a reference on a process, to prevent it from exiting or execing.
   1398  */
   1399 int
   1400 proc_addref(struct proc *p)
   1401 {
   1402 
   1403 	KASSERT(mutex_owned(&p->p_mutex));
   1404 
   1405 	if (p->p_refcnt <= 0)
   1406 		return EAGAIN;
   1407 	p->p_refcnt++;
   1408 
   1409 	return 0;
   1410 }
   1411 
   1412 /*
   1413  * Release a reference on a process.
   1414  */
   1415 void
   1416 proc_delref(struct proc *p)
   1417 {
   1418 
   1419 	KASSERT(mutex_owned(&p->p_mutex));
   1420 
   1421 	if (p->p_refcnt < 0) {
   1422 		if (++p->p_refcnt == 0)
   1423 			cv_broadcast(&p->p_refcv);
   1424 	} else {
   1425 		p->p_refcnt--;
   1426 		KASSERT(p->p_refcnt != 0);
   1427 	}
   1428 }
   1429 
   1430 /*
   1431  * Wait for all references on the process to drain, and prevent new
   1432  * references from being acquired.
   1433  */
   1434 void
   1435 proc_drainrefs(struct proc *p)
   1436 {
   1437 
   1438 	KASSERT(mutex_owned(&p->p_mutex));
   1439 	KASSERT(p->p_refcnt >= 0);
   1440 
   1441 	/*
   1442 	 * The process itself holds the last reference.  Once it's released,
   1443 	 * no new references will be granted.  If we have already locked out
   1444 	 * new references (refcnt <= 0), potentially due to a failed exec,
   1445 	 * there is nothing more to do.
   1446 	 */
   1447 	if (p->p_refcnt == 0)
   1448 		return;
   1449 	p->p_refcnt = 1 - p->p_refcnt;
   1450 	while (p->p_refcnt != 0)
   1451 		cv_wait(&p->p_refcv, &p->p_mutex);
   1452 }
   1453 
   1454 /*
   1455  * proc_specific_key_create --
   1456  *	Create a key for subsystem proc-specific data.
   1457  */
   1458 int
   1459 proc_specific_key_create(specificdata_key_t *keyp, specificdata_dtor_t dtor)
   1460 {
   1461 
   1462 	return (specificdata_key_create(proc_specificdata_domain, keyp, dtor));
   1463 }
   1464 
   1465 /*
   1466  * proc_specific_key_delete --
   1467  *	Delete a key for subsystem proc-specific data.
   1468  */
   1469 void
   1470 proc_specific_key_delete(specificdata_key_t key)
   1471 {
   1472 
   1473 	specificdata_key_delete(proc_specificdata_domain, key);
   1474 }
   1475 
   1476 /*
   1477  * proc_initspecific --
   1478  *	Initialize a proc's specificdata container.
   1479  */
   1480 void
   1481 proc_initspecific(struct proc *p)
   1482 {
   1483 	int error;
   1484 
   1485 	error = specificdata_init(proc_specificdata_domain, &p->p_specdataref);
   1486 	KASSERT(error == 0);
   1487 }
   1488 
   1489 /*
   1490  * proc_finispecific --
   1491  *	Finalize a proc's specificdata container.
   1492  */
   1493 void
   1494 proc_finispecific(struct proc *p)
   1495 {
   1496 
   1497 	specificdata_fini(proc_specificdata_domain, &p->p_specdataref);
   1498 }
   1499 
   1500 /*
   1501  * proc_getspecific --
   1502  *	Return proc-specific data corresponding to the specified key.
   1503  */
   1504 void *
   1505 proc_getspecific(struct proc *p, specificdata_key_t key)
   1506 {
   1507 
   1508 	return (specificdata_getspecific(proc_specificdata_domain,
   1509 					 &p->p_specdataref, key));
   1510 }
   1511 
   1512 /*
   1513  * proc_setspecific --
   1514  *	Set proc-specific data corresponding to the specified key.
   1515  */
   1516 void
   1517 proc_setspecific(struct proc *p, specificdata_key_t key, void *data)
   1518 {
   1519 
   1520 	specificdata_setspecific(proc_specificdata_domain,
   1521 				 &p->p_specdataref, key, data);
   1522 }
   1523