kern_lwp.c revision 1.61.2.8 1 /* $NetBSD: kern_lwp.c,v 1.61.2.8 2007/04/10 13:26:39 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.8 2007/04/10 13:26:39 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 TAILQ_INIT(&l2->l_selwait);
595
596 if (p2->p_flag & PK_SYSTEM) {
597 /*
598 * Mark it as a system process and not a candidate for
599 * swapping.
600 */
601 l2->l_flag |= LW_SYSTEM;
602 }
603
604 lwp_update_creds(l2);
605 callout_init(&l2->l_tsleep_ch);
606 mutex_init(&l2->l_swaplock, MUTEX_DEFAULT, IPL_NONE);
607 cv_init(&l2->l_sigcv, "sigwait");
608 l2->l_syncobj = &sched_syncobj;
609
610 if (rnewlwpp != NULL)
611 *rnewlwpp = l2;
612
613 l2->l_addr = UAREA_TO_USER(uaddr);
614 KERNEL_LOCK(1, curlwp);
615 uvm_lwp_fork(l1, l2, stack, stacksize, func,
616 (arg != NULL) ? arg : l2);
617 KERNEL_UNLOCK_ONE(curlwp);
618
619 mutex_enter(&p2->p_smutex);
620
621 if ((flags & LWP_DETACHED) != 0) {
622 l2->l_prflag = LPR_DETACHED;
623 p2->p_ndlwps++;
624 } else
625 l2->l_prflag = 0;
626
627 l2->l_sigmask = l1->l_sigmask;
628 CIRCLEQ_INIT(&l2->l_sigpend.sp_info);
629 sigemptyset(&l2->l_sigpend.sp_set);
630
631 p2->p_nlwpid++;
632 if (p2->p_nlwpid == 0)
633 p2->p_nlwpid++;
634 l2->l_lid = p2->p_nlwpid;
635 LIST_INSERT_HEAD(&p2->p_lwps, l2, l_sibling);
636 p2->p_nlwps++;
637
638 mutex_exit(&p2->p_smutex);
639
640 mutex_enter(&proclist_lock);
641 mutex_enter(&proclist_mutex);
642 LIST_INSERT_HEAD(&alllwp, l2, l_list);
643 mutex_exit(&proclist_mutex);
644 mutex_exit(&proclist_lock);
645
646 SYSCALL_TIME_LWP_INIT(l2);
647
648 if (p2->p_emul->e_lwp_fork)
649 (*p2->p_emul->e_lwp_fork)(l1, l2);
650
651 return (0);
652 }
653
654 /*
655 * Quit the process. This will call cpu_exit, which will call cpu_switch,
656 * so this can only be used meaningfully if you're willing to switch away.
657 * Calling with l!=curlwp would be weird.
658 */
659 void
660 lwp_exit(struct lwp *l)
661 {
662 struct proc *p = l->l_proc;
663 struct lwp *l2;
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
668 /*
669 * Verify that we hold no locks other than the kernel lock.
670 */
671 #ifdef MULTIPROCESSOR
672 LOCKDEBUG_BARRIER(&kernel_lock, 0);
673 #else
674 LOCKDEBUG_BARRIER(NULL, 0);
675 #endif
676
677 /*
678 * If we are the last live LWP in a process, we need to exit the
679 * entire process. We do so with an exit status of zero, because
680 * it's a "controlled" exit, and because that's what Solaris does.
681 *
682 * We are not quite a zombie yet, but for accounting purposes we
683 * must increment the count of zombies here.
684 *
685 * Note: the last LWP's specificdata will be deleted here.
686 */
687 mutex_enter(&p->p_smutex);
688 if (p->p_nlwps - p->p_nzlwps == 1) {
689 DPRINTF(("lwp_exit: %d.%d calling exit1()\n",
690 p->p_pid, l->l_lid));
691 exit1(l, 0);
692 /* NOTREACHED */
693 }
694 p->p_nzlwps++;
695 mutex_exit(&p->p_smutex);
696
697 if (p->p_emul->e_lwp_exit)
698 (*p->p_emul->e_lwp_exit)(l);
699
700 /* Delete the specificdata while it's still safe to sleep. */
701 specificdata_fini(lwp_specificdata_domain, &l->l_specdataref);
702
703 /*
704 * Release our cached credentials.
705 */
706 kauth_cred_free(l->l_cred);
707
708 /*
709 * While we can still block, mark the LWP as unswappable to
710 * prevent conflicts with the with the swapper.
711 */
712 uvm_lwp_hold(l);
713
714 /*
715 * Remove the LWP from the global list.
716 */
717 mutex_enter(&proclist_lock);
718 mutex_enter(&proclist_mutex);
719 LIST_REMOVE(l, l_list);
720 mutex_exit(&proclist_mutex);
721 mutex_exit(&proclist_lock);
722
723 /*
724 * Get rid of all references to the LWP that others (e.g. procfs)
725 * may have, and mark the LWP as a zombie. If the LWP is detached,
726 * mark it waiting for collection in the proc structure. Note that
727 * before we can do that, we need to free any other dead, deatched
728 * LWP waiting to meet its maker.
729 *
730 * XXXSMP disable preemption.
731 */
732 mutex_enter(&p->p_smutex);
733 lwp_drainrefs(l);
734
735 if ((l->l_prflag & LPR_DETACHED) != 0) {
736 while ((l2 = p->p_zomblwp) != NULL) {
737 p->p_zomblwp = NULL;
738 lwp_free(l2, false, false);/* releases proc mutex */
739 mutex_enter(&p->p_smutex);
740 }
741 p->p_zomblwp = l;
742 }
743
744 /*
745 * If we find a pending signal for the process and we have been
746 * asked to check for signals, then we loose: arrange to have
747 * all other LWPs in the process check for signals.
748 */
749 if ((l->l_flag & LW_PENDSIG) != 0 &&
750 firstsig(&p->p_sigpend.sp_set) != 0) {
751 LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
752 lwp_lock(l2);
753 l2->l_flag |= LW_PENDSIG;
754 lwp_unlock(l2);
755 }
756 }
757
758 lwp_lock(l);
759 l->l_stat = LSZOMB;
760 lwp_unlock(l);
761 p->p_nrlwps--;
762 cv_broadcast(&p->p_lwpcv);
763 mutex_exit(&p->p_smutex);
764
765 /*
766 * We can no longer block. At this point, lwp_free() may already
767 * be gunning for us. On a multi-CPU system, we may be off p_lwps.
768 *
769 * Free MD LWP resources.
770 */
771 #ifndef __NO_CPU_LWP_FREE
772 cpu_lwp_free(l, 0);
773 #endif
774 pmap_deactivate(l);
775
776 /*
777 * Release the kernel lock, signal another LWP to collect us,
778 * and switch away into oblivion.
779 */
780 #ifdef notyet
781 /* XXXSMP hold in lwp_userret() */
782 KERNEL_UNLOCK_LAST(l);
783 #else
784 KERNEL_UNLOCK_ALL(l, NULL);
785 #endif
786
787 cpu_exit(l);
788 }
789
790 /*
791 * We are called from cpu_exit() once it is safe to schedule the dead LWP's
792 * resources to be freed (i.e., once we've switched to the idle PCB for the
793 * current CPU).
794 */
795 void
796 lwp_exit2(struct lwp *l)
797 {
798 /* XXXSMP re-enable preemption */
799 }
800
801 /*
802 * Free a dead LWP's remaining resources.
803 *
804 * XXXLWP limits.
805 */
806 void
807 lwp_free(struct lwp *l, bool recycle, bool last)
808 {
809 struct proc *p = l->l_proc;
810 ksiginfoq_t kq;
811
812 /*
813 * If this was not the last LWP in the process, then adjust
814 * counters and unlock.
815 */
816 if (!last) {
817 /*
818 * Add the LWP's run time to the process' base value.
819 * This needs to co-incide with coming off p_lwps.
820 */
821 timeradd(&l->l_rtime, &p->p_rtime, &p->p_rtime);
822 LIST_REMOVE(l, l_sibling);
823 p->p_nlwps--;
824 p->p_nzlwps--;
825 if ((l->l_prflag & LPR_DETACHED) != 0)
826 p->p_ndlwps--;
827
828 /*
829 * Have any LWPs sleeping in lwp_wait() recheck for
830 * deadlock.
831 */
832 cv_broadcast(&p->p_lwpcv);
833 mutex_exit(&p->p_smutex);
834 }
835
836 #ifdef MULTIPROCESSOR
837 /*
838 * In the unlikely event that the LWP is still on the CPU,
839 * then spin until it has switched away. We need to release
840 * all locks to avoid deadlock against interrupt handlers on
841 * the target CPU.
842 */
843 if (l->l_cpu->ci_curlwp == l) {
844 int count;
845 KERNEL_UNLOCK_ALL(curlwp, &count);
846 while (l->l_cpu->ci_curlwp == l)
847 SPINLOCK_BACKOFF_HOOK;
848 KERNEL_LOCK(count, curlwp);
849 }
850 #endif
851
852 /*
853 * Destroy the LWP's remaining signal information.
854 */
855 ksiginfo_queue_init(&kq);
856 sigclear(&l->l_sigpend, NULL, &kq);
857 ksiginfo_queue_drain(&kq);
858 cv_destroy(&l->l_sigcv);
859 mutex_destroy(&l->l_swaplock);
860
861 /*
862 * Free the LWP's turnstile and the LWP structure itself unless the
863 * caller wants to recycle them.
864 *
865 * We can't return turnstile0 to the pool (it didn't come from it),
866 * so if it comes up just drop it quietly and move on.
867 *
868 * We don't recycle the VM resources at this time.
869 */
870 if (!recycle && l->l_ts != &turnstile0)
871 pool_cache_put(&turnstile_cache, l->l_ts);
872 #ifndef __NO_CPU_LWP_FREE
873 cpu_lwp_free2(l);
874 #endif
875 uvm_lwp_exit(l);
876 KASSERT(SLIST_EMPTY(&l->l_pi_lenders));
877 KASSERT(l->l_inheritedprio == MAXPRI);
878 if (!recycle)
879 pool_put(&lwp_pool, l);
880 }
881
882 /*
883 * Pick a LWP to represent the process for those operations which
884 * want information about a "process" that is actually associated
885 * with a LWP.
886 *
887 * If 'locking' is false, no locking or lock checks are performed.
888 * This is intended for use by DDB.
889 *
890 * We don't bother locking the LWP here, since code that uses this
891 * interface is broken by design and an exact match is not required.
892 */
893 struct lwp *
894 proc_representative_lwp(struct proc *p, int *nrlwps, int locking)
895 {
896 struct lwp *l, *onproc, *running, *sleeping, *stopped, *suspended;
897 struct lwp *signalled;
898 int cnt;
899
900 if (locking) {
901 KASSERT(mutex_owned(&p->p_smutex));
902 }
903
904 /* Trivial case: only one LWP */
905 if (p->p_nlwps == 1) {
906 l = LIST_FIRST(&p->p_lwps);
907 if (nrlwps)
908 *nrlwps = (l->l_stat == LSONPROC || LSRUN);
909 return l;
910 }
911
912 cnt = 0;
913 switch (p->p_stat) {
914 case SSTOP:
915 case SACTIVE:
916 /* Pick the most live LWP */
917 onproc = running = sleeping = stopped = suspended = NULL;
918 signalled = NULL;
919 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
920 if (l->l_lid == p->p_sigctx.ps_lwp)
921 signalled = l;
922 switch (l->l_stat) {
923 case LSONPROC:
924 onproc = l;
925 cnt++;
926 break;
927 case LSRUN:
928 running = l;
929 cnt++;
930 break;
931 case LSSLEEP:
932 sleeping = l;
933 break;
934 case LSSTOP:
935 stopped = l;
936 break;
937 case LSSUSPENDED:
938 suspended = l;
939 break;
940 }
941 }
942 if (nrlwps)
943 *nrlwps = cnt;
944 if (signalled)
945 l = signalled;
946 else if (onproc)
947 l = onproc;
948 else if (running)
949 l = running;
950 else if (sleeping)
951 l = sleeping;
952 else if (stopped)
953 l = stopped;
954 else if (suspended)
955 l = suspended;
956 else
957 break;
958 return l;
959 if (nrlwps)
960 *nrlwps = 0;
961 l = LIST_FIRST(&p->p_lwps);
962 return l;
963 #ifdef DIAGNOSTIC
964 case SIDL:
965 case SZOMB:
966 case SDYING:
967 case SDEAD:
968 if (locking)
969 mutex_exit(&p->p_smutex);
970 /* We have more than one LWP and we're in SIDL?
971 * How'd that happen?
972 */
973 panic("Too many LWPs in idle/dying process %d (%s) stat = %d",
974 p->p_pid, p->p_comm, p->p_stat);
975 break;
976 default:
977 if (locking)
978 mutex_exit(&p->p_smutex);
979 panic("Process %d (%s) in unknown state %d",
980 p->p_pid, p->p_comm, p->p_stat);
981 #endif
982 }
983
984 if (locking)
985 mutex_exit(&p->p_smutex);
986 panic("proc_representative_lwp: couldn't find a lwp for process"
987 " %d (%s)", p->p_pid, p->p_comm);
988 /* NOTREACHED */
989 return NULL;
990 }
991
992 /*
993 * Look up a live LWP within the speicifed process, and return it locked.
994 *
995 * Must be called with p->p_smutex held.
996 */
997 struct lwp *
998 lwp_find(struct proc *p, int id)
999 {
1000 struct lwp *l;
1001
1002 KASSERT(mutex_owned(&p->p_smutex));
1003
1004 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1005 if (l->l_lid == id)
1006 break;
1007 }
1008
1009 /*
1010 * No need to lock - all of these conditions will
1011 * be visible with the process level mutex held.
1012 */
1013 if (l != NULL && (l->l_stat == LSIDL || l->l_stat == LSZOMB))
1014 l = NULL;
1015
1016 return l;
1017 }
1018
1019 /*
1020 * Update an LWP's cached credentials to mirror the process' master copy.
1021 *
1022 * This happens early in the syscall path, on user trap, and on LWP
1023 * creation. A long-running LWP can also voluntarily choose to update
1024 * it's credentials by calling this routine. This may be called from
1025 * LWP_CACHE_CREDS(), which checks l->l_cred != p->p_cred beforehand.
1026 */
1027 void
1028 lwp_update_creds(struct lwp *l)
1029 {
1030 kauth_cred_t oc;
1031 struct proc *p;
1032
1033 p = l->l_proc;
1034 oc = l->l_cred;
1035
1036 mutex_enter(&p->p_mutex);
1037 kauth_cred_hold(p->p_cred);
1038 l->l_cred = p->p_cred;
1039 mutex_exit(&p->p_mutex);
1040 if (oc != NULL)
1041 kauth_cred_free(oc);
1042 }
1043
1044 /*
1045 * Verify that an LWP is locked, and optionally verify that the lock matches
1046 * one we specify.
1047 */
1048 int
1049 lwp_locked(struct lwp *l, kmutex_t *mtx)
1050 {
1051 kmutex_t *cur = l->l_mutex;
1052
1053 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
1054 return mutex_owned(cur) && (mtx == cur || mtx == NULL);
1055 #else
1056 return mutex_owned(cur);
1057 #endif
1058 }
1059
1060 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
1061 /*
1062 * Lock an LWP.
1063 */
1064 void
1065 lwp_lock_retry(struct lwp *l, kmutex_t *old)
1066 {
1067
1068 /*
1069 * XXXgcc ignoring kmutex_t * volatile on i386
1070 *
1071 * gcc version 4.1.2 20061021 prerelease (NetBSD nb1 20061021)
1072 */
1073 #if 1
1074 while (l->l_mutex != old) {
1075 #else
1076 for (;;) {
1077 #endif
1078 mutex_spin_exit(old);
1079 old = l->l_mutex;
1080 mutex_spin_enter(old);
1081
1082 /*
1083 * mutex_enter() will have posted a read barrier. Re-test
1084 * l->l_mutex. If it has changed, we need to try again.
1085 */
1086 #if 1
1087 }
1088 #else
1089 } while (__predict_false(l->l_mutex != old));
1090 #endif
1091 }
1092 #endif
1093
1094 /*
1095 * Lend a new mutex to an LWP. The old mutex must be held.
1096 */
1097 void
1098 lwp_setlock(struct lwp *l, kmutex_t *new)
1099 {
1100
1101 KASSERT(mutex_owned(l->l_mutex));
1102
1103 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
1104 mb_write();
1105 l->l_mutex = new;
1106 #else
1107 (void)new;
1108 #endif
1109 }
1110
1111 /*
1112 * Lend a new mutex to an LWP, and release the old mutex. The old mutex
1113 * must be held.
1114 */
1115 void
1116 lwp_unlock_to(struct lwp *l, kmutex_t *new)
1117 {
1118 kmutex_t *old;
1119
1120 KASSERT(mutex_owned(l->l_mutex));
1121
1122 old = l->l_mutex;
1123 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
1124 mb_write();
1125 l->l_mutex = new;
1126 #else
1127 (void)new;
1128 #endif
1129 mutex_spin_exit(old);
1130 }
1131
1132 /*
1133 * Acquire a new mutex, and donate it to an LWP. The LWP must already be
1134 * locked.
1135 */
1136 void
1137 lwp_relock(struct lwp *l, kmutex_t *new)
1138 {
1139 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
1140 kmutex_t *old;
1141 #endif
1142
1143 KASSERT(mutex_owned(l->l_mutex));
1144
1145 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
1146 old = l->l_mutex;
1147 if (old != new) {
1148 mutex_spin_enter(new);
1149 l->l_mutex = new;
1150 mutex_spin_exit(old);
1151 }
1152 #else
1153 (void)new;
1154 #endif
1155 }
1156
1157 int
1158 lwp_trylock(struct lwp *l)
1159 {
1160 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
1161 kmutex_t *old;
1162
1163 for (;;) {
1164 if (!mutex_tryenter(old = l->l_mutex))
1165 return 0;
1166 if (__predict_true(l->l_mutex == old))
1167 return 1;
1168 mutex_spin_exit(old);
1169 }
1170 #else
1171 return mutex_tryenter(l->l_mutex);
1172 #endif
1173 }
1174
1175 /*
1176 * Handle exceptions for mi_userret(). Called if a member of LW_USERRET is
1177 * set.
1178 */
1179 void
1180 lwp_userret(struct lwp *l)
1181 {
1182 struct proc *p;
1183 void (*hook)(void);
1184 int sig;
1185
1186 p = l->l_proc;
1187
1188 /*
1189 * It should be safe to do this read unlocked on a multiprocessor
1190 * system..
1191 */
1192 while ((l->l_flag & LW_USERRET) != 0) {
1193 /*
1194 * Process pending signals first, unless the process
1195 * is dumping core or exiting, where we will instead
1196 * enter the L_WSUSPEND case below.
1197 */
1198 if ((l->l_flag & (LW_PENDSIG | LW_WCORE | LW_WEXIT)) ==
1199 LW_PENDSIG) {
1200 mutex_enter(&p->p_smutex);
1201 while ((sig = issignal(l)) != 0)
1202 postsig(sig);
1203 mutex_exit(&p->p_smutex);
1204 }
1205
1206 /*
1207 * Core-dump or suspend pending.
1208 *
1209 * In case of core dump, suspend ourselves, so that the
1210 * kernel stack and therefore the userland registers saved
1211 * in the trapframe are around for coredump() to write them
1212 * out. We issue a wakeup on p->p_lwpcv so that sigexit()
1213 * will write the core file out once all other LWPs are
1214 * suspended.
1215 */
1216 if ((l->l_flag & LW_WSUSPEND) != 0) {
1217 mutex_enter(&p->p_smutex);
1218 p->p_nrlwps--;
1219 cv_broadcast(&p->p_lwpcv);
1220 lwp_lock(l);
1221 l->l_stat = LSSUSPENDED;
1222 mutex_exit(&p->p_smutex);
1223 mi_switch(l, NULL);
1224 }
1225
1226 /* Process is exiting. */
1227 if ((l->l_flag & LW_WEXIT) != 0) {
1228 KERNEL_LOCK(1, l);
1229 lwp_exit(l);
1230 KASSERT(0);
1231 /* NOTREACHED */
1232 }
1233
1234 /* Call userret hook; used by Linux emulation. */
1235 if ((l->l_flag & LW_WUSERRET) != 0) {
1236 lwp_lock(l);
1237 l->l_flag &= ~LW_WUSERRET;
1238 lwp_unlock(l);
1239 hook = p->p_userret;
1240 p->p_userret = NULL;
1241 (*hook)();
1242 }
1243 }
1244 }
1245
1246 /*
1247 * Force an LWP to enter the kernel, to take a trip through lwp_userret().
1248 */
1249 void
1250 lwp_need_userret(struct lwp *l)
1251 {
1252 KASSERT(lwp_locked(l, NULL));
1253
1254 /*
1255 * Since the tests in lwp_userret() are done unlocked, make sure
1256 * that the condition will be seen before forcing the LWP to enter
1257 * kernel mode.
1258 */
1259 mb_write();
1260 cpu_signotify(l);
1261 }
1262
1263 /*
1264 * Add one reference to an LWP. This will prevent the LWP from
1265 * exiting, thus keep the lwp structure and PCB around to inspect.
1266 */
1267 void
1268 lwp_addref(struct lwp *l)
1269 {
1270
1271 KASSERT(mutex_owned(&l->l_proc->p_smutex));
1272 KASSERT(l->l_stat != LSZOMB);
1273 KASSERT(l->l_refcnt != 0);
1274
1275 l->l_refcnt++;
1276 }
1277
1278 /*
1279 * Remove one reference to an LWP. If this is the last reference,
1280 * then we must finalize the LWP's death.
1281 */
1282 void
1283 lwp_delref(struct lwp *l)
1284 {
1285 struct proc *p = l->l_proc;
1286
1287 mutex_enter(&p->p_smutex);
1288 if (--l->l_refcnt == 0)
1289 cv_broadcast(&p->p_refcv);
1290 mutex_exit(&p->p_smutex);
1291 }
1292
1293 /*
1294 * Drain all references to the current LWP.
1295 */
1296 void
1297 lwp_drainrefs(struct lwp *l)
1298 {
1299 struct proc *p = l->l_proc;
1300
1301 KASSERT(mutex_owned(&p->p_smutex));
1302 KASSERT(l->l_refcnt != 0);
1303
1304 l->l_refcnt--;
1305 while (l->l_refcnt != 0)
1306 cv_wait(&p->p_refcv, &p->p_smutex);
1307 }
1308
1309 /*
1310 * lwp_specific_key_create --
1311 * Create a key for subsystem lwp-specific data.
1312 */
1313 int
1314 lwp_specific_key_create(specificdata_key_t *keyp, specificdata_dtor_t dtor)
1315 {
1316
1317 return (specificdata_key_create(lwp_specificdata_domain, keyp, dtor));
1318 }
1319
1320 /*
1321 * lwp_specific_key_delete --
1322 * Delete a key for subsystem lwp-specific data.
1323 */
1324 void
1325 lwp_specific_key_delete(specificdata_key_t key)
1326 {
1327
1328 specificdata_key_delete(lwp_specificdata_domain, key);
1329 }
1330
1331 /*
1332 * lwp_initspecific --
1333 * Initialize an LWP's specificdata container.
1334 */
1335 void
1336 lwp_initspecific(struct lwp *l)
1337 {
1338 int error;
1339
1340 error = specificdata_init(lwp_specificdata_domain, &l->l_specdataref);
1341 KASSERT(error == 0);
1342 }
1343
1344 /*
1345 * lwp_finispecific --
1346 * Finalize an LWP's specificdata container.
1347 */
1348 void
1349 lwp_finispecific(struct lwp *l)
1350 {
1351
1352 specificdata_fini(lwp_specificdata_domain, &l->l_specdataref);
1353 }
1354
1355 /*
1356 * lwp_getspecific --
1357 * Return lwp-specific data corresponding to the specified key.
1358 *
1359 * Note: LWP specific data is NOT INTERLOCKED. An LWP should access
1360 * only its OWN SPECIFIC DATA. If it is necessary to access another
1361 * LWP's specifc data, care must be taken to ensure that doing so
1362 * would not cause internal data structure inconsistency (i.e. caller
1363 * can guarantee that the target LWP is not inside an lwp_getspecific()
1364 * or lwp_setspecific() call).
1365 */
1366 void *
1367 lwp_getspecific(specificdata_key_t key)
1368 {
1369
1370 return (specificdata_getspecific_unlocked(lwp_specificdata_domain,
1371 &curlwp->l_specdataref, key));
1372 }
1373
1374 void *
1375 _lwp_getspecific_by_lwp(struct lwp *l, specificdata_key_t key)
1376 {
1377
1378 return (specificdata_getspecific_unlocked(lwp_specificdata_domain,
1379 &l->l_specdataref, key));
1380 }
1381
1382 /*
1383 * lwp_setspecific --
1384 * Set lwp-specific data corresponding to the specified key.
1385 */
1386 void
1387 lwp_setspecific(specificdata_key_t key, void *data)
1388 {
1389
1390 specificdata_setspecific(lwp_specificdata_domain,
1391 &curlwp->l_specdataref, key, data);
1392 }
1393