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