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