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