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