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