xref: /netbsd-src/sys/kern/kern_proc.c (revision d877c4c3c02304002c0642d7f34a58d07138d6a9)
1 /*	$NetBSD: kern_proc.c,v 1.150 2009/04/16 14:56:41 rmind Exp $	*/
2 
3 /*-
4  * Copyright (c) 1999, 2006, 2007, 2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9  * NASA Ames Research Center, and by Andrew Doran.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * Copyright (c) 1982, 1986, 1989, 1991, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. Neither the name of the University nor the names of its contributors
46  *    may be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  *
61  *	@(#)kern_proc.c	8.7 (Berkeley) 2/14/95
62  */
63 
64 #include <sys/cdefs.h>
65 __KERNEL_RCSID(0, "$NetBSD: kern_proc.c,v 1.150 2009/04/16 14:56:41 rmind Exp $");
66 
67 #include "opt_kstack.h"
68 #include "opt_maxuprc.h"
69 
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/kernel.h>
73 #include <sys/proc.h>
74 #include <sys/resourcevar.h>
75 #include <sys/buf.h>
76 #include <sys/acct.h>
77 #include <sys/wait.h>
78 #include <sys/file.h>
79 #include <ufs/ufs/quota.h>
80 #include <sys/uio.h>
81 #include <sys/pool.h>
82 #include <sys/pset.h>
83 #include <sys/mbuf.h>
84 #include <sys/ioctl.h>
85 #include <sys/tty.h>
86 #include <sys/signalvar.h>
87 #include <sys/ras.h>
88 #include <sys/sa.h>
89 #include <sys/savar.h>
90 #include <sys/filedesc.h>
91 #include "sys/syscall_stats.h"
92 #include <sys/kauth.h>
93 #include <sys/sleepq.h>
94 #include <sys/atomic.h>
95 #include <sys/kmem.h>
96 
97 #include <uvm/uvm.h>
98 #include <uvm/uvm_extern.h>
99 
100 /*
101  * Other process lists
102  */
103 
104 struct proclist allproc;
105 struct proclist zombproc;	/* resources have been freed */
106 
107 kmutex_t	*proc_lock;
108 
109 /*
110  * pid to proc lookup is done by indexing the pid_table array.
111  * Since pid numbers are only allocated when an empty slot
112  * has been found, there is no need to search any lists ever.
113  * (an orphaned pgrp will lock the slot, a session will lock
114  * the pgrp with the same number.)
115  * If the table is too small it is reallocated with twice the
116  * previous size and the entries 'unzipped' into the two halves.
117  * A linked list of free entries is passed through the pt_proc
118  * field of 'free' items - set odd to be an invalid ptr.
119  */
120 
121 struct pid_table {
122 	struct proc	*pt_proc;
123 	struct pgrp	*pt_pgrp;
124 };
125 #if 1	/* strongly typed cast - should be a noop */
126 static inline uint p2u(struct proc *p) { return (uint)(uintptr_t)p; }
127 #else
128 #define p2u(p) ((uint)p)
129 #endif
130 #define P_VALID(p) (!(p2u(p) & 1))
131 #define P_NEXT(p) (p2u(p) >> 1)
132 #define P_FREE(pid) ((struct proc *)(uintptr_t)((pid) << 1 | 1))
133 
134 #define INITIAL_PID_TABLE_SIZE	(1 << 5)
135 static struct pid_table *pid_table;
136 static uint pid_tbl_mask = INITIAL_PID_TABLE_SIZE - 1;
137 static uint pid_alloc_lim;	/* max we allocate before growing table */
138 static uint pid_alloc_cnt;	/* number of allocated pids */
139 
140 /* links through free slots - never empty! */
141 static uint next_free_pt, last_free_pt;
142 static pid_t pid_max = PID_MAX;		/* largest value we allocate */
143 
144 /* Components of the first process -- never freed. */
145 
146 extern struct emul emul_netbsd;	/* defined in kern_exec.c */
147 
148 struct session session0 = {
149 	.s_count = 1,
150 	.s_sid = 0,
151 };
152 struct pgrp pgrp0 = {
153 	.pg_members = LIST_HEAD_INITIALIZER(&pgrp0.pg_members),
154 	.pg_session = &session0,
155 };
156 filedesc_t filedesc0;
157 struct cwdinfo cwdi0 = {
158 	.cwdi_cmask = CMASK,		/* see cmask below */
159 	.cwdi_refcnt = 1,
160 };
161 struct plimit limit0;
162 struct pstats pstat0;
163 struct vmspace vmspace0;
164 struct sigacts sigacts0;
165 struct turnstile turnstile0;
166 struct proc proc0 = {
167 	.p_lwps = LIST_HEAD_INITIALIZER(&proc0.p_lwps),
168 	.p_sigwaiters = LIST_HEAD_INITIALIZER(&proc0.p_sigwaiters),
169 	.p_nlwps = 1,
170 	.p_nrlwps = 1,
171 	.p_nlwpid = 1,		/* must match lwp0.l_lid */
172 	.p_pgrp = &pgrp0,
173 	.p_comm = "system",
174 	/*
175 	 * Set P_NOCLDWAIT so that kernel threads are reparented to init(8)
176 	 * when they exit.  init(8) can easily wait them out for us.
177 	 */
178 	.p_flag = PK_SYSTEM | PK_NOCLDWAIT,
179 	.p_stat = SACTIVE,
180 	.p_nice = NZERO,
181 	.p_emul = &emul_netbsd,
182 	.p_cwdi = &cwdi0,
183 	.p_limit = &limit0,
184 	.p_fd = &filedesc0,
185 	.p_vmspace = &vmspace0,
186 	.p_stats = &pstat0,
187 	.p_sigacts = &sigacts0,
188 };
189 struct lwp lwp0 __aligned(MIN_LWP_ALIGNMENT) = {
190 #ifdef LWP0_CPU_INFO
191 	.l_cpu = LWP0_CPU_INFO,
192 #endif
193 	.l_proc = &proc0,
194 	.l_lid = 1,
195 	.l_flag = LW_INMEM | LW_SYSTEM,
196 	.l_stat = LSONPROC,
197 	.l_ts = &turnstile0,
198 	.l_syncobj = &sched_syncobj,
199 	.l_refcnt = 1,
200 	.l_priority = PRI_USER + NPRI_USER - 1,
201 	.l_inheritedprio = -1,
202 	.l_class = SCHED_OTHER,
203 	.l_psid = PS_NONE,
204 	.l_pi_lenders = SLIST_HEAD_INITIALIZER(&lwp0.l_pi_lenders),
205 	.l_name = __UNCONST("swapper"),
206 };
207 kauth_cred_t cred0;
208 
209 extern struct user *proc0paddr;
210 
211 int nofile = NOFILE;
212 int maxuprc = MAXUPRC;
213 int cmask = CMASK;
214 
215 MALLOC_DEFINE(M_EMULDATA, "emuldata", "Per-process emulation data");
216 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
217 
218 /*
219  * The process list descriptors, used during pid allocation and
220  * by sysctl.  No locking on this data structure is needed since
221  * it is completely static.
222  */
223 const struct proclist_desc proclists[] = {
224 	{ &allproc	},
225 	{ &zombproc	},
226 	{ NULL		},
227 };
228 
229 static void orphanpg(struct pgrp *);
230 static void pg_delete(pid_t);
231 
232 static specificdata_domain_t proc_specificdata_domain;
233 
234 static pool_cache_t proc_cache;
235 
236 /*
237  * Initialize global process hashing structures.
238  */
239 void
240 procinit(void)
241 {
242 	const struct proclist_desc *pd;
243 	u_int i;
244 #define	LINK_EMPTY ((PID_MAX + INITIAL_PID_TABLE_SIZE) & ~(INITIAL_PID_TABLE_SIZE - 1))
245 
246 	for (pd = proclists; pd->pd_list != NULL; pd++)
247 		LIST_INIT(pd->pd_list);
248 
249 	proc_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
250 	pid_table = kmem_alloc(INITIAL_PID_TABLE_SIZE
251 	    * sizeof(struct pid_table), KM_SLEEP);
252 
253 	/* Set free list running through table...
254 	   Preset 'use count' above PID_MAX so we allocate pid 1 next. */
255 	for (i = 0; i <= pid_tbl_mask; i++) {
256 		pid_table[i].pt_proc = P_FREE(LINK_EMPTY + i + 1);
257 		pid_table[i].pt_pgrp = 0;
258 	}
259 	/* slot 0 is just grabbed */
260 	next_free_pt = 1;
261 	/* Need to fix last entry. */
262 	last_free_pt = pid_tbl_mask;
263 	pid_table[last_free_pt].pt_proc = P_FREE(LINK_EMPTY);
264 	/* point at which we grow table - to avoid reusing pids too often */
265 	pid_alloc_lim = pid_tbl_mask - 1;
266 #undef LINK_EMPTY
267 
268 	proc_specificdata_domain = specificdata_domain_create();
269 	KASSERT(proc_specificdata_domain != NULL);
270 
271 	proc_cache = pool_cache_init(sizeof(struct proc), 0, 0, 0,
272 	    "procpl", NULL, IPL_NONE, NULL, NULL, NULL);
273 }
274 
275 /*
276  * Initialize process 0.
277  */
278 void
279 proc0_init(void)
280 {
281 	struct proc *p;
282 	struct pgrp *pg;
283 	struct session *sess;
284 	struct lwp *l;
285 	rlim_t lim;
286 	int i;
287 
288 	p = &proc0;
289 	pg = &pgrp0;
290 	sess = &session0;
291 	l = &lwp0;
292 
293 	KASSERT(l->l_lid == p->p_nlwpid);
294 
295 	mutex_init(&p->p_stmutex, MUTEX_DEFAULT, IPL_HIGH);
296 	mutex_init(&p->p_auxlock, MUTEX_DEFAULT, IPL_NONE);
297 	mutex_init(&l->l_swaplock, MUTEX_DEFAULT, IPL_NONE);
298 	p->p_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
299 
300 	rw_init(&p->p_reflock);
301 	cv_init(&p->p_waitcv, "wait");
302 	cv_init(&p->p_lwpcv, "lwpwait");
303 
304 	LIST_INSERT_HEAD(&p->p_lwps, l, l_sibling);
305 
306 	pid_table[0].pt_proc = p;
307 	LIST_INSERT_HEAD(&allproc, p, p_list);
308 	LIST_INSERT_HEAD(&alllwp, l, l_list);
309 
310 	pid_table[0].pt_pgrp = pg;
311 	LIST_INSERT_HEAD(&pg->pg_members, p, p_pglist);
312 
313 #ifdef __HAVE_SYSCALL_INTERN
314 	(*p->p_emul->e_syscall_intern)(p);
315 #endif
316 
317 	callout_init(&l->l_timeout_ch, CALLOUT_MPSAFE);
318 	callout_setfunc(&l->l_timeout_ch, sleepq_timeout, l);
319 	cv_init(&l->l_sigcv, "sigwait");
320 
321 	/* Create credentials. */
322 	cred0 = kauth_cred_alloc();
323 	p->p_cred = cred0;
324 	kauth_cred_hold(cred0);
325 	l->l_cred = cred0;
326 
327 	/* Create the CWD info. */
328 	rw_init(&cwdi0.cwdi_lock);
329 
330 	/* Create the limits structures. */
331 	mutex_init(&limit0.pl_lock, MUTEX_DEFAULT, IPL_NONE);
332 	for (i = 0; i < __arraycount(limit0.pl_rlimit); i++)
333 		limit0.pl_rlimit[i].rlim_cur =
334 		    limit0.pl_rlimit[i].rlim_max = RLIM_INFINITY;
335 
336 	limit0.pl_rlimit[RLIMIT_NOFILE].rlim_max = maxfiles;
337 	limit0.pl_rlimit[RLIMIT_NOFILE].rlim_cur =
338 	    maxfiles < nofile ? maxfiles : nofile;
339 
340 	limit0.pl_rlimit[RLIMIT_NPROC].rlim_max = maxproc;
341 	limit0.pl_rlimit[RLIMIT_NPROC].rlim_cur =
342 	    maxproc < maxuprc ? maxproc : maxuprc;
343 
344 	lim = ptoa(uvmexp.free);
345 	limit0.pl_rlimit[RLIMIT_RSS].rlim_max = lim;
346 	limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_max = lim;
347 	limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_cur = lim / 3;
348 	limit0.pl_corename = defcorename;
349 	limit0.pl_refcnt = 1;
350 	limit0.pl_sv_limit = NULL;
351 
352 	/* Configure virtual memory system, set vm rlimits. */
353 	uvm_init_limits(p);
354 
355 	/* Initialize file descriptor table for proc0. */
356 	fd_init(&filedesc0);
357 
358 	/*
359 	 * Initialize proc0's vmspace, which uses the kernel pmap.
360 	 * All kernel processes (which never have user space mappings)
361 	 * share proc0's vmspace, and thus, the kernel pmap.
362 	 */
363 	uvmspace_init(&vmspace0, pmap_kernel(), round_page(VM_MIN_ADDRESS),
364 	    trunc_page(VM_MAX_ADDRESS));
365 
366 	l->l_addr = proc0paddr;				/* XXX */
367 
368 	/* Initialize signal state for proc0. XXX IPL_SCHED */
369 	mutex_init(&p->p_sigacts->sa_mutex, MUTEX_DEFAULT, IPL_SCHED);
370 	siginit(p);
371 
372 	proc_initspecific(p);
373 	lwp_initspecific(l);
374 
375 	SYSCALL_TIME_LWP_INIT(l);
376 }
377 
378 /*
379  * Check that the specified process group is in the session of the
380  * specified process.
381  * Treats -ve ids as process ids.
382  * Used to validate TIOCSPGRP requests.
383  */
384 int
385 pgid_in_session(struct proc *p, pid_t pg_id)
386 {
387 	struct pgrp *pgrp;
388 	struct session *session;
389 	int error;
390 
391 	mutex_enter(proc_lock);
392 	if (pg_id < 0) {
393 		struct proc *p1 = p_find(-pg_id, PFIND_LOCKED | PFIND_UNLOCK_FAIL);
394 		if (p1 == NULL)
395 			return EINVAL;
396 		pgrp = p1->p_pgrp;
397 	} else {
398 		pgrp = pg_find(pg_id, PFIND_LOCKED | PFIND_UNLOCK_FAIL);
399 		if (pgrp == NULL)
400 			return EINVAL;
401 	}
402 	session = pgrp->pg_session;
403 	if (session != p->p_pgrp->pg_session)
404 		error = EPERM;
405 	else
406 		error = 0;
407 	mutex_exit(proc_lock);
408 
409 	return error;
410 }
411 
412 /*
413  * p_inferior: is p an inferior of q?
414  */
415 static inline bool
416 p_inferior(struct proc *p, struct proc *q)
417 {
418 
419 	KASSERT(mutex_owned(proc_lock));
420 
421 	for (; p != q; p = p->p_pptr)
422 		if (p->p_pid == 0)
423 			return false;
424 	return true;
425 }
426 
427 /*
428  * Locate a process by number
429  */
430 struct proc *
431 p_find(pid_t pid, uint flags)
432 {
433 	struct proc *p;
434 	char stat;
435 
436 	if (!(flags & PFIND_LOCKED))
437 		mutex_enter(proc_lock);
438 
439 	p = pid_table[pid & pid_tbl_mask].pt_proc;
440 
441 	/* Only allow live processes to be found by pid. */
442 	/* XXXSMP p_stat */
443 	if (P_VALID(p) && p->p_pid == pid && ((stat = p->p_stat) == SACTIVE ||
444 	    stat == SSTOP || ((flags & PFIND_ZOMBIE) &&
445 	    (stat == SZOMB || stat == SDEAD || stat == SDYING)))) {
446 		if (flags & PFIND_UNLOCK_OK)
447 			 mutex_exit(proc_lock);
448 		return p;
449 	}
450 	if (flags & PFIND_UNLOCK_FAIL)
451 		mutex_exit(proc_lock);
452 	return NULL;
453 }
454 
455 
456 /*
457  * Locate a process group by number
458  */
459 struct pgrp *
460 pg_find(pid_t pgid, uint flags)
461 {
462 	struct pgrp *pg;
463 
464 	if (!(flags & PFIND_LOCKED))
465 		mutex_enter(proc_lock);
466 	pg = pid_table[pgid & pid_tbl_mask].pt_pgrp;
467 	/*
468 	 * Can't look up a pgrp that only exists because the session
469 	 * hasn't died yet (traditional)
470 	 */
471 	if (pg == NULL || pg->pg_id != pgid || LIST_EMPTY(&pg->pg_members)) {
472 		if (flags & PFIND_UNLOCK_FAIL)
473 			 mutex_exit(proc_lock);
474 		return NULL;
475 	}
476 
477 	if (flags & PFIND_UNLOCK_OK)
478 		mutex_exit(proc_lock);
479 	return pg;
480 }
481 
482 static void
483 expand_pid_table(void)
484 {
485 	size_t pt_size, tsz;
486 	struct pid_table *n_pt, *new_pt;
487 	struct proc *proc;
488 	struct pgrp *pgrp;
489 	pid_t pid;
490 	u_int i;
491 
492 	pt_size = pid_tbl_mask + 1;
493 	tsz = pt_size * 2 * sizeof(struct pid_table);
494 	new_pt = kmem_alloc(tsz, KM_SLEEP);
495 
496 	mutex_enter(proc_lock);
497 	if (pt_size != pid_tbl_mask + 1) {
498 		/* Another process beat us to it... */
499 		mutex_exit(proc_lock);
500 		kmem_free(new_pt, tsz);
501 		return;
502 	}
503 
504 	/*
505 	 * Copy entries from old table into new one.
506 	 * If 'pid' is 'odd' we need to place in the upper half,
507 	 * even pid's to the lower half.
508 	 * Free items stay in the low half so we don't have to
509 	 * fixup the reference to them.
510 	 * We stuff free items on the front of the freelist
511 	 * because we can't write to unmodified entries.
512 	 * Processing the table backwards maintains a semblance
513 	 * of issueing pid numbers that increase with time.
514 	 */
515 	i = pt_size - 1;
516 	n_pt = new_pt + i;
517 	for (; ; i--, n_pt--) {
518 		proc = pid_table[i].pt_proc;
519 		pgrp = pid_table[i].pt_pgrp;
520 		if (!P_VALID(proc)) {
521 			/* Up 'use count' so that link is valid */
522 			pid = (P_NEXT(proc) + pt_size) & ~pt_size;
523 			proc = P_FREE(pid);
524 			if (pgrp)
525 				pid = pgrp->pg_id;
526 		} else
527 			pid = proc->p_pid;
528 
529 		/* Save entry in appropriate half of table */
530 		n_pt[pid & pt_size].pt_proc = proc;
531 		n_pt[pid & pt_size].pt_pgrp = pgrp;
532 
533 		/* Put other piece on start of free list */
534 		pid = (pid ^ pt_size) & ~pid_tbl_mask;
535 		n_pt[pid & pt_size].pt_proc =
536 				    P_FREE((pid & ~pt_size) | next_free_pt);
537 		n_pt[pid & pt_size].pt_pgrp = 0;
538 		next_free_pt = i | (pid & pt_size);
539 		if (i == 0)
540 			break;
541 	}
542 
543 	/* Save old table size and switch tables */
544 	tsz = pt_size * sizeof(struct pid_table);
545 	n_pt = pid_table;
546 	pid_table = new_pt;
547 	pid_tbl_mask = pt_size * 2 - 1;
548 
549 	/*
550 	 * pid_max starts as PID_MAX (= 30000), once we have 16384
551 	 * allocated pids we need it to be larger!
552 	 */
553 	if (pid_tbl_mask > PID_MAX) {
554 		pid_max = pid_tbl_mask * 2 + 1;
555 		pid_alloc_lim |= pid_alloc_lim << 1;
556 	} else
557 		pid_alloc_lim <<= 1;	/* doubles number of free slots... */
558 
559 	mutex_exit(proc_lock);
560 	kmem_free(n_pt, tsz);
561 }
562 
563 struct proc *
564 proc_alloc(void)
565 {
566 	struct proc *p;
567 	int nxt;
568 	pid_t pid;
569 	struct pid_table *pt;
570 
571 	p = pool_cache_get(proc_cache, PR_WAITOK);
572 	p->p_stat = SIDL;			/* protect against others */
573 
574 	proc_initspecific(p);
575 	/* allocate next free pid */
576 
577 	for (;;expand_pid_table()) {
578 		if (__predict_false(pid_alloc_cnt >= pid_alloc_lim))
579 			/* ensure pids cycle through 2000+ values */
580 			continue;
581 		mutex_enter(proc_lock);
582 		pt = &pid_table[next_free_pt];
583 #ifdef DIAGNOSTIC
584 		if (__predict_false(P_VALID(pt->pt_proc) || pt->pt_pgrp))
585 			panic("proc_alloc: slot busy");
586 #endif
587 		nxt = P_NEXT(pt->pt_proc);
588 		if (nxt & pid_tbl_mask)
589 			break;
590 		/* Table full - expand (NB last entry not used....) */
591 		mutex_exit(proc_lock);
592 	}
593 
594 	/* pid is 'saved use count' + 'size' + entry */
595 	pid = (nxt & ~pid_tbl_mask) + pid_tbl_mask + 1 + next_free_pt;
596 	if ((uint)pid > (uint)pid_max)
597 		pid &= pid_tbl_mask;
598 	p->p_pid = pid;
599 	next_free_pt = nxt & pid_tbl_mask;
600 
601 	/* Grab table slot */
602 	pt->pt_proc = p;
603 	pid_alloc_cnt++;
604 
605 	mutex_exit(proc_lock);
606 
607 	return p;
608 }
609 
610 /*
611  * Free a process id - called from proc_free (in kern_exit.c)
612  *
613  * Called with the proc_lock held.
614  */
615 void
616 proc_free_pid(struct proc *p)
617 {
618 	pid_t pid = p->p_pid;
619 	struct pid_table *pt;
620 
621 	KASSERT(mutex_owned(proc_lock));
622 
623 	pt = &pid_table[pid & pid_tbl_mask];
624 #ifdef DIAGNOSTIC
625 	if (__predict_false(pt->pt_proc != p))
626 		panic("proc_free: pid_table mismatch, pid %x, proc %p",
627 			pid, p);
628 #endif
629 	/* save pid use count in slot */
630 	pt->pt_proc = P_FREE(pid & ~pid_tbl_mask);
631 
632 	if (pt->pt_pgrp == NULL) {
633 		/* link last freed entry onto ours */
634 		pid &= pid_tbl_mask;
635 		pt = &pid_table[last_free_pt];
636 		pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pid);
637 		last_free_pt = pid;
638 		pid_alloc_cnt--;
639 	}
640 
641 	atomic_dec_uint(&nprocs);
642 }
643 
644 void
645 proc_free_mem(struct proc *p)
646 {
647 
648 	pool_cache_put(proc_cache, p);
649 }
650 
651 /*
652  * Move p to a new or existing process group (and session)
653  *
654  * If we are creating a new pgrp, the pgid should equal
655  * the calling process' pid.
656  * If is only valid to enter a process group that is in the session
657  * of the process.
658  * Also mksess should only be set if we are creating a process group
659  *
660  * Only called from sys_setsid and sys_setpgid.
661  */
662 int
663 enterpgrp(struct proc *curp, pid_t pid, pid_t pgid, int mksess)
664 {
665 	struct pgrp *new_pgrp, *pgrp;
666 	struct session *sess;
667 	struct proc *p;
668 	int rval;
669 	pid_t pg_id = NO_PGID;
670 
671 	if (mksess)
672 		sess = kmem_alloc(sizeof(*sess), KM_SLEEP);
673 	else
674 		sess = NULL;
675 
676 	/* Allocate data areas we might need before doing any validity checks */
677 	mutex_enter(proc_lock);		/* Because pid_table might change */
678 	if (pid_table[pgid & pid_tbl_mask].pt_pgrp == 0) {
679 		mutex_exit(proc_lock);
680 		new_pgrp = kmem_alloc(sizeof(*new_pgrp), KM_SLEEP);
681 		mutex_enter(proc_lock);
682 	} else
683 		new_pgrp = NULL;
684 	rval = EPERM;	/* most common error (to save typing) */
685 
686 	/* Check pgrp exists or can be created */
687 	pgrp = pid_table[pgid & pid_tbl_mask].pt_pgrp;
688 	if (pgrp != NULL && pgrp->pg_id != pgid)
689 		goto done;
690 
691 	/* Can only set another process under restricted circumstances. */
692 	if (pid != curp->p_pid) {
693 		/* must exist and be one of our children... */
694 		if ((p = p_find(pid, PFIND_LOCKED)) == NULL ||
695 		    !p_inferior(p, curp)) {
696 			rval = ESRCH;
697 			goto done;
698 		}
699 		/* ... in the same session... */
700 		if (sess != NULL || p->p_session != curp->p_session)
701 			goto done;
702 		/* ... existing pgid must be in same session ... */
703 		if (pgrp != NULL && pgrp->pg_session != p->p_session)
704 			goto done;
705 		/* ... and not done an exec. */
706 		if (p->p_flag & PK_EXEC) {
707 			rval = EACCES;
708 			goto done;
709 		}
710 	} else {
711 		/* ... setsid() cannot re-enter a pgrp */
712 		if (mksess && (curp->p_pgid == curp->p_pid ||
713 		    pg_find(curp->p_pid, PFIND_LOCKED)))
714 			goto done;
715 		p = curp;
716 	}
717 
718 	/* Changing the process group/session of a session
719 	   leader is definitely off limits. */
720 	if (SESS_LEADER(p)) {
721 		if (sess == NULL && p->p_pgrp == pgrp)
722 			/* unless it's a definite noop */
723 			rval = 0;
724 		goto done;
725 	}
726 
727 	/* Can only create a process group with id of process */
728 	if (pgrp == NULL && pgid != pid)
729 		goto done;
730 
731 	/* Can only create a session if creating pgrp */
732 	if (sess != NULL && pgrp != NULL)
733 		goto done;
734 
735 	/* Check we allocated memory for a pgrp... */
736 	if (pgrp == NULL && new_pgrp == NULL)
737 		goto done;
738 
739 	/* Don't attach to 'zombie' pgrp */
740 	if (pgrp != NULL && LIST_EMPTY(&pgrp->pg_members))
741 		goto done;
742 
743 	/* Expect to succeed now */
744 	rval = 0;
745 
746 	if (pgrp == p->p_pgrp)
747 		/* nothing to do */
748 		goto done;
749 
750 	/* Ok all setup, link up required structures */
751 
752 	if (pgrp == NULL) {
753 		pgrp = new_pgrp;
754 		new_pgrp = NULL;
755 		if (sess != NULL) {
756 			sess->s_sid = p->p_pid;
757 			sess->s_leader = p;
758 			sess->s_count = 1;
759 			sess->s_ttyvp = NULL;
760 			sess->s_ttyp = NULL;
761 			sess->s_flags = p->p_session->s_flags & ~S_LOGIN_SET;
762 			memcpy(sess->s_login, p->p_session->s_login,
763 			    sizeof(sess->s_login));
764 			p->p_lflag &= ~PL_CONTROLT;
765 		} else {
766 			sess = p->p_pgrp->pg_session;
767 			SESSHOLD(sess);
768 		}
769 		pgrp->pg_session = sess;
770 		sess = NULL;
771 
772 		pgrp->pg_id = pgid;
773 		LIST_INIT(&pgrp->pg_members);
774 #ifdef DIAGNOSTIC
775 		if (__predict_false(pid_table[pgid & pid_tbl_mask].pt_pgrp))
776 			panic("enterpgrp: pgrp table slot in use");
777 		if (__predict_false(mksess && p != curp))
778 			panic("enterpgrp: mksession and p != curproc");
779 #endif
780 		pid_table[pgid & pid_tbl_mask].pt_pgrp = pgrp;
781 		pgrp->pg_jobc = 0;
782 	}
783 
784 	/*
785 	 * Adjust eligibility of affected pgrps to participate in job control.
786 	 * Increment eligibility counts before decrementing, otherwise we
787 	 * could reach 0 spuriously during the first call.
788 	 */
789 	fixjobc(p, pgrp, 1);
790 	fixjobc(p, p->p_pgrp, 0);
791 
792 	/* Interlock with ttread(). */
793 	mutex_spin_enter(&tty_lock);
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 with the swap; we can release the tty mutex. */
804 	mutex_spin_exit(&tty_lock);
805 
806     done:
807 	if (pg_id != NO_PGID)
808 		pg_delete(pg_id);
809 	mutex_exit(proc_lock);
810 	if (sess != NULL)
811 		kmem_free(sess, sizeof(*sess));
812 	if (new_pgrp != NULL)
813 		kmem_free(new_pgrp, sizeof(*new_pgrp));
814 #ifdef DEBUG_PGRP
815 	if (__predict_false(rval))
816 		printf("enterpgrp(%d,%d,%d), curproc %d, rval %d\n",
817 			pid, pgid, mksess, curp->p_pid, rval);
818 #endif
819 	return rval;
820 }
821 
822 /*
823  * Remove a process from its process group.  Must be called with the
824  * proc_lock held.
825  */
826 void
827 leavepgrp(struct proc *p)
828 {
829 	struct pgrp *pgrp;
830 
831 	KASSERT(mutex_owned(proc_lock));
832 
833 	/* Interlock with ttread() */
834 	mutex_spin_enter(&tty_lock);
835 	pgrp = p->p_pgrp;
836 	LIST_REMOVE(p, p_pglist);
837 	p->p_pgrp = NULL;
838 	mutex_spin_exit(&tty_lock);
839 
840 	if (LIST_EMPTY(&pgrp->pg_members))
841 		pg_delete(pgrp->pg_id);
842 }
843 
844 /*
845  * Free a process group.  Must be called with the proc_lock held.
846  */
847 static void
848 pg_free(pid_t pg_id)
849 {
850 	struct pgrp *pgrp;
851 	struct pid_table *pt;
852 
853 	KASSERT(mutex_owned(proc_lock));
854 
855 	pt = &pid_table[pg_id & pid_tbl_mask];
856 	pgrp = pt->pt_pgrp;
857 #ifdef DIAGNOSTIC
858 	if (__predict_false(!pgrp || pgrp->pg_id != pg_id
859 	    || !LIST_EMPTY(&pgrp->pg_members)))
860 		panic("pg_free: process group absent or has members");
861 #endif
862 	pt->pt_pgrp = 0;
863 
864 	if (!P_VALID(pt->pt_proc)) {
865 		/* orphaned pgrp, put slot onto free list */
866 #ifdef DIAGNOSTIC
867 		if (__predict_false(P_NEXT(pt->pt_proc) & pid_tbl_mask))
868 			panic("pg_free: process slot on free list");
869 #endif
870 		pg_id &= pid_tbl_mask;
871 		pt = &pid_table[last_free_pt];
872 		pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pg_id);
873 		last_free_pt = pg_id;
874 		pid_alloc_cnt--;
875 	}
876 	kmem_free(pgrp, sizeof(*pgrp));
877 }
878 
879 /*
880  * Delete a process group.  Must be called with the proc_lock held.
881  */
882 static void
883 pg_delete(pid_t pg_id)
884 {
885 	struct pgrp *pgrp;
886 	struct tty *ttyp;
887 	struct session *ss;
888 	int is_pgrp_leader;
889 
890 	KASSERT(mutex_owned(proc_lock));
891 
892 	pgrp = pid_table[pg_id & pid_tbl_mask].pt_pgrp;
893 	if (pgrp == NULL || pgrp->pg_id != pg_id ||
894 	    !LIST_EMPTY(&pgrp->pg_members))
895 		return;
896 
897 	ss = pgrp->pg_session;
898 
899 	/* Remove reference (if any) from tty to this process group */
900 	mutex_spin_enter(&tty_lock);
901 	ttyp = ss->s_ttyp;
902 	if (ttyp != NULL && ttyp->t_pgrp == pgrp) {
903 		ttyp->t_pgrp = NULL;
904 #ifdef DIAGNOSTIC
905 		if (ttyp->t_session != ss)
906 			panic("pg_delete: wrong session on terminal");
907 #endif
908 	}
909 	mutex_spin_exit(&tty_lock);
910 
911 	/*
912 	 * The leading process group in a session is freed
913 	 * by sessdelete() if last reference.
914 	 */
915 	is_pgrp_leader = (ss->s_sid == pgrp->pg_id);
916 	SESSRELE(ss);
917 
918 	if (is_pgrp_leader)
919 		return;
920 
921 	pg_free(pg_id);
922 }
923 
924 /*
925  * Delete session - called from SESSRELE when s_count becomes zero.
926  * Must be called with the proc_lock held.
927  */
928 void
929 sessdelete(struct session *ss)
930 {
931 
932 	KASSERT(mutex_owned(proc_lock));
933 
934 	/*
935 	 * We keep the pgrp with the same id as the session in
936 	 * order to stop a process being given the same pid.
937 	 * Since the pgrp holds a reference to the session, it
938 	 * must be a 'zombie' pgrp by now.
939 	 */
940 	pg_free(ss->s_sid);
941 	kmem_free(ss, sizeof(*ss));
942 }
943 
944 /*
945  * Adjust pgrp jobc counters when specified process changes process group.
946  * We count the number of processes in each process group that "qualify"
947  * the group for terminal job control (those with a parent in a different
948  * process group of the same session).  If that count reaches zero, the
949  * process group becomes orphaned.  Check both the specified process'
950  * process group and that of its children.
951  * entering == 0 => p is leaving specified group.
952  * entering == 1 => p is entering specified group.
953  *
954  * Call with proc_lock held.
955  */
956 void
957 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
958 {
959 	struct pgrp *hispgrp;
960 	struct session *mysession = pgrp->pg_session;
961 	struct proc *child;
962 
963 	KASSERT(mutex_owned(proc_lock));
964 
965 	/*
966 	 * Check p's parent to see whether p qualifies its own process
967 	 * group; if so, adjust count for p's process group.
968 	 */
969 	hispgrp = p->p_pptr->p_pgrp;
970 	if (hispgrp != pgrp && hispgrp->pg_session == mysession) {
971 		if (entering) {
972 			pgrp->pg_jobc++;
973 			p->p_lflag &= ~PL_ORPHANPG;
974 		} else if (--pgrp->pg_jobc == 0)
975 			orphanpg(pgrp);
976 	}
977 
978 	/*
979 	 * Check this process' children to see whether they qualify
980 	 * their process groups; if so, adjust counts for children's
981 	 * process groups.
982 	 */
983 	LIST_FOREACH(child, &p->p_children, p_sibling) {
984 		hispgrp = child->p_pgrp;
985 		if (hispgrp != pgrp && hispgrp->pg_session == mysession &&
986 		    !P_ZOMBIE(child)) {
987 			if (entering) {
988 				child->p_lflag &= ~PL_ORPHANPG;
989 				hispgrp->pg_jobc++;
990 			} else if (--hispgrp->pg_jobc == 0)
991 				orphanpg(hispgrp);
992 		}
993 	}
994 }
995 
996 /*
997  * A process group has become orphaned;
998  * if there are any stopped processes in the group,
999  * hang-up all process in that group.
1000  *
1001  * Call with proc_lock held.
1002  */
1003 static void
1004 orphanpg(struct pgrp *pg)
1005 {
1006 	struct proc *p;
1007 	int doit;
1008 
1009 	KASSERT(mutex_owned(proc_lock));
1010 
1011 	doit = 0;
1012 
1013 	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
1014 		if (p->p_stat == SSTOP) {
1015 			p->p_lflag |= PL_ORPHANPG;
1016 			psignal(p, SIGHUP);
1017 			psignal(p, SIGCONT);
1018 		}
1019 	}
1020 }
1021 
1022 #ifdef DDB
1023 #include <ddb/db_output.h>
1024 void pidtbl_dump(void);
1025 void
1026 pidtbl_dump(void)
1027 {
1028 	struct pid_table *pt;
1029 	struct proc *p;
1030 	struct pgrp *pgrp;
1031 	int id;
1032 
1033 	db_printf("pid table %p size %x, next %x, last %x\n",
1034 		pid_table, pid_tbl_mask+1,
1035 		next_free_pt, last_free_pt);
1036 	for (pt = pid_table, id = 0; id <= pid_tbl_mask; id++, pt++) {
1037 		p = pt->pt_proc;
1038 		if (!P_VALID(p) && !pt->pt_pgrp)
1039 			continue;
1040 		db_printf("  id %x: ", id);
1041 		if (P_VALID(p))
1042 			db_printf("proc %p id %d (0x%x) %s\n",
1043 				p, p->p_pid, p->p_pid, p->p_comm);
1044 		else
1045 			db_printf("next %x use %x\n",
1046 				P_NEXT(p) & pid_tbl_mask,
1047 				P_NEXT(p) & ~pid_tbl_mask);
1048 		if ((pgrp = pt->pt_pgrp)) {
1049 			db_printf("\tsession %p, sid %d, count %d, login %s\n",
1050 			    pgrp->pg_session, pgrp->pg_session->s_sid,
1051 			    pgrp->pg_session->s_count,
1052 			    pgrp->pg_session->s_login);
1053 			db_printf("\tpgrp %p, pg_id %d, pg_jobc %d, members %p\n",
1054 			    pgrp, pgrp->pg_id, pgrp->pg_jobc,
1055 			    LIST_FIRST(&pgrp->pg_members));
1056 			LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
1057 				db_printf("\t\tpid %d addr %p pgrp %p %s\n",
1058 				    p->p_pid, p, p->p_pgrp, p->p_comm);
1059 			}
1060 		}
1061 	}
1062 }
1063 #endif /* DDB */
1064 
1065 #ifdef KSTACK_CHECK_MAGIC
1066 #include <sys/user.h>
1067 
1068 #define	KSTACK_MAGIC	0xdeadbeaf
1069 
1070 /* XXX should be per process basis? */
1071 static int	kstackleftmin = KSTACK_SIZE;
1072 static int	kstackleftthres = KSTACK_SIZE / 8;
1073 
1074 void
1075 kstack_setup_magic(const struct lwp *l)
1076 {
1077 	uint32_t *ip;
1078 	uint32_t const *end;
1079 
1080 	KASSERT(l != NULL);
1081 	KASSERT(l != &lwp0);
1082 
1083 	/*
1084 	 * fill all the stack with magic number
1085 	 * so that later modification on it can be detected.
1086 	 */
1087 	ip = (uint32_t *)KSTACK_LOWEST_ADDR(l);
1088 	end = (uint32_t *)((char *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
1089 	for (; ip < end; ip++) {
1090 		*ip = KSTACK_MAGIC;
1091 	}
1092 }
1093 
1094 void
1095 kstack_check_magic(const struct lwp *l)
1096 {
1097 	uint32_t const *ip, *end;
1098 	int stackleft;
1099 
1100 	KASSERT(l != NULL);
1101 
1102 	/* don't check proc0 */ /*XXX*/
1103 	if (l == &lwp0)
1104 		return;
1105 
1106 #ifdef __MACHINE_STACK_GROWS_UP
1107 	/* stack grows upwards (eg. hppa) */
1108 	ip = (uint32_t *)((void *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
1109 	end = (uint32_t *)KSTACK_LOWEST_ADDR(l);
1110 	for (ip--; ip >= end; ip--)
1111 		if (*ip != KSTACK_MAGIC)
1112 			break;
1113 
1114 	stackleft = (void *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE - (void *)ip;
1115 #else /* __MACHINE_STACK_GROWS_UP */
1116 	/* stack grows downwards (eg. i386) */
1117 	ip = (uint32_t *)KSTACK_LOWEST_ADDR(l);
1118 	end = (uint32_t *)((char *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
1119 	for (; ip < end; ip++)
1120 		if (*ip != KSTACK_MAGIC)
1121 			break;
1122 
1123 	stackleft = ((const char *)ip) - (const char *)KSTACK_LOWEST_ADDR(l);
1124 #endif /* __MACHINE_STACK_GROWS_UP */
1125 
1126 	if (kstackleftmin > stackleft) {
1127 		kstackleftmin = stackleft;
1128 		if (stackleft < kstackleftthres)
1129 			printf("warning: kernel stack left %d bytes"
1130 			    "(pid %u:lid %u)\n", stackleft,
1131 			    (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
1132 	}
1133 
1134 	if (stackleft <= 0) {
1135 		panic("magic on the top of kernel stack changed for "
1136 		    "pid %u, lid %u: maybe kernel stack overflow",
1137 		    (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
1138 	}
1139 }
1140 #endif /* KSTACK_CHECK_MAGIC */
1141 
1142 int
1143 proclist_foreach_call(struct proclist *list,
1144     int (*callback)(struct proc *, void *arg), void *arg)
1145 {
1146 	struct proc marker;
1147 	struct proc *p;
1148 	struct lwp * const l = curlwp;
1149 	int ret = 0;
1150 
1151 	marker.p_flag = PK_MARKER;
1152 	uvm_lwp_hold(l);
1153 	mutex_enter(proc_lock);
1154 	for (p = LIST_FIRST(list); ret == 0 && p != NULL;) {
1155 		if (p->p_flag & PK_MARKER) {
1156 			p = LIST_NEXT(p, p_list);
1157 			continue;
1158 		}
1159 		LIST_INSERT_AFTER(p, &marker, p_list);
1160 		ret = (*callback)(p, arg);
1161 		KASSERT(mutex_owned(proc_lock));
1162 		p = LIST_NEXT(&marker, p_list);
1163 		LIST_REMOVE(&marker, p_list);
1164 	}
1165 	mutex_exit(proc_lock);
1166 	uvm_lwp_rele(l);
1167 
1168 	return ret;
1169 }
1170 
1171 int
1172 proc_vmspace_getref(struct proc *p, struct vmspace **vm)
1173 {
1174 
1175 	/* XXXCDC: how should locking work here? */
1176 
1177 	/* curproc exception is for coredump. */
1178 
1179 	if ((p != curproc && (p->p_sflag & PS_WEXIT) != 0) ||
1180 	    (p->p_vmspace->vm_refcnt < 1)) { /* XXX */
1181 		return EFAULT;
1182 	}
1183 
1184 	uvmspace_addref(p->p_vmspace);
1185 	*vm = p->p_vmspace;
1186 
1187 	return 0;
1188 }
1189 
1190 /*
1191  * Acquire a write lock on the process credential.
1192  */
1193 void
1194 proc_crmod_enter(void)
1195 {
1196 	struct lwp *l = curlwp;
1197 	struct proc *p = l->l_proc;
1198 	struct plimit *lim;
1199 	kauth_cred_t oc;
1200 	char *cn;
1201 
1202 	/* Reset what needs to be reset in plimit. */
1203 	if (p->p_limit->pl_corename != defcorename) {
1204 		lim_privatise(p, false);
1205 		lim = p->p_limit;
1206 		mutex_enter(&lim->pl_lock);
1207 		cn = lim->pl_corename;
1208 		lim->pl_corename = defcorename;
1209 		mutex_exit(&lim->pl_lock);
1210 		if (cn != defcorename)
1211 			free(cn, M_TEMP);
1212 	}
1213 
1214 	mutex_enter(p->p_lock);
1215 
1216 	/* Ensure the LWP cached credentials are up to date. */
1217 	if ((oc = l->l_cred) != p->p_cred) {
1218 		kauth_cred_hold(p->p_cred);
1219 		l->l_cred = p->p_cred;
1220 		kauth_cred_free(oc);
1221 	}
1222 
1223 }
1224 
1225 /*
1226  * Set in a new process credential, and drop the write lock.  The credential
1227  * must have a reference already.  Optionally, free a no-longer required
1228  * credential.  The scheduler also needs to inspect p_cred, so we also
1229  * briefly acquire the sched state mutex.
1230  */
1231 void
1232 proc_crmod_leave(kauth_cred_t scred, kauth_cred_t fcred, bool sugid)
1233 {
1234 	struct lwp *l = curlwp, *l2;
1235 	struct proc *p = l->l_proc;
1236 	kauth_cred_t oc;
1237 
1238 	KASSERT(mutex_owned(p->p_lock));
1239 
1240 	/* Is there a new credential to set in? */
1241 	if (scred != NULL) {
1242 		p->p_cred = scred;
1243 		LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
1244 			if (l2 != l)
1245 				l2->l_prflag |= LPR_CRMOD;
1246 		}
1247 
1248 		/* Ensure the LWP cached credentials are up to date. */
1249 		if ((oc = l->l_cred) != scred) {
1250 			kauth_cred_hold(scred);
1251 			l->l_cred = scred;
1252 		}
1253 	} else
1254 		oc = NULL;	/* XXXgcc */
1255 
1256 	if (sugid) {
1257 		/*
1258 		 * Mark process as having changed credentials, stops
1259 		 * tracing etc.
1260 		 */
1261 		p->p_flag |= PK_SUGID;
1262 	}
1263 
1264 	mutex_exit(p->p_lock);
1265 
1266 	/* If there is a credential to be released, free it now. */
1267 	if (fcred != NULL) {
1268 		KASSERT(scred != NULL);
1269 		kauth_cred_free(fcred);
1270 		if (oc != scred)
1271 			kauth_cred_free(oc);
1272 	}
1273 }
1274 
1275 /*
1276  * proc_specific_key_create --
1277  *	Create a key for subsystem proc-specific data.
1278  */
1279 int
1280 proc_specific_key_create(specificdata_key_t *keyp, specificdata_dtor_t dtor)
1281 {
1282 
1283 	return (specificdata_key_create(proc_specificdata_domain, keyp, dtor));
1284 }
1285 
1286 /*
1287  * proc_specific_key_delete --
1288  *	Delete a key for subsystem proc-specific data.
1289  */
1290 void
1291 proc_specific_key_delete(specificdata_key_t key)
1292 {
1293 
1294 	specificdata_key_delete(proc_specificdata_domain, key);
1295 }
1296 
1297 /*
1298  * proc_initspecific --
1299  *	Initialize a proc's specificdata container.
1300  */
1301 void
1302 proc_initspecific(struct proc *p)
1303 {
1304 	int error;
1305 
1306 	error = specificdata_init(proc_specificdata_domain, &p->p_specdataref);
1307 	KASSERT(error == 0);
1308 }
1309 
1310 /*
1311  * proc_finispecific --
1312  *	Finalize a proc's specificdata container.
1313  */
1314 void
1315 proc_finispecific(struct proc *p)
1316 {
1317 
1318 	specificdata_fini(proc_specificdata_domain, &p->p_specdataref);
1319 }
1320 
1321 /*
1322  * proc_getspecific --
1323  *	Return proc-specific data corresponding to the specified key.
1324  */
1325 void *
1326 proc_getspecific(struct proc *p, specificdata_key_t key)
1327 {
1328 
1329 	return (specificdata_getspecific(proc_specificdata_domain,
1330 					 &p->p_specdataref, key));
1331 }
1332 
1333 /*
1334  * proc_setspecific --
1335  *	Set proc-specific data corresponding to the specified key.
1336  */
1337 void
1338 proc_setspecific(struct proc *p, specificdata_key_t key, void *data)
1339 {
1340 
1341 	specificdata_setspecific(proc_specificdata_domain,
1342 				 &p->p_specdataref, key, data);
1343 }
1344