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