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