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