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