kern_lwp.c revision 1.61.2.23 1 /* $NetBSD: kern_lwp.c,v 1.61.2.23 2007/10/23 20:17:10 ad Exp $ */
2
3 /*-
4 * Copyright (c) 2001, 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 Nathan J. Williams, and Andrew Doran.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39 /*
40 * Overview
41 *
42 * Lightweight processes (LWPs) are the basic unit or thread of
43 * execution within the kernel. The core state of an LWP is described
44 * by "struct lwp", also known as lwp_t.
45 *
46 * Each LWP is contained within a process (described by "struct proc"),
47 * Every process contains at least one LWP, but may contain more. The
48 * process describes attributes shared among all of its LWPs such as a
49 * private address space, global execution state (stopped, active,
50 * zombie, ...), signal disposition and so on. On a multiprocessor
51 * machine, multiple LWPs be executing concurrently in the kernel.
52 *
53 * Execution states
54 *
55 * At any given time, an LWP has overall state that is described by
56 * lwp::l_stat. The states are broken into two sets below. The first
57 * set is guaranteed to represent the absolute, current state of the
58 * LWP:
59 *
60 * LSONPROC
61 *
62 * On processor: the LWP is executing on a CPU, either in the
63 * kernel or in user space.
64 *
65 * LSRUN
66 *
67 * Runnable: the LWP is parked on a run queue, and may soon be
68 * chosen to run by a idle processor, or by a processor that
69 * has been asked to preempt a currently runnning but lower
70 * priority LWP. If the LWP is not swapped in (L_INMEM == 0)
71 * then the LWP is not on a run queue, but may be soon.
72 *
73 * LSIDL
74 *
75 * Idle: the LWP has been created but has not yet executed,
76 * or it has ceased executing a unit of work and is waiting
77 * to be started again.
78 *
79 * LSSUSPENDED:
80 *
81 * Suspended: the LWP has had its execution suspended by
82 * another LWP in the same process using the _lwp_suspend()
83 * system call. User-level LWPs also enter the suspended
84 * state when the system is shutting down.
85 *
86 * The second set represent a "statement of intent" on behalf of the
87 * LWP. The LWP may in fact be executing on a processor, may be
88 * sleeping or idle. It is expected to take the necessary action to
89 * stop executing or become "running" again within a short timeframe.
90 * The LW_RUNNING flag in lwp::l_flag indicates that an LWP is running.
91 * Importantly, in indicates that its state is tied to a CPU.
92 *
93 * LSZOMB:
94 *
95 * Dead or dying: the LWP has released most of its resources
96 * and is a) about to switch away into oblivion b) has already
97 * switched away. When it switches away, its few remaining
98 * resources can be collected.
99 *
100 * LSSLEEP:
101 *
102 * Sleeping: the LWP has entered itself onto a sleep queue, and
103 * has switched away or will switch away shortly to allow other
104 * LWPs to run on the CPU.
105 *
106 * LSSTOP:
107 *
108 * Stopped: the LWP has been stopped as a result of a job
109 * control signal, or as a result of the ptrace() interface.
110 *
111 * Stopped LWPs may run briefly within the kernel to handle
112 * signals that they receive, but will not return to user space
113 * until their process' state is changed away from stopped.
114 *
115 * Single LWPs within a process can not be set stopped
116 * selectively: all actions that can stop or continue LWPs
117 * occur at the process level.
118 *
119 * State transitions
120 *
121 * Note that the LSSTOP state may only be set when returning to
122 * user space in userret(), or when sleeping interruptably. The
123 * LSSUSPENDED state may only be set in userret(). Before setting
124 * those states, we try to ensure that the LWPs will release all
125 * locks that they hold, and at a minimum try to ensure that the
126 * LWP can be set runnable again by a signal.
127 *
128 * LWPs may transition states in the following ways:
129 *
130 * RUN -------> ONPROC ONPROC -----> RUN
131 * > STOPPED > SLEEP
132 * > SUSPENDED > STOPPED
133 * > SUSPENDED
134 * > ZOMB
135 *
136 * STOPPED ---> RUN SUSPENDED --> RUN
137 * > SLEEP > SLEEP
138 *
139 * SLEEP -----> ONPROC IDL --------> RUN
140 * > RUN > SUSPENDED
141 * > STOPPED > STOPPED
142 * > SUSPENDED
143 *
144 * Other state transitions are possible with kernel threads (eg
145 * ONPROC -> IDL), but only happen under tightly controlled
146 * circumstances the side effects are understood.
147 *
148 * Locking
149 *
150 * The majority of fields in 'struct lwp' are covered by a single,
151 * general spin lock pointed to by lwp::l_mutex. The locks covering
152 * each field are documented in sys/lwp.h.
153 *
154 * State transitions must be made with the LWP's general lock held,
155 * and may cause the LWP's lock pointer to change. Manipulation of
156 * the general lock is not performed directly, but through calls to
157 * lwp_lock(), lwp_relock() and similar.
158 *
159 * States and their associated locks:
160 *
161 * LSONPROC, LSZOMB:
162 *
163 * Always covered by spc_lwplock, which protects running LWPs.
164 * This is a per-CPU lock.
165 *
166 * LSIDL, LSRUN:
167 *
168 * Always covered by spc_mutex, which protects the run queues.
169 * This may be a per-CPU lock, depending on the scheduler.
170 *
171 * LSSLEEP:
172 *
173 * Covered by a lock associated with the sleep queue that the
174 * LWP resides on, indirectly referenced by l_sleepq->sq_mutex.
175 *
176 * LSSTOP, LSSUSPENDED:
177 *
178 * If the LWP was previously sleeping (l_wchan != NULL), then
179 * l_mutex references the sleep queue lock. If the LWP was
180 * runnable or on the CPU when halted, or has been removed from
181 * the sleep queue since halted, then the lock is spc_lwplock.
182 *
183 * The lock order is as follows:
184 *
185 * spc::spc_lwplock ->
186 * sleepq_t::sq_mutex ->
187 * tschain_t::tc_mutex ->
188 * spc::spc_mutex
189 *
190 * Each process has an scheduler state lock (proc::p_smutex), and a
191 * number of counters on LWPs and their states: p_nzlwps, p_nrlwps, and
192 * so on. When an LWP is to be entered into or removed from one of the
193 * following states, p_mutex must be held and the process wide counters
194 * adjusted:
195 *
196 * LSIDL, LSZOMB, LSSTOP, LSSUSPENDED
197 *
198 * Note that an LWP is considered running or likely to run soon if in
199 * one of the following states. This affects the value of p_nrlwps:
200 *
201 * LSRUN, LSONPROC, LSSLEEP
202 *
203 * p_smutex does not need to be held when transitioning among these
204 * three states.
205 */
206
207 #include <sys/cdefs.h>
208 __KERNEL_RCSID(0, "$NetBSD: kern_lwp.c,v 1.61.2.23 2007/10/23 20:17:10 ad Exp $");
209
210 #include "opt_multiprocessor.h"
211 #include "opt_lockdebug.h"
212
213 #define _LWP_API_PRIVATE
214
215 #include <sys/param.h>
216 #include <sys/systm.h>
217 #include <sys/cpu.h>
218 #include <sys/pool.h>
219 #include <sys/proc.h>
220 #include <sys/syscallargs.h>
221 #include <sys/syscall_stats.h>
222 #include <sys/kauth.h>
223 #include <sys/sleepq.h>
224 #include <sys/lockdebug.h>
225 #include <sys/kmem.h>
226 #include <sys/intr.h>
227
228 #include <uvm/uvm_extern.h>
229
230 struct lwplist alllwp;
231
232 POOL_INIT(lwp_pool, sizeof(struct lwp), MIN_LWP_ALIGNMENT, 0, 0, "lwppl",
233 &pool_allocator_nointr, IPL_NONE);
234 POOL_INIT(lwp_uc_pool, sizeof(ucontext_t), 0, 0, 0, "lwpucpl",
235 &pool_allocator_nointr, IPL_NONE);
236
237 static specificdata_domain_t lwp_specificdata_domain;
238
239 #define LWP_DEBUG
240
241 #ifdef LWP_DEBUG
242 int lwp_debug = 0;
243 #define DPRINTF(x) if (lwp_debug) printf x
244 #else
245 #define DPRINTF(x)
246 #endif
247
248 void
249 lwpinit(void)
250 {
251
252 lwp_specificdata_domain = specificdata_domain_create();
253 KASSERT(lwp_specificdata_domain != NULL);
254 lwp_sys_init();
255 }
256
257 /*
258 * Set an suspended.
259 *
260 * Must be called with p_smutex held, and the LWP locked. Will unlock the
261 * LWP before return.
262 */
263 int
264 lwp_suspend(struct lwp *curl, struct lwp *t)
265 {
266 int error;
267
268 KASSERT(mutex_owned(&t->l_proc->p_smutex));
269 KASSERT(lwp_locked(t, NULL));
270
271 KASSERT(curl != t || curl->l_stat == LSONPROC);
272
273 /*
274 * If the current LWP has been told to exit, we must not suspend anyone
275 * else or deadlock could occur. We won't return to userspace.
276 */
277 if ((curl->l_stat & (LW_WEXIT | LW_WCORE)) != 0) {
278 lwp_unlock(t);
279 return (EDEADLK);
280 }
281
282 error = 0;
283
284 switch (t->l_stat) {
285 case LSRUN:
286 case LSONPROC:
287 t->l_flag |= LW_WSUSPEND;
288 lwp_need_userret(t);
289 lwp_unlock(t);
290 break;
291
292 case LSSLEEP:
293 t->l_flag |= LW_WSUSPEND;
294
295 /*
296 * Kick the LWP and try to get it to the kernel boundary
297 * so that it will release any locks that it holds.
298 * setrunnable() will release the lock.
299 */
300 if ((t->l_flag & LW_SINTR) != 0)
301 setrunnable(t);
302 else
303 lwp_unlock(t);
304 break;
305
306 case LSSUSPENDED:
307 lwp_unlock(t);
308 break;
309
310 case LSSTOP:
311 t->l_flag |= LW_WSUSPEND;
312 setrunnable(t);
313 break;
314
315 case LSIDL:
316 case LSZOMB:
317 error = EINTR; /* It's what Solaris does..... */
318 lwp_unlock(t);
319 break;
320 }
321
322 return (error);
323 }
324
325 /*
326 * Restart a suspended LWP.
327 *
328 * Must be called with p_smutex held, and the LWP locked. Will unlock the
329 * LWP before return.
330 */
331 void
332 lwp_continue(struct lwp *l)
333 {
334
335 KASSERT(mutex_owned(&l->l_proc->p_smutex));
336 KASSERT(lwp_locked(l, NULL));
337
338 DPRINTF(("lwp_continue of %d.%d (%s), state %d, wchan %p\n",
339 l->l_proc->p_pid, l->l_lid, l->l_proc->p_comm, l->l_stat,
340 l->l_wchan));
341
342 /* If rebooting or not suspended, then just bail out. */
343 if ((l->l_flag & LW_WREBOOT) != 0) {
344 lwp_unlock(l);
345 return;
346 }
347
348 l->l_flag &= ~LW_WSUSPEND;
349
350 if (l->l_stat != LSSUSPENDED) {
351 lwp_unlock(l);
352 return;
353 }
354
355 /* setrunnable() will release the lock. */
356 setrunnable(l);
357 }
358
359 /*
360 * Wait for an LWP within the current process to exit. If 'lid' is
361 * non-zero, we are waiting for a specific LWP.
362 *
363 * Must be called with p->p_smutex held.
364 */
365 int
366 lwp_wait1(struct lwp *l, lwpid_t lid, lwpid_t *departed, int flags)
367 {
368 struct proc *p = l->l_proc;
369 struct lwp *l2;
370 int nfound, error;
371 lwpid_t curlid;
372 bool exiting;
373
374 DPRINTF(("lwp_wait1: %d.%d waiting for %d.\n",
375 p->p_pid, l->l_lid, lid));
376
377 KASSERT(mutex_owned(&p->p_smutex));
378
379 p->p_nlwpwait++;
380 l->l_waitingfor = lid;
381 curlid = l->l_lid;
382 exiting = ((flags & LWPWAIT_EXITCONTROL) != 0);
383
384 for (;;) {
385 /*
386 * Avoid a race between exit1() and sigexit(): if the
387 * process is dumping core, then we need to bail out: call
388 * into lwp_userret() where we will be suspended until the
389 * deed is done.
390 */
391 if ((p->p_sflag & PS_WCORE) != 0) {
392 mutex_exit(&p->p_smutex);
393 lwp_userret(l);
394 #ifdef DIAGNOSTIC
395 panic("lwp_wait1");
396 #endif
397 /* NOTREACHED */
398 }
399
400 /*
401 * First off, drain any detached LWP that is waiting to be
402 * reaped.
403 */
404 while ((l2 = p->p_zomblwp) != NULL) {
405 p->p_zomblwp = NULL;
406 lwp_free(l2, false, false);/* releases proc mutex */
407 mutex_enter(&p->p_smutex);
408 }
409
410 /*
411 * Now look for an LWP to collect. If the whole process is
412 * exiting, count detached LWPs as eligible to be collected,
413 * but don't drain them here.
414 */
415 nfound = 0;
416 error = 0;
417 LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
418 /*
419 * If a specific wait and the target is waiting on
420 * us, then avoid deadlock. This also traps LWPs
421 * that try to wait on themselves.
422 *
423 * Note that this does not handle more complicated
424 * cycles, like: t1 -> t2 -> t3 -> t1. The process
425 * can still be killed so it is not a major problem.
426 */
427 if (l2->l_lid == lid && l2->l_waitingfor == curlid) {
428 error = EDEADLK;
429 break;
430 }
431 if (l2 == l)
432 continue;
433 if ((l2->l_prflag & LPR_DETACHED) != 0) {
434 nfound += exiting;
435 continue;
436 }
437 if (lid != 0) {
438 if (l2->l_lid != lid)
439 continue;
440 /*
441 * Mark this LWP as the first waiter, if there
442 * is no other.
443 */
444 if (l2->l_waiter == 0)
445 l2->l_waiter = curlid;
446 } else if (l2->l_waiter != 0) {
447 /*
448 * It already has a waiter - so don't
449 * collect it. If the waiter doesn't
450 * grab it we'll get another chance
451 * later.
452 */
453 nfound++;
454 continue;
455 }
456 nfound++;
457
458 /* No need to lock the LWP in order to see LSZOMB. */
459 if (l2->l_stat != LSZOMB)
460 continue;
461
462 /*
463 * We're no longer waiting. Reset the "first waiter"
464 * pointer on the target, in case it was us.
465 */
466 l->l_waitingfor = 0;
467 l2->l_waiter = 0;
468 p->p_nlwpwait--;
469 if (departed)
470 *departed = l2->l_lid;
471
472 /* lwp_free() releases the proc lock. */
473 lwp_free(l2, false, false);
474 mutex_enter(&p->p_smutex);
475 return 0;
476 }
477
478 if (error != 0)
479 break;
480 if (nfound == 0) {
481 error = ESRCH;
482 break;
483 }
484
485 /*
486 * The kernel is careful to ensure that it can not deadlock
487 * when exiting - just keep waiting.
488 */
489 if (exiting) {
490 KASSERT(p->p_nlwps > 1);
491 cv_wait(&p->p_lwpcv, &p->p_smutex);
492 continue;
493 }
494
495 /*
496 * If all other LWPs are waiting for exits or suspends
497 * and the supply of zombies and potential zombies is
498 * exhausted, then we are about to deadlock.
499 *
500 * If the process is exiting (and this LWP is not the one
501 * that is coordinating the exit) then bail out now.
502 */
503 if ((p->p_sflag & PS_WEXIT) != 0 ||
504 p->p_nrlwps + p->p_nzlwps - p->p_ndlwps <= p->p_nlwpwait) {
505 error = EDEADLK;
506 break;
507 }
508
509 /*
510 * Sit around and wait for something to happen. We'll be
511 * awoken if any of the conditions examined change: if an
512 * LWP exits, is collected, or is detached.
513 */
514 if ((error = cv_wait_sig(&p->p_lwpcv, &p->p_smutex)) != 0)
515 break;
516 }
517
518 /*
519 * We didn't find any LWPs to collect, we may have received a
520 * signal, or some other condition has caused us to bail out.
521 *
522 * If waiting on a specific LWP, clear the waiters marker: some
523 * other LWP may want it. Then, kick all the remaining waiters
524 * so that they can re-check for zombies and for deadlock.
525 */
526 if (lid != 0) {
527 LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
528 if (l2->l_lid == lid) {
529 if (l2->l_waiter == curlid)
530 l2->l_waiter = 0;
531 break;
532 }
533 }
534 }
535 p->p_nlwpwait--;
536 l->l_waitingfor = 0;
537 cv_broadcast(&p->p_lwpcv);
538
539 return error;
540 }
541
542 /*
543 * Create a new LWP within process 'p2', using LWP 'l1' as a template.
544 * The new LWP is created in state LSIDL and must be set running,
545 * suspended, or stopped by the caller.
546 */
547 int
548 newlwp(struct lwp *l1, struct proc *p2, vaddr_t uaddr, bool inmem,
549 int flags, void *stack, size_t stacksize,
550 void (*func)(void *), void *arg, struct lwp **rnewlwpp)
551 {
552 struct lwp *l2, *isfree;
553 turnstile_t *ts;
554
555 /*
556 * First off, reap any detached LWP waiting to be collected.
557 * We can re-use its LWP structure and turnstile.
558 */
559 isfree = NULL;
560 if (p2->p_zomblwp != NULL) {
561 mutex_enter(&p2->p_smutex);
562 if ((isfree = p2->p_zomblwp) != NULL) {
563 p2->p_zomblwp = NULL;
564 lwp_free(isfree, true, false);/* releases proc mutex */
565 } else
566 mutex_exit(&p2->p_smutex);
567 }
568 if (isfree == NULL) {
569 l2 = pool_get(&lwp_pool, PR_WAITOK);
570 memset(l2, 0, sizeof(*l2));
571 l2->l_ts = pool_cache_get(turnstile_cache, PR_WAITOK);
572 SLIST_INIT(&l2->l_pi_lenders);
573 } else {
574 l2 = isfree;
575 ts = l2->l_ts;
576 KASSERT(l2->l_inheritedprio == -1);
577 KASSERT(SLIST_EMPTY(&l2->l_pi_lenders));
578 memset(l2, 0, sizeof(*l2));
579 l2->l_ts = ts;
580 }
581
582 l2->l_stat = LSIDL;
583 l2->l_proc = p2;
584 l2->l_refcnt = 1;
585 l2->l_priority = l1->l_priority;
586 l2->l_usrpri = l1->l_usrpri;
587 l2->l_inheritedprio = -1;
588 l2->l_mutex = l1->l_cpu->ci_schedstate.spc_mutex;
589 l2->l_cpu = l1->l_cpu;
590 l2->l_flag = inmem ? LW_INMEM : 0;
591 l2->l_pflag = LP_MPSAFE;
592
593 if (p2->p_flag & PK_SYSTEM) {
594 /*
595 * Mark it as a system process and not a candidate for
596 * swapping.
597 */
598 l2->l_flag |= LW_SYSTEM;
599 } else {
600 /* Look for a CPU to start */
601 l2->l_cpu = sched_takecpu(l2);
602 l2->l_mutex = l2->l_cpu->ci_schedstate.spc_mutex;
603 }
604
605 lwp_initspecific(l2);
606 sched_lwp_fork(l2);
607 lwp_update_creds(l2);
608 callout_init(&l2->l_timeout_ch, CALLOUT_MPSAFE);
609 callout_setfunc(&l2->l_timeout_ch, sleepq_timeout, l2);
610 mutex_init(&l2->l_swaplock, MUTEX_DEFAULT, IPL_NONE);
611 cv_init(&l2->l_sigcv, "sigwait");
612 l2->l_syncobj = &sched_syncobj;
613
614 if (rnewlwpp != NULL)
615 *rnewlwpp = l2;
616
617 l2->l_addr = UAREA_TO_USER(uaddr);
618 KERNEL_LOCK(1, curlwp);
619 uvm_lwp_fork(l1, l2, stack, stacksize, func,
620 (arg != NULL) ? arg : l2);
621 KERNEL_UNLOCK_ONE(curlwp);
622
623 mutex_enter(&p2->p_smutex);
624
625 if ((flags & LWP_DETACHED) != 0) {
626 l2->l_prflag = LPR_DETACHED;
627 p2->p_ndlwps++;
628 } else
629 l2->l_prflag = 0;
630
631 l2->l_sigmask = l1->l_sigmask;
632 CIRCLEQ_INIT(&l2->l_sigpend.sp_info);
633 sigemptyset(&l2->l_sigpend.sp_set);
634
635 p2->p_nlwpid++;
636 if (p2->p_nlwpid == 0)
637 p2->p_nlwpid++;
638 l2->l_lid = p2->p_nlwpid;
639 LIST_INSERT_HEAD(&p2->p_lwps, l2, l_sibling);
640 p2->p_nlwps++;
641
642 mutex_exit(&p2->p_smutex);
643
644 mutex_enter(&proclist_lock);
645 mutex_enter(&proclist_mutex);
646 LIST_INSERT_HEAD(&alllwp, l2, l_list);
647 mutex_exit(&proclist_mutex);
648 mutex_exit(&proclist_lock);
649
650 SYSCALL_TIME_LWP_INIT(l2);
651
652 if (p2->p_emul->e_lwp_fork)
653 (*p2->p_emul->e_lwp_fork)(l1, l2);
654
655 return (0);
656 }
657
658 /*
659 * Called by MD code when a new LWP begins execution. Must be called
660 * with the previous LWP locked (so at splsched), or if there is no
661 * previous LWP, at splsched.
662 */
663 void
664 lwp_startup(struct lwp *prev, struct lwp *new)
665 {
666
667 if (prev != NULL) {
668 lwp_unlock(prev);
669 }
670 spl0();
671 pmap_activate(new);
672 LOCKDEBUG_BARRIER(NULL, 0);
673 if ((new->l_pflag & LP_MPSAFE) == 0) {
674 KERNEL_LOCK(1, new);
675 }
676 }
677
678 /*
679 * Exit an LWP.
680 */
681 void
682 lwp_exit(struct lwp *l)
683 {
684 struct proc *p = l->l_proc;
685 struct lwp *l2;
686 bool current;
687
688 current = (l == curlwp);
689
690 DPRINTF(("lwp_exit: %d.%d exiting.\n", p->p_pid, l->l_lid));
691 DPRINTF((" nlwps: %d nzlwps: %d\n", p->p_nlwps, p->p_nzlwps));
692 KASSERT(current || l->l_stat == LSIDL);
693
694 /*
695 * Verify that we hold no locks other than the kernel lock.
696 */
697 #ifdef MULTIPROCESSOR
698 LOCKDEBUG_BARRIER(&kernel_lock, 0);
699 #else
700 LOCKDEBUG_BARRIER(NULL, 0);
701 #endif
702
703 /*
704 * If we are the last live LWP in a process, we need to exit the
705 * entire process. We do so with an exit status of zero, because
706 * it's a "controlled" exit, and because that's what Solaris does.
707 *
708 * We are not quite a zombie yet, but for accounting purposes we
709 * must increment the count of zombies here.
710 *
711 * Note: the last LWP's specificdata will be deleted here.
712 */
713 mutex_enter(&p->p_smutex);
714 if (p->p_nlwps - p->p_nzlwps == 1) {
715 KASSERT(current == true);
716 DPRINTF(("lwp_exit: %d.%d calling exit1()\n",
717 p->p_pid, l->l_lid));
718 exit1(l, 0);
719 /* NOTREACHED */
720 }
721 p->p_nzlwps++;
722 mutex_exit(&p->p_smutex);
723
724 if (p->p_emul->e_lwp_exit)
725 (*p->p_emul->e_lwp_exit)(l);
726
727 /* Delete the specificdata while it's still safe to sleep. */
728 specificdata_fini(lwp_specificdata_domain, &l->l_specdataref);
729
730 /*
731 * Release our cached credentials.
732 */
733 kauth_cred_free(l->l_cred);
734 callout_destroy(&l->l_timeout_ch);
735
736 /*
737 * While we can still block, mark the LWP as unswappable to
738 * prevent conflicts with the with the swapper.
739 */
740 if (current)
741 uvm_lwp_hold(l);
742
743 /*
744 * Remove the LWP from the global list.
745 */
746 mutex_enter(&proclist_lock);
747 mutex_enter(&proclist_mutex);
748 LIST_REMOVE(l, l_list);
749 mutex_exit(&proclist_mutex);
750 mutex_exit(&proclist_lock);
751
752 /*
753 * Get rid of all references to the LWP that others (e.g. procfs)
754 * may have, and mark the LWP as a zombie. If the LWP is detached,
755 * mark it waiting for collection in the proc structure. Note that
756 * before we can do that, we need to free any other dead, deatched
757 * LWP waiting to meet its maker.
758 *
759 * XXXSMP disable preemption.
760 */
761 mutex_enter(&p->p_smutex);
762 lwp_drainrefs(l);
763
764 if ((l->l_prflag & LPR_DETACHED) != 0) {
765 while ((l2 = p->p_zomblwp) != NULL) {
766 p->p_zomblwp = NULL;
767 lwp_free(l2, false, false);/* releases proc mutex */
768 mutex_enter(&p->p_smutex);
769 l->l_refcnt++;
770 lwp_drainrefs(l);
771 }
772 p->p_zomblwp = l;
773 }
774
775 /*
776 * If we find a pending signal for the process and we have been
777 * asked to check for signals, then we loose: arrange to have
778 * all other LWPs in the process check for signals.
779 */
780 if ((l->l_flag & LW_PENDSIG) != 0 &&
781 firstsig(&p->p_sigpend.sp_set) != 0) {
782 LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
783 lwp_lock(l2);
784 l2->l_flag |= LW_PENDSIG;
785 lwp_unlock(l2);
786 }
787 }
788
789 lwp_lock(l);
790 l->l_stat = LSZOMB;
791 lwp_unlock(l);
792 p->p_nrlwps--;
793 cv_broadcast(&p->p_lwpcv);
794 mutex_exit(&p->p_smutex);
795
796 /*
797 * We can no longer block. At this point, lwp_free() may already
798 * be gunning for us. On a multi-CPU system, we may be off p_lwps.
799 *
800 * Free MD LWP resources.
801 */
802 #ifndef __NO_CPU_LWP_FREE
803 cpu_lwp_free(l, 0);
804 #endif
805
806 if (current) {
807 pmap_deactivate(l);
808
809 /*
810 * Release the kernel lock, and switch away into
811 * oblivion.
812 */
813 #ifdef notyet
814 /* XXXSMP hold in lwp_userret() */
815 KERNEL_UNLOCK_LAST(l);
816 #else
817 KERNEL_UNLOCK_ALL(l, NULL);
818 #endif
819 lwp_exit_switchaway(l);
820 }
821 }
822
823 void
824 lwp_exit_switchaway(struct lwp *l)
825 {
826 struct cpu_info *ci;
827 struct lwp *idlelwp;
828
829 /* Unlocked, but is for statistics only. */
830 uvmexp.swtch++;
831
832 (void)splsched();
833 l->l_flag &= ~LW_RUNNING;
834 ci = curcpu();
835 idlelwp = ci->ci_data.cpu_idlelwp;
836 idlelwp->l_stat = LSONPROC;
837 cpu_switchto(NULL, idlelwp, false);
838 }
839
840 /*
841 * Free a dead LWP's remaining resources.
842 *
843 * XXXLWP limits.
844 */
845 void
846 lwp_free(struct lwp *l, bool recycle, bool last)
847 {
848 struct proc *p = l->l_proc;
849 ksiginfoq_t kq;
850
851 /*
852 * If this was not the last LWP in the process, then adjust
853 * counters and unlock.
854 */
855 if (!last) {
856 /*
857 * Add the LWP's run time to the process' base value.
858 * This needs to co-incide with coming off p_lwps.
859 */
860 timeradd(&l->l_rtime, &p->p_rtime, &p->p_rtime);
861 p->p_pctcpu += l->l_pctcpu;
862 LIST_REMOVE(l, l_sibling);
863 p->p_nlwps--;
864 p->p_nzlwps--;
865 if ((l->l_prflag & LPR_DETACHED) != 0)
866 p->p_ndlwps--;
867
868 /*
869 * Have any LWPs sleeping in lwp_wait() recheck for
870 * deadlock.
871 */
872 cv_broadcast(&p->p_lwpcv);
873 mutex_exit(&p->p_smutex);
874 }
875
876 #ifdef MULTIPROCESSOR
877 /*
878 * In the unlikely event that the LWP is still on the CPU,
879 * then spin until it has switched away. We need to release
880 * all locks to avoid deadlock against interrupt handlers on
881 * the target CPU.
882 */
883 if ((l->l_flag & LW_RUNNING) != 0 || l->l_cpu->ci_curlwp == l) {
884 int count;
885 (void)count; /* XXXgcc */
886 KERNEL_UNLOCK_ALL(curlwp, &count);
887 while ((l->l_flag & LW_RUNNING) != 0 ||
888 l->l_cpu->ci_curlwp == l)
889 SPINLOCK_BACKOFF_HOOK;
890 KERNEL_LOCK(count, curlwp);
891 }
892 #endif
893
894 /*
895 * Destroy the LWP's remaining signal information.
896 */
897 ksiginfo_queue_init(&kq);
898 sigclear(&l->l_sigpend, NULL, &kq);
899 ksiginfo_queue_drain(&kq);
900 cv_destroy(&l->l_sigcv);
901 mutex_destroy(&l->l_swaplock);
902
903 /*
904 * Free the LWP's turnstile and the LWP structure itself unless the
905 * caller wants to recycle them. Also, free the scheduler specific data.
906 *
907 * We can't return turnstile0 to the pool (it didn't come from it),
908 * so if it comes up just drop it quietly and move on.
909 *
910 * We don't recycle the VM resources at this time.
911 */
912 if (!recycle && l->l_ts != &turnstile0)
913 pool_cache_put(turnstile_cache, l->l_ts);
914 #ifndef __NO_CPU_LWP_FREE
915 cpu_lwp_free2(l);
916 #endif
917 uvm_lwp_exit(l);
918 KASSERT(SLIST_EMPTY(&l->l_pi_lenders));
919 KASSERT(l->l_inheritedprio == -1);
920 sched_lwp_exit(l);
921 if (!recycle)
922 pool_put(&lwp_pool, l);
923 }
924
925 /*
926 * Pick a LWP to represent the process for those operations which
927 * want information about a "process" that is actually associated
928 * with a LWP.
929 *
930 * If 'locking' is false, no locking or lock checks are performed.
931 * This is intended for use by DDB.
932 *
933 * We don't bother locking the LWP here, since code that uses this
934 * interface is broken by design and an exact match is not required.
935 */
936 struct lwp *
937 proc_representative_lwp(struct proc *p, int *nrlwps, int locking)
938 {
939 struct lwp *l, *onproc, *running, *sleeping, *stopped, *suspended;
940 struct lwp *signalled;
941 int cnt;
942
943 if (locking) {
944 KASSERT(mutex_owned(&p->p_smutex));
945 }
946
947 /* Trivial case: only one LWP */
948 if (p->p_nlwps == 1) {
949 l = LIST_FIRST(&p->p_lwps);
950 if (nrlwps)
951 *nrlwps = (l->l_stat == LSONPROC || l->l_stat == LSRUN);
952 return l;
953 }
954
955 cnt = 0;
956 switch (p->p_stat) {
957 case SSTOP:
958 case SACTIVE:
959 /* Pick the most live LWP */
960 onproc = running = sleeping = stopped = suspended = NULL;
961 signalled = NULL;
962 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
963 if ((l->l_flag & LW_IDLE) != 0) {
964 continue;
965 }
966 if (l->l_lid == p->p_sigctx.ps_lwp)
967 signalled = l;
968 switch (l->l_stat) {
969 case LSONPROC:
970 onproc = l;
971 cnt++;
972 break;
973 case LSRUN:
974 running = l;
975 cnt++;
976 break;
977 case LSSLEEP:
978 sleeping = l;
979 break;
980 case LSSTOP:
981 stopped = l;
982 break;
983 case LSSUSPENDED:
984 suspended = l;
985 break;
986 }
987 }
988 if (nrlwps)
989 *nrlwps = cnt;
990 if (signalled)
991 l = signalled;
992 else if (onproc)
993 l = onproc;
994 else if (running)
995 l = running;
996 else if (sleeping)
997 l = sleeping;
998 else if (stopped)
999 l = stopped;
1000 else if (suspended)
1001 l = suspended;
1002 else
1003 break;
1004 return l;
1005 #ifdef DIAGNOSTIC
1006 case SIDL:
1007 case SZOMB:
1008 case SDYING:
1009 case SDEAD:
1010 if (locking)
1011 mutex_exit(&p->p_smutex);
1012 /* We have more than one LWP and we're in SIDL?
1013 * How'd that happen?
1014 */
1015 panic("Too many LWPs in idle/dying process %d (%s) stat = %d",
1016 p->p_pid, p->p_comm, p->p_stat);
1017 break;
1018 default:
1019 if (locking)
1020 mutex_exit(&p->p_smutex);
1021 panic("Process %d (%s) in unknown state %d",
1022 p->p_pid, p->p_comm, p->p_stat);
1023 #endif
1024 }
1025
1026 if (locking)
1027 mutex_exit(&p->p_smutex);
1028 panic("proc_representative_lwp: couldn't find a lwp for process"
1029 " %d (%s)", p->p_pid, p->p_comm);
1030 /* NOTREACHED */
1031 return NULL;
1032 }
1033
1034 /*
1035 * Look up a live LWP within the speicifed process, and return it locked.
1036 *
1037 * Must be called with p->p_smutex held.
1038 */
1039 struct lwp *
1040 lwp_find(struct proc *p, int id)
1041 {
1042 struct lwp *l;
1043
1044 KASSERT(mutex_owned(&p->p_smutex));
1045
1046 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1047 if (l->l_lid == id)
1048 break;
1049 }
1050
1051 /*
1052 * No need to lock - all of these conditions will
1053 * be visible with the process level mutex held.
1054 */
1055 if (l != NULL && (l->l_stat == LSIDL || l->l_stat == LSZOMB))
1056 l = NULL;
1057
1058 return l;
1059 }
1060
1061 /*
1062 * Update an LWP's cached credentials to mirror the process' master copy.
1063 *
1064 * This happens early in the syscall path, on user trap, and on LWP
1065 * creation. A long-running LWP can also voluntarily choose to update
1066 * it's credentials by calling this routine. This may be called from
1067 * LWP_CACHE_CREDS(), which checks l->l_cred != p->p_cred beforehand.
1068 */
1069 void
1070 lwp_update_creds(struct lwp *l)
1071 {
1072 kauth_cred_t oc;
1073 struct proc *p;
1074
1075 p = l->l_proc;
1076 oc = l->l_cred;
1077
1078 mutex_enter(&p->p_mutex);
1079 kauth_cred_hold(p->p_cred);
1080 l->l_cred = p->p_cred;
1081 mutex_exit(&p->p_mutex);
1082 if (oc != NULL)
1083 kauth_cred_free(oc);
1084 }
1085
1086 /*
1087 * Verify that an LWP is locked, and optionally verify that the lock matches
1088 * one we specify.
1089 */
1090 int
1091 lwp_locked(struct lwp *l, kmutex_t *mtx)
1092 {
1093 kmutex_t *cur = l->l_mutex;
1094
1095 return mutex_owned(cur) && (mtx == cur || mtx == NULL);
1096 }
1097
1098 /*
1099 * Lock an LWP.
1100 */
1101 void
1102 lwp_lock_retry(struct lwp *l, kmutex_t *old)
1103 {
1104
1105 /*
1106 * XXXgcc ignoring kmutex_t * volatile on i386
1107 *
1108 * gcc version 4.1.2 20061021 prerelease (NetBSD nb1 20061021)
1109 */
1110 #if 1
1111 while (l->l_mutex != old) {
1112 #else
1113 for (;;) {
1114 #endif
1115 mutex_spin_exit(old);
1116 old = l->l_mutex;
1117 mutex_spin_enter(old);
1118
1119 /*
1120 * mutex_enter() will have posted a read barrier. Re-test
1121 * l->l_mutex. If it has changed, we need to try again.
1122 */
1123 #if 1
1124 }
1125 #else
1126 } while (__predict_false(l->l_mutex != old));
1127 #endif
1128 }
1129
1130 /*
1131 * Lend a new mutex to an LWP. The old mutex must be held.
1132 */
1133 void
1134 lwp_setlock(struct lwp *l, kmutex_t *new)
1135 {
1136
1137 KASSERT(mutex_owned(l->l_mutex));
1138
1139 mb_write();
1140 l->l_mutex = new;
1141 }
1142
1143 /*
1144 * Lend a new mutex to an LWP, and release the old mutex. The old mutex
1145 * must be held.
1146 */
1147 void
1148 lwp_unlock_to(struct lwp *l, kmutex_t *new)
1149 {
1150 kmutex_t *old;
1151
1152 KASSERT(mutex_owned(l->l_mutex));
1153
1154 old = l->l_mutex;
1155 mb_write();
1156 l->l_mutex = new;
1157 mutex_spin_exit(old);
1158 }
1159
1160 /*
1161 * Acquire a new mutex, and donate it to an LWP. The LWP must already be
1162 * locked.
1163 */
1164 void
1165 lwp_relock(struct lwp *l, kmutex_t *new)
1166 {
1167 kmutex_t *old;
1168
1169 KASSERT(mutex_owned(l->l_mutex));
1170
1171 old = l->l_mutex;
1172 if (old != new) {
1173 mutex_spin_enter(new);
1174 l->l_mutex = new;
1175 mutex_spin_exit(old);
1176 }
1177 }
1178
1179 int
1180 lwp_trylock(struct lwp *l)
1181 {
1182 kmutex_t *old;
1183
1184 for (;;) {
1185 if (!mutex_tryenter(old = l->l_mutex))
1186 return 0;
1187 if (__predict_true(l->l_mutex == old))
1188 return 1;
1189 mutex_spin_exit(old);
1190 }
1191 }
1192
1193 /*
1194 * Handle exceptions for mi_userret(). Called if a member of LW_USERRET is
1195 * set.
1196 */
1197 void
1198 lwp_userret(struct lwp *l)
1199 {
1200 struct proc *p;
1201 void (*hook)(void);
1202 int sig;
1203
1204 p = l->l_proc;
1205
1206 /*
1207 * It should be safe to do this read unlocked on a multiprocessor
1208 * system..
1209 */
1210 while ((l->l_flag & LW_USERRET) != 0) {
1211 /*
1212 * Process pending signals first, unless the process
1213 * is dumping core or exiting, where we will instead
1214 * enter the L_WSUSPEND case below.
1215 */
1216 if ((l->l_flag & (LW_PENDSIG | LW_WCORE | LW_WEXIT)) ==
1217 LW_PENDSIG) {
1218 mutex_enter(&p->p_smutex);
1219 while ((sig = issignal(l)) != 0)
1220 postsig(sig);
1221 mutex_exit(&p->p_smutex);
1222 }
1223
1224 /*
1225 * Core-dump or suspend pending.
1226 *
1227 * In case of core dump, suspend ourselves, so that the
1228 * kernel stack and therefore the userland registers saved
1229 * in the trapframe are around for coredump() to write them
1230 * out. We issue a wakeup on p->p_lwpcv so that sigexit()
1231 * will write the core file out once all other LWPs are
1232 * suspended.
1233 */
1234 if ((l->l_flag & LW_WSUSPEND) != 0) {
1235 mutex_enter(&p->p_smutex);
1236 p->p_nrlwps--;
1237 cv_broadcast(&p->p_lwpcv);
1238 lwp_lock(l);
1239 l->l_stat = LSSUSPENDED;
1240 mutex_exit(&p->p_smutex);
1241 mi_switch(l);
1242 }
1243
1244 /* Process is exiting. */
1245 if ((l->l_flag & LW_WEXIT) != 0) {
1246 KERNEL_LOCK(1, l);
1247 lwp_exit(l);
1248 KASSERT(0);
1249 /* NOTREACHED */
1250 }
1251
1252 /* Call userret hook; used by Linux emulation. */
1253 if ((l->l_flag & LW_WUSERRET) != 0) {
1254 lwp_lock(l);
1255 l->l_flag &= ~LW_WUSERRET;
1256 lwp_unlock(l);
1257 hook = p->p_userret;
1258 p->p_userret = NULL;
1259 (*hook)();
1260 }
1261 }
1262
1263 #ifndef __HAVE_FAST_SOFTINTS
1264 /* If there are pending soft interrupts, then run them. */
1265 if (l->l_cpu->ci_data.cpu_softints != 0)
1266 softint_overlay();
1267 #endif
1268 }
1269
1270 /*
1271 * Force an LWP to enter the kernel, to take a trip through lwp_userret().
1272 */
1273 void
1274 lwp_need_userret(struct lwp *l)
1275 {
1276 KASSERT(lwp_locked(l, NULL));
1277
1278 /*
1279 * Since the tests in lwp_userret() are done unlocked, make sure
1280 * that the condition will be seen before forcing the LWP to enter
1281 * kernel mode.
1282 */
1283 mb_write();
1284 cpu_signotify(l);
1285 }
1286
1287 /*
1288 * Add one reference to an LWP. This will prevent the LWP from
1289 * exiting, thus keep the lwp structure and PCB around to inspect.
1290 */
1291 void
1292 lwp_addref(struct lwp *l)
1293 {
1294
1295 KASSERT(mutex_owned(&l->l_proc->p_smutex));
1296 KASSERT(l->l_stat != LSZOMB);
1297 KASSERT(l->l_refcnt != 0);
1298
1299 l->l_refcnt++;
1300 }
1301
1302 /*
1303 * Remove one reference to an LWP. If this is the last reference,
1304 * then we must finalize the LWP's death.
1305 */
1306 void
1307 lwp_delref(struct lwp *l)
1308 {
1309 struct proc *p = l->l_proc;
1310
1311 mutex_enter(&p->p_smutex);
1312 KASSERT(l->l_stat != LSZOMB);
1313 KASSERT(l->l_refcnt > 0);
1314 if (--l->l_refcnt == 0)
1315 cv_broadcast(&p->p_refcv);
1316 mutex_exit(&p->p_smutex);
1317 }
1318
1319 /*
1320 * Drain all references to the current LWP.
1321 */
1322 void
1323 lwp_drainrefs(struct lwp *l)
1324 {
1325 struct proc *p = l->l_proc;
1326
1327 KASSERT(mutex_owned(&p->p_smutex));
1328 KASSERT(l->l_refcnt != 0);
1329
1330 l->l_refcnt--;
1331 while (l->l_refcnt != 0)
1332 cv_wait(&p->p_refcv, &p->p_smutex);
1333 }
1334
1335 /*
1336 * lwp_specific_key_create --
1337 * Create a key for subsystem lwp-specific data.
1338 */
1339 int
1340 lwp_specific_key_create(specificdata_key_t *keyp, specificdata_dtor_t dtor)
1341 {
1342
1343 return (specificdata_key_create(lwp_specificdata_domain, keyp, dtor));
1344 }
1345
1346 /*
1347 * lwp_specific_key_delete --
1348 * Delete a key for subsystem lwp-specific data.
1349 */
1350 void
1351 lwp_specific_key_delete(specificdata_key_t key)
1352 {
1353
1354 specificdata_key_delete(lwp_specificdata_domain, key);
1355 }
1356
1357 /*
1358 * lwp_initspecific --
1359 * Initialize an LWP's specificdata container.
1360 */
1361 void
1362 lwp_initspecific(struct lwp *l)
1363 {
1364 int error;
1365
1366 error = specificdata_init(lwp_specificdata_domain, &l->l_specdataref);
1367 KASSERT(error == 0);
1368 }
1369
1370 /*
1371 * lwp_finispecific --
1372 * Finalize an LWP's specificdata container.
1373 */
1374 void
1375 lwp_finispecific(struct lwp *l)
1376 {
1377
1378 specificdata_fini(lwp_specificdata_domain, &l->l_specdataref);
1379 }
1380
1381 /*
1382 * lwp_getspecific --
1383 * Return lwp-specific data corresponding to the specified key.
1384 *
1385 * Note: LWP specific data is NOT INTERLOCKED. An LWP should access
1386 * only its OWN SPECIFIC DATA. If it is necessary to access another
1387 * LWP's specifc data, care must be taken to ensure that doing so
1388 * would not cause internal data structure inconsistency (i.e. caller
1389 * can guarantee that the target LWP is not inside an lwp_getspecific()
1390 * or lwp_setspecific() call).
1391 */
1392 void *
1393 lwp_getspecific(specificdata_key_t key)
1394 {
1395
1396 return (specificdata_getspecific_unlocked(lwp_specificdata_domain,
1397 &curlwp->l_specdataref, key));
1398 }
1399
1400 void *
1401 _lwp_getspecific_by_lwp(struct lwp *l, specificdata_key_t key)
1402 {
1403
1404 return (specificdata_getspecific_unlocked(lwp_specificdata_domain,
1405 &l->l_specdataref, key));
1406 }
1407
1408 /*
1409 * lwp_setspecific --
1410 * Set lwp-specific data corresponding to the specified key.
1411 */
1412 void
1413 lwp_setspecific(specificdata_key_t key, void *data)
1414 {
1415
1416 specificdata_setspecific(lwp_specificdata_domain,
1417 &curlwp->l_specdataref, key, data);
1418 }
1419