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