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