xref: /netbsd-src/sys/kern/kern_proc.c (revision d708163f7f0abab4c3b88f79c8cf7ec8bc530426)
1 /*	$NetBSD: kern_proc.c,v 1.67 2003/11/04 10:33:15 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.67 2003/11/04 10:33:15 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 pfind(pid_t pid)
419 {
420 	struct proc *p;
421 
422 	proclist_lock_read();
423 	p = pid_table[pid & pid_tbl_mask].pt_proc;
424 	/* Only allow live processes to be found by pid. */
425 	if (!P_VALID(p) || p->p_pid != pid ||
426 	    !((1 << SACTIVE | 1 << SSTOP) & 1 << p->p_stat))
427 		p = 0;
428 
429 	/* XXX MP - need to have a reference count... */
430 	proclist_unlock_read();
431 	return p;
432 }
433 
434 
435 /*
436  * Locate a process group by number
437  */
438 struct pgrp *
439 pgfind(pid_t pgid)
440 {
441 	struct pgrp *pgrp;
442 
443 	proclist_lock_read();
444 	pgrp = pid_table[pgid & pid_tbl_mask].pt_pgrp;
445 	/*
446 	 * Can't look up a pgrp that only exists because the session
447 	 * hasn't died yet (traditional)
448 	 */
449 	if (pgrp == NULL || pgrp->pg_id != pgid
450 	    || LIST_EMPTY(&pgrp->pg_members))
451 		pgrp = 0;
452 
453 	/* XXX MP - need to have a reference count... */
454 	proclist_unlock_read();
455 	return pgrp;
456 }
457 
458 /*
459  * Set entry for process 0
460  */
461 void
462 proc0_insert(struct proc *p, struct lwp *l, struct pgrp *pgrp,
463 	struct session *sess)
464 {
465 	int s;
466 
467 	simple_lock_init(&p->p_lock);
468 	LIST_INIT(&p->p_lwps);
469 	LIST_INSERT_HEAD(&p->p_lwps, l, l_sibling);
470 	p->p_nlwps = 1;
471 	simple_lock_init(&p->p_sigctx.ps_silock);
472 	CIRCLEQ_INIT(&p->p_sigctx.ps_siginfo);
473 
474 	s = proclist_lock_write();
475 
476 	pid_table[0].pt_proc = p;
477 	LIST_INSERT_HEAD(&allproc, p, p_list);
478 	LIST_INSERT_HEAD(&alllwp, l, l_list);
479 
480 	p->p_pgrp = pgrp;
481 	pid_table[0].pt_pgrp = pgrp;
482 	LIST_INIT(&pgrp->pg_members);
483 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
484 
485 	pgrp->pg_session = sess;
486 	sess->s_count = 1;
487 	sess->s_sid = 0;
488 	sess->s_leader = p;
489 
490 	proclist_unlock_write(s);
491 }
492 
493 static void
494 expand_pid_table(void)
495 {
496 	uint pt_size = pid_tbl_mask + 1;
497 	struct pid_table *n_pt, *new_pt;
498 	struct proc *proc;
499 	struct pgrp *pgrp;
500 	int i;
501 	int s;
502 	pid_t pid;
503 
504 	new_pt = malloc(pt_size * 2 * sizeof *new_pt, M_PROC, M_WAITOK);
505 
506 	s = proclist_lock_write();
507 	if (pt_size != pid_tbl_mask + 1) {
508 		/* Another process beat us to it... */
509 		proclist_unlock_write(s);
510 		FREE(new_pt, M_PROC);
511 		return;
512 	}
513 
514 	/*
515 	 * Copy entries from old table into new one.
516 	 * If 'pid' is 'odd' we need to place in the upper half,
517 	 * even pid's to the lower half.
518 	 * Free items stay in the low half so we don't have to
519 	 * fixup the reference to them.
520 	 * We stuff free items on the front of the freelist
521 	 * because we can't write to unmodified entries.
522 	 * Processing the table backwards maintians a semblance
523 	 * of issueing pid numbers that increase with time.
524 	 */
525 	i = pt_size - 1;
526 	n_pt = new_pt + i;
527 	for (; ; i--, n_pt--) {
528 		proc = pid_table[i].pt_proc;
529 		pgrp = pid_table[i].pt_pgrp;
530 		if (!P_VALID(proc)) {
531 			/* Up 'use count' so that link is valid */
532 			pid = (P_NEXT(proc) + pt_size) & ~pt_size;
533 			proc = P_FREE(pid);
534 			if (pgrp)
535 				pid = pgrp->pg_id;
536 		} else
537 			pid = proc->p_pid;
538 
539 		/* Save entry in appropriate half of table */
540 		n_pt[pid & pt_size].pt_proc = proc;
541 		n_pt[pid & pt_size].pt_pgrp = pgrp;
542 
543 		/* Put other piece on start of free list */
544 		pid = (pid ^ pt_size) & ~pid_tbl_mask;
545 		n_pt[pid & pt_size].pt_proc =
546 				    P_FREE((pid & ~pt_size) | next_free_pt);
547 		n_pt[pid & pt_size].pt_pgrp = 0;
548 		next_free_pt = i | (pid & pt_size);
549 		if (i == 0)
550 			break;
551 	}
552 
553 	/* Switch tables */
554 	n_pt = pid_table;
555 	pid_table = new_pt;
556 	pid_tbl_mask = pt_size * 2 - 1;
557 
558 	/*
559 	 * pid_max starts as PID_MAX (= 30000), once we have 16384
560 	 * allocated pids we need it to be larger!
561 	 */
562 	if (pid_tbl_mask > PID_MAX) {
563 		pid_max = pid_tbl_mask * 2 + 1;
564 		pid_alloc_lim |= pid_alloc_lim << 1;
565 	} else
566 		pid_alloc_lim <<= 1;	/* doubles number of free slots... */
567 
568 	proclist_unlock_write(s);
569 	FREE(n_pt, M_PROC);
570 }
571 
572 struct proc *
573 proc_alloc(void)
574 {
575 	struct proc *p;
576 	int s;
577 	int nxt;
578 	pid_t pid;
579 	struct pid_table *pt;
580 
581 	p = pool_get(&proc_pool, PR_WAITOK);
582 	p->p_stat = SIDL;			/* protect against others */
583 
584 	/* allocate next free pid */
585 
586 	for (;;expand_pid_table()) {
587 		if (__predict_false(pid_alloc_cnt >= pid_alloc_lim))
588 			/* ensure pids cycle through 2000+ values */
589 			continue;
590 		s = proclist_lock_write();
591 		pt = &pid_table[next_free_pt];
592 #ifdef DIAGNOSTIC
593 		if (__predict_false(P_VALID(pt->pt_proc) || pt->pt_pgrp))
594 			panic("proc_alloc: slot busy");
595 #endif
596 		nxt = P_NEXT(pt->pt_proc);
597 		if (nxt & pid_tbl_mask)
598 			break;
599 		/* Table full - expand (NB last entry not used....) */
600 		proclist_unlock_write(s);
601 	}
602 
603 	/* pid is 'saved use count' + 'size' + entry */
604 	pid = (nxt & ~pid_tbl_mask) + pid_tbl_mask + 1 + next_free_pt;
605 	if ((uint)pid > (uint)pid_max)
606 		pid &= pid_tbl_mask;
607 	p->p_pid = pid;
608 	next_free_pt = nxt & pid_tbl_mask;
609 
610 	/* Grab table slot */
611 	pt->pt_proc = p;
612 	pid_alloc_cnt++;
613 
614 	proclist_unlock_write(s);
615 
616 	return p;
617 }
618 
619 /*
620  * Free last resources of a process - called from proc_free (in kern_exit.c)
621  */
622 void
623 proc_free_mem(struct proc *p)
624 {
625 	int s;
626 	pid_t pid = p->p_pid;
627 	struct pid_table *pt;
628 
629 	s = proclist_lock_write();
630 
631 	pt = &pid_table[pid & pid_tbl_mask];
632 #ifdef DIAGNOSTIC
633 	if (__predict_false(pt->pt_proc != p))
634 		panic("proc_free: pid_table mismatch, pid %x, proc %p",
635 			pid, p);
636 #endif
637 	/* save pid use count in slot */
638 	pt->pt_proc = P_FREE(pid & ~pid_tbl_mask);
639 
640 	if (pt->pt_pgrp == NULL) {
641 		/* link last freed entry onto ours */
642 		pid &= pid_tbl_mask;
643 		pt = &pid_table[last_free_pt];
644 		pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pid);
645 		last_free_pt = pid;
646 		pid_alloc_cnt--;
647 	}
648 
649 	nprocs--;
650 	proclist_unlock_write(s);
651 
652 	pool_put(&proc_pool, p);
653 }
654 
655 /*
656  * Move p to a new or existing process group (and session)
657  *
658  * If we are creating a new pgrp, the pgid should equal
659  * the calling processes pid.
660  * If is only valid to enter a process group that is in the session
661  * of the process.
662  * Also mksess should only be set if we are creating a process group
663  *
664  * Only called from sys_setsid, sys_setpgid/sys_setprp and the
665  * SYSV setpgrp support for hpux == enterpgrp(curproc, curproc->p_pid)
666  */
667 int
668 enterpgrp(struct proc *p, pid_t pgid, int mksess)
669 {
670 	struct pgrp *new_pgrp, *pgrp;
671 	struct session *sess;
672 	struct proc *curp = curproc;
673 	pid_t pid = p->p_pid;
674 	int rval;
675 	int s;
676 	pid_t pg_id = NO_PGID;
677 
678 	/* Allocate data areas we might need before doing any validity checks */
679 	proclist_lock_read();		/* Because pid_table might change */
680 	if (pid_table[pgid & pid_tbl_mask].pt_pgrp == 0) {
681 		proclist_unlock_read();
682 		new_pgrp = pool_get(&pgrp_pool, PR_WAITOK);
683 	} else {
684 		proclist_unlock_read();
685 		new_pgrp = NULL;
686 	}
687 	if (mksess)
688 		MALLOC(sess, struct session *, sizeof(struct session),
689 			    M_SESSION, M_WAITOK);
690 	else
691 		sess = NULL;
692 
693 	s = proclist_lock_write();
694 	rval = EPERM;	/* most common error (to save typing) */
695 
696 	/* Check pgrp exists or can be created */
697 	pgrp = pid_table[pgid & pid_tbl_mask].pt_pgrp;
698 	if (pgrp != NULL && pgrp->pg_id != pgid)
699 		goto done;
700 
701 	/* Can only set another process under restricted circumstances. */
702 	if (p != curp) {
703 		/* must exist and be one of our children... */
704 		if (p != pid_table[pid & pid_tbl_mask].pt_proc
705 		    || !inferior(p, curp)) {
706 			rval = ESRCH;
707 			goto done;
708 		}
709 		/* ... in the same session... */
710 		if (sess != NULL || p->p_session != curp->p_session)
711 			goto done;
712 		/* ... existing pgid must be in same session ... */
713 		if (pgrp != NULL && pgrp->pg_session != p->p_session)
714 			goto done;
715 		/* ... and not done an exec. */
716 		if (p->p_flag & P_EXEC) {
717 			rval = EACCES;
718 			goto done;
719 		}
720 	}
721 
722 	/* Changing the process group/session of a session
723 	   leader is definitely off limits. */
724 	if (SESS_LEADER(p)) {
725 		if (sess == NULL && p->p_pgrp == pgrp)
726 			/* unless it's a definite noop */
727 			rval = 0;
728 		goto done;
729 	}
730 
731 	/* Can only create a process group with id of process */
732 	if (pgrp == NULL && pgid != pid)
733 		goto done;
734 
735 	/* Can only create a session if creating pgrp */
736 	if (sess != NULL && pgrp != NULL)
737 		goto done;
738 
739 	/* Check we allocated memory for a pgrp... */
740 	if (pgrp == NULL && new_pgrp == NULL)
741 		goto done;
742 
743 	/* Don't attach to 'zombie' pgrp */
744 	if (pgrp != NULL && LIST_EMPTY(&pgrp->pg_members))
745 		goto done;
746 
747 	/* Expect to succeed now */
748 	rval = 0;
749 
750 	if (pgrp == p->p_pgrp)
751 		/* nothing to do */
752 		goto done;
753 
754 	/* Ok all setup, link up required structures */
755 	if (pgrp == NULL) {
756 		pgrp = new_pgrp;
757 		new_pgrp = 0;
758 		if (sess != NULL) {
759 			sess->s_sid = p->p_pid;
760 			sess->s_leader = p;
761 			sess->s_count = 1;
762 			sess->s_ttyvp = NULL;
763 			sess->s_ttyp = NULL;
764 			sess->s_flags = p->p_session->s_flags & ~S_LOGIN_SET;
765 			memcpy(sess->s_login, p->p_session->s_login,
766 			    sizeof(sess->s_login));
767 			p->p_flag &= ~P_CONTROLT;
768 		} else {
769 			sess = p->p_pgrp->pg_session;
770 			SESSHOLD(sess);
771 		}
772 		pgrp->pg_session = sess;
773 		sess = 0;
774 
775 		pgrp->pg_id = pgid;
776 		LIST_INIT(&pgrp->pg_members);
777 #ifdef DIAGNOSTIC
778 		if (__predict_false(pid_table[pgid & pid_tbl_mask].pt_pgrp))
779 			panic("enterpgrp: pgrp table slot in use");
780 		if (__predict_false(mksess && p != curp))
781 			panic("enterpgrp: mksession and p != curproc");
782 #endif
783 		pid_table[pgid & pid_tbl_mask].pt_pgrp = pgrp;
784 		pgrp->pg_jobc = 0;
785 	}
786 
787 	/*
788 	 * Adjust eligibility of affected pgrps to participate in job control.
789 	 * Increment eligibility counts before decrementing, otherwise we
790 	 * could reach 0 spuriously during the first call.
791 	 */
792 	fixjobc(p, pgrp, 1);
793 	fixjobc(p, p->p_pgrp, 0);
794 
795 	/* Move process to requested group */
796 	LIST_REMOVE(p, p_pglist);
797 	if (LIST_EMPTY(&p->p_pgrp->pg_members))
798 		/* defer delete until we've dumped the lock */
799 		pg_id = p->p_pgrp->pg_id;
800 	p->p_pgrp = pgrp;
801 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
802 
803     done:
804 	proclist_unlock_write(s);
805 	if (sess != NULL)
806 		free(sess, M_SESSION);
807 	if (new_pgrp != NULL)
808 		pool_put(&pgrp_pool, new_pgrp);
809 	if (pg_id != NO_PGID)
810 		pg_delete(pg_id);
811 #ifdef DEBUG_PGRP
812 	if (__predict_false(rval))
813 		printf("enterpgrp(%d,%d,%d), curproc %d, rval %d\n",
814 			pid, pgid, mksess, curp->p_pid, rval);
815 #endif
816 	return rval;
817 }
818 
819 /*
820  * remove process from process group
821  */
822 int
823 leavepgrp(struct proc *p)
824 {
825 	int s = proclist_lock_write();
826 	struct pgrp *pgrp;
827 	pid_t pg_id;
828 
829 	pgrp = p->p_pgrp;
830 	LIST_REMOVE(p, p_pglist);
831 	p->p_pgrp = 0;
832 	pg_id = LIST_EMPTY(&pgrp->pg_members) ? pgrp->pg_id : NO_PGID;
833 	proclist_unlock_write(s);
834 
835 	if (pg_id != NO_PGID)
836 		pg_delete(pg_id);
837 	return 0;
838 }
839 
840 static void
841 pg_free(pid_t pg_id)
842 {
843 	struct pgrp *pgrp;
844 	struct pid_table *pt;
845 	int s;
846 
847 	s = proclist_lock_write();
848 	pt = &pid_table[pg_id & pid_tbl_mask];
849 	pgrp = pt->pt_pgrp;
850 #ifdef DIAGNOSTIC
851 	if (__predict_false(!pgrp || pgrp->pg_id != pg_id
852 	    || !LIST_EMPTY(&pgrp->pg_members)))
853 		panic("pg_free: process group absent or has members");
854 #endif
855 	pt->pt_pgrp = 0;
856 
857 	if (!P_VALID(pt->pt_proc)) {
858 		/* orphaned pgrp, put slot onto free list */
859 #ifdef DIAGNOSTIC
860 		if (__predict_false(P_NEXT(pt->pt_proc) & pid_tbl_mask))
861 			panic("pg_free: process slot on free list");
862 #endif
863 
864 		pg_id &= pid_tbl_mask;
865 		pt = &pid_table[last_free_pt];
866 		pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pg_id);
867 		last_free_pt = pg_id;
868 		pid_alloc_cnt--;
869 	}
870 	proclist_unlock_write(s);
871 
872 	pool_put(&pgrp_pool, pgrp);
873 }
874 
875 /*
876  * delete a process group
877  */
878 static void
879 pg_delete(pid_t pg_id)
880 {
881 	struct pgrp *pgrp;
882 	struct tty *ttyp;
883 	struct session *ss;
884 	int s;
885 
886 	s = proclist_lock_write();
887 	pgrp = pid_table[pg_id & pid_tbl_mask].pt_pgrp;
888 	if (pgrp == NULL || pgrp->pg_id != pg_id ||
889 	    !LIST_EMPTY(&pgrp->pg_members)) {
890 		proclist_unlock_write(s);
891 		return;
892 	}
893 
894 	/* Remove reference (if any) from tty to this process group */
895 	ttyp = pgrp->pg_session->s_ttyp;
896 	if (ttyp != NULL && ttyp->t_pgrp == pgrp)
897 		ttyp->t_pgrp = NULL;
898 
899 	ss = pgrp->pg_session;
900 
901 	if (ss->s_sid == pgrp->pg_id) {
902 		proclist_unlock_write(s);
903 		SESSRELE(ss);
904 		/* pgrp freed by sessdelete() if last reference */
905 		return;
906 	}
907 
908 	proclist_unlock_write(s);
909 	SESSRELE(ss);
910 	pg_free(pg_id);
911 }
912 
913 /*
914  * Delete session - called from SESSRELE when s_count becomes zero.
915  */
916 void
917 sessdelete(struct session *ss)
918 {
919 	/*
920 	 * We keep the pgrp with the same id as the session in
921 	 * order to stop a process being given the same pid.
922 	 * Since the pgrp holds a reference to the session, it
923 	 * must be a 'zombie' pgrp by now.
924 	 */
925 
926 	pg_free(ss->s_sid);
927 
928 	FREE(ss, M_SESSION);
929 }
930 
931 /*
932  * Adjust pgrp jobc counters when specified process changes process group.
933  * We count the number of processes in each process group that "qualify"
934  * the group for terminal job control (those with a parent in a different
935  * process group of the same session).  If that count reaches zero, the
936  * process group becomes orphaned.  Check both the specified process'
937  * process group and that of its children.
938  * entering == 0 => p is leaving specified group.
939  * entering == 1 => p is entering specified group.
940  */
941 void
942 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
943 {
944 	struct pgrp *hispgrp;
945 	struct session *mysession = pgrp->pg_session;
946 
947 	/*
948 	 * Check p's parent to see whether p qualifies its own process
949 	 * group; if so, adjust count for p's process group.
950 	 */
951 	if ((hispgrp = p->p_pptr->p_pgrp) != pgrp &&
952 	    hispgrp->pg_session == mysession) {
953 		if (entering)
954 			pgrp->pg_jobc++;
955 		else if (--pgrp->pg_jobc == 0)
956 			orphanpg(pgrp);
957 	}
958 
959 	/*
960 	 * Check this process' children to see whether they qualify
961 	 * their process groups; if so, adjust counts for children's
962 	 * process groups.
963 	 */
964 	LIST_FOREACH(p, &p->p_children, p_sibling) {
965 		if ((hispgrp = p->p_pgrp) != pgrp &&
966 		    hispgrp->pg_session == mysession &&
967 		    P_ZOMBIE(p) == 0) {
968 			if (entering)
969 				hispgrp->pg_jobc++;
970 			else if (--hispgrp->pg_jobc == 0)
971 				orphanpg(hispgrp);
972 		}
973 	}
974 }
975 
976 /*
977  * A process group has become orphaned;
978  * if there are any stopped processes in the group,
979  * hang-up all process in that group.
980  */
981 static void
982 orphanpg(struct pgrp *pg)
983 {
984 	struct proc *p;
985 
986 	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
987 		if (p->p_stat == SSTOP) {
988 			LIST_FOREACH(p, &pg->pg_members, p_pglist) {
989 				psignal(p, SIGHUP);
990 				psignal(p, SIGCONT);
991 			}
992 			return;
993 		}
994 	}
995 }
996 
997 /* mark process as suid/sgid, reset some values to defaults */
998 void
999 p_sugid(struct proc *p)
1000 {
1001 	struct plimit *newlim;
1002 
1003 	p->p_flag |= P_SUGID;
1004 	/* reset what needs to be reset in plimit */
1005 	if (p->p_limit->pl_corename != defcorename) {
1006 		if (p->p_limit->p_refcnt > 1 &&
1007 		    (p->p_limit->p_lflags & PL_SHAREMOD) == 0) {
1008 			newlim = limcopy(p->p_limit);
1009 			limfree(p->p_limit);
1010 			p->p_limit = newlim;
1011 		}
1012 		free(p->p_limit->pl_corename, M_TEMP);
1013 		p->p_limit->pl_corename = defcorename;
1014 	}
1015 }
1016 
1017 #ifdef DDB
1018 #include <ddb/db_output.h>
1019 void pidtbl_dump(void);
1020 void
1021 pidtbl_dump(void)
1022 {
1023 	struct pid_table *pt;
1024 	struct proc *p;
1025 	struct pgrp *pgrp;
1026 	int id;
1027 
1028 	db_printf("pid table %p size %x, next %x, last %x\n",
1029 		pid_table, pid_tbl_mask+1,
1030 		next_free_pt, last_free_pt);
1031 	for (pt = pid_table, id = 0; id <= pid_tbl_mask; id++, pt++) {
1032 		p = pt->pt_proc;
1033 		if (!P_VALID(p) && !pt->pt_pgrp)
1034 			continue;
1035 		db_printf("  id %x: ", id);
1036 		if (P_VALID(p))
1037 			db_printf("proc %p id %d (0x%x) %s\n",
1038 				p, p->p_pid, p->p_pid, p->p_comm);
1039 		else
1040 			db_printf("next %x use %x\n",
1041 				P_NEXT(p) & pid_tbl_mask,
1042 				P_NEXT(p) & ~pid_tbl_mask);
1043 		if ((pgrp = pt->pt_pgrp)) {
1044 			db_printf("\tsession %p, sid %d, count %d, login %s\n",
1045 			    pgrp->pg_session, pgrp->pg_session->s_sid,
1046 			    pgrp->pg_session->s_count,
1047 			    pgrp->pg_session->s_login);
1048 			db_printf("\tpgrp %p, pg_id %d, pg_jobc %d, members %p\n",
1049 			    pgrp, pgrp->pg_id, pgrp->pg_jobc,
1050 			    pgrp->pg_members.lh_first);
1051 			for (p = pgrp->pg_members.lh_first; p != 0;
1052 			    p = p->p_pglist.le_next) {
1053 				db_printf("\t\tpid %d addr %p pgrp %p %s\n",
1054 				    p->p_pid, p, p->p_pgrp, p->p_comm);
1055 			}
1056 		}
1057 	}
1058 }
1059 #endif /* DDB */
1060 
1061 #ifdef KSTACK_CHECK_MAGIC
1062 #include <sys/user.h>
1063 
1064 #define	KSTACK_MAGIC	0xdeadbeaf
1065 
1066 /* XXX should be per process basis? */
1067 int kstackleftmin = KSTACK_SIZE;
1068 int kstackleftthres = KSTACK_SIZE / 8; /* warn if remaining stack is
1069 					  less than this */
1070 
1071 void
1072 kstack_setup_magic(const struct lwp *l)
1073 {
1074 	u_int32_t *ip;
1075 	u_int32_t const *end;
1076 
1077 	KASSERT(l != NULL);
1078 	KASSERT(l != &lwp0);
1079 
1080 	/*
1081 	 * fill all the stack with magic number
1082 	 * so that later modification on it can be detected.
1083 	 */
1084 	ip = (u_int32_t *)KSTACK_LOWEST_ADDR(l);
1085 	end = (u_int32_t *)((caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
1086 	for (; ip < end; ip++) {
1087 		*ip = KSTACK_MAGIC;
1088 	}
1089 }
1090 
1091 void
1092 kstack_check_magic(const struct lwp *l)
1093 {
1094 	u_int32_t const *ip, *end;
1095 	int stackleft;
1096 
1097 	KASSERT(l != NULL);
1098 
1099 	/* don't check proc0 */ /*XXX*/
1100 	if (l == &lwp0)
1101 		return;
1102 
1103 #ifdef __MACHINE_STACK_GROWS_UP
1104 	/* stack grows upwards (eg. hppa) */
1105 	ip = (u_int32_t *)((caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
1106 	end = (u_int32_t *)KSTACK_LOWEST_ADDR(l);
1107 	for (ip--; ip >= end; ip--)
1108 		if (*ip != KSTACK_MAGIC)
1109 			break;
1110 
1111 	stackleft = (caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE - (caddr_t)ip;
1112 #else /* __MACHINE_STACK_GROWS_UP */
1113 	/* stack grows downwards (eg. i386) */
1114 	ip = (u_int32_t *)KSTACK_LOWEST_ADDR(l);
1115 	end = (u_int32_t *)((caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
1116 	for (; ip < end; ip++)
1117 		if (*ip != KSTACK_MAGIC)
1118 			break;
1119 
1120 	stackleft = (caddr_t)ip - KSTACK_LOWEST_ADDR(l);
1121 #endif /* __MACHINE_STACK_GROWS_UP */
1122 
1123 	if (kstackleftmin > stackleft) {
1124 		kstackleftmin = stackleft;
1125 		if (stackleft < kstackleftthres)
1126 			printf("warning: kernel stack left %d bytes"
1127 			    "(pid %u:lid %u)\n", stackleft,
1128 			    (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
1129 	}
1130 
1131 	if (stackleft <= 0) {
1132 		panic("magic on the top of kernel stack changed for "
1133 		    "pid %u, lid %u: maybe kernel stack overflow",
1134 		    (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
1135 	}
1136 }
1137 #endif /* KSTACK_CHECK_MAGIC */
1138