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