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