Home | History | Annotate | Line # | Download | only in kern
kern_proc.c revision 1.69
      1 /*	$NetBSD: kern_proc.c,v 1.69 2003/11/17 22:52:09 cl Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the NetBSD
     22  *	Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 /*
     41  * Copyright (c) 1982, 1986, 1989, 1991, 1993
     42  *	The Regents of the University of California.  All rights reserved.
     43  *
     44  * Redistribution and use in source and binary forms, with or without
     45  * modification, are permitted provided that the following conditions
     46  * are met:
     47  * 1. Redistributions of source code must retain the above copyright
     48  *    notice, this list of conditions and the following disclaimer.
     49  * 2. Redistributions in binary form must reproduce the above copyright
     50  *    notice, this list of conditions and the following disclaimer in the
     51  *    documentation and/or other materials provided with the distribution.
     52  * 3. Neither the name of the University nor the names of its contributors
     53  *    may be used to endorse or promote products derived from this software
     54  *    without specific prior written permission.
     55  *
     56  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     57  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     58  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     59  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     60  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     61  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     62  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     63  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     64  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     65  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     66  * SUCH DAMAGE.
     67  *
     68  *	@(#)kern_proc.c	8.7 (Berkeley) 2/14/95
     69  */
     70 
     71 #include <sys/cdefs.h>
     72 __KERNEL_RCSID(0, "$NetBSD: kern_proc.c,v 1.69 2003/11/17 22:52:09 cl Exp $");
     73 
     74 #include "opt_kstack.h"
     75 
     76 #include <sys/param.h>
     77 #include <sys/systm.h>
     78 #include <sys/kernel.h>
     79 #include <sys/proc.h>
     80 #include <sys/resourcevar.h>
     81 #include <sys/buf.h>
     82 #include <sys/acct.h>
     83 #include <sys/wait.h>
     84 #include <sys/file.h>
     85 #include <ufs/ufs/quota.h>
     86 #include <sys/uio.h>
     87 #include <sys/malloc.h>
     88 #include <sys/pool.h>
     89 #include <sys/mbuf.h>
     90 #include <sys/ioctl.h>
     91 #include <sys/tty.h>
     92 #include <sys/signalvar.h>
     93 #include <sys/ras.h>
     94 #include <sys/sa.h>
     95 #include <sys/savar.h>
     96 
     97 static void pg_delete(pid_t);
     98 
     99 /*
    100  * Structure associated with user cacheing.
    101  */
    102 struct uidinfo {
    103 	LIST_ENTRY(uidinfo) ui_hash;
    104 	uid_t	ui_uid;
    105 	long	ui_proccnt;
    106 };
    107 #define	UIHASH(uid)	(&uihashtbl[(uid) & uihash])
    108 LIST_HEAD(uihashhead, uidinfo) *uihashtbl;
    109 u_long uihash;		/* size of hash table - 1 */
    110 
    111 /*
    112  * Other process lists
    113  */
    114 
    115 struct proclist allproc;
    116 struct proclist zombproc;	/* resources have been freed */
    117 
    118 
    119 /*
    120  * Process list locking:
    121  *
    122  * We have two types of locks on the proclists: read locks and write
    123  * locks.  Read locks can be used in interrupt context, so while we
    124  * hold the write lock, we must also block clock interrupts to
    125  * lock out any scheduling changes that may happen in interrupt
    126  * context.
    127  *
    128  * The proclist lock locks the following structures:
    129  *
    130  *	allproc
    131  *	zombproc
    132  *	pid_table
    133  */
    134 struct lock proclist_lock;
    135 
    136 /*
    137  * List of processes that has called exit, but need to be reaped.
    138  * Locking of this proclist is special; it's accessed in a
    139  * critical section of process exit, and thus locking it can't
    140  * modify interrupt state.
    141  * We use a simple spin lock for this proclist.
    142  * Processes on this proclist are also on zombproc.
    143  */
    144 struct simplelock deadproc_slock;
    145 struct deadprocs deadprocs = SLIST_HEAD_INITIALIZER(deadprocs);
    146 
    147 /*
    148  * pid to proc lookup is done by indexing the pid_table array.
    149  * Since pid numbers are only allocated when an empty slot
    150  * has been found, there is no need to search any lists ever.
    151  * (an orphaned pgrp will lock the slot, a session will lock
    152  * the pgrp with the same number.)
    153  * If the table is too small it is reallocated with twice the
    154  * previous size and the entries 'unzipped' into the two halves.
    155  * A linked list of free entries is passed through the pt_proc
    156  * field of 'free' items - set odd to be an invalid ptr.
    157  */
    158 
    159 struct pid_table {
    160 	struct proc	*pt_proc;
    161 	struct pgrp	*pt_pgrp;
    162 };
    163 #if 1	/* strongly typed cast - should be a noop */
    164 static __inline uint p2u(struct proc *p) { return (uint)(uintptr_t)p; };
    165 #else
    166 #define p2u(p) ((uint)p)
    167 #endif
    168 #define P_VALID(p) (!(p2u(p) & 1))
    169 #define P_NEXT(p) (p2u(p) >> 1)
    170 #define P_FREE(pid) ((struct proc *)(uintptr_t)((pid) << 1 | 1))
    171 
    172 #define INITIAL_PID_TABLE_SIZE	(1 << 5)
    173 static struct pid_table *pid_table;
    174 static uint pid_tbl_mask = INITIAL_PID_TABLE_SIZE - 1;
    175 static uint pid_alloc_lim;	/* max we allocate before growing table */
    176 static uint pid_alloc_cnt;	/* number of allocated pids */
    177 
    178 /* links through free slots - never empty! */
    179 static uint next_free_pt, last_free_pt;
    180 static pid_t pid_max = PID_MAX;		/* largest value we allocate */
    181 
    182 struct pool proc_pool;
    183 struct pool lwp_pool;
    184 struct pool lwp_uc_pool;
    185 struct pool pcred_pool;
    186 struct pool plimit_pool;
    187 struct pool pstats_pool;
    188 struct pool pgrp_pool;
    189 struct pool rusage_pool;
    190 struct pool ras_pool;
    191 struct pool sadata_pool;
    192 struct pool saupcall_pool;
    193 struct pool sastack_pool;
    194 struct pool ptimer_pool;
    195 
    196 MALLOC_DEFINE(M_EMULDATA, "emuldata", "Per-process emulation data");
    197 MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
    198 MALLOC_DEFINE(M_SESSION, "session", "session header");
    199 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
    200 
    201 /*
    202  * The process list descriptors, used during pid allocation and
    203  * by sysctl.  No locking on this data structure is needed since
    204  * it is completely static.
    205  */
    206 const struct proclist_desc proclists[] = {
    207 	{ &allproc	},
    208 	{ &zombproc	},
    209 	{ NULL		},
    210 };
    211 
    212 static void orphanpg __P((struct pgrp *));
    213 #ifdef DEBUG
    214 void pgrpdump __P((void));
    215 #endif
    216 
    217 /*
    218  * Initialize global process hashing structures.
    219  */
    220 void
    221 procinit(void)
    222 {
    223 	const struct proclist_desc *pd;
    224 	int i;
    225 #define	LINK_EMPTY ((PID_MAX + INITIAL_PID_TABLE_SIZE) & ~(INITIAL_PID_TABLE_SIZE - 1))
    226 
    227 	for (pd = proclists; pd->pd_list != NULL; pd++)
    228 		LIST_INIT(pd->pd_list);
    229 
    230 	spinlockinit(&proclist_lock, "proclk", 0);
    231 
    232 	simple_lock_init(&deadproc_slock);
    233 
    234 	pid_table = malloc(INITIAL_PID_TABLE_SIZE * sizeof *pid_table,
    235 			    M_PROC, M_WAITOK);
    236 	/* Set free list running through table...
    237 	   Preset 'use count' above PID_MAX so we allocate pid 1 next. */
    238 	for (i = 0; i <= pid_tbl_mask; i++) {
    239 		pid_table[i].pt_proc = P_FREE(LINK_EMPTY + i + 1);
    240 		pid_table[i].pt_pgrp = 0;
    241 	}
    242 	/* slot 0 is just grabbed */
    243 	next_free_pt = 1;
    244 	/* Need to fix last entry. */
    245 	last_free_pt = pid_tbl_mask;
    246 	pid_table[last_free_pt].pt_proc = P_FREE(LINK_EMPTY);
    247 	/* point at which we grow table - to avoid reusing pids too often */
    248 	pid_alloc_lim = pid_tbl_mask - 1;
    249 #undef LINK_EMPTY
    250 
    251 	LIST_INIT(&alllwp);
    252 	LIST_INIT(&deadlwp);
    253 	LIST_INIT(&zomblwp);
    254 
    255 	uihashtbl =
    256 	    hashinit(maxproc / 16, HASH_LIST, M_PROC, M_WAITOK, &uihash);
    257 
    258 	pool_init(&proc_pool, sizeof(struct proc), 0, 0, 0, "procpl",
    259 	    &pool_allocator_nointr);
    260 	pool_init(&lwp_pool, sizeof(struct lwp), 0, 0, 0, "lwppl",
    261 	    &pool_allocator_nointr);
    262 	pool_init(&lwp_uc_pool, sizeof(ucontext_t), 0, 0, 0, "lwpucpl",
    263 	    &pool_allocator_nointr);
    264 	pool_init(&pgrp_pool, sizeof(struct pgrp), 0, 0, 0, "pgrppl",
    265 	    &pool_allocator_nointr);
    266 	pool_init(&pcred_pool, sizeof(struct pcred), 0, 0, 0, "pcredpl",
    267 	    &pool_allocator_nointr);
    268 	pool_init(&plimit_pool, sizeof(struct plimit), 0, 0, 0, "plimitpl",
    269 	    &pool_allocator_nointr);
    270 	pool_init(&pstats_pool, sizeof(struct pstats), 0, 0, 0, "pstatspl",
    271 	    &pool_allocator_nointr);
    272 	pool_init(&rusage_pool, sizeof(struct rusage), 0, 0, 0, "rusgepl",
    273 	    &pool_allocator_nointr);
    274 	pool_init(&ras_pool, sizeof(struct ras), 0, 0, 0, "raspl",
    275 	    &pool_allocator_nointr);
    276 	pool_init(&sadata_pool, sizeof(struct sadata), 0, 0, 0, "sadatapl",
    277 	    &pool_allocator_nointr);
    278 	pool_init(&saupcall_pool, sizeof(struct sadata_upcall), 0, 0, 0,
    279 	    "saupcpl", &pool_allocator_nointr);
    280 	pool_init(&sastack_pool, sizeof(struct sastack), 0, 0, 0, "sastackpl",
    281 	    &pool_allocator_nointr);
    282 	pool_init(&ptimer_pool, sizeof(struct ptimer), 0, 0, 0, "ptimerpl",
    283 	    &pool_allocator_nointr);
    284 }
    285 
    286 /*
    287  * Acquire a read lock on the proclist.
    288  */
    289 void
    290 proclist_lock_read(void)
    291 {
    292 	int error;
    293 
    294 	error = spinlockmgr(&proclist_lock, LK_SHARED, NULL);
    295 #ifdef DIAGNOSTIC
    296 	if (__predict_false(error != 0))
    297 		panic("proclist_lock_read: failed to acquire lock");
    298 #endif
    299 }
    300 
    301 /*
    302  * Release a read lock on the proclist.
    303  */
    304 void
    305 proclist_unlock_read(void)
    306 {
    307 
    308 	(void) spinlockmgr(&proclist_lock, LK_RELEASE, NULL);
    309 }
    310 
    311 /*
    312  * Acquire a write lock on the proclist.
    313  */
    314 int
    315 proclist_lock_write(void)
    316 {
    317 	int s, error;
    318 
    319 	s = splclock();
    320 	error = spinlockmgr(&proclist_lock, LK_EXCLUSIVE, NULL);
    321 #ifdef DIAGNOSTIC
    322 	if (__predict_false(error != 0))
    323 		panic("proclist_lock: failed to acquire lock");
    324 #endif
    325 	return (s);
    326 }
    327 
    328 /*
    329  * Release a write lock on the proclist.
    330  */
    331 void
    332 proclist_unlock_write(int s)
    333 {
    334 
    335 	(void) spinlockmgr(&proclist_lock, LK_RELEASE, NULL);
    336 	splx(s);
    337 }
    338 
    339 /*
    340  * Change the count associated with number of processes
    341  * a given user is using.
    342  */
    343 int
    344 chgproccnt(uid_t uid, int diff)
    345 {
    346 	struct uidinfo *uip;
    347 	struct uihashhead *uipp;
    348 
    349 	uipp = UIHASH(uid);
    350 
    351 	LIST_FOREACH(uip, uipp, ui_hash)
    352 		if (uip->ui_uid == uid)
    353 			break;
    354 
    355 	if (uip) {
    356 		uip->ui_proccnt += diff;
    357 		if (uip->ui_proccnt > 0)
    358 			return (uip->ui_proccnt);
    359 		if (uip->ui_proccnt < 0)
    360 			panic("chgproccnt: procs < 0");
    361 		LIST_REMOVE(uip, ui_hash);
    362 		FREE(uip, M_PROC);
    363 		return (0);
    364 	}
    365 	if (diff <= 0) {
    366 		if (diff == 0)
    367 			return(0);
    368 		panic("chgproccnt: lost user");
    369 	}
    370 	MALLOC(uip, struct uidinfo *, sizeof(*uip), M_PROC, M_WAITOK);
    371 	LIST_INSERT_HEAD(uipp, uip, ui_hash);
    372 	uip->ui_uid = uid;
    373 	uip->ui_proccnt = diff;
    374 	return (diff);
    375 }
    376 
    377 /*
    378  * Check that the specifies process group in in the session of the
    379  * specified process.
    380  * Treats -ve ids as process ids.
    381  * Used to validate TIOCSPGRP requests.
    382  */
    383 int
    384 pgid_in_session(struct proc *p, pid_t pg_id)
    385 {
    386 	struct pgrp *pgrp;
    387 
    388 	if (pg_id < 0) {
    389 		struct proc *p1 = pfind(-pg_id);
    390 		if (p1 == NULL)
    391 			return EINVAL;
    392 		pgrp = p1->p_pgrp;
    393 	} else {
    394 		pgrp = pgfind(pg_id);
    395 		if (pgrp == NULL)
    396 			return EINVAL;
    397 	}
    398 	if (pgrp->pg_session != p->p_pgrp->pg_session)
    399 		return EPERM;
    400 	return 0;
    401 }
    402 
    403 /*
    404  * Is p an inferior of q?
    405  */
    406 int
    407 inferior(struct proc *p, struct proc *q)
    408 {
    409 
    410 	for (; p != q; p = p->p_pptr)
    411 		if (p->p_pid == 0)
    412 			return (0);
    413 	return (1);
    414 }
    415 
    416 /*
    417  * Locate a process by number
    418  */
    419 struct proc *
    420 p_find(pid_t pid, uint flags)
    421 {
    422 	struct proc *p;
    423 	char stat;
    424 
    425 	if (!(flags & PFIND_LOCKED))
    426 		proclist_lock_read();
    427 	p = pid_table[pid & pid_tbl_mask].pt_proc;
    428 	/* Only allow live processes to be found by pid. */
    429 	if (P_VALID(p) && p->p_pid == pid &&
    430 	    ((stat = p->p_stat) == SACTIVE || stat == SSTOP
    431 		    || (stat == SZOMB && (flags & PFIND_ZOMBIE)))) {
    432 		if (flags & PFIND_UNLOCK_OK)
    433 			 proclist_unlock_read();
    434 		return p;
    435 	}
    436 	if (flags & PFIND_UNLOCK_FAIL)
    437 		 proclist_unlock_read();
    438 	return NULL;
    439 }
    440 
    441 
    442 /*
    443  * Locate a process group by number
    444  */
    445 struct pgrp *
    446 pg_find(pid_t pgid, uint flags)
    447 {
    448 	struct pgrp *pg;
    449 
    450 	if (!(flags & PFIND_LOCKED))
    451 		proclist_lock_read();
    452 	pg = pid_table[pgid & pid_tbl_mask].pt_pgrp;
    453 	/*
    454 	 * Can't look up a pgrp that only exists because the session
    455 	 * hasn't died yet (traditional)
    456 	 */
    457 	if (pg == NULL || pg->pg_id != pgid || LIST_EMPTY(&pg->pg_members)) {
    458 		if (flags & PFIND_UNLOCK_FAIL)
    459 			 proclist_unlock_read();
    460 		return NULL;
    461 	}
    462 
    463 	if (flags & PFIND_UNLOCK_OK)
    464 		proclist_unlock_read();
    465 	return pg;
    466 }
    467 
    468 /*
    469  * Set entry for process 0
    470  */
    471 void
    472 proc0_insert(struct proc *p, struct lwp *l, struct pgrp *pgrp,
    473 	struct session *sess)
    474 {
    475 	int s;
    476 
    477 	simple_lock_init(&p->p_lock);
    478 	LIST_INIT(&p->p_lwps);
    479 	LIST_INSERT_HEAD(&p->p_lwps, l, l_sibling);
    480 	p->p_nlwps = 1;
    481 	simple_lock_init(&p->p_sigctx.ps_silock);
    482 	CIRCLEQ_INIT(&p->p_sigctx.ps_siginfo);
    483 
    484 	s = proclist_lock_write();
    485 
    486 	pid_table[0].pt_proc = p;
    487 	LIST_INSERT_HEAD(&allproc, p, p_list);
    488 	LIST_INSERT_HEAD(&alllwp, l, l_list);
    489 
    490 	p->p_pgrp = pgrp;
    491 	pid_table[0].pt_pgrp = pgrp;
    492 	LIST_INIT(&pgrp->pg_members);
    493 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
    494 
    495 	pgrp->pg_session = sess;
    496 	sess->s_count = 1;
    497 	sess->s_sid = 0;
    498 	sess->s_leader = p;
    499 
    500 	proclist_unlock_write(s);
    501 }
    502 
    503 static void
    504 expand_pid_table(void)
    505 {
    506 	uint pt_size = pid_tbl_mask + 1;
    507 	struct pid_table *n_pt, *new_pt;
    508 	struct proc *proc;
    509 	struct pgrp *pgrp;
    510 	int i;
    511 	int s;
    512 	pid_t pid;
    513 
    514 	new_pt = malloc(pt_size * 2 * sizeof *new_pt, M_PROC, M_WAITOK);
    515 
    516 	s = proclist_lock_write();
    517 	if (pt_size != pid_tbl_mask + 1) {
    518 		/* Another process beat us to it... */
    519 		proclist_unlock_write(s);
    520 		FREE(new_pt, M_PROC);
    521 		return;
    522 	}
    523 
    524 	/*
    525 	 * Copy entries from old table into new one.
    526 	 * If 'pid' is 'odd' we need to place in the upper half,
    527 	 * even pid's to the lower half.
    528 	 * Free items stay in the low half so we don't have to
    529 	 * fixup the reference to them.
    530 	 * We stuff free items on the front of the freelist
    531 	 * because we can't write to unmodified entries.
    532 	 * Processing the table backwards maintians a semblance
    533 	 * of issueing pid numbers that increase with time.
    534 	 */
    535 	i = pt_size - 1;
    536 	n_pt = new_pt + i;
    537 	for (; ; i--, n_pt--) {
    538 		proc = pid_table[i].pt_proc;
    539 		pgrp = pid_table[i].pt_pgrp;
    540 		if (!P_VALID(proc)) {
    541 			/* Up 'use count' so that link is valid */
    542 			pid = (P_NEXT(proc) + pt_size) & ~pt_size;
    543 			proc = P_FREE(pid);
    544 			if (pgrp)
    545 				pid = pgrp->pg_id;
    546 		} else
    547 			pid = proc->p_pid;
    548 
    549 		/* Save entry in appropriate half of table */
    550 		n_pt[pid & pt_size].pt_proc = proc;
    551 		n_pt[pid & pt_size].pt_pgrp = pgrp;
    552 
    553 		/* Put other piece on start of free list */
    554 		pid = (pid ^ pt_size) & ~pid_tbl_mask;
    555 		n_pt[pid & pt_size].pt_proc =
    556 				    P_FREE((pid & ~pt_size) | next_free_pt);
    557 		n_pt[pid & pt_size].pt_pgrp = 0;
    558 		next_free_pt = i | (pid & pt_size);
    559 		if (i == 0)
    560 			break;
    561 	}
    562 
    563 	/* Switch tables */
    564 	n_pt = pid_table;
    565 	pid_table = new_pt;
    566 	pid_tbl_mask = pt_size * 2 - 1;
    567 
    568 	/*
    569 	 * pid_max starts as PID_MAX (= 30000), once we have 16384
    570 	 * allocated pids we need it to be larger!
    571 	 */
    572 	if (pid_tbl_mask > PID_MAX) {
    573 		pid_max = pid_tbl_mask * 2 + 1;
    574 		pid_alloc_lim |= pid_alloc_lim << 1;
    575 	} else
    576 		pid_alloc_lim <<= 1;	/* doubles number of free slots... */
    577 
    578 	proclist_unlock_write(s);
    579 	FREE(n_pt, M_PROC);
    580 }
    581 
    582 struct proc *
    583 proc_alloc(void)
    584 {
    585 	struct proc *p;
    586 	int s;
    587 	int nxt;
    588 	pid_t pid;
    589 	struct pid_table *pt;
    590 
    591 	p = pool_get(&proc_pool, PR_WAITOK);
    592 	p->p_stat = SIDL;			/* protect against others */
    593 
    594 	/* allocate next free pid */
    595 
    596 	for (;;expand_pid_table()) {
    597 		if (__predict_false(pid_alloc_cnt >= pid_alloc_lim))
    598 			/* ensure pids cycle through 2000+ values */
    599 			continue;
    600 		s = proclist_lock_write();
    601 		pt = &pid_table[next_free_pt];
    602 #ifdef DIAGNOSTIC
    603 		if (__predict_false(P_VALID(pt->pt_proc) || pt->pt_pgrp))
    604 			panic("proc_alloc: slot busy");
    605 #endif
    606 		nxt = P_NEXT(pt->pt_proc);
    607 		if (nxt & pid_tbl_mask)
    608 			break;
    609 		/* Table full - expand (NB last entry not used....) */
    610 		proclist_unlock_write(s);
    611 	}
    612 
    613 	/* pid is 'saved use count' + 'size' + entry */
    614 	pid = (nxt & ~pid_tbl_mask) + pid_tbl_mask + 1 + next_free_pt;
    615 	if ((uint)pid > (uint)pid_max)
    616 		pid &= pid_tbl_mask;
    617 	p->p_pid = pid;
    618 	next_free_pt = nxt & pid_tbl_mask;
    619 
    620 	/* Grab table slot */
    621 	pt->pt_proc = p;
    622 	pid_alloc_cnt++;
    623 
    624 	proclist_unlock_write(s);
    625 
    626 	return p;
    627 }
    628 
    629 /*
    630  * Free last resources of a process - called from proc_free (in kern_exit.c)
    631  */
    632 void
    633 proc_free_mem(struct proc *p)
    634 {
    635 	int s;
    636 	pid_t pid = p->p_pid;
    637 	struct pid_table *pt;
    638 
    639 	s = proclist_lock_write();
    640 
    641 	pt = &pid_table[pid & pid_tbl_mask];
    642 #ifdef DIAGNOSTIC
    643 	if (__predict_false(pt->pt_proc != p))
    644 		panic("proc_free: pid_table mismatch, pid %x, proc %p",
    645 			pid, p);
    646 #endif
    647 	/* save pid use count in slot */
    648 	pt->pt_proc = P_FREE(pid & ~pid_tbl_mask);
    649 
    650 	if (pt->pt_pgrp == NULL) {
    651 		/* link last freed entry onto ours */
    652 		pid &= pid_tbl_mask;
    653 		pt = &pid_table[last_free_pt];
    654 		pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pid);
    655 		last_free_pt = pid;
    656 		pid_alloc_cnt--;
    657 	}
    658 
    659 	nprocs--;
    660 	proclist_unlock_write(s);
    661 
    662 	pool_put(&proc_pool, p);
    663 }
    664 
    665 /*
    666  * Move p to a new or existing process group (and session)
    667  *
    668  * If we are creating a new pgrp, the pgid should equal
    669  * the calling processes pid.
    670  * If is only valid to enter a process group that is in the session
    671  * of the process.
    672  * Also mksess should only be set if we are creating a process group
    673  *
    674  * Only called from sys_setsid, sys_setpgid/sys_setprp and the
    675  * SYSV setpgrp support for hpux == enterpgrp(curproc, curproc->p_pid)
    676  */
    677 int
    678 enterpgrp(struct proc *p, pid_t pgid, int mksess)
    679 {
    680 	struct pgrp *new_pgrp, *pgrp;
    681 	struct session *sess;
    682 	struct proc *curp = curproc;
    683 	pid_t pid = p->p_pid;
    684 	int rval;
    685 	int s;
    686 	pid_t pg_id = NO_PGID;
    687 
    688 	/* Allocate data areas we might need before doing any validity checks */
    689 	proclist_lock_read();		/* Because pid_table might change */
    690 	if (pid_table[pgid & pid_tbl_mask].pt_pgrp == 0) {
    691 		proclist_unlock_read();
    692 		new_pgrp = pool_get(&pgrp_pool, PR_WAITOK);
    693 	} else {
    694 		proclist_unlock_read();
    695 		new_pgrp = NULL;
    696 	}
    697 	if (mksess)
    698 		MALLOC(sess, struct session *, sizeof(struct session),
    699 			    M_SESSION, M_WAITOK);
    700 	else
    701 		sess = NULL;
    702 
    703 	s = proclist_lock_write();
    704 	rval = EPERM;	/* most common error (to save typing) */
    705 
    706 	/* Check pgrp exists or can be created */
    707 	pgrp = pid_table[pgid & pid_tbl_mask].pt_pgrp;
    708 	if (pgrp != NULL && pgrp->pg_id != pgid)
    709 		goto done;
    710 
    711 	/* Can only set another process under restricted circumstances. */
    712 	if (p != curp) {
    713 		/* must exist and be one of our children... */
    714 		if (p != pid_table[pid & pid_tbl_mask].pt_proc
    715 		    || !inferior(p, curp)) {
    716 			rval = ESRCH;
    717 			goto done;
    718 		}
    719 		/* ... in the same session... */
    720 		if (sess != NULL || p->p_session != curp->p_session)
    721 			goto done;
    722 		/* ... existing pgid must be in same session ... */
    723 		if (pgrp != NULL && pgrp->pg_session != p->p_session)
    724 			goto done;
    725 		/* ... and not done an exec. */
    726 		if (p->p_flag & P_EXEC) {
    727 			rval = EACCES;
    728 			goto done;
    729 		}
    730 	}
    731 
    732 	/* Changing the process group/session of a session
    733 	   leader is definitely off limits. */
    734 	if (SESS_LEADER(p)) {
    735 		if (sess == NULL && p->p_pgrp == pgrp)
    736 			/* unless it's a definite noop */
    737 			rval = 0;
    738 		goto done;
    739 	}
    740 
    741 	/* Can only create a process group with id of process */
    742 	if (pgrp == NULL && pgid != pid)
    743 		goto done;
    744 
    745 	/* Can only create a session if creating pgrp */
    746 	if (sess != NULL && pgrp != NULL)
    747 		goto done;
    748 
    749 	/* Check we allocated memory for a pgrp... */
    750 	if (pgrp == NULL && new_pgrp == NULL)
    751 		goto done;
    752 
    753 	/* Don't attach to 'zombie' pgrp */
    754 	if (pgrp != NULL && LIST_EMPTY(&pgrp->pg_members))
    755 		goto done;
    756 
    757 	/* Expect to succeed now */
    758 	rval = 0;
    759 
    760 	if (pgrp == p->p_pgrp)
    761 		/* nothing to do */
    762 		goto done;
    763 
    764 	/* Ok all setup, link up required structures */
    765 	if (pgrp == NULL) {
    766 		pgrp = new_pgrp;
    767 		new_pgrp = 0;
    768 		if (sess != NULL) {
    769 			sess->s_sid = p->p_pid;
    770 			sess->s_leader = p;
    771 			sess->s_count = 1;
    772 			sess->s_ttyvp = NULL;
    773 			sess->s_ttyp = NULL;
    774 			sess->s_flags = p->p_session->s_flags & ~S_LOGIN_SET;
    775 			memcpy(sess->s_login, p->p_session->s_login,
    776 			    sizeof(sess->s_login));
    777 			p->p_flag &= ~P_CONTROLT;
    778 		} else {
    779 			sess = p->p_pgrp->pg_session;
    780 			SESSHOLD(sess);
    781 		}
    782 		pgrp->pg_session = sess;
    783 		sess = 0;
    784 
    785 		pgrp->pg_id = pgid;
    786 		LIST_INIT(&pgrp->pg_members);
    787 #ifdef DIAGNOSTIC
    788 		if (__predict_false(pid_table[pgid & pid_tbl_mask].pt_pgrp))
    789 			panic("enterpgrp: pgrp table slot in use");
    790 		if (__predict_false(mksess && p != curp))
    791 			panic("enterpgrp: mksession and p != curproc");
    792 #endif
    793 		pid_table[pgid & pid_tbl_mask].pt_pgrp = pgrp;
    794 		pgrp->pg_jobc = 0;
    795 	}
    796 
    797 	/*
    798 	 * Adjust eligibility of affected pgrps to participate in job control.
    799 	 * Increment eligibility counts before decrementing, otherwise we
    800 	 * could reach 0 spuriously during the first call.
    801 	 */
    802 	fixjobc(p, pgrp, 1);
    803 	fixjobc(p, p->p_pgrp, 0);
    804 
    805 	/* Move process to requested group */
    806 	LIST_REMOVE(p, p_pglist);
    807 	if (LIST_EMPTY(&p->p_pgrp->pg_members))
    808 		/* defer delete until we've dumped the lock */
    809 		pg_id = p->p_pgrp->pg_id;
    810 	p->p_pgrp = pgrp;
    811 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
    812 
    813     done:
    814 	proclist_unlock_write(s);
    815 	if (sess != NULL)
    816 		free(sess, M_SESSION);
    817 	if (new_pgrp != NULL)
    818 		pool_put(&pgrp_pool, new_pgrp);
    819 	if (pg_id != NO_PGID)
    820 		pg_delete(pg_id);
    821 #ifdef DEBUG_PGRP
    822 	if (__predict_false(rval))
    823 		printf("enterpgrp(%d,%d,%d), curproc %d, rval %d\n",
    824 			pid, pgid, mksess, curp->p_pid, rval);
    825 #endif
    826 	return rval;
    827 }
    828 
    829 /*
    830  * remove process from process group
    831  */
    832 int
    833 leavepgrp(struct proc *p)
    834 {
    835 	int s;
    836 	struct pgrp *pgrp;
    837 	pid_t pg_id;
    838 
    839 	s = proclist_lock_write();
    840 	pgrp = p->p_pgrp;
    841 	LIST_REMOVE(p, p_pglist);
    842 	p->p_pgrp = 0;
    843 	pg_id = LIST_EMPTY(&pgrp->pg_members) ? pgrp->pg_id : NO_PGID;
    844 	proclist_unlock_write(s);
    845 
    846 	if (pg_id != NO_PGID)
    847 		pg_delete(pg_id);
    848 	return 0;
    849 }
    850 
    851 static void
    852 pg_free(pid_t pg_id)
    853 {
    854 	struct pgrp *pgrp;
    855 	struct pid_table *pt;
    856 	int s;
    857 
    858 	s = proclist_lock_write();
    859 	pt = &pid_table[pg_id & pid_tbl_mask];
    860 	pgrp = pt->pt_pgrp;
    861 #ifdef DIAGNOSTIC
    862 	if (__predict_false(!pgrp || pgrp->pg_id != pg_id
    863 	    || !LIST_EMPTY(&pgrp->pg_members)))
    864 		panic("pg_free: process group absent or has members");
    865 #endif
    866 	pt->pt_pgrp = 0;
    867 
    868 	if (!P_VALID(pt->pt_proc)) {
    869 		/* orphaned pgrp, put slot onto free list */
    870 #ifdef DIAGNOSTIC
    871 		if (__predict_false(P_NEXT(pt->pt_proc) & pid_tbl_mask))
    872 			panic("pg_free: process slot on free list");
    873 #endif
    874 
    875 		pg_id &= pid_tbl_mask;
    876 		pt = &pid_table[last_free_pt];
    877 		pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pg_id);
    878 		last_free_pt = pg_id;
    879 		pid_alloc_cnt--;
    880 	}
    881 	proclist_unlock_write(s);
    882 
    883 	pool_put(&pgrp_pool, pgrp);
    884 }
    885 
    886 /*
    887  * delete a process group
    888  */
    889 static void
    890 pg_delete(pid_t pg_id)
    891 {
    892 	struct pgrp *pgrp;
    893 	struct tty *ttyp;
    894 	struct session *ss;
    895 	int s;
    896 
    897 	s = proclist_lock_write();
    898 	pgrp = pid_table[pg_id & pid_tbl_mask].pt_pgrp;
    899 	if (pgrp == NULL || pgrp->pg_id != pg_id ||
    900 	    !LIST_EMPTY(&pgrp->pg_members)) {
    901 		proclist_unlock_write(s);
    902 		return;
    903 	}
    904 
    905 	/* Remove reference (if any) from tty to this process group */
    906 	ttyp = pgrp->pg_session->s_ttyp;
    907 	if (ttyp != NULL && ttyp->t_pgrp == pgrp)
    908 		ttyp->t_pgrp = NULL;
    909 
    910 	ss = pgrp->pg_session;
    911 
    912 	if (ss->s_sid == pgrp->pg_id) {
    913 		proclist_unlock_write(s);
    914 		SESSRELE(ss);
    915 		/* pgrp freed by sessdelete() if last reference */
    916 		return;
    917 	}
    918 
    919 	proclist_unlock_write(s);
    920 	SESSRELE(ss);
    921 	pg_free(pg_id);
    922 }
    923 
    924 /*
    925  * Delete session - called from SESSRELE when s_count becomes zero.
    926  */
    927 void
    928 sessdelete(struct session *ss)
    929 {
    930 	/*
    931 	 * We keep the pgrp with the same id as the session in
    932 	 * order to stop a process being given the same pid.
    933 	 * Since the pgrp holds a reference to the session, it
    934 	 * must be a 'zombie' pgrp by now.
    935 	 */
    936 
    937 	pg_free(ss->s_sid);
    938 
    939 	FREE(ss, M_SESSION);
    940 }
    941 
    942 /*
    943  * Adjust pgrp jobc counters when specified process changes process group.
    944  * We count the number of processes in each process group that "qualify"
    945  * the group for terminal job control (those with a parent in a different
    946  * process group of the same session).  If that count reaches zero, the
    947  * process group becomes orphaned.  Check both the specified process'
    948  * process group and that of its children.
    949  * entering == 0 => p is leaving specified group.
    950  * entering == 1 => p is entering specified group.
    951  *
    952  * Call with proclist_lock held.
    953  */
    954 void
    955 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
    956 {
    957 	struct pgrp *hispgrp;
    958 	struct session *mysession = pgrp->pg_session;
    959 	struct proc *child;
    960 
    961 	/*
    962 	 * Check p's parent to see whether p qualifies its own process
    963 	 * group; if so, adjust count for p's process group.
    964 	 */
    965 	hispgrp = p->p_pptr->p_pgrp;
    966 	if (hispgrp != pgrp && hispgrp->pg_session == mysession) {
    967 		if (entering)
    968 			pgrp->pg_jobc++;
    969 		else if (--pgrp->pg_jobc == 0)
    970 			orphanpg(pgrp);
    971 	}
    972 
    973 	/*
    974 	 * Check this process' children to see whether they qualify
    975 	 * their process groups; if so, adjust counts for children's
    976 	 * process groups.
    977 	 */
    978 	LIST_FOREACH(child, &p->p_children, p_sibling) {
    979 		hispgrp = child->p_pgrp;
    980 		if (hispgrp != pgrp && hispgrp->pg_session == mysession &&
    981 		    !P_ZOMBIE(child)) {
    982 			if (entering)
    983 				hispgrp->pg_jobc++;
    984 			else if (--hispgrp->pg_jobc == 0)
    985 				orphanpg(hispgrp);
    986 		}
    987 	}
    988 }
    989 
    990 /*
    991  * A process group has become orphaned;
    992  * if there are any stopped processes in the group,
    993  * hang-up all process in that group.
    994  *
    995  * Call with proclist_lock held.
    996  */
    997 static void
    998 orphanpg(struct pgrp *pg)
    999 {
   1000 	struct proc *p;
   1001 
   1002 	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
   1003 		if (p->p_stat == SSTOP) {
   1004 			LIST_FOREACH(p, &pg->pg_members, p_pglist) {
   1005 				psignal(p, SIGHUP);
   1006 				psignal(p, SIGCONT);
   1007 			}
   1008 			return;
   1009 		}
   1010 	}
   1011 }
   1012 
   1013 /* mark process as suid/sgid, reset some values to defaults */
   1014 void
   1015 p_sugid(struct proc *p)
   1016 {
   1017 	struct plimit *newlim;
   1018 
   1019 	p->p_flag |= P_SUGID;
   1020 	/* reset what needs to be reset in plimit */
   1021 	if (p->p_limit->pl_corename != defcorename) {
   1022 		if (p->p_limit->p_refcnt > 1 &&
   1023 		    (p->p_limit->p_lflags & PL_SHAREMOD) == 0) {
   1024 			newlim = limcopy(p->p_limit);
   1025 			limfree(p->p_limit);
   1026 			p->p_limit = newlim;
   1027 		}
   1028 		free(p->p_limit->pl_corename, M_TEMP);
   1029 		p->p_limit->pl_corename = defcorename;
   1030 	}
   1031 }
   1032 
   1033 #ifdef DDB
   1034 #include <ddb/db_output.h>
   1035 void pidtbl_dump(void);
   1036 void
   1037 pidtbl_dump(void)
   1038 {
   1039 	struct pid_table *pt;
   1040 	struct proc *p;
   1041 	struct pgrp *pgrp;
   1042 	int id;
   1043 
   1044 	db_printf("pid table %p size %x, next %x, last %x\n",
   1045 		pid_table, pid_tbl_mask+1,
   1046 		next_free_pt, last_free_pt);
   1047 	for (pt = pid_table, id = 0; id <= pid_tbl_mask; id++, pt++) {
   1048 		p = pt->pt_proc;
   1049 		if (!P_VALID(p) && !pt->pt_pgrp)
   1050 			continue;
   1051 		db_printf("  id %x: ", id);
   1052 		if (P_VALID(p))
   1053 			db_printf("proc %p id %d (0x%x) %s\n",
   1054 				p, p->p_pid, p->p_pid, p->p_comm);
   1055 		else
   1056 			db_printf("next %x use %x\n",
   1057 				P_NEXT(p) & pid_tbl_mask,
   1058 				P_NEXT(p) & ~pid_tbl_mask);
   1059 		if ((pgrp = pt->pt_pgrp)) {
   1060 			db_printf("\tsession %p, sid %d, count %d, login %s\n",
   1061 			    pgrp->pg_session, pgrp->pg_session->s_sid,
   1062 			    pgrp->pg_session->s_count,
   1063 			    pgrp->pg_session->s_login);
   1064 			db_printf("\tpgrp %p, pg_id %d, pg_jobc %d, members %p\n",
   1065 			    pgrp, pgrp->pg_id, pgrp->pg_jobc,
   1066 			    pgrp->pg_members.lh_first);
   1067 			for (p = pgrp->pg_members.lh_first; p != 0;
   1068 			    p = p->p_pglist.le_next) {
   1069 				db_printf("\t\tpid %d addr %p pgrp %p %s\n",
   1070 				    p->p_pid, p, p->p_pgrp, p->p_comm);
   1071 			}
   1072 		}
   1073 	}
   1074 }
   1075 #endif /* DDB */
   1076 
   1077 #ifdef KSTACK_CHECK_MAGIC
   1078 #include <sys/user.h>
   1079 
   1080 #define	KSTACK_MAGIC	0xdeadbeaf
   1081 
   1082 /* XXX should be per process basis? */
   1083 int kstackleftmin = KSTACK_SIZE;
   1084 int kstackleftthres = KSTACK_SIZE / 8; /* warn if remaining stack is
   1085 					  less than this */
   1086 
   1087 void
   1088 kstack_setup_magic(const struct lwp *l)
   1089 {
   1090 	u_int32_t *ip;
   1091 	u_int32_t const *end;
   1092 
   1093 	KASSERT(l != NULL);
   1094 	KASSERT(l != &lwp0);
   1095 
   1096 	/*
   1097 	 * fill all the stack with magic number
   1098 	 * so that later modification on it can be detected.
   1099 	 */
   1100 	ip = (u_int32_t *)KSTACK_LOWEST_ADDR(l);
   1101 	end = (u_int32_t *)((caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
   1102 	for (; ip < end; ip++) {
   1103 		*ip = KSTACK_MAGIC;
   1104 	}
   1105 }
   1106 
   1107 void
   1108 kstack_check_magic(const struct lwp *l)
   1109 {
   1110 	u_int32_t const *ip, *end;
   1111 	int stackleft;
   1112 
   1113 	KASSERT(l != NULL);
   1114 
   1115 	/* don't check proc0 */ /*XXX*/
   1116 	if (l == &lwp0)
   1117 		return;
   1118 
   1119 #ifdef __MACHINE_STACK_GROWS_UP
   1120 	/* stack grows upwards (eg. hppa) */
   1121 	ip = (u_int32_t *)((caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
   1122 	end = (u_int32_t *)KSTACK_LOWEST_ADDR(l);
   1123 	for (ip--; ip >= end; ip--)
   1124 		if (*ip != KSTACK_MAGIC)
   1125 			break;
   1126 
   1127 	stackleft = (caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE - (caddr_t)ip;
   1128 #else /* __MACHINE_STACK_GROWS_UP */
   1129 	/* stack grows downwards (eg. i386) */
   1130 	ip = (u_int32_t *)KSTACK_LOWEST_ADDR(l);
   1131 	end = (u_int32_t *)((caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
   1132 	for (; ip < end; ip++)
   1133 		if (*ip != KSTACK_MAGIC)
   1134 			break;
   1135 
   1136 	stackleft = (caddr_t)ip - KSTACK_LOWEST_ADDR(l);
   1137 #endif /* __MACHINE_STACK_GROWS_UP */
   1138 
   1139 	if (kstackleftmin > stackleft) {
   1140 		kstackleftmin = stackleft;
   1141 		if (stackleft < kstackleftthres)
   1142 			printf("warning: kernel stack left %d bytes"
   1143 			    "(pid %u:lid %u)\n", stackleft,
   1144 			    (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
   1145 	}
   1146 
   1147 	if (stackleft <= 0) {
   1148 		panic("magic on the top of kernel stack changed for "
   1149 		    "pid %u, lid %u: maybe kernel stack overflow",
   1150 		    (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
   1151 	}
   1152 }
   1153 #endif /* KSTACK_CHECK_MAGIC */
   1154