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