kern_proc.c revision 1.120 1 /* $NetBSD: kern_proc.c,v 1.120 2007/10/24 14:50:41 ad Exp $ */
2
3 /*-
4 * Copyright (c) 1999, 2006, 2007 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 * 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.120 2007/10/24 14:50:41 ad Exp $");
73
74 #include "opt_kstack.h"
75 #include "opt_maxuprc.h"
76 #include "opt_multiprocessor.h"
77 #include "opt_lockdebug.h"
78
79 #include <sys/param.h>
80 #include <sys/systm.h>
81 #include <sys/kernel.h>
82 #include <sys/proc.h>
83 #include <sys/resourcevar.h>
84 #include <sys/buf.h>
85 #include <sys/acct.h>
86 #include <sys/wait.h>
87 #include <sys/file.h>
88 #include <ufs/ufs/quota.h>
89 #include <sys/uio.h>
90 #include <sys/malloc.h>
91 #include <sys/pool.h>
92 #include <sys/mbuf.h>
93 #include <sys/ioctl.h>
94 #include <sys/tty.h>
95 #include <sys/signalvar.h>
96 #include <sys/ras.h>
97 #include <sys/filedesc.h>
98 #include "sys/syscall_stats.h"
99 #include <sys/kauth.h>
100 #include <sys/sleepq.h>
101
102 #include <uvm/uvm.h>
103 #include <uvm/uvm_extern.h>
104
105 /*
106 * Other process lists
107 */
108
109 struct proclist allproc;
110 struct proclist zombproc; /* resources have been freed */
111
112 /*
113 * There are two locks on global process state.
114 *
115 * 1. proclist_lock is an adaptive mutex and is used when modifying
116 * or examining process state from a process context. It protects
117 * the internal tables, all of the process lists, and a number of
118 * members of struct proc.
119 *
120 * 2. proclist_mutex is used when allproc must be traversed from an
121 * interrupt context, or when changing the state of processes. The
122 * proclist_lock should always be used in preference. In some cases,
123 * both locks need to be held.
124 *
125 * proclist_lock proclist_mutex structure
126 * --------------- --------------- -----------------
127 * x zombproc
128 * x x pid_table
129 * x proc::p_pptr
130 * x proc::p_sibling
131 * x proc::p_children
132 * x x allproc
133 * x x proc::p_pgrp
134 * x x proc::p_pglist
135 * x x proc::p_session
136 * x x proc::p_list
137 * x alllwp
138 * x lwp::l_list
139 *
140 * The lock order for processes and LWPs is approximately as following:
141 *
142 * kernel_lock
143 * -> proclist_lock
144 * -> proc::p_mutex
145 * -> proclist_mutex
146 * -> proc::p_smutex
147 * -> proc::p_stmutex
148 *
149 * XXX p_smutex can be run at IPL_VM once audio drivers on the x86
150 * platform are made MP safe. Currently it blocks interrupts at
151 * IPL_SCHED and below.
152 *
153 * XXX The two process locks (p_smutex + p_mutex), and the two global
154 * state locks (proclist_lock + proclist_mutex) should be merged
155 * together. However, to do so requires interrupts that interrupts
156 * be run with LWP context.
157 */
158 kmutex_t proclist_lock;
159 kmutex_t proclist_mutex;
160
161 /*
162 * pid to proc lookup is done by indexing the pid_table array.
163 * Since pid numbers are only allocated when an empty slot
164 * has been found, there is no need to search any lists ever.
165 * (an orphaned pgrp will lock the slot, a session will lock
166 * the pgrp with the same number.)
167 * If the table is too small it is reallocated with twice the
168 * previous size and the entries 'unzipped' into the two halves.
169 * A linked list of free entries is passed through the pt_proc
170 * field of 'free' items - set odd to be an invalid ptr.
171 */
172
173 struct pid_table {
174 struct proc *pt_proc;
175 struct pgrp *pt_pgrp;
176 };
177 #if 1 /* strongly typed cast - should be a noop */
178 static inline uint p2u(struct proc *p) { return (uint)(uintptr_t)p; }
179 #else
180 #define p2u(p) ((uint)p)
181 #endif
182 #define P_VALID(p) (!(p2u(p) & 1))
183 #define P_NEXT(p) (p2u(p) >> 1)
184 #define P_FREE(pid) ((struct proc *)(uintptr_t)((pid) << 1 | 1))
185
186 #define INITIAL_PID_TABLE_SIZE (1 << 5)
187 static struct pid_table *pid_table;
188 static uint pid_tbl_mask = INITIAL_PID_TABLE_SIZE - 1;
189 static uint pid_alloc_lim; /* max we allocate before growing table */
190 static uint pid_alloc_cnt; /* number of allocated pids */
191
192 /* links through free slots - never empty! */
193 static uint next_free_pt, last_free_pt;
194 static pid_t pid_max = PID_MAX; /* largest value we allocate */
195
196 /* Components of the first process -- never freed. */
197 struct session session0;
198 struct pgrp pgrp0;
199 struct proc proc0;
200 struct lwp lwp0 __aligned(MIN_LWP_ALIGNMENT);
201 kauth_cred_t cred0;
202 struct filedesc0 filedesc0;
203 struct cwdinfo cwdi0;
204 struct plimit limit0;
205 struct pstats pstat0;
206 struct vmspace vmspace0;
207 struct sigacts sigacts0;
208 struct turnstile turnstile0;
209
210 extern struct user *proc0paddr;
211
212 extern const struct emul emul_netbsd; /* defined in kern_exec.c */
213
214 int nofile = NOFILE;
215 int maxuprc = MAXUPRC;
216 int cmask = CMASK;
217
218 POOL_INIT(proc_pool, sizeof(struct proc), 0, 0, 0, "procpl",
219 &pool_allocator_nointr, IPL_NONE);
220 POOL_INIT(pgrp_pool, sizeof(struct pgrp), 0, 0, 0, "pgrppl",
221 &pool_allocator_nointr, IPL_NONE);
222 POOL_INIT(plimit_pool, sizeof(struct plimit), 0, 0, 0, "plimitpl",
223 &pool_allocator_nointr, IPL_NONE);
224 POOL_INIT(pstats_pool, sizeof(struct pstats), 0, 0, 0, "pstatspl",
225 &pool_allocator_nointr, IPL_NONE);
226 POOL_INIT(session_pool, sizeof(struct session), 0, 0, 0, "sessionpl",
227 &pool_allocator_nointr, IPL_NONE);
228
229 MALLOC_DEFINE(M_EMULDATA, "emuldata", "Per-process emulation data");
230 MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
231 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
232
233 /*
234 * The process list descriptors, used during pid allocation and
235 * by sysctl. No locking on this data structure is needed since
236 * it is completely static.
237 */
238 const struct proclist_desc proclists[] = {
239 { &allproc },
240 { &zombproc },
241 { NULL },
242 };
243
244 static void orphanpg(struct pgrp *);
245 static void pg_delete(pid_t);
246
247 static specificdata_domain_t proc_specificdata_domain;
248
249 /*
250 * Initialize global process hashing structures.
251 */
252 void
253 procinit(void)
254 {
255 const struct proclist_desc *pd;
256 int i;
257 #define LINK_EMPTY ((PID_MAX + INITIAL_PID_TABLE_SIZE) & ~(INITIAL_PID_TABLE_SIZE - 1))
258
259 for (pd = proclists; pd->pd_list != NULL; pd++)
260 LIST_INIT(pd->pd_list);
261
262 mutex_init(&proclist_lock, MUTEX_DEFAULT, IPL_NONE);
263 mutex_init(&proclist_mutex, MUTEX_SPIN, IPL_SCHED);
264
265 pid_table = malloc(INITIAL_PID_TABLE_SIZE * sizeof *pid_table,
266 M_PROC, M_WAITOK);
267 /* Set free list running through table...
268 Preset 'use count' above PID_MAX so we allocate pid 1 next. */
269 for (i = 0; i <= pid_tbl_mask; i++) {
270 pid_table[i].pt_proc = P_FREE(LINK_EMPTY + i + 1);
271 pid_table[i].pt_pgrp = 0;
272 }
273 /* slot 0 is just grabbed */
274 next_free_pt = 1;
275 /* Need to fix last entry. */
276 last_free_pt = pid_tbl_mask;
277 pid_table[last_free_pt].pt_proc = P_FREE(LINK_EMPTY);
278 /* point at which we grow table - to avoid reusing pids too often */
279 pid_alloc_lim = pid_tbl_mask - 1;
280 #undef LINK_EMPTY
281
282 LIST_INIT(&alllwp);
283
284 uihashtbl =
285 hashinit(maxproc / 16, HASH_LIST, M_PROC, M_WAITOK, &uihash);
286
287 proc_specificdata_domain = specificdata_domain_create();
288 KASSERT(proc_specificdata_domain != NULL);
289 }
290
291 /*
292 * Initialize process 0.
293 */
294 void
295 proc0_init(void)
296 {
297 struct proc *p;
298 struct pgrp *pg;
299 struct session *sess;
300 struct lwp *l;
301 u_int i;
302 rlim_t lim;
303
304 p = &proc0;
305 pg = &pgrp0;
306 sess = &session0;
307 l = &lwp0;
308
309 mutex_init(&p->p_smutex, MUTEX_SPIN, IPL_SCHED);
310 mutex_init(&p->p_stmutex, MUTEX_SPIN, IPL_HIGH);
311 mutex_init(&p->p_raslock, MUTEX_DEFAULT, IPL_NONE);
312 mutex_init(&p->p_mutex, MUTEX_DEFAULT, IPL_NONE);
313 mutex_init(&l->l_swaplock, MUTEX_DEFAULT, IPL_NONE);
314
315 cv_init(&p->p_refcv, "drainref");
316 cv_init(&p->p_waitcv, "wait");
317 cv_init(&p->p_lwpcv, "lwpwait");
318
319 LIST_INIT(&p->p_lwps);
320 LIST_INIT(&p->p_sigwaiters);
321 LIST_INSERT_HEAD(&p->p_lwps, l, l_sibling);
322
323 p->p_nlwps = 1;
324 p->p_nrlwps = 1;
325 p->p_nlwpid = l->l_lid;
326 p->p_refcnt = 1;
327
328 pid_table[0].pt_proc = p;
329 LIST_INSERT_HEAD(&allproc, p, p_list);
330 LIST_INSERT_HEAD(&alllwp, l, l_list);
331
332 p->p_pgrp = pg;
333 pid_table[0].pt_pgrp = pg;
334 LIST_INIT(&pg->pg_members);
335 LIST_INSERT_HEAD(&pg->pg_members, p, p_pglist);
336
337 pg->pg_session = sess;
338 sess->s_count = 1;
339 sess->s_sid = 0;
340 sess->s_leader = p;
341
342 /*
343 * Set P_NOCLDWAIT so that kernel threads are reparented to
344 * init(8) when they exit. init(8) can easily wait them out
345 * for us.
346 */
347 p->p_flag = PK_SYSTEM | PK_NOCLDWAIT;
348 p->p_stat = SACTIVE;
349 p->p_nice = NZERO;
350 p->p_emul = &emul_netbsd;
351 #ifdef __HAVE_SYSCALL_INTERN
352 (*p->p_emul->e_syscall_intern)(p);
353 #endif
354 strlcpy(p->p_comm, "system", sizeof(p->p_comm));
355
356 l->l_flag = LW_INMEM | LW_SYSTEM;
357 l->l_stat = LSONPROC;
358 l->l_ts = &turnstile0;
359 l->l_syncobj = &sched_syncobj;
360 l->l_refcnt = 1;
361 l->l_cpu = curcpu();
362 l->l_priority = PUSER;
363 l->l_usrpri = PUSER;
364 l->l_inheritedprio = MAXPRI;
365 SLIST_INIT(&l->l_pi_lenders);
366 l->l_name = __UNCONST("swapper");
367
368 callout_init(&l->l_timeout_ch, 0);
369 callout_setfunc(&l->l_timeout_ch, sleepq_timeout, l);
370 cv_init(&l->l_sigcv, "sigwait");
371
372 /* Create credentials. */
373 cred0 = kauth_cred_alloc();
374 p->p_cred = cred0;
375 kauth_cred_hold(cred0);
376 l->l_cred = cred0;
377
378 /* Create the CWD info. */
379 p->p_cwdi = &cwdi0;
380 cwdi0.cwdi_cmask = cmask;
381 cwdi0.cwdi_refcnt = 1;
382 rw_init(&cwdi0.cwdi_lock);
383
384 /* Create the limits structures. */
385 p->p_limit = &limit0;
386 mutex_init(&limit0.pl_lock, MUTEX_DEFAULT, IPL_NONE);
387 for (i = 0; i < sizeof(p->p_rlimit)/sizeof(p->p_rlimit[0]); i++)
388 limit0.pl_rlimit[i].rlim_cur =
389 limit0.pl_rlimit[i].rlim_max = RLIM_INFINITY;
390
391 limit0.pl_rlimit[RLIMIT_NOFILE].rlim_max = maxfiles;
392 limit0.pl_rlimit[RLIMIT_NOFILE].rlim_cur =
393 maxfiles < nofile ? maxfiles : nofile;
394
395 limit0.pl_rlimit[RLIMIT_NPROC].rlim_max = maxproc;
396 limit0.pl_rlimit[RLIMIT_NPROC].rlim_cur =
397 maxproc < maxuprc ? maxproc : maxuprc;
398
399 lim = ptoa(uvmexp.free);
400 limit0.pl_rlimit[RLIMIT_RSS].rlim_max = lim;
401 limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_max = lim;
402 limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_cur = lim / 3;
403 limit0.pl_corename = defcorename;
404 limit0.pl_refcnt = 1;
405 limit0.pl_sv_limit = NULL;
406
407 /* Configure virtual memory system, set vm rlimits. */
408 uvm_init_limits(p);
409
410 /* Initialize file descriptor table for proc0. */
411 p->p_fd = &filedesc0.fd_fd;
412 fdinit1(&filedesc0);
413
414 /*
415 * Initialize proc0's vmspace, which uses the kernel pmap.
416 * All kernel processes (which never have user space mappings)
417 * share proc0's vmspace, and thus, the kernel pmap.
418 */
419 uvmspace_init(&vmspace0, pmap_kernel(), round_page(VM_MIN_ADDRESS),
420 trunc_page(VM_MAX_ADDRESS));
421 p->p_vmspace = &vmspace0;
422
423 l->l_addr = proc0paddr; /* XXX */
424
425 p->p_stats = &pstat0;
426
427 /* Initialize signal state for proc0. */
428 p->p_sigacts = &sigacts0;
429 mutex_init(&p->p_sigacts->sa_mutex, MUTEX_SPIN, IPL_NONE);
430 siginit(p);
431
432 proc_initspecific(p);
433 lwp_initspecific(l);
434
435 SYSCALL_TIME_LWP_INIT(l);
436 }
437
438 /*
439 * Check that the specified process group is in the session of the
440 * specified process.
441 * Treats -ve ids as process ids.
442 * Used to validate TIOCSPGRP requests.
443 */
444 int
445 pgid_in_session(struct proc *p, pid_t pg_id)
446 {
447 struct pgrp *pgrp;
448 struct session *session;
449 int error;
450
451 mutex_enter(&proclist_lock);
452 if (pg_id < 0) {
453 struct proc *p1 = p_find(-pg_id, PFIND_LOCKED | PFIND_UNLOCK_FAIL);
454 if (p1 == NULL)
455 return EINVAL;
456 pgrp = p1->p_pgrp;
457 } else {
458 pgrp = pg_find(pg_id, PFIND_LOCKED | PFIND_UNLOCK_FAIL);
459 if (pgrp == NULL)
460 return EINVAL;
461 }
462 session = pgrp->pg_session;
463 if (session != p->p_pgrp->pg_session)
464 error = EPERM;
465 else
466 error = 0;
467 mutex_exit(&proclist_lock);
468
469 return error;
470 }
471
472 /*
473 * Is p an inferior of q?
474 *
475 * Call with the proclist_lock held.
476 */
477 int
478 inferior(struct proc *p, struct proc *q)
479 {
480
481 for (; p != q; p = p->p_pptr)
482 if (p->p_pid == 0)
483 return 0;
484 return 1;
485 }
486
487 /*
488 * Locate a process by number
489 */
490 struct proc *
491 p_find(pid_t pid, uint flags)
492 {
493 struct proc *p;
494 char stat;
495
496 if (!(flags & PFIND_LOCKED))
497 mutex_enter(&proclist_lock);
498
499 p = pid_table[pid & pid_tbl_mask].pt_proc;
500
501 /* Only allow live processes to be found by pid. */
502 /* XXXSMP p_stat */
503 if (P_VALID(p) && p->p_pid == pid && ((stat = p->p_stat) == SACTIVE ||
504 stat == SSTOP || ((flags & PFIND_ZOMBIE) &&
505 (stat == SZOMB || stat == SDEAD || stat == SDYING)))) {
506 if (flags & PFIND_UNLOCK_OK)
507 mutex_exit(&proclist_lock);
508 return p;
509 }
510 if (flags & PFIND_UNLOCK_FAIL)
511 mutex_exit(&proclist_lock);
512 return NULL;
513 }
514
515
516 /*
517 * Locate a process group by number
518 */
519 struct pgrp *
520 pg_find(pid_t pgid, uint flags)
521 {
522 struct pgrp *pg;
523
524 if (!(flags & PFIND_LOCKED))
525 mutex_enter(&proclist_lock);
526 pg = pid_table[pgid & pid_tbl_mask].pt_pgrp;
527 /*
528 * Can't look up a pgrp that only exists because the session
529 * hasn't died yet (traditional)
530 */
531 if (pg == NULL || pg->pg_id != pgid || LIST_EMPTY(&pg->pg_members)) {
532 if (flags & PFIND_UNLOCK_FAIL)
533 mutex_exit(&proclist_lock);
534 return NULL;
535 }
536
537 if (flags & PFIND_UNLOCK_OK)
538 mutex_exit(&proclist_lock);
539 return pg;
540 }
541
542 static void
543 expand_pid_table(void)
544 {
545 uint pt_size = pid_tbl_mask + 1;
546 struct pid_table *n_pt, *new_pt;
547 struct proc *proc;
548 struct pgrp *pgrp;
549 int i;
550 pid_t pid;
551
552 new_pt = malloc(pt_size * 2 * sizeof *new_pt, M_PROC, M_WAITOK);
553
554 mutex_enter(&proclist_lock);
555 if (pt_size != pid_tbl_mask + 1) {
556 /* Another process beat us to it... */
557 mutex_exit(&proclist_lock);
558 FREE(new_pt, M_PROC);
559 return;
560 }
561
562 /*
563 * Copy entries from old table into new one.
564 * If 'pid' is 'odd' we need to place in the upper half,
565 * even pid's to the lower half.
566 * Free items stay in the low half so we don't have to
567 * fixup the reference to them.
568 * We stuff free items on the front of the freelist
569 * because we can't write to unmodified entries.
570 * Processing the table backwards maintains a semblance
571 * of issueing pid numbers that increase with time.
572 */
573 i = pt_size - 1;
574 n_pt = new_pt + i;
575 for (; ; i--, n_pt--) {
576 proc = pid_table[i].pt_proc;
577 pgrp = pid_table[i].pt_pgrp;
578 if (!P_VALID(proc)) {
579 /* Up 'use count' so that link is valid */
580 pid = (P_NEXT(proc) + pt_size) & ~pt_size;
581 proc = P_FREE(pid);
582 if (pgrp)
583 pid = pgrp->pg_id;
584 } else
585 pid = proc->p_pid;
586
587 /* Save entry in appropriate half of table */
588 n_pt[pid & pt_size].pt_proc = proc;
589 n_pt[pid & pt_size].pt_pgrp = pgrp;
590
591 /* Put other piece on start of free list */
592 pid = (pid ^ pt_size) & ~pid_tbl_mask;
593 n_pt[pid & pt_size].pt_proc =
594 P_FREE((pid & ~pt_size) | next_free_pt);
595 n_pt[pid & pt_size].pt_pgrp = 0;
596 next_free_pt = i | (pid & pt_size);
597 if (i == 0)
598 break;
599 }
600
601 /* Switch tables */
602 mutex_enter(&proclist_mutex);
603 n_pt = pid_table;
604 pid_table = new_pt;
605 mutex_exit(&proclist_mutex);
606 pid_tbl_mask = pt_size * 2 - 1;
607
608 /*
609 * pid_max starts as PID_MAX (= 30000), once we have 16384
610 * allocated pids we need it to be larger!
611 */
612 if (pid_tbl_mask > PID_MAX) {
613 pid_max = pid_tbl_mask * 2 + 1;
614 pid_alloc_lim |= pid_alloc_lim << 1;
615 } else
616 pid_alloc_lim <<= 1; /* doubles number of free slots... */
617
618 mutex_exit(&proclist_lock);
619 FREE(n_pt, M_PROC);
620 }
621
622 struct proc *
623 proc_alloc(void)
624 {
625 struct proc *p;
626 int nxt;
627 pid_t pid;
628 struct pid_table *pt;
629
630 p = pool_get(&proc_pool, PR_WAITOK);
631 p->p_stat = SIDL; /* protect against others */
632
633 proc_initspecific(p);
634 /* allocate next free pid */
635
636 for (;;expand_pid_table()) {
637 if (__predict_false(pid_alloc_cnt >= pid_alloc_lim))
638 /* ensure pids cycle through 2000+ values */
639 continue;
640 mutex_enter(&proclist_lock);
641 pt = &pid_table[next_free_pt];
642 #ifdef DIAGNOSTIC
643 if (__predict_false(P_VALID(pt->pt_proc) || pt->pt_pgrp))
644 panic("proc_alloc: slot busy");
645 #endif
646 nxt = P_NEXT(pt->pt_proc);
647 if (nxt & pid_tbl_mask)
648 break;
649 /* Table full - expand (NB last entry not used....) */
650 mutex_exit(&proclist_lock);
651 }
652
653 /* pid is 'saved use count' + 'size' + entry */
654 pid = (nxt & ~pid_tbl_mask) + pid_tbl_mask + 1 + next_free_pt;
655 if ((uint)pid > (uint)pid_max)
656 pid &= pid_tbl_mask;
657 p->p_pid = pid;
658 next_free_pt = nxt & pid_tbl_mask;
659
660 /* Grab table slot */
661 mutex_enter(&proclist_mutex);
662 pt->pt_proc = p;
663 mutex_exit(&proclist_mutex);
664 pid_alloc_cnt++;
665
666 mutex_exit(&proclist_lock);
667
668 return p;
669 }
670
671 /*
672 * Free a process id - called from proc_free (in kern_exit.c)
673 *
674 * Called with the proclist_lock held.
675 */
676 void
677 proc_free_pid(struct proc *p)
678 {
679 pid_t pid = p->p_pid;
680 struct pid_table *pt;
681
682 KASSERT(mutex_owned(&proclist_lock));
683
684 pt = &pid_table[pid & pid_tbl_mask];
685 #ifdef DIAGNOSTIC
686 if (__predict_false(pt->pt_proc != p))
687 panic("proc_free: pid_table mismatch, pid %x, proc %p",
688 pid, p);
689 #endif
690 mutex_enter(&proclist_mutex);
691 /* save pid use count in slot */
692 pt->pt_proc = P_FREE(pid & ~pid_tbl_mask);
693
694 if (pt->pt_pgrp == NULL) {
695 /* link last freed entry onto ours */
696 pid &= pid_tbl_mask;
697 pt = &pid_table[last_free_pt];
698 pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pid);
699 last_free_pt = pid;
700 pid_alloc_cnt--;
701 }
702 mutex_exit(&proclist_mutex);
703
704 nprocs--;
705 }
706
707 /*
708 * Move p to a new or existing process group (and session)
709 *
710 * If we are creating a new pgrp, the pgid should equal
711 * the calling process' pid.
712 * If is only valid to enter a process group that is in the session
713 * of the process.
714 * Also mksess should only be set if we are creating a process group
715 *
716 * Only called from sys_setsid, sys_setpgid/sys_setpgrp and the
717 * SYSV setpgrp support for hpux.
718 */
719 int
720 enterpgrp(struct proc *curp, pid_t pid, pid_t pgid, int mksess)
721 {
722 struct pgrp *new_pgrp, *pgrp;
723 struct session *sess;
724 struct proc *p;
725 int rval;
726 pid_t pg_id = NO_PGID;
727
728 if (mksess)
729 sess = pool_get(&session_pool, PR_WAITOK);
730 else
731 sess = NULL;
732
733 /* Allocate data areas we might need before doing any validity checks */
734 mutex_enter(&proclist_lock); /* Because pid_table might change */
735 if (pid_table[pgid & pid_tbl_mask].pt_pgrp == 0) {
736 mutex_exit(&proclist_lock);
737 new_pgrp = pool_get(&pgrp_pool, PR_WAITOK);
738 mutex_enter(&proclist_lock);
739 } else
740 new_pgrp = NULL;
741 rval = EPERM; /* most common error (to save typing) */
742
743 /* Check pgrp exists or can be created */
744 pgrp = pid_table[pgid & pid_tbl_mask].pt_pgrp;
745 if (pgrp != NULL && pgrp->pg_id != pgid)
746 goto done;
747
748 /* Can only set another process under restricted circumstances. */
749 if (pid != curp->p_pid) {
750 /* must exist and be one of our children... */
751 if ((p = p_find(pid, PFIND_LOCKED)) == NULL ||
752 !inferior(p, curp)) {
753 rval = ESRCH;
754 goto done;
755 }
756 /* ... in the same session... */
757 if (sess != NULL || p->p_session != curp->p_session)
758 goto done;
759 /* ... existing pgid must be in same session ... */
760 if (pgrp != NULL && pgrp->pg_session != p->p_session)
761 goto done;
762 /* ... and not done an exec. */
763 if (p->p_flag & PK_EXEC) {
764 rval = EACCES;
765 goto done;
766 }
767 } else {
768 /* ... setsid() cannot re-enter a pgrp */
769 if (mksess && (curp->p_pgid == curp->p_pid ||
770 pg_find(curp->p_pid, PFIND_LOCKED)))
771 goto done;
772 p = curp;
773 }
774
775 /* Changing the process group/session of a session
776 leader is definitely off limits. */
777 if (SESS_LEADER(p)) {
778 if (sess == NULL && p->p_pgrp == pgrp)
779 /* unless it's a definite noop */
780 rval = 0;
781 goto done;
782 }
783
784 /* Can only create a process group with id of process */
785 if (pgrp == NULL && pgid != pid)
786 goto done;
787
788 /* Can only create a session if creating pgrp */
789 if (sess != NULL && pgrp != NULL)
790 goto done;
791
792 /* Check we allocated memory for a pgrp... */
793 if (pgrp == NULL && new_pgrp == NULL)
794 goto done;
795
796 /* Don't attach to 'zombie' pgrp */
797 if (pgrp != NULL && LIST_EMPTY(&pgrp->pg_members))
798 goto done;
799
800 /* Expect to succeed now */
801 rval = 0;
802
803 if (pgrp == p->p_pgrp)
804 /* nothing to do */
805 goto done;
806
807 /* Ok all setup, link up required structures */
808
809 if (pgrp == NULL) {
810 pgrp = new_pgrp;
811 new_pgrp = 0;
812 if (sess != NULL) {
813 sess->s_sid = p->p_pid;
814 sess->s_leader = p;
815 sess->s_count = 1;
816 sess->s_ttyvp = NULL;
817 sess->s_ttyp = NULL;
818 sess->s_flags = p->p_session->s_flags & ~S_LOGIN_SET;
819 memcpy(sess->s_login, p->p_session->s_login,
820 sizeof(sess->s_login));
821 p->p_lflag &= ~PL_CONTROLT;
822 } else {
823 sess = p->p_pgrp->pg_session;
824 SESSHOLD(sess);
825 }
826 pgrp->pg_session = sess;
827 sess = 0;
828
829 pgrp->pg_id = pgid;
830 LIST_INIT(&pgrp->pg_members);
831 #ifdef DIAGNOSTIC
832 if (__predict_false(pid_table[pgid & pid_tbl_mask].pt_pgrp))
833 panic("enterpgrp: pgrp table slot in use");
834 if (__predict_false(mksess && p != curp))
835 panic("enterpgrp: mksession and p != curproc");
836 #endif
837 mutex_enter(&proclist_mutex);
838 pid_table[pgid & pid_tbl_mask].pt_pgrp = pgrp;
839 pgrp->pg_jobc = 0;
840 } else
841 mutex_enter(&proclist_mutex);
842
843 #ifdef notyet
844 /*
845 * If there's a controlling terminal for the current session, we
846 * have to interlock with it. See ttread().
847 */
848 if (p->p_session->s_ttyvp != NULL) {
849 tp = p->p_session->s_ttyp;
850 mutex_enter(&tp->t_mutex);
851 } else
852 tp = NULL;
853 #endif
854
855 /*
856 * Adjust eligibility of affected pgrps to participate in job control.
857 * Increment eligibility counts before decrementing, otherwise we
858 * could reach 0 spuriously during the first call.
859 */
860 fixjobc(p, pgrp, 1);
861 fixjobc(p, p->p_pgrp, 0);
862
863 /* Move process to requested group. */
864 LIST_REMOVE(p, p_pglist);
865 if (LIST_EMPTY(&p->p_pgrp->pg_members))
866 /* defer delete until we've dumped the lock */
867 pg_id = p->p_pgrp->pg_id;
868 p->p_pgrp = pgrp;
869 LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
870 mutex_exit(&proclist_mutex);
871
872 #ifdef notyet
873 /* Done with the swap; we can release the tty mutex. */
874 if (tp != NULL)
875 mutex_exit(&tp->t_mutex);
876 #endif
877
878 done:
879 if (pg_id != NO_PGID)
880 pg_delete(pg_id);
881 mutex_exit(&proclist_lock);
882 if (sess != NULL)
883 pool_put(&session_pool, sess);
884 if (new_pgrp != NULL)
885 pool_put(&pgrp_pool, new_pgrp);
886 #ifdef DEBUG_PGRP
887 if (__predict_false(rval))
888 printf("enterpgrp(%d,%d,%d), curproc %d, rval %d\n",
889 pid, pgid, mksess, curp->p_pid, rval);
890 #endif
891 return rval;
892 }
893
894 /*
895 * Remove a process from its process group. Must be called with the
896 * proclist_lock held.
897 */
898 void
899 leavepgrp(struct proc *p)
900 {
901 struct pgrp *pgrp;
902
903 KASSERT(mutex_owned(&proclist_lock));
904
905 /*
906 * If there's a controlling terminal for the session, we have to
907 * interlock with it. See ttread().
908 */
909 mutex_enter(&proclist_mutex);
910 #ifdef notyet
911 if (p_>p_session->s_ttyvp != NULL) {
912 tp = p->p_session->s_ttyp;
913 mutex_enter(&tp->t_mutex);
914 } else
915 tp = NULL;
916 #endif
917
918 pgrp = p->p_pgrp;
919 LIST_REMOVE(p, p_pglist);
920 p->p_pgrp = NULL;
921
922 #ifdef notyet
923 if (tp != NULL)
924 mutex_exit(&tp->t_mutex);
925 #endif
926 mutex_exit(&proclist_mutex);
927
928 if (LIST_EMPTY(&pgrp->pg_members))
929 pg_delete(pgrp->pg_id);
930 }
931
932 /*
933 * Free a process group. Must be called with the proclist_lock held.
934 */
935 static void
936 pg_free(pid_t pg_id)
937 {
938 struct pgrp *pgrp;
939 struct pid_table *pt;
940
941 KASSERT(mutex_owned(&proclist_lock));
942
943 pt = &pid_table[pg_id & pid_tbl_mask];
944 pgrp = pt->pt_pgrp;
945 #ifdef DIAGNOSTIC
946 if (__predict_false(!pgrp || pgrp->pg_id != pg_id
947 || !LIST_EMPTY(&pgrp->pg_members)))
948 panic("pg_free: process group absent or has members");
949 #endif
950 pt->pt_pgrp = 0;
951
952 if (!P_VALID(pt->pt_proc)) {
953 /* orphaned pgrp, put slot onto free list */
954 #ifdef DIAGNOSTIC
955 if (__predict_false(P_NEXT(pt->pt_proc) & pid_tbl_mask))
956 panic("pg_free: process slot on free list");
957 #endif
958 mutex_enter(&proclist_mutex);
959 pg_id &= pid_tbl_mask;
960 pt = &pid_table[last_free_pt];
961 pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pg_id);
962 mutex_exit(&proclist_mutex);
963 last_free_pt = pg_id;
964 pid_alloc_cnt--;
965 }
966 pool_put(&pgrp_pool, pgrp);
967 }
968
969 /*
970 * Delete a process group. Must be called with the proclist_lock held.
971 */
972 static void
973 pg_delete(pid_t pg_id)
974 {
975 struct pgrp *pgrp;
976 struct tty *ttyp;
977 struct session *ss;
978 int is_pgrp_leader;
979
980 KASSERT(mutex_owned(&proclist_lock));
981
982 pgrp = pid_table[pg_id & pid_tbl_mask].pt_pgrp;
983 if (pgrp == NULL || pgrp->pg_id != pg_id ||
984 !LIST_EMPTY(&pgrp->pg_members))
985 return;
986
987 ss = pgrp->pg_session;
988
989 /* Remove reference (if any) from tty to this process group */
990 ttyp = ss->s_ttyp;
991 if (ttyp != NULL && ttyp->t_pgrp == pgrp) {
992 ttyp->t_pgrp = NULL;
993 #ifdef DIAGNOSTIC
994 if (ttyp->t_session != ss)
995 panic("pg_delete: wrong session on terminal");
996 #endif
997 }
998
999 /*
1000 * The leading process group in a session is freed
1001 * by sessdelete() if last reference.
1002 */
1003 is_pgrp_leader = (ss->s_sid == pgrp->pg_id);
1004 SESSRELE(ss);
1005
1006 if (is_pgrp_leader)
1007 return;
1008
1009 pg_free(pg_id);
1010 }
1011
1012 /*
1013 * Delete session - called from SESSRELE when s_count becomes zero.
1014 * Must be called with the proclist_lock held.
1015 */
1016 void
1017 sessdelete(struct session *ss)
1018 {
1019
1020 KASSERT(mutex_owned(&proclist_lock));
1021
1022 /*
1023 * We keep the pgrp with the same id as the session in
1024 * order to stop a process being given the same pid.
1025 * Since the pgrp holds a reference to the session, it
1026 * must be a 'zombie' pgrp by now.
1027 */
1028 pg_free(ss->s_sid);
1029 pool_put(&session_pool, ss);
1030 }
1031
1032 /*
1033 * Adjust pgrp jobc counters when specified process changes process group.
1034 * We count the number of processes in each process group that "qualify"
1035 * the group for terminal job control (those with a parent in a different
1036 * process group of the same session). If that count reaches zero, the
1037 * process group becomes orphaned. Check both the specified process'
1038 * process group and that of its children.
1039 * entering == 0 => p is leaving specified group.
1040 * entering == 1 => p is entering specified group.
1041 *
1042 * Call with proclist_lock held.
1043 */
1044 void
1045 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
1046 {
1047 struct pgrp *hispgrp;
1048 struct session *mysession = pgrp->pg_session;
1049 struct proc *child;
1050
1051 KASSERT(mutex_owned(&proclist_lock));
1052 KASSERT(mutex_owned(&proclist_mutex));
1053
1054 /*
1055 * Check p's parent to see whether p qualifies its own process
1056 * group; if so, adjust count for p's process group.
1057 */
1058 hispgrp = p->p_pptr->p_pgrp;
1059 if (hispgrp != pgrp && hispgrp->pg_session == mysession) {
1060 if (entering) {
1061 mutex_enter(&p->p_smutex);
1062 p->p_sflag &= ~PS_ORPHANPG;
1063 mutex_exit(&p->p_smutex);
1064 pgrp->pg_jobc++;
1065 } else if (--pgrp->pg_jobc == 0)
1066 orphanpg(pgrp);
1067 }
1068
1069 /*
1070 * Check this process' children to see whether they qualify
1071 * their process groups; if so, adjust counts for children's
1072 * process groups.
1073 */
1074 LIST_FOREACH(child, &p->p_children, p_sibling) {
1075 hispgrp = child->p_pgrp;
1076 if (hispgrp != pgrp && hispgrp->pg_session == mysession &&
1077 !P_ZOMBIE(child)) {
1078 if (entering) {
1079 mutex_enter(&child->p_smutex);
1080 child->p_sflag &= ~PS_ORPHANPG;
1081 mutex_exit(&child->p_smutex);
1082 hispgrp->pg_jobc++;
1083 } else if (--hispgrp->pg_jobc == 0)
1084 orphanpg(hispgrp);
1085 }
1086 }
1087 }
1088
1089 /*
1090 * A process group has become orphaned;
1091 * if there are any stopped processes in the group,
1092 * hang-up all process in that group.
1093 *
1094 * Call with proclist_lock held.
1095 */
1096 static void
1097 orphanpg(struct pgrp *pg)
1098 {
1099 struct proc *p;
1100 int doit;
1101
1102 KASSERT(mutex_owned(&proclist_lock));
1103 KASSERT(mutex_owned(&proclist_mutex));
1104
1105 doit = 0;
1106
1107 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
1108 mutex_enter(&p->p_smutex);
1109 if (p->p_stat == SSTOP) {
1110 doit = 1;
1111 p->p_sflag |= PS_ORPHANPG;
1112 }
1113 mutex_exit(&p->p_smutex);
1114 }
1115
1116 if (doit) {
1117 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
1118 psignal(p, SIGHUP);
1119 psignal(p, SIGCONT);
1120 }
1121 }
1122 }
1123
1124 #ifdef DDB
1125 #include <ddb/db_output.h>
1126 void pidtbl_dump(void);
1127 void
1128 pidtbl_dump(void)
1129 {
1130 struct pid_table *pt;
1131 struct proc *p;
1132 struct pgrp *pgrp;
1133 int id;
1134
1135 db_printf("pid table %p size %x, next %x, last %x\n",
1136 pid_table, pid_tbl_mask+1,
1137 next_free_pt, last_free_pt);
1138 for (pt = pid_table, id = 0; id <= pid_tbl_mask; id++, pt++) {
1139 p = pt->pt_proc;
1140 if (!P_VALID(p) && !pt->pt_pgrp)
1141 continue;
1142 db_printf(" id %x: ", id);
1143 if (P_VALID(p))
1144 db_printf("proc %p id %d (0x%x) %s\n",
1145 p, p->p_pid, p->p_pid, p->p_comm);
1146 else
1147 db_printf("next %x use %x\n",
1148 P_NEXT(p) & pid_tbl_mask,
1149 P_NEXT(p) & ~pid_tbl_mask);
1150 if ((pgrp = pt->pt_pgrp)) {
1151 db_printf("\tsession %p, sid %d, count %d, login %s\n",
1152 pgrp->pg_session, pgrp->pg_session->s_sid,
1153 pgrp->pg_session->s_count,
1154 pgrp->pg_session->s_login);
1155 db_printf("\tpgrp %p, pg_id %d, pg_jobc %d, members %p\n",
1156 pgrp, pgrp->pg_id, pgrp->pg_jobc,
1157 pgrp->pg_members.lh_first);
1158 for (p = pgrp->pg_members.lh_first; p != 0;
1159 p = p->p_pglist.le_next) {
1160 db_printf("\t\tpid %d addr %p pgrp %p %s\n",
1161 p->p_pid, p, p->p_pgrp, p->p_comm);
1162 }
1163 }
1164 }
1165 }
1166 #endif /* DDB */
1167
1168 #ifdef KSTACK_CHECK_MAGIC
1169 #include <sys/user.h>
1170
1171 #define KSTACK_MAGIC 0xdeadbeaf
1172
1173 /* XXX should be per process basis? */
1174 int kstackleftmin = KSTACK_SIZE;
1175 int kstackleftthres = KSTACK_SIZE / 8; /* warn if remaining stack is
1176 less than this */
1177
1178 void
1179 kstack_setup_magic(const struct lwp *l)
1180 {
1181 uint32_t *ip;
1182 uint32_t const *end;
1183
1184 KASSERT(l != NULL);
1185 KASSERT(l != &lwp0);
1186
1187 /*
1188 * fill all the stack with magic number
1189 * so that later modification on it can be detected.
1190 */
1191 ip = (uint32_t *)KSTACK_LOWEST_ADDR(l);
1192 end = (uint32_t *)((char *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
1193 for (; ip < end; ip++) {
1194 *ip = KSTACK_MAGIC;
1195 }
1196 }
1197
1198 void
1199 kstack_check_magic(const struct lwp *l)
1200 {
1201 uint32_t const *ip, *end;
1202 int stackleft;
1203
1204 KASSERT(l != NULL);
1205
1206 /* don't check proc0 */ /*XXX*/
1207 if (l == &lwp0)
1208 return;
1209
1210 #ifdef __MACHINE_STACK_GROWS_UP
1211 /* stack grows upwards (eg. hppa) */
1212 ip = (uint32_t *)((void *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
1213 end = (uint32_t *)KSTACK_LOWEST_ADDR(l);
1214 for (ip--; ip >= end; ip--)
1215 if (*ip != KSTACK_MAGIC)
1216 break;
1217
1218 stackleft = (void *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE - (void *)ip;
1219 #else /* __MACHINE_STACK_GROWS_UP */
1220 /* stack grows downwards (eg. i386) */
1221 ip = (uint32_t *)KSTACK_LOWEST_ADDR(l);
1222 end = (uint32_t *)((char *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
1223 for (; ip < end; ip++)
1224 if (*ip != KSTACK_MAGIC)
1225 break;
1226
1227 stackleft = ((const char *)ip) - (const char *)KSTACK_LOWEST_ADDR(l);
1228 #endif /* __MACHINE_STACK_GROWS_UP */
1229
1230 if (kstackleftmin > stackleft) {
1231 kstackleftmin = stackleft;
1232 if (stackleft < kstackleftthres)
1233 printf("warning: kernel stack left %d bytes"
1234 "(pid %u:lid %u)\n", stackleft,
1235 (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
1236 }
1237
1238 if (stackleft <= 0) {
1239 panic("magic on the top of kernel stack changed for "
1240 "pid %u, lid %u: maybe kernel stack overflow",
1241 (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
1242 }
1243 }
1244 #endif /* KSTACK_CHECK_MAGIC */
1245
1246 /*
1247 * XXXSMP this is bust, it grabs a read lock and then messes about
1248 * with allproc.
1249 */
1250 int
1251 proclist_foreach_call(struct proclist *list,
1252 int (*callback)(struct proc *, void *arg), void *arg)
1253 {
1254 struct proc marker;
1255 struct proc *p;
1256 struct lwp * const l = curlwp;
1257 int ret = 0;
1258
1259 marker.p_flag = PK_MARKER;
1260 uvm_lwp_hold(l);
1261 mutex_enter(&proclist_lock);
1262 for (p = LIST_FIRST(list); ret == 0 && p != NULL;) {
1263 if (p->p_flag & PK_MARKER) {
1264 p = LIST_NEXT(p, p_list);
1265 continue;
1266 }
1267 LIST_INSERT_AFTER(p, &marker, p_list);
1268 ret = (*callback)(p, arg);
1269 KASSERT(mutex_owned(&proclist_lock));
1270 p = LIST_NEXT(&marker, p_list);
1271 LIST_REMOVE(&marker, p_list);
1272 }
1273 mutex_exit(&proclist_lock);
1274 uvm_lwp_rele(l);
1275
1276 return ret;
1277 }
1278
1279 int
1280 proc_vmspace_getref(struct proc *p, struct vmspace **vm)
1281 {
1282
1283 /* XXXCDC: how should locking work here? */
1284
1285 /* curproc exception is for coredump. */
1286
1287 if ((p != curproc && (p->p_sflag & PS_WEXIT) != 0) ||
1288 (p->p_vmspace->vm_refcnt < 1)) { /* XXX */
1289 return EFAULT;
1290 }
1291
1292 uvmspace_addref(p->p_vmspace);
1293 *vm = p->p_vmspace;
1294
1295 return 0;
1296 }
1297
1298 /*
1299 * Acquire a write lock on the process credential.
1300 */
1301 void
1302 proc_crmod_enter(void)
1303 {
1304 struct lwp *l = curlwp;
1305 struct proc *p = l->l_proc;
1306 struct plimit *lim;
1307 kauth_cred_t oc;
1308 char *cn;
1309
1310 /* Reset what needs to be reset in plimit. */
1311 if (p->p_limit->pl_corename != defcorename) {
1312 lim_privatise(p, false);
1313 lim = p->p_limit;
1314 mutex_enter(&lim->pl_lock);
1315 cn = lim->pl_corename;
1316 lim->pl_corename = defcorename;
1317 mutex_exit(&lim->pl_lock);
1318 if (cn != defcorename)
1319 free(cn, M_TEMP);
1320 }
1321
1322 mutex_enter(&p->p_mutex);
1323
1324 /* Ensure the LWP cached credentials are up to date. */
1325 if ((oc = l->l_cred) != p->p_cred) {
1326 kauth_cred_hold(p->p_cred);
1327 l->l_cred = p->p_cred;
1328 kauth_cred_free(oc);
1329 }
1330
1331 }
1332
1333 /*
1334 * Set in a new process credential, and drop the write lock. The credential
1335 * must have a reference already. Optionally, free a no-longer required
1336 * credential. The scheduler also needs to inspect p_cred, so we also
1337 * briefly acquire the sched state mutex.
1338 */
1339 void
1340 proc_crmod_leave(kauth_cred_t scred, kauth_cred_t fcred, bool sugid)
1341 {
1342 struct lwp *l = curlwp;
1343 struct proc *p = l->l_proc;
1344 kauth_cred_t oc;
1345
1346 /* Is there a new credential to set in? */
1347 if (scred != NULL) {
1348 mutex_enter(&p->p_smutex);
1349 p->p_cred = scred;
1350 mutex_exit(&p->p_smutex);
1351
1352 /* Ensure the LWP cached credentials are up to date. */
1353 if ((oc = l->l_cred) != scred) {
1354 kauth_cred_hold(scred);
1355 l->l_cred = scred;
1356 }
1357 } else
1358 oc = NULL; /* XXXgcc */
1359
1360 if (sugid) {
1361 /*
1362 * Mark process as having changed credentials, stops
1363 * tracing etc.
1364 */
1365 p->p_flag |= PK_SUGID;
1366 }
1367
1368 mutex_exit(&p->p_mutex);
1369
1370 /* If there is a credential to be released, free it now. */
1371 if (fcred != NULL) {
1372 KASSERT(scred != NULL);
1373 kauth_cred_free(fcred);
1374 if (oc != scred)
1375 kauth_cred_free(oc);
1376 }
1377 }
1378
1379 /*
1380 * Acquire a reference on a process, to prevent it from exiting or execing.
1381 */
1382 int
1383 proc_addref(struct proc *p)
1384 {
1385
1386 KASSERT(mutex_owned(&p->p_mutex));
1387
1388 if (p->p_refcnt <= 0)
1389 return EAGAIN;
1390 p->p_refcnt++;
1391
1392 return 0;
1393 }
1394
1395 /*
1396 * Release a reference on a process.
1397 */
1398 void
1399 proc_delref(struct proc *p)
1400 {
1401
1402 KASSERT(mutex_owned(&p->p_mutex));
1403
1404 if (p->p_refcnt < 0) {
1405 if (++p->p_refcnt == 0)
1406 cv_broadcast(&p->p_refcv);
1407 } else {
1408 p->p_refcnt--;
1409 KASSERT(p->p_refcnt != 0);
1410 }
1411 }
1412
1413 /*
1414 * Wait for all references on the process to drain, and prevent new
1415 * references from being acquired.
1416 */
1417 void
1418 proc_drainrefs(struct proc *p)
1419 {
1420
1421 KASSERT(mutex_owned(&p->p_mutex));
1422 KASSERT(p->p_refcnt >= 0);
1423
1424 /*
1425 * The process itself holds the last reference. Once it's released,
1426 * no new references will be granted. If we have already locked out
1427 * new references (refcnt <= 0), potentially due to a failed exec,
1428 * there is nothing more to do.
1429 */
1430 if (p->p_refcnt == 0)
1431 return;
1432 p->p_refcnt = 1 - p->p_refcnt;
1433 while (p->p_refcnt != 0)
1434 cv_wait(&p->p_refcv, &p->p_mutex);
1435 }
1436
1437 /*
1438 * proc_specific_key_create --
1439 * Create a key for subsystem proc-specific data.
1440 */
1441 int
1442 proc_specific_key_create(specificdata_key_t *keyp, specificdata_dtor_t dtor)
1443 {
1444
1445 return (specificdata_key_create(proc_specificdata_domain, keyp, dtor));
1446 }
1447
1448 /*
1449 * proc_specific_key_delete --
1450 * Delete a key for subsystem proc-specific data.
1451 */
1452 void
1453 proc_specific_key_delete(specificdata_key_t key)
1454 {
1455
1456 specificdata_key_delete(proc_specificdata_domain, key);
1457 }
1458
1459 /*
1460 * proc_initspecific --
1461 * Initialize a proc's specificdata container.
1462 */
1463 void
1464 proc_initspecific(struct proc *p)
1465 {
1466 int error;
1467
1468 error = specificdata_init(proc_specificdata_domain, &p->p_specdataref);
1469 KASSERT(error == 0);
1470 }
1471
1472 /*
1473 * proc_finispecific --
1474 * Finalize a proc's specificdata container.
1475 */
1476 void
1477 proc_finispecific(struct proc *p)
1478 {
1479
1480 specificdata_fini(proc_specificdata_domain, &p->p_specdataref);
1481 }
1482
1483 /*
1484 * proc_getspecific --
1485 * Return proc-specific data corresponding to the specified key.
1486 */
1487 void *
1488 proc_getspecific(struct proc *p, specificdata_key_t key)
1489 {
1490
1491 return (specificdata_getspecific(proc_specificdata_domain,
1492 &p->p_specdataref, key));
1493 }
1494
1495 /*
1496 * proc_setspecific --
1497 * Set proc-specific data corresponding to the specified key.
1498 */
1499 void
1500 proc_setspecific(struct proc *p, specificdata_key_t key, void *data)
1501 {
1502
1503 specificdata_setspecific(proc_specificdata_domain,
1504 &p->p_specdataref, key, data);
1505 }
1506