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