kern_proc.c revision 1.92 1 /* $NetBSD: kern_proc.c,v 1.92 2006/07/19 21:11:37 ad Exp $ */
2
3 /*-
4 * Copyright (c) 1999 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.
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.92 2006/07/19 21:11:37 ad 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/sa.h>
98 #include <sys/savar.h>
99 #include <sys/filedesc.h>
100 #include <sys/kauth.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 /*
114 * Process list locking:
115 *
116 * We have two types of locks on the proclists: read locks and write
117 * locks. Read locks can be used in interrupt context, so while we
118 * hold the write lock, we must also block clock interrupts to
119 * lock out any scheduling changes that may happen in interrupt
120 * context.
121 *
122 * The proclist lock locks the following structures:
123 *
124 * allproc
125 * zombproc
126 * pid_table
127 */
128 struct lock proclist_lock;
129
130 /*
131 * pid to proc lookup is done by indexing the pid_table array.
132 * Since pid numbers are only allocated when an empty slot
133 * has been found, there is no need to search any lists ever.
134 * (an orphaned pgrp will lock the slot, a session will lock
135 * the pgrp with the same number.)
136 * If the table is too small it is reallocated with twice the
137 * previous size and the entries 'unzipped' into the two halves.
138 * A linked list of free entries is passed through the pt_proc
139 * field of 'free' items - set odd to be an invalid ptr.
140 */
141
142 struct pid_table {
143 struct proc *pt_proc;
144 struct pgrp *pt_pgrp;
145 };
146 #if 1 /* strongly typed cast - should be a noop */
147 static inline uint p2u(struct proc *p) { return (uint)(uintptr_t)p; }
148 #else
149 #define p2u(p) ((uint)p)
150 #endif
151 #define P_VALID(p) (!(p2u(p) & 1))
152 #define P_NEXT(p) (p2u(p) >> 1)
153 #define P_FREE(pid) ((struct proc *)(uintptr_t)((pid) << 1 | 1))
154
155 #define INITIAL_PID_TABLE_SIZE (1 << 5)
156 static struct pid_table *pid_table;
157 static uint pid_tbl_mask = INITIAL_PID_TABLE_SIZE - 1;
158 static uint pid_alloc_lim; /* max we allocate before growing table */
159 static uint pid_alloc_cnt; /* number of allocated pids */
160
161 /* links through free slots - never empty! */
162 static uint next_free_pt, last_free_pt;
163 static pid_t pid_max = PID_MAX; /* largest value we allocate */
164
165 /* Components of the first process -- never freed. */
166 struct session session0;
167 struct pgrp pgrp0;
168 struct proc proc0;
169 struct lwp lwp0;
170 kauth_cred_t cred0;
171 struct filedesc0 filedesc0;
172 struct cwdinfo cwdi0;
173 struct plimit limit0;
174 struct pstats pstat0;
175 struct vmspace vmspace0;
176 struct sigacts sigacts0;
177
178 extern struct user *proc0paddr;
179
180 extern const struct emul emul_netbsd; /* defined in kern_exec.c */
181
182 int nofile = NOFILE;
183 int maxuprc = MAXUPRC;
184 int cmask = CMASK;
185
186 POOL_INIT(proc_pool, sizeof(struct proc), 0, 0, 0, "procpl",
187 &pool_allocator_nointr);
188 POOL_INIT(lwp_pool, sizeof(struct lwp), 0, 0, 0, "lwppl",
189 &pool_allocator_nointr);
190 POOL_INIT(lwp_uc_pool, sizeof(ucontext_t), 0, 0, 0, "lwpucpl",
191 &pool_allocator_nointr);
192 POOL_INIT(pgrp_pool, sizeof(struct pgrp), 0, 0, 0, "pgrppl",
193 &pool_allocator_nointr);
194 POOL_INIT(plimit_pool, sizeof(struct plimit), 0, 0, 0, "plimitpl",
195 &pool_allocator_nointr);
196 POOL_INIT(pstats_pool, sizeof(struct pstats), 0, 0, 0, "pstatspl",
197 &pool_allocator_nointr);
198 POOL_INIT(rusage_pool, sizeof(struct rusage), 0, 0, 0, "rusgepl",
199 &pool_allocator_nointr);
200 POOL_INIT(ras_pool, sizeof(struct ras), 0, 0, 0, "raspl",
201 &pool_allocator_nointr);
202 POOL_INIT(session_pool, sizeof(struct session), 0, 0, 0, "sessionpl",
203 &pool_allocator_nointr);
204
205 MALLOC_DEFINE(M_EMULDATA, "emuldata", "Per-process emulation data");
206 MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
207 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
208
209 /*
210 * The process list descriptors, used during pid allocation and
211 * by sysctl. No locking on this data structure is needed since
212 * it is completely static.
213 */
214 const struct proclist_desc proclists[] = {
215 { &allproc },
216 { &zombproc },
217 { NULL },
218 };
219
220 static void orphanpg(struct pgrp *);
221 static void pg_delete(pid_t);
222
223 /*
224 * Initialize global process hashing structures.
225 */
226 void
227 procinit(void)
228 {
229 const struct proclist_desc *pd;
230 int i;
231 #define LINK_EMPTY ((PID_MAX + INITIAL_PID_TABLE_SIZE) & ~(INITIAL_PID_TABLE_SIZE - 1))
232
233 for (pd = proclists; pd->pd_list != NULL; pd++)
234 LIST_INIT(pd->pd_list);
235
236 spinlockinit(&proclist_lock, "proclk", 0);
237
238 pid_table = malloc(INITIAL_PID_TABLE_SIZE * sizeof *pid_table,
239 M_PROC, M_WAITOK);
240 /* Set free list running through table...
241 Preset 'use count' above PID_MAX so we allocate pid 1 next. */
242 for (i = 0; i <= pid_tbl_mask; i++) {
243 pid_table[i].pt_proc = P_FREE(LINK_EMPTY + i + 1);
244 pid_table[i].pt_pgrp = 0;
245 }
246 /* slot 0 is just grabbed */
247 next_free_pt = 1;
248 /* Need to fix last entry. */
249 last_free_pt = pid_tbl_mask;
250 pid_table[last_free_pt].pt_proc = P_FREE(LINK_EMPTY);
251 /* point at which we grow table - to avoid reusing pids too often */
252 pid_alloc_lim = pid_tbl_mask - 1;
253 #undef LINK_EMPTY
254
255 LIST_INIT(&alllwp);
256
257 uihashtbl =
258 hashinit(maxproc / 16, HASH_LIST, M_PROC, M_WAITOK, &uihash);
259 }
260
261 /*
262 * Initialize process 0.
263 */
264 void
265 proc0_init(void)
266 {
267 struct proc *p;
268 struct pgrp *pg;
269 struct session *sess;
270 struct lwp *l;
271 int s;
272 u_int i;
273 rlim_t lim;
274
275 p = &proc0;
276 pg = &pgrp0;
277 sess = &session0;
278 l = &lwp0;
279
280 simple_lock_init(&p->p_lock);
281 LIST_INIT(&p->p_lwps);
282 LIST_INSERT_HEAD(&p->p_lwps, l, l_sibling);
283 p->p_nlwps = 1;
284 simple_lock_init(&p->p_sigctx.ps_silock);
285 CIRCLEQ_INIT(&p->p_sigctx.ps_siginfo);
286
287 s = proclist_lock_write();
288
289 pid_table[0].pt_proc = p;
290 LIST_INSERT_HEAD(&allproc, p, p_list);
291 LIST_INSERT_HEAD(&alllwp, l, l_list);
292
293 p->p_pgrp = pg;
294 pid_table[0].pt_pgrp = pg;
295 LIST_INIT(&pg->pg_members);
296 LIST_INSERT_HEAD(&pg->pg_members, p, p_pglist);
297
298 pg->pg_session = sess;
299 sess->s_count = 1;
300 sess->s_sid = 0;
301 sess->s_leader = p;
302
303 proclist_unlock_write(s);
304
305 /*
306 * Set P_NOCLDWAIT so that kernel threads are reparented to
307 * init(8) when they exit. init(8) can easily wait them out
308 * for us.
309 */
310 p->p_flag = P_SYSTEM | P_NOCLDWAIT;
311 p->p_stat = SACTIVE;
312 p->p_nice = NZERO;
313 p->p_emul = &emul_netbsd;
314 #ifdef __HAVE_SYSCALL_INTERN
315 (*p->p_emul->e_syscall_intern)(p);
316 #endif
317 strncpy(p->p_comm, "swapper", MAXCOMLEN);
318
319 l->l_flag = L_INMEM;
320 l->l_stat = LSONPROC;
321 p->p_nrlwps = 1;
322
323 callout_init(&l->l_tsleep_ch);
324
325 /* Create credentials. */
326 cred0 = kauth_cred_alloc();
327 p->p_cred = cred0;
328 lwp_update_creds(l);
329
330 /* Create the CWD info. */
331 p->p_cwdi = &cwdi0;
332 cwdi0.cwdi_cmask = cmask;
333 cwdi0.cwdi_refcnt = 1;
334 simple_lock_init(&cwdi0.cwdi_slock);
335
336 /* Create the limits structures. */
337 p->p_limit = &limit0;
338 simple_lock_init(&limit0.p_slock);
339 for (i = 0; i < sizeof(p->p_rlimit)/sizeof(p->p_rlimit[0]); i++)
340 limit0.pl_rlimit[i].rlim_cur =
341 limit0.pl_rlimit[i].rlim_max = RLIM_INFINITY;
342
343 limit0.pl_rlimit[RLIMIT_NOFILE].rlim_max = maxfiles;
344 limit0.pl_rlimit[RLIMIT_NOFILE].rlim_cur =
345 maxfiles < nofile ? maxfiles : nofile;
346
347 limit0.pl_rlimit[RLIMIT_NPROC].rlim_max = maxproc;
348 limit0.pl_rlimit[RLIMIT_NPROC].rlim_cur =
349 maxproc < maxuprc ? maxproc : maxuprc;
350
351 lim = ptoa(uvmexp.free);
352 limit0.pl_rlimit[RLIMIT_RSS].rlim_max = lim;
353 limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_max = lim;
354 limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_cur = lim / 3;
355 limit0.pl_corename = defcorename;
356 limit0.p_refcnt = 1;
357
358 /* Configure virtual memory system, set vm rlimits. */
359 uvm_init_limits(p);
360
361 /* Initialize file descriptor table for proc0. */
362 p->p_fd = &filedesc0.fd_fd;
363 fdinit1(&filedesc0);
364
365 /*
366 * Initialize proc0's vmspace, which uses the kernel pmap.
367 * All kernel processes (which never have user space mappings)
368 * share proc0's vmspace, and thus, the kernel pmap.
369 */
370 uvmspace_init(&vmspace0, pmap_kernel(), round_page(VM_MIN_ADDRESS),
371 trunc_page(VM_MAX_ADDRESS));
372 p->p_vmspace = &vmspace0;
373
374 l->l_addr = proc0paddr; /* XXX */
375
376 p->p_stats = &pstat0;
377
378 /* Initialize signal state for proc0. */
379 p->p_sigacts = &sigacts0;
380 siginit(p);
381 }
382
383 /*
384 * Acquire a read lock on the proclist.
385 */
386 void
387 proclist_lock_read(void)
388 {
389 int error;
390
391 error = spinlockmgr(&proclist_lock, LK_SHARED, NULL);
392 #ifdef DIAGNOSTIC
393 if (__predict_false(error != 0))
394 panic("proclist_lock_read: failed to acquire lock");
395 #endif
396 }
397
398 /*
399 * Release a read lock on the proclist.
400 */
401 void
402 proclist_unlock_read(void)
403 {
404
405 (void) spinlockmgr(&proclist_lock, LK_RELEASE, NULL);
406 }
407
408 /*
409 * Acquire a write lock on the proclist.
410 */
411 int
412 proclist_lock_write(void)
413 {
414 int s, error;
415
416 s = splclock();
417 error = spinlockmgr(&proclist_lock, LK_EXCLUSIVE, NULL);
418 #ifdef DIAGNOSTIC
419 if (__predict_false(error != 0))
420 panic("proclist_lock: failed to acquire lock");
421 #endif
422 return s;
423 }
424
425 /*
426 * Release a write lock on the proclist.
427 */
428 void
429 proclist_unlock_write(int s)
430 {
431
432 (void) spinlockmgr(&proclist_lock, LK_RELEASE, NULL);
433 splx(s);
434 }
435
436 /*
437 * Check that the specified process group is in the session of the
438 * specified process.
439 * Treats -ve ids as process ids.
440 * Used to validate TIOCSPGRP requests.
441 */
442 int
443 pgid_in_session(struct proc *p, pid_t pg_id)
444 {
445 struct pgrp *pgrp;
446
447 if (pg_id < 0) {
448 struct proc *p1 = pfind(-pg_id);
449 if (p1 == NULL)
450 return EINVAL;
451 pgrp = p1->p_pgrp;
452 } else {
453 pgrp = pgfind(pg_id);
454 if (pgrp == NULL)
455 return EINVAL;
456 }
457 if (pgrp->pg_session != p->p_pgrp->pg_session)
458 return EPERM;
459 return 0;
460 }
461
462 /*
463 * Is p an inferior of q?
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 proclist_lock_read();
486 p = pid_table[pid & pid_tbl_mask].pt_proc;
487 /* Only allow live processes to be found by pid. */
488 if (P_VALID(p) && p->p_pid == pid &&
489 ((stat = p->p_stat) == SACTIVE || stat == SSTOP
490 || (stat == SZOMB && (flags & PFIND_ZOMBIE)))) {
491 if (flags & PFIND_UNLOCK_OK)
492 proclist_unlock_read();
493 return p;
494 }
495 if (flags & PFIND_UNLOCK_FAIL)
496 proclist_unlock_read();
497 return NULL;
498 }
499
500
501 /*
502 * Locate a process group by number
503 */
504 struct pgrp *
505 pg_find(pid_t pgid, uint flags)
506 {
507 struct pgrp *pg;
508
509 if (!(flags & PFIND_LOCKED))
510 proclist_lock_read();
511 pg = pid_table[pgid & pid_tbl_mask].pt_pgrp;
512 /*
513 * Can't look up a pgrp that only exists because the session
514 * hasn't died yet (traditional)
515 */
516 if (pg == NULL || pg->pg_id != pgid || LIST_EMPTY(&pg->pg_members)) {
517 if (flags & PFIND_UNLOCK_FAIL)
518 proclist_unlock_read();
519 return NULL;
520 }
521
522 if (flags & PFIND_UNLOCK_OK)
523 proclist_unlock_read();
524 return pg;
525 }
526
527 static void
528 expand_pid_table(void)
529 {
530 uint pt_size = pid_tbl_mask + 1;
531 struct pid_table *n_pt, *new_pt;
532 struct proc *proc;
533 struct pgrp *pgrp;
534 int i;
535 int s;
536 pid_t pid;
537
538 new_pt = malloc(pt_size * 2 * sizeof *new_pt, M_PROC, M_WAITOK);
539
540 s = proclist_lock_write();
541 if (pt_size != pid_tbl_mask + 1) {
542 /* Another process beat us to it... */
543 proclist_unlock_write(s);
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 n_pt = pid_table;
589 pid_table = new_pt;
590 pid_tbl_mask = pt_size * 2 - 1;
591
592 /*
593 * pid_max starts as PID_MAX (= 30000), once we have 16384
594 * allocated pids we need it to be larger!
595 */
596 if (pid_tbl_mask > PID_MAX) {
597 pid_max = pid_tbl_mask * 2 + 1;
598 pid_alloc_lim |= pid_alloc_lim << 1;
599 } else
600 pid_alloc_lim <<= 1; /* doubles number of free slots... */
601
602 proclist_unlock_write(s);
603 FREE(n_pt, M_PROC);
604 }
605
606 struct proc *
607 proc_alloc(void)
608 {
609 struct proc *p;
610 int s;
611 int nxt;
612 pid_t pid;
613 struct pid_table *pt;
614
615 p = pool_get(&proc_pool, PR_WAITOK);
616 p->p_stat = SIDL; /* protect against others */
617
618 /* allocate next free pid */
619
620 for (;;expand_pid_table()) {
621 if (__predict_false(pid_alloc_cnt >= pid_alloc_lim))
622 /* ensure pids cycle through 2000+ values */
623 continue;
624 s = proclist_lock_write();
625 pt = &pid_table[next_free_pt];
626 #ifdef DIAGNOSTIC
627 if (__predict_false(P_VALID(pt->pt_proc) || pt->pt_pgrp))
628 panic("proc_alloc: slot busy");
629 #endif
630 nxt = P_NEXT(pt->pt_proc);
631 if (nxt & pid_tbl_mask)
632 break;
633 /* Table full - expand (NB last entry not used....) */
634 proclist_unlock_write(s);
635 }
636
637 /* pid is 'saved use count' + 'size' + entry */
638 pid = (nxt & ~pid_tbl_mask) + pid_tbl_mask + 1 + next_free_pt;
639 if ((uint)pid > (uint)pid_max)
640 pid &= pid_tbl_mask;
641 p->p_pid = pid;
642 next_free_pt = nxt & pid_tbl_mask;
643
644 /* Grab table slot */
645 pt->pt_proc = p;
646 pid_alloc_cnt++;
647
648 proclist_unlock_write(s);
649
650 return p;
651 }
652
653 /*
654 * Free last resources of a process - called from proc_free (in kern_exit.c)
655 */
656 void
657 proc_free_mem(struct proc *p)
658 {
659 int s;
660 pid_t pid = p->p_pid;
661 struct pid_table *pt;
662
663 s = proclist_lock_write();
664
665 pt = &pid_table[pid & pid_tbl_mask];
666 #ifdef DIAGNOSTIC
667 if (__predict_false(pt->pt_proc != p))
668 panic("proc_free: pid_table mismatch, pid %x, proc %p",
669 pid, p);
670 #endif
671 /* save pid use count in slot */
672 pt->pt_proc = P_FREE(pid & ~pid_tbl_mask);
673
674 if (pt->pt_pgrp == NULL) {
675 /* link last freed entry onto ours */
676 pid &= pid_tbl_mask;
677 pt = &pid_table[last_free_pt];
678 pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pid);
679 last_free_pt = pid;
680 pid_alloc_cnt--;
681 }
682
683 nprocs--;
684 proclist_unlock_write(s);
685
686 pool_put(&proc_pool, p);
687 }
688
689 /*
690 * Move p to a new or existing process group (and session)
691 *
692 * If we are creating a new pgrp, the pgid should equal
693 * the calling process' pid.
694 * If is only valid to enter a process group that is in the session
695 * of the process.
696 * Also mksess should only be set if we are creating a process group
697 *
698 * Only called from sys_setsid, sys_setpgid/sys_setpgrp and the
699 * SYSV setpgrp support for hpux == enterpgrp(curproc, curproc->p_pid)
700 */
701 int
702 enterpgrp(struct proc *p, pid_t pgid, int mksess)
703 {
704 struct pgrp *new_pgrp, *pgrp;
705 struct session *sess;
706 struct proc *curp = curproc;
707 pid_t pid = p->p_pid;
708 int rval;
709 int s;
710 pid_t pg_id = NO_PGID;
711
712 /* Allocate data areas we might need before doing any validity checks */
713 proclist_lock_read(); /* Because pid_table might change */
714 if (pid_table[pgid & pid_tbl_mask].pt_pgrp == 0) {
715 proclist_unlock_read();
716 new_pgrp = pool_get(&pgrp_pool, PR_WAITOK);
717 } else {
718 proclist_unlock_read();
719 new_pgrp = NULL;
720 }
721 if (mksess)
722 sess = pool_get(&session_pool, M_WAITOK);
723 else
724 sess = NULL;
725
726 s = proclist_lock_write();
727 rval = EPERM; /* most common error (to save typing) */
728
729 /* Check pgrp exists or can be created */
730 pgrp = pid_table[pgid & pid_tbl_mask].pt_pgrp;
731 if (pgrp != NULL && pgrp->pg_id != pgid)
732 goto done;
733
734 /* Can only set another process under restricted circumstances. */
735 if (p != curp) {
736 /* must exist and be one of our children... */
737 if (p != pid_table[pid & pid_tbl_mask].pt_proc
738 || !inferior(p, curp)) {
739 rval = ESRCH;
740 goto done;
741 }
742 /* ... in the same session... */
743 if (sess != NULL || p->p_session != curp->p_session)
744 goto done;
745 /* ... existing pgid must be in same session ... */
746 if (pgrp != NULL && pgrp->pg_session != p->p_session)
747 goto done;
748 /* ... and not done an exec. */
749 if (p->p_flag & P_EXEC) {
750 rval = EACCES;
751 goto done;
752 }
753 }
754
755 /* Changing the process group/session of a session
756 leader is definitely off limits. */
757 if (SESS_LEADER(p)) {
758 if (sess == NULL && p->p_pgrp == pgrp)
759 /* unless it's a definite noop */
760 rval = 0;
761 goto done;
762 }
763
764 /* Can only create a process group with id of process */
765 if (pgrp == NULL && pgid != pid)
766 goto done;
767
768 /* Can only create a session if creating pgrp */
769 if (sess != NULL && pgrp != NULL)
770 goto done;
771
772 /* Check we allocated memory for a pgrp... */
773 if (pgrp == NULL && new_pgrp == NULL)
774 goto done;
775
776 /* Don't attach to 'zombie' pgrp */
777 if (pgrp != NULL && LIST_EMPTY(&pgrp->pg_members))
778 goto done;
779
780 /* Expect to succeed now */
781 rval = 0;
782
783 if (pgrp == p->p_pgrp)
784 /* nothing to do */
785 goto done;
786
787 /* Ok all setup, link up required structures */
788 if (pgrp == NULL) {
789 pgrp = new_pgrp;
790 new_pgrp = 0;
791 if (sess != NULL) {
792 sess->s_sid = p->p_pid;
793 sess->s_leader = p;
794 sess->s_count = 1;
795 sess->s_ttyvp = NULL;
796 sess->s_ttyp = NULL;
797 sess->s_flags = p->p_session->s_flags & ~S_LOGIN_SET;
798 memcpy(sess->s_login, p->p_session->s_login,
799 sizeof(sess->s_login));
800 p->p_flag &= ~P_CONTROLT;
801 } else {
802 sess = p->p_pgrp->pg_session;
803 SESSHOLD(sess);
804 }
805 pgrp->pg_session = sess;
806 sess = 0;
807
808 pgrp->pg_id = pgid;
809 LIST_INIT(&pgrp->pg_members);
810 #ifdef DIAGNOSTIC
811 if (__predict_false(pid_table[pgid & pid_tbl_mask].pt_pgrp))
812 panic("enterpgrp: pgrp table slot in use");
813 if (__predict_false(mksess && p != curp))
814 panic("enterpgrp: mksession and p != curproc");
815 #endif
816 pid_table[pgid & pid_tbl_mask].pt_pgrp = pgrp;
817 pgrp->pg_jobc = 0;
818 }
819
820 /*
821 * Adjust eligibility of affected pgrps to participate in job control.
822 * Increment eligibility counts before decrementing, otherwise we
823 * could reach 0 spuriously during the first call.
824 */
825 fixjobc(p, pgrp, 1);
826 fixjobc(p, p->p_pgrp, 0);
827
828 /* Move process to requested group */
829 LIST_REMOVE(p, p_pglist);
830 if (LIST_EMPTY(&p->p_pgrp->pg_members))
831 /* defer delete until we've dumped the lock */
832 pg_id = p->p_pgrp->pg_id;
833 p->p_pgrp = pgrp;
834 LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
835
836 done:
837 proclist_unlock_write(s);
838 if (sess != NULL)
839 pool_put(&session_pool, sess);
840 if (new_pgrp != NULL)
841 pool_put(&pgrp_pool, new_pgrp);
842 if (pg_id != NO_PGID)
843 pg_delete(pg_id);
844 #ifdef DEBUG_PGRP
845 if (__predict_false(rval))
846 printf("enterpgrp(%d,%d,%d), curproc %d, rval %d\n",
847 pid, pgid, mksess, curp->p_pid, rval);
848 #endif
849 return rval;
850 }
851
852 /*
853 * remove process from process group
854 */
855 int
856 leavepgrp(struct proc *p)
857 {
858 int s;
859 struct pgrp *pgrp;
860 pid_t pg_id;
861
862 s = proclist_lock_write();
863 pgrp = p->p_pgrp;
864 LIST_REMOVE(p, p_pglist);
865 p->p_pgrp = 0;
866 pg_id = LIST_EMPTY(&pgrp->pg_members) ? pgrp->pg_id : NO_PGID;
867 proclist_unlock_write(s);
868
869 if (pg_id != NO_PGID)
870 pg_delete(pg_id);
871 return 0;
872 }
873
874 static void
875 pg_free(pid_t pg_id)
876 {
877 struct pgrp *pgrp;
878 struct pid_table *pt;
879 int s;
880
881 s = proclist_lock_write();
882 pt = &pid_table[pg_id & pid_tbl_mask];
883 pgrp = pt->pt_pgrp;
884 #ifdef DIAGNOSTIC
885 if (__predict_false(!pgrp || pgrp->pg_id != pg_id
886 || !LIST_EMPTY(&pgrp->pg_members)))
887 panic("pg_free: process group absent or has members");
888 #endif
889 pt->pt_pgrp = 0;
890
891 if (!P_VALID(pt->pt_proc)) {
892 /* orphaned pgrp, put slot onto free list */
893 #ifdef DIAGNOSTIC
894 if (__predict_false(P_NEXT(pt->pt_proc) & pid_tbl_mask))
895 panic("pg_free: process slot on free list");
896 #endif
897
898 pg_id &= pid_tbl_mask;
899 pt = &pid_table[last_free_pt];
900 pt->pt_proc = P_FREE(P_NEXT(pt->pt_proc) | pg_id);
901 last_free_pt = pg_id;
902 pid_alloc_cnt--;
903 }
904 proclist_unlock_write(s);
905
906 pool_put(&pgrp_pool, pgrp);
907 }
908
909 /*
910 * delete a process group
911 */
912 static void
913 pg_delete(pid_t pg_id)
914 {
915 struct pgrp *pgrp;
916 struct tty *ttyp;
917 struct session *ss;
918 int s, is_pgrp_leader;
919
920 s = proclist_lock_write();
921 pgrp = pid_table[pg_id & pid_tbl_mask].pt_pgrp;
922 if (pgrp == NULL || pgrp->pg_id != pg_id ||
923 !LIST_EMPTY(&pgrp->pg_members)) {
924 proclist_unlock_write(s);
925 return;
926 }
927
928 ss = pgrp->pg_session;
929
930 /* Remove reference (if any) from tty to this process group */
931 ttyp = ss->s_ttyp;
932 if (ttyp != NULL && ttyp->t_pgrp == pgrp) {
933 ttyp->t_pgrp = NULL;
934 #ifdef DIAGNOSTIC
935 if (ttyp->t_session != ss)
936 panic("pg_delete: wrong session on terminal");
937 #endif
938 }
939
940 /*
941 * The leading process group in a session is freed
942 * by sessdelete() if last reference.
943 */
944 is_pgrp_leader = (ss->s_sid == pgrp->pg_id);
945 proclist_unlock_write(s);
946 SESSRELE(ss);
947
948 if (is_pgrp_leader)
949 return;
950
951 pg_free(pg_id);
952 }
953
954 /*
955 * Delete session - called from SESSRELE when s_count becomes zero.
956 */
957 void
958 sessdelete(struct session *ss)
959 {
960 /*
961 * We keep the pgrp with the same id as the session in
962 * order to stop a process being given the same pid.
963 * Since the pgrp holds a reference to the session, it
964 * must be a 'zombie' pgrp by now.
965 */
966
967 pg_free(ss->s_sid);
968
969 pool_put(&session_pool, ss);
970 }
971
972 /*
973 * Adjust pgrp jobc counters when specified process changes process group.
974 * We count the number of processes in each process group that "qualify"
975 * the group for terminal job control (those with a parent in a different
976 * process group of the same session). If that count reaches zero, the
977 * process group becomes orphaned. Check both the specified process'
978 * process group and that of its children.
979 * entering == 0 => p is leaving specified group.
980 * entering == 1 => p is entering specified group.
981 *
982 * Call with proclist_lock held.
983 */
984 void
985 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
986 {
987 struct pgrp *hispgrp;
988 struct session *mysession = pgrp->pg_session;
989 struct proc *child;
990
991 /*
992 * Check p's parent to see whether p qualifies its own process
993 * group; if so, adjust count for p's process group.
994 */
995 hispgrp = p->p_pptr->p_pgrp;
996 if (hispgrp != pgrp && hispgrp->pg_session == mysession) {
997 if (entering)
998 pgrp->pg_jobc++;
999 else if (--pgrp->pg_jobc == 0)
1000 orphanpg(pgrp);
1001 }
1002
1003 /*
1004 * Check this process' children to see whether they qualify
1005 * their process groups; if so, adjust counts for children's
1006 * process groups.
1007 */
1008 LIST_FOREACH(child, &p->p_children, p_sibling) {
1009 hispgrp = child->p_pgrp;
1010 if (hispgrp != pgrp && hispgrp->pg_session == mysession &&
1011 !P_ZOMBIE(child)) {
1012 if (entering)
1013 hispgrp->pg_jobc++;
1014 else if (--hispgrp->pg_jobc == 0)
1015 orphanpg(hispgrp);
1016 }
1017 }
1018 }
1019
1020 /*
1021 * A process group has become orphaned;
1022 * if there are any stopped processes in the group,
1023 * hang-up all process in that group.
1024 *
1025 * Call with proclist_lock held.
1026 */
1027 static void
1028 orphanpg(struct pgrp *pg)
1029 {
1030 struct proc *p;
1031
1032 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
1033 if (p->p_stat == SSTOP) {
1034 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
1035 psignal(p, SIGHUP);
1036 psignal(p, SIGCONT);
1037 }
1038 return;
1039 }
1040 }
1041 }
1042
1043 /* mark process as suid/sgid, reset some values to defaults */
1044 void
1045 p_sugid(struct proc *p)
1046 {
1047 struct plimit *lim;
1048 char *cn;
1049
1050 p->p_flag |= P_SUGID;
1051 /* reset what needs to be reset in plimit */
1052 lim = p->p_limit;
1053 if (lim->pl_corename != defcorename) {
1054 if (lim->p_refcnt > 1 &&
1055 (lim->p_lflags & PL_SHAREMOD) == 0) {
1056 p->p_limit = limcopy(lim);
1057 limfree(lim);
1058 lim = p->p_limit;
1059 }
1060 simple_lock(&lim->p_slock);
1061 cn = lim->pl_corename;
1062 lim->pl_corename = defcorename;
1063 simple_unlock(&lim->p_slock);
1064 if (cn != defcorename)
1065 free(cn, M_TEMP);
1066 }
1067 }
1068
1069 #ifdef DDB
1070 #include <ddb/db_output.h>
1071 void pidtbl_dump(void);
1072 void
1073 pidtbl_dump(void)
1074 {
1075 struct pid_table *pt;
1076 struct proc *p;
1077 struct pgrp *pgrp;
1078 int id;
1079
1080 db_printf("pid table %p size %x, next %x, last %x\n",
1081 pid_table, pid_tbl_mask+1,
1082 next_free_pt, last_free_pt);
1083 for (pt = pid_table, id = 0; id <= pid_tbl_mask; id++, pt++) {
1084 p = pt->pt_proc;
1085 if (!P_VALID(p) && !pt->pt_pgrp)
1086 continue;
1087 db_printf(" id %x: ", id);
1088 if (P_VALID(p))
1089 db_printf("proc %p id %d (0x%x) %s\n",
1090 p, p->p_pid, p->p_pid, p->p_comm);
1091 else
1092 db_printf("next %x use %x\n",
1093 P_NEXT(p) & pid_tbl_mask,
1094 P_NEXT(p) & ~pid_tbl_mask);
1095 if ((pgrp = pt->pt_pgrp)) {
1096 db_printf("\tsession %p, sid %d, count %d, login %s\n",
1097 pgrp->pg_session, pgrp->pg_session->s_sid,
1098 pgrp->pg_session->s_count,
1099 pgrp->pg_session->s_login);
1100 db_printf("\tpgrp %p, pg_id %d, pg_jobc %d, members %p\n",
1101 pgrp, pgrp->pg_id, pgrp->pg_jobc,
1102 pgrp->pg_members.lh_first);
1103 for (p = pgrp->pg_members.lh_first; p != 0;
1104 p = p->p_pglist.le_next) {
1105 db_printf("\t\tpid %d addr %p pgrp %p %s\n",
1106 p->p_pid, p, p->p_pgrp, p->p_comm);
1107 }
1108 }
1109 }
1110 }
1111 #endif /* DDB */
1112
1113 #ifdef KSTACK_CHECK_MAGIC
1114 #include <sys/user.h>
1115
1116 #define KSTACK_MAGIC 0xdeadbeaf
1117
1118 /* XXX should be per process basis? */
1119 int kstackleftmin = KSTACK_SIZE;
1120 int kstackleftthres = KSTACK_SIZE / 8; /* warn if remaining stack is
1121 less than this */
1122
1123 void
1124 kstack_setup_magic(const struct lwp *l)
1125 {
1126 uint32_t *ip;
1127 uint32_t const *end;
1128
1129 KASSERT(l != NULL);
1130 KASSERT(l != &lwp0);
1131
1132 /*
1133 * fill all the stack with magic number
1134 * so that later modification on it can be detected.
1135 */
1136 ip = (uint32_t *)KSTACK_LOWEST_ADDR(l);
1137 end = (uint32_t *)((caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
1138 for (; ip < end; ip++) {
1139 *ip = KSTACK_MAGIC;
1140 }
1141 }
1142
1143 void
1144 kstack_check_magic(const struct lwp *l)
1145 {
1146 uint32_t const *ip, *end;
1147 int stackleft;
1148
1149 KASSERT(l != NULL);
1150
1151 /* don't check proc0 */ /*XXX*/
1152 if (l == &lwp0)
1153 return;
1154
1155 #ifdef __MACHINE_STACK_GROWS_UP
1156 /* stack grows upwards (eg. hppa) */
1157 ip = (uint32_t *)((caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
1158 end = (uint32_t *)KSTACK_LOWEST_ADDR(l);
1159 for (ip--; ip >= end; ip--)
1160 if (*ip != KSTACK_MAGIC)
1161 break;
1162
1163 stackleft = (caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE - (caddr_t)ip;
1164 #else /* __MACHINE_STACK_GROWS_UP */
1165 /* stack grows downwards (eg. i386) */
1166 ip = (uint32_t *)KSTACK_LOWEST_ADDR(l);
1167 end = (uint32_t *)((caddr_t)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
1168 for (; ip < end; ip++)
1169 if (*ip != KSTACK_MAGIC)
1170 break;
1171
1172 stackleft = (caddr_t)ip - KSTACK_LOWEST_ADDR(l);
1173 #endif /* __MACHINE_STACK_GROWS_UP */
1174
1175 if (kstackleftmin > stackleft) {
1176 kstackleftmin = stackleft;
1177 if (stackleft < kstackleftthres)
1178 printf("warning: kernel stack left %d bytes"
1179 "(pid %u:lid %u)\n", stackleft,
1180 (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
1181 }
1182
1183 if (stackleft <= 0) {
1184 panic("magic on the top of kernel stack changed for "
1185 "pid %u, lid %u: maybe kernel stack overflow",
1186 (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
1187 }
1188 }
1189 #endif /* KSTACK_CHECK_MAGIC */
1190
1191 /* XXX shouldn't be here */
1192 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
1193 #define PROCLIST_ASSERT_LOCKED_READ() \
1194 KASSERT(lockstatus(&proclist_lock) == LK_SHARED)
1195 #else
1196 #define PROCLIST_ASSERT_LOCKED_READ() /* nothing */
1197 #endif
1198
1199 int
1200 proclist_foreach_call(struct proclist *list,
1201 int (*callback)(struct proc *, void *arg), void *arg)
1202 {
1203 struct proc marker;
1204 struct proc *p;
1205 struct lwp * const l = curlwp;
1206 int ret = 0;
1207
1208 marker.p_flag = P_MARKER;
1209 PHOLD(l);
1210 proclist_lock_read();
1211 for (p = LIST_FIRST(list); ret == 0 && p != NULL;) {
1212 if (p->p_flag & P_MARKER) {
1213 p = LIST_NEXT(p, p_list);
1214 continue;
1215 }
1216 LIST_INSERT_AFTER(p, &marker, p_list);
1217 ret = (*callback)(p, arg);
1218 PROCLIST_ASSERT_LOCKED_READ();
1219 p = LIST_NEXT(&marker, p_list);
1220 LIST_REMOVE(&marker, p_list);
1221 }
1222 proclist_unlock_read();
1223 PRELE(l);
1224
1225 return ret;
1226 }
1227
1228 int
1229 proc_vmspace_getref(struct proc *p, struct vmspace **vm)
1230 {
1231
1232 /* XXXCDC: how should locking work here? */
1233
1234 /* curproc exception is for coredump. */
1235
1236 if ((p != curproc && (p->p_flag & P_WEXIT) != 0) ||
1237 (p->p_vmspace->vm_refcnt < 1)) { /* XXX */
1238 return EFAULT;
1239 }
1240
1241 uvmspace_addref(p->p_vmspace);
1242 *vm = p->p_vmspace;
1243
1244 return 0;
1245 }
1246