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