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