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