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