Home | History | Annotate | Line # | Download | only in kern
kern_proc.c revision 1.68
      1 /*	$NetBSD: kern_proc.c,v 1.68 2003/11/12 21:07:38 dsl 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.68 2003/11/12 21:07:38 dsl 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 ptimer_pool;
    194 
    195 MALLOC_DEFINE(M_EMULDATA, "emuldata", "Per-process emulation data");
    196 MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
    197 MALLOC_DEFINE(M_SESSION, "session", "session header");
    198 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
    199 
    200 /*
    201  * The process list descriptors, used during pid allocation and
    202  * by sysctl.  No locking on this data structure is needed since
    203  * it is completely static.
    204  */
    205 const struct proclist_desc proclists[] = {
    206 	{ &allproc	},
    207 	{ &zombproc	},
    208 	{ NULL		},
    209 };
    210 
    211 static void orphanpg __P((struct pgrp *));
    212 #ifdef DEBUG
    213 void pgrpdump __P((void));
    214 #endif
    215 
    216 /*
    217  * Initialize global process hashing structures.
    218  */
    219 void
    220 procinit(void)
    221 {
    222 	const struct proclist_desc *pd;
    223 	int i;
    224 #define	LINK_EMPTY ((PID_MAX + INITIAL_PID_TABLE_SIZE) & ~(INITIAL_PID_TABLE_SIZE - 1))
    225 
    226 	for (pd = proclists; pd->pd_list != NULL; pd++)
    227 		LIST_INIT(pd->pd_list);
    228 
    229 	spinlockinit(&proclist_lock, "proclk", 0);
    230 
    231 	simple_lock_init(&deadproc_slock);
    232 
    233 	pid_table = malloc(INITIAL_PID_TABLE_SIZE * sizeof *pid_table,
    234 			    M_PROC, M_WAITOK);
    235 	/* Set free list running through table...
    236 	   Preset 'use count' above PID_MAX so we allocate pid 1 next. */
    237 	for (i = 0; i <= pid_tbl_mask; i++) {
    238 		pid_table[i].pt_proc = P_FREE(LINK_EMPTY + i + 1);
    239 		pid_table[i].pt_pgrp = 0;
    240 	}
    241 	/* slot 0 is just grabbed */
    242 	next_free_pt = 1;
    243 	/* Need to fix last entry. */
    244 	last_free_pt = pid_tbl_mask;
    245 	pid_table[last_free_pt].pt_proc = P_FREE(LINK_EMPTY);
    246 	/* point at which we grow table - to avoid reusing pids too often */
    247 	pid_alloc_lim = pid_tbl_mask - 1;
    248 #undef LINK_EMPTY
    249 
    250 	LIST_INIT(&alllwp);
    251 	LIST_INIT(&deadlwp);
    252 	LIST_INIT(&zomblwp);
    253 
    254 	uihashtbl =
    255 	    hashinit(maxproc / 16, HASH_LIST, M_PROC, M_WAITOK, &uihash);
    256 
    257 	pool_init(&proc_pool, sizeof(struct proc), 0, 0, 0, "procpl",
    258 	    &pool_allocator_nointr);
    259 	pool_init(&lwp_pool, sizeof(struct lwp), 0, 0, 0, "lwppl",
    260 	    &pool_allocator_nointr);
    261 	pool_init(&lwp_uc_pool, sizeof(ucontext_t), 0, 0, 0, "lwpucpl",
    262 	    &pool_allocator_nointr);
    263 	pool_init(&pgrp_pool, sizeof(struct pgrp), 0, 0, 0, "pgrppl",
    264 	    &pool_allocator_nointr);
    265 	pool_init(&pcred_pool, sizeof(struct pcred), 0, 0, 0, "pcredpl",
    266 	    &pool_allocator_nointr);
    267 	pool_init(&plimit_pool, sizeof(struct plimit), 0, 0, 0, "plimitpl",
    268 	    &pool_allocator_nointr);
    269 	pool_init(&pstats_pool, sizeof(struct pstats), 0, 0, 0, "pstatspl",
    270 	    &pool_allocator_nointr);
    271 	pool_init(&rusage_pool, sizeof(struct rusage), 0, 0, 0, "rusgepl",
    272 	    &pool_allocator_nointr);
    273 	pool_init(&ras_pool, sizeof(struct ras), 0, 0, 0, "raspl",
    274 	    &pool_allocator_nointr);
    275 	pool_init(&sadata_pool, sizeof(struct sadata), 0, 0, 0, "sadatapl",
    276 	    &pool_allocator_nointr);
    277 	pool_init(&saupcall_pool, sizeof(struct sadata_upcall), 0, 0, 0,
    278 	    "saupcpl",
    279 	    &pool_allocator_nointr);
    280 	pool_init(&ptimer_pool, sizeof(struct ptimer), 0, 0, 0, "ptimerpl",
    281 	    &pool_allocator_nointr);
    282 }
    283 
    284 /*
    285  * Acquire a read lock on the proclist.
    286  */
    287 void
    288 proclist_lock_read(void)
    289 {
    290 	int error;
    291 
    292 	error = spinlockmgr(&proclist_lock, LK_SHARED, NULL);
    293 #ifdef DIAGNOSTIC
    294 	if (__predict_false(error != 0))
    295 		panic("proclist_lock_read: failed to acquire lock");
    296 #endif
    297 }
    298 
    299 /*
    300  * Release a read lock on the proclist.
    301  */
    302 void
    303 proclist_unlock_read(void)
    304 {
    305 
    306 	(void) spinlockmgr(&proclist_lock, LK_RELEASE, NULL);
    307 }
    308 
    309 /*
    310  * Acquire a write lock on the proclist.
    311  */
    312 int
    313 proclist_lock_write(void)
    314 {
    315 	int s, error;
    316 
    317 	s = splclock();
    318 	error = spinlockmgr(&proclist_lock, LK_EXCLUSIVE, NULL);
    319 #ifdef DIAGNOSTIC
    320 	if (__predict_false(error != 0))
    321 		panic("proclist_lock: failed to acquire lock");
    322 #endif
    323 	return (s);
    324 }
    325 
    326 /*
    327  * Release a write lock on the proclist.
    328  */
    329 void
    330 proclist_unlock_write(int s)
    331 {
    332 
    333 	(void) spinlockmgr(&proclist_lock, LK_RELEASE, NULL);
    334 	splx(s);
    335 }
    336 
    337 /*
    338  * Change the count associated with number of processes
    339  * a given user is using.
    340  */
    341 int
    342 chgproccnt(uid_t uid, int diff)
    343 {
    344 	struct uidinfo *uip;
    345 	struct uihashhead *uipp;
    346 
    347 	uipp = UIHASH(uid);
    348 
    349 	LIST_FOREACH(uip, uipp, ui_hash)
    350 		if (uip->ui_uid == uid)
    351 			break;
    352 
    353 	if (uip) {
    354 		uip->ui_proccnt += diff;
    355 		if (uip->ui_proccnt > 0)
    356 			return (uip->ui_proccnt);
    357 		if (uip->ui_proccnt < 0)
    358 			panic("chgproccnt: procs < 0");
    359 		LIST_REMOVE(uip, ui_hash);
    360 		FREE(uip, M_PROC);
    361 		return (0);
    362 	}
    363 	if (diff <= 0) {
    364 		if (diff == 0)
    365 			return(0);
    366 		panic("chgproccnt: lost user");
    367 	}
    368 	MALLOC(uip, struct uidinfo *, sizeof(*uip), M_PROC, M_WAITOK);
    369 	LIST_INSERT_HEAD(uipp, uip, ui_hash);
    370 	uip->ui_uid = uid;
    371 	uip->ui_proccnt = diff;
    372 	return (diff);
    373 }
    374 
    375 /*
    376  * Check that the specifies process group in in the session of the
    377  * specified process.
    378  * Treats -ve ids as process ids.
    379  * Used to validate TIOCSPGRP requests.
    380  */
    381 int
    382 pgid_in_session(struct proc *p, pid_t pg_id)
    383 {
    384 	struct pgrp *pgrp;
    385 
    386 	if (pg_id < 0) {
    387 		struct proc *p1 = pfind(-pg_id);
    388 		if (p1 == NULL)
    389 			return EINVAL;
    390 		pgrp = p1->p_pgrp;
    391 	} else {
    392 		pgrp = pgfind(pg_id);
    393 		if (pgrp == NULL)
    394 			return EINVAL;
    395 	}
    396 	if (pgrp->pg_session != p->p_pgrp->pg_session)
    397 		return EPERM;
    398 	return 0;
    399 }
    400 
    401 /*
    402  * Is p an inferior of q?
    403  */
    404 int
    405 inferior(struct proc *p, struct proc *q)
    406 {
    407 
    408 	for (; p != q; p = p->p_pptr)
    409 		if (p->p_pid == 0)
    410 			return (0);
    411 	return (1);
    412 }
    413 
    414 /*
    415  * Locate a process by number
    416  */
    417 struct proc *
    418 p_find(pid_t pid, uint flags)
    419 {
    420 	struct proc *p;
    421 	char stat;
    422 
    423 	if (!(flags & PFIND_LOCKED))
    424 		proclist_lock_read();
    425 	p = pid_table[pid & pid_tbl_mask].pt_proc;
    426 	/* Only allow live processes to be found by pid. */
    427 	if (P_VALID(p) && p->p_pid == pid &&
    428 	    ((stat = p->p_stat) == SACTIVE || stat == SSTOP
    429 		    || (stat == SZOMB && (flags & PFIND_ZOMBIE)))) {
    430 		if (flags & PFIND_UNLOCK_OK)
    431 			 proclist_unlock_read();
    432 		return p;
    433 	}
    434 	if (flags & PFIND_UNLOCK_FAIL)
    435 		 proclist_unlock_read();
    436 	return NULL;
    437 }
    438 
    439 
    440 /*
    441  * Locate a process group by number
    442  */
    443 struct pgrp *
    444 pg_find(pid_t pgid, uint flags)
    445 {
    446 	struct pgrp *pg;
    447 
    448 	if (!(flags & PFIND_LOCKED))
    449 		proclist_lock_read();
    450 	pg = pid_table[pgid & pid_tbl_mask].pt_pgrp;
    451 	/*
    452 	 * Can't look up a pgrp that only exists because the session
    453 	 * hasn't died yet (traditional)
    454 	 */
    455 	if (pg == NULL || pg->pg_id != pgid || LIST_EMPTY(&pg->pg_members)) {
    456 		if (flags & PFIND_UNLOCK_FAIL)
    457 			 proclist_unlock_read();
    458 		return NULL;
    459 	}
    460 
    461 	if (flags & PFIND_UNLOCK_OK)
    462 		proclist_unlock_read();
    463 	return pg;
    464 }
    465 
    466 /*
    467  * Set entry for process 0
    468  */
    469 void
    470 proc0_insert(struct proc *p, struct lwp *l, struct pgrp *pgrp,
    471 	struct session *sess)
    472 {
    473 	int s;
    474 
    475 	simple_lock_init(&p->p_lock);
    476 	LIST_INIT(&p->p_lwps);
    477 	LIST_INSERT_HEAD(&p->p_lwps, l, l_sibling);
    478 	p->p_nlwps = 1;
    479 	simple_lock_init(&p->p_sigctx.ps_silock);
    480 	CIRCLEQ_INIT(&p->p_sigctx.ps_siginfo);
    481 
    482 	s = proclist_lock_write();
    483 
    484 	pid_table[0].pt_proc = p;
    485 	LIST_INSERT_HEAD(&allproc, p, p_list);
    486 	LIST_INSERT_HEAD(&alllwp, l, l_list);
    487 
    488 	p->p_pgrp = pgrp;
    489 	pid_table[0].pt_pgrp = pgrp;
    490 	LIST_INIT(&pgrp->pg_members);
    491 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
    492 
    493 	pgrp->pg_session = sess;
    494 	sess->s_count = 1;
    495 	sess->s_sid = 0;
    496 	sess->s_leader = p;
    497 
    498 	proclist_unlock_write(s);
    499 }
    500 
    501 static void
    502 expand_pid_table(void)
    503 {
    504 	uint pt_size = pid_tbl_mask + 1;
    505 	struct pid_table *n_pt, *new_pt;
    506 	struct proc *proc;
    507 	struct pgrp *pgrp;
    508 	int i;
    509 	int s;
    510 	pid_t pid;
    511 
    512 	new_pt = malloc(pt_size * 2 * sizeof *new_pt, M_PROC, M_WAITOK);
    513 
    514 	s = proclist_lock_write();
    515 	if (pt_size != pid_tbl_mask + 1) {
    516 		/* Another process beat us to it... */
    517 		proclist_unlock_write(s);
    518 		FREE(new_pt, M_PROC);
    519 		return;
    520 	}
    521 
    522 	/*
    523 	 * Copy entries from old table into new one.
    524 	 * If 'pid' is 'odd' we need to place in the upper half,
    525 	 * even pid's to the lower half.
    526 	 * Free items stay in the low half so we don't have to
    527 	 * fixup the reference to them.
    528 	 * We stuff free items on the front of the freelist
    529 	 * because we can't write to unmodified entries.
    530 	 * Processing the table backwards maintians a semblance
    531 	 * of issueing pid numbers that increase with time.
    532 	 */
    533 	i = pt_size - 1;
    534 	n_pt = new_pt + i;
    535 	for (; ; i--, n_pt--) {
    536 		proc = pid_table[i].pt_proc;
    537 		pgrp = pid_table[i].pt_pgrp;
    538 		if (!P_VALID(proc)) {
    539 			/* Up 'use count' so that link is valid */
    540 			pid = (P_NEXT(proc) + pt_size) & ~pt_size;
    541 			proc = P_FREE(pid);
    542 			if (pgrp)
    543 				pid = pgrp->pg_id;
    544 		} else
    545 			pid = proc->p_pid;
    546 
    547 		/* Save entry in appropriate half of table */
    548 		n_pt[pid & pt_size].pt_proc = proc;
    549 		n_pt[pid & pt_size].pt_pgrp = pgrp;
    550 
    551 		/* Put other piece on start of free list */
    552 		pid = (pid ^ pt_size) & ~pid_tbl_mask;
    553 		n_pt[pid & pt_size].pt_proc =
    554 				    P_FREE((pid & ~pt_size) | next_free_pt);
    555 		n_pt[pid & pt_size].pt_pgrp = 0;
    556 		next_free_pt = i | (pid & pt_size);
    557 		if (i == 0)
    558 			break;
    559 	}
    560 
    561 	/* Switch tables */
    562 	n_pt = pid_table;
    563 	pid_table = new_pt;
    564 	pid_tbl_mask = pt_size * 2 - 1;
    565 
    566 	/*
    567 	 * pid_max starts as PID_MAX (= 30000), once we have 16384
    568 	 * allocated pids we need it to be larger!
    569 	 */
    570 	if (pid_tbl_mask > PID_MAX) {
    571 		pid_max = pid_tbl_mask * 2 + 1;
    572 		pid_alloc_lim |= pid_alloc_lim << 1;
    573 	} else
    574 		pid_alloc_lim <<= 1;	/* doubles number of free slots... */
    575 
    576 	proclist_unlock_write(s);
    577 	FREE(n_pt, M_PROC);
    578 }
    579 
    580 struct proc *
    581 proc_alloc(void)
    582 {
    583 	struct proc *p;
    584 	int s;
    585 	int nxt;
    586 	pid_t pid;
    587 	struct pid_table *pt;
    588 
    589 	p = pool_get(&proc_pool, PR_WAITOK);
    590 	p->p_stat = SIDL;			/* protect against others */
    591 
    592 	/* allocate next free pid */
    593 
    594 	for (;;expand_pid_table()) {
    595 		if (__predict_false(pid_alloc_cnt >= pid_alloc_lim))
    596 			/* ensure pids cycle through 2000+ values */
    597 			continue;
    598 		s = proclist_lock_write();
    599 		pt = &pid_table[next_free_pt];
    600 #ifdef DIAGNOSTIC
    601 		if (__predict_false(P_VALID(pt->pt_proc) || pt->pt_pgrp))
    602 			panic("proc_alloc: slot busy");
    603 #endif
    604 		nxt = P_NEXT(pt->pt_proc);
    605 		if (nxt & pid_tbl_mask)
    606 			break;
    607 		/* Table full - expand (NB last entry not used....) */
    608 		proclist_unlock_write(s);
    609 	}
    610 
    611 	/* pid is 'saved use count' + 'size' + entry */
    612 	pid = (nxt & ~pid_tbl_mask) + pid_tbl_mask + 1 + next_free_pt;
    613 	if ((uint)pid > (uint)pid_max)
    614 		pid &= pid_tbl_mask;
    615 	p->p_pid = pid;
    616 	next_free_pt = nxt & pid_tbl_mask;
    617 
    618 	/* Grab table slot */
    619 	pt->pt_proc = p;
    620 	pid_alloc_cnt++;
    621 
    622 	proclist_unlock_write(s);
    623 
    624 	return p;
    625 }
    626 
    627 /*
    628  * Free last resources of a process - called from proc_free (in kern_exit.c)
    629  */
    630 void
    631 proc_free_mem(struct proc *p)
    632 {
    633 	int s;
    634 	pid_t pid = p->p_pid;
    635 	struct pid_table *pt;
    636 
    637 	s = proclist_lock_write();
    638 
    639 	pt = &pid_table[pid & pid_tbl_mask];
    640 #ifdef DIAGNOSTIC
    641 	if (__predict_false(pt->pt_proc != p))
    642 		panic("proc_free: pid_table mismatch, pid %x, proc %p",
    643 			pid, p);
    644 #endif
    645 	/* save pid use count in slot */
    646 	pt->pt_proc = P_FREE(pid & ~pid_tbl_mask);
    647 
    648 	if (pt->pt_pgrp == NULL) {
    649 		/* link last freed entry onto ours */
    650 		pid &= pid_tbl_mask;
    651 		pt = &pid_table[last_free_pt];
    652 		pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pid);
    653 		last_free_pt = pid;
    654 		pid_alloc_cnt--;
    655 	}
    656 
    657 	nprocs--;
    658 	proclist_unlock_write(s);
    659 
    660 	pool_put(&proc_pool, p);
    661 }
    662 
    663 /*
    664  * Move p to a new or existing process group (and session)
    665  *
    666  * If we are creating a new pgrp, the pgid should equal
    667  * the calling processes pid.
    668  * If is only valid to enter a process group that is in the session
    669  * of the process.
    670  * Also mksess should only be set if we are creating a process group
    671  *
    672  * Only called from sys_setsid, sys_setpgid/sys_setprp and the
    673  * SYSV setpgrp support for hpux == enterpgrp(curproc, curproc->p_pid)
    674  */
    675 int
    676 enterpgrp(struct proc *p, pid_t pgid, int mksess)
    677 {
    678 	struct pgrp *new_pgrp, *pgrp;
    679 	struct session *sess;
    680 	struct proc *curp = curproc;
    681 	pid_t pid = p->p_pid;
    682 	int rval;
    683 	int s;
    684 	pid_t pg_id = NO_PGID;
    685 
    686 	/* Allocate data areas we might need before doing any validity checks */
    687 	proclist_lock_read();		/* Because pid_table might change */
    688 	if (pid_table[pgid & pid_tbl_mask].pt_pgrp == 0) {
    689 		proclist_unlock_read();
    690 		new_pgrp = pool_get(&pgrp_pool, PR_WAITOK);
    691 	} else {
    692 		proclist_unlock_read();
    693 		new_pgrp = NULL;
    694 	}
    695 	if (mksess)
    696 		MALLOC(sess, struct session *, sizeof(struct session),
    697 			    M_SESSION, M_WAITOK);
    698 	else
    699 		sess = NULL;
    700 
    701 	s = proclist_lock_write();
    702 	rval = EPERM;	/* most common error (to save typing) */
    703 
    704 	/* Check pgrp exists or can be created */
    705 	pgrp = pid_table[pgid & pid_tbl_mask].pt_pgrp;
    706 	if (pgrp != NULL && pgrp->pg_id != pgid)
    707 		goto done;
    708 
    709 	/* Can only set another process under restricted circumstances. */
    710 	if (p != curp) {
    711 		/* must exist and be one of our children... */
    712 		if (p != pid_table[pid & pid_tbl_mask].pt_proc
    713 		    || !inferior(p, curp)) {
    714 			rval = ESRCH;
    715 			goto done;
    716 		}
    717 		/* ... in the same session... */
    718 		if (sess != NULL || p->p_session != curp->p_session)
    719 			goto done;
    720 		/* ... existing pgid must be in same session ... */
    721 		if (pgrp != NULL && pgrp->pg_session != p->p_session)
    722 			goto done;
    723 		/* ... and not done an exec. */
    724 		if (p->p_flag & P_EXEC) {
    725 			rval = EACCES;
    726 			goto done;
    727 		}
    728 	}
    729 
    730 	/* Changing the process group/session of a session
    731 	   leader is definitely off limits. */
    732 	if (SESS_LEADER(p)) {
    733 		if (sess == NULL && p->p_pgrp == pgrp)
    734 			/* unless it's a definite noop */
    735 			rval = 0;
    736 		goto done;
    737 	}
    738 
    739 	/* Can only create a process group with id of process */
    740 	if (pgrp == NULL && pgid != pid)
    741 		goto done;
    742 
    743 	/* Can only create a session if creating pgrp */
    744 	if (sess != NULL && pgrp != NULL)
    745 		goto done;
    746 
    747 	/* Check we allocated memory for a pgrp... */
    748 	if (pgrp == NULL && new_pgrp == NULL)
    749 		goto done;
    750 
    751 	/* Don't attach to 'zombie' pgrp */
    752 	if (pgrp != NULL && LIST_EMPTY(&pgrp->pg_members))
    753 		goto done;
    754 
    755 	/* Expect to succeed now */
    756 	rval = 0;
    757 
    758 	if (pgrp == p->p_pgrp)
    759 		/* nothing to do */
    760 		goto done;
    761 
    762 	/* Ok all setup, link up required structures */
    763 	if (pgrp == NULL) {
    764 		pgrp = new_pgrp;
    765 		new_pgrp = 0;
    766 		if (sess != NULL) {
    767 			sess->s_sid = p->p_pid;
    768 			sess->s_leader = p;
    769 			sess->s_count = 1;
    770 			sess->s_ttyvp = NULL;
    771 			sess->s_ttyp = NULL;
    772 			sess->s_flags = p->p_session->s_flags & ~S_LOGIN_SET;
    773 			memcpy(sess->s_login, p->p_session->s_login,
    774 			    sizeof(sess->s_login));
    775 			p->p_flag &= ~P_CONTROLT;
    776 		} else {
    777 			sess = p->p_pgrp->pg_session;
    778 			SESSHOLD(sess);
    779 		}
    780 		pgrp->pg_session = sess;
    781 		sess = 0;
    782 
    783 		pgrp->pg_id = pgid;
    784 		LIST_INIT(&pgrp->pg_members);
    785 #ifdef DIAGNOSTIC
    786 		if (__predict_false(pid_table[pgid & pid_tbl_mask].pt_pgrp))
    787 			panic("enterpgrp: pgrp table slot in use");
    788 		if (__predict_false(mksess && p != curp))
    789 			panic("enterpgrp: mksession and p != curproc");
    790 #endif
    791 		pid_table[pgid & pid_tbl_mask].pt_pgrp = pgrp;
    792 		pgrp->pg_jobc = 0;
    793 	}
    794 
    795 	/*
    796 	 * Adjust eligibility of affected pgrps to participate in job control.
    797 	 * Increment eligibility counts before decrementing, otherwise we
    798 	 * could reach 0 spuriously during the first call.
    799 	 */
    800 	fixjobc(p, pgrp, 1);
    801 	fixjobc(p, p->p_pgrp, 0);
    802 
    803 	/* Move process to requested group */
    804 	LIST_REMOVE(p, p_pglist);
    805 	if (LIST_EMPTY(&p->p_pgrp->pg_members))
    806 		/* defer delete until we've dumped the lock */
    807 		pg_id = p->p_pgrp->pg_id;
    808 	p->p_pgrp = pgrp;
    809 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
    810 
    811     done:
    812 	proclist_unlock_write(s);
    813 	if (sess != NULL)
    814 		free(sess, M_SESSION);
    815 	if (new_pgrp != NULL)
    816 		pool_put(&pgrp_pool, new_pgrp);
    817 	if (pg_id != NO_PGID)
    818 		pg_delete(pg_id);
    819 #ifdef DEBUG_PGRP
    820 	if (__predict_false(rval))
    821 		printf("enterpgrp(%d,%d,%d), curproc %d, rval %d\n",
    822 			pid, pgid, mksess, curp->p_pid, rval);
    823 #endif
    824 	return rval;
    825 }
    826 
    827 /*
    828  * remove process from process group
    829  */
    830 int
    831 leavepgrp(struct proc *p)
    832 {
    833 	int s;
    834 	struct pgrp *pgrp;
    835 	pid_t pg_id;
    836 
    837 	s = proclist_lock_write();
    838 	pgrp = p->p_pgrp;
    839 	LIST_REMOVE(p, p_pglist);
    840 	p->p_pgrp = 0;
    841 	pg_id = LIST_EMPTY(&pgrp->pg_members) ? pgrp->pg_id : NO_PGID;
    842 	proclist_unlock_write(s);
    843 
    844 	if (pg_id != NO_PGID)
    845 		pg_delete(pg_id);
    846 	return 0;
    847 }
    848 
    849 static void
    850 pg_free(pid_t pg_id)
    851 {
    852 	struct pgrp *pgrp;
    853 	struct pid_table *pt;
    854 	int s;
    855 
    856 	s = proclist_lock_write();
    857 	pt = &pid_table[pg_id & pid_tbl_mask];
    858 	pgrp = pt->pt_pgrp;
    859 #ifdef DIAGNOSTIC
    860 	if (__predict_false(!pgrp || pgrp->pg_id != pg_id
    861 	    || !LIST_EMPTY(&pgrp->pg_members)))
    862 		panic("pg_free: process group absent or has members");
    863 #endif
    864 	pt->pt_pgrp = 0;
    865 
    866 	if (!P_VALID(pt->pt_proc)) {
    867 		/* orphaned pgrp, put slot onto free list */
    868 #ifdef DIAGNOSTIC
    869 		if (__predict_false(P_NEXT(pt->pt_proc) & pid_tbl_mask))
    870 			panic("pg_free: process slot on free list");
    871 #endif
    872 
    873 		pg_id &= pid_tbl_mask;
    874 		pt = &pid_table[last_free_pt];
    875 		pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pg_id);
    876 		last_free_pt = pg_id;
    877 		pid_alloc_cnt--;
    878 	}
    879 	proclist_unlock_write(s);
    880 
    881 	pool_put(&pgrp_pool, pgrp);
    882 }
    883 
    884 /*
    885  * delete a process group
    886  */
    887 static void
    888 pg_delete(pid_t pg_id)
    889 {
    890 	struct pgrp *pgrp;
    891 	struct tty *ttyp;
    892 	struct session *ss;
    893 	int s;
    894 
    895 	s = proclist_lock_write();
    896 	pgrp = pid_table[pg_id & pid_tbl_mask].pt_pgrp;
    897 	if (pgrp == NULL || pgrp->pg_id != pg_id ||
    898 	    !LIST_EMPTY(&pgrp->pg_members)) {
    899 		proclist_unlock_write(s);
    900 		return;
    901 	}
    902 
    903 	/* Remove reference (if any) from tty to this process group */
    904 	ttyp = pgrp->pg_session->s_ttyp;
    905 	if (ttyp != NULL && ttyp->t_pgrp == pgrp)
    906 		ttyp->t_pgrp = NULL;
    907 
    908 	ss = pgrp->pg_session;
    909 
    910 	if (ss->s_sid == pgrp->pg_id) {
    911 		proclist_unlock_write(s);
    912 		SESSRELE(ss);
    913 		/* pgrp freed by sessdelete() if last reference */
    914 		return;
    915 	}
    916 
    917 	proclist_unlock_write(s);
    918 	SESSRELE(ss);
    919 	pg_free(pg_id);
    920 }
    921 
    922 /*
    923  * Delete session - called from SESSRELE when s_count becomes zero.
    924  */
    925 void
    926 sessdelete(struct session *ss)
    927 {
    928 	/*
    929 	 * We keep the pgrp with the same id as the session in
    930 	 * order to stop a process being given the same pid.
    931 	 * Since the pgrp holds a reference to the session, it
    932 	 * must be a 'zombie' pgrp by now.
    933 	 */
    934 
    935 	pg_free(ss->s_sid);
    936 
    937 	FREE(ss, M_SESSION);
    938 }
    939 
    940 /*
    941  * Adjust pgrp jobc counters when specified process changes process group.
    942  * We count the number of processes in each process group that "qualify"
    943  * the group for terminal job control (those with a parent in a different
    944  * process group of the same session).  If that count reaches zero, the
    945  * process group becomes orphaned.  Check both the specified process'
    946  * process group and that of its children.
    947  * entering == 0 => p is leaving specified group.
    948  * entering == 1 => p is entering specified group.
    949  *
    950  * Call with proclist_lock held.
    951  */
    952 void
    953 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
    954 {
    955 	struct pgrp *hispgrp;
    956 	struct session *mysession = pgrp->pg_session;
    957 	struct proc *child;
    958 
    959 	/*
    960 	 * Check p's parent to see whether p qualifies its own process
    961 	 * group; if so, adjust count for p's process group.
    962 	 */
    963 	hispgrp = p->p_pptr->p_pgrp;
    964 	if (hispgrp != pgrp && hispgrp->pg_session == mysession) {
    965 		if (entering)
    966 			pgrp->pg_jobc++;
    967 		else if (--pgrp->pg_jobc == 0)
    968 			orphanpg(pgrp);
    969 	}
    970 
    971 	/*
    972 	 * Check this process' children to see whether they qualify
    973 	 * their process groups; if so, adjust counts for children's
    974 	 * process groups.
    975 	 */
    976 	LIST_FOREACH(child, &p->p_children, p_sibling) {
    977 		hispgrp = child->p_pgrp;
    978 		if (hispgrp != pgrp && hispgrp->pg_session == mysession &&
    979 		    !P_ZOMBIE(child)) {
    980 			if (entering)
    981 				hispgrp->pg_jobc++;
    982 			else if (--hispgrp->pg_jobc == 0)
    983 				orphanpg(hispgrp);
    984 		}
    985 	}
    986 }
    987 
    988 /*
    989  * A process group has become orphaned;
    990  * if there are any stopped processes in the group,
    991  * hang-up all process in that group.
    992  *
    993  * Call with proclist_lock held.
    994  */
    995 static void
    996 orphanpg(struct pgrp *pg)
    997 {
    998 	struct proc *p;
    999 
   1000 	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
   1001 		if (p->p_stat == SSTOP) {
   1002 			LIST_FOREACH(p, &pg->pg_members, p_pglist) {
   1003 				psignal(p, SIGHUP);
   1004 				psignal(p, SIGCONT);
   1005 			}
   1006 			return;
   1007 		}
   1008 	}
   1009 }
   1010 
   1011 /* mark process as suid/sgid, reset some values to defaults */
   1012 void
   1013 p_sugid(struct proc *p)
   1014 {
   1015 	struct plimit *newlim;
   1016 
   1017 	p->p_flag |= P_SUGID;
   1018 	/* reset what needs to be reset in plimit */
   1019 	if (p->p_limit->pl_corename != defcorename) {
   1020 		if (p->p_limit->p_refcnt > 1 &&
   1021 		    (p->p_limit->p_lflags & PL_SHAREMOD) == 0) {
   1022 			newlim = limcopy(p->p_limit);
   1023 			limfree(p->p_limit);
   1024 			p->p_limit = newlim;
   1025 		}
   1026 		free(p->p_limit->pl_corename, M_TEMP);
   1027 		p->p_limit->pl_corename = defcorename;
   1028 	}
   1029 }
   1030 
   1031 #ifdef DDB
   1032 #include <ddb/db_output.h>
   1033 void pidtbl_dump(void);
   1034 void
   1035 pidtbl_dump(void)
   1036 {
   1037 	struct pid_table *pt;
   1038 	struct proc *p;
   1039 	struct pgrp *pgrp;
   1040 	int id;
   1041 
   1042 	db_printf("pid table %p size %x, next %x, last %x\n",
   1043 		pid_table, pid_tbl_mask+1,
   1044 		next_free_pt, last_free_pt);
   1045 	for (pt = pid_table, id = 0; id <= pid_tbl_mask; id++, pt++) {
   1046 		p = pt->pt_proc;
   1047 		if (!P_VALID(p) && !pt->pt_pgrp)
   1048 			continue;
   1049 		db_printf("  id %x: ", id);
   1050 		if (P_VALID(p))
   1051 			db_printf("proc %p id %d (0x%x) %s\n",
   1052 				p, p->p_pid, p->p_pid, p->p_comm);
   1053 		else
   1054 			db_printf("next %x use %x\n",
   1055 				P_NEXT(p) & pid_tbl_mask,
   1056 				P_NEXT(p) & ~pid_tbl_mask);
   1057 		if ((pgrp = pt->pt_pgrp)) {
   1058 			db_printf("\tsession %p, sid %d, count %d, login %s\n",
   1059 			    pgrp->pg_session, pgrp->pg_session->s_sid,
   1060 			    pgrp->pg_session->s_count,
   1061 			    pgrp->pg_session->s_login);
   1062 			db_printf("\tpgrp %p, pg_id %d, pg_jobc %d, members %p\n",
   1063 			    pgrp, pgrp->pg_id, pgrp->pg_jobc,
   1064 			    pgrp->pg_members.lh_first);
   1065 			for (p = pgrp->pg_members.lh_first; p != 0;
   1066 			    p = p->p_pglist.le_next) {
   1067 				db_printf("\t\tpid %d addr %p pgrp %p %s\n",
   1068 				    p->p_pid, p, p->p_pgrp, p->p_comm);
   1069 			}
   1070 		}
   1071 	}
   1072 }
   1073 #endif /* DDB */
   1074 
   1075 #ifdef KSTACK_CHECK_MAGIC
   1076 #include <sys/user.h>
   1077 
   1078 #define	KSTACK_MAGIC	0xdeadbeaf
   1079 
   1080 /* XXX should be per process basis? */
   1081 int kstackleftmin = KSTACK_SIZE;
   1082 int kstackleftthres = KSTACK_SIZE / 8; /* warn if remaining stack is
   1083 					  less than this */
   1084 
   1085 void
   1086 kstack_setup_magic(const struct lwp *l)
   1087 {
   1088 	u_int32_t *ip;
   1089 	u_int32_t const *end;
   1090 
   1091 	KASSERT(l != NULL);
   1092 	KASSERT(l != &lwp0);
   1093 
   1094 	/*
   1095 	 * fill all the stack with magic number
   1096 	 * so that later modification on it can be detected.
   1097 	 */
   1098 	ip = (u_int32_t *)KSTACK_LOWEST_ADDR(l);
   1099 	end = (u_int32_t *)((caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
   1100 	for (; ip < end; ip++) {
   1101 		*ip = KSTACK_MAGIC;
   1102 	}
   1103 }
   1104 
   1105 void
   1106 kstack_check_magic(const struct lwp *l)
   1107 {
   1108 	u_int32_t const *ip, *end;
   1109 	int stackleft;
   1110 
   1111 	KASSERT(l != NULL);
   1112 
   1113 	/* don't check proc0 */ /*XXX*/
   1114 	if (l == &lwp0)
   1115 		return;
   1116 
   1117 #ifdef __MACHINE_STACK_GROWS_UP
   1118 	/* stack grows upwards (eg. hppa) */
   1119 	ip = (u_int32_t *)((caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
   1120 	end = (u_int32_t *)KSTACK_LOWEST_ADDR(l);
   1121 	for (ip--; ip >= end; ip--)
   1122 		if (*ip != KSTACK_MAGIC)
   1123 			break;
   1124 
   1125 	stackleft = (caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE - (caddr_t)ip;
   1126 #else /* __MACHINE_STACK_GROWS_UP */
   1127 	/* stack grows downwards (eg. i386) */
   1128 	ip = (u_int32_t *)KSTACK_LOWEST_ADDR(l);
   1129 	end = (u_int32_t *)((caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
   1130 	for (; ip < end; ip++)
   1131 		if (*ip != KSTACK_MAGIC)
   1132 			break;
   1133 
   1134 	stackleft = (caddr_t)ip - KSTACK_LOWEST_ADDR(l);
   1135 #endif /* __MACHINE_STACK_GROWS_UP */
   1136 
   1137 	if (kstackleftmin > stackleft) {
   1138 		kstackleftmin = stackleft;
   1139 		if (stackleft < kstackleftthres)
   1140 			printf("warning: kernel stack left %d bytes"
   1141 			    "(pid %u:lid %u)\n", stackleft,
   1142 			    (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
   1143 	}
   1144 
   1145 	if (stackleft <= 0) {
   1146 		panic("magic on the top of kernel stack changed for "
   1147 		    "pid %u, lid %u: maybe kernel stack overflow",
   1148 		    (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
   1149 	}
   1150 }
   1151 #endif /* KSTACK_CHECK_MAGIC */
   1152