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