kern_lwp.c revision 1.61.2.5 1 /* $NetBSD: kern_lwp.c,v 1.61.2.5 2007/04/09 22:10:03 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.5 2007/04/09 22:10:03 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
374 DPRINTF(("lwp_wait1: %d.%d waiting for %d.\n",
375 p->p_pid, l->l_lid, lid));
376
377 KASSERT(mutex_owned(&p->p_smutex));
378
379 /*
380 * We try to check for deadlock:
381 *
382 * 1) If all other LWPs are waiting for exits or suspended.
383 * 2) If we are trying to wait on ourself.
384 *
385 * XXX we'd like to check for a cycle of waiting LWPs (specific LID
386 * waits, not any-LWP waits) and detect that sort of deadlock, but
387 * we don't have a good place to store the lwp that is being waited
388 * for. wchan is already filled with &p->p_nlwps, and putting the
389 * lwp address in there for deadlock tracing would require exiting
390 * LWPs to call wakeup on both their own address and &p->p_nlwps, to
391 * get threads sleeping on any LWP exiting.
392 */
393 if (lid == l->l_lid)
394 return EDEADLK;
395
396 p->p_nlwpwait++;
397
398 for (;;) {
399 /*
400 * Avoid a race between exit1() and sigexit(): if the
401 * process is dumping core, then we need to bail out: call
402 * into lwp_userret() where we will be suspended until the
403 * deed is done.
404 */
405 if ((p->p_sflag & PS_WCORE) != 0) {
406 mutex_exit(&p->p_smutex);
407 lwp_userret(l);
408 #ifdef DIAGNOSTIC
409 panic("lwp_wait1");
410 #endif
411 /* NOTREACHED */
412 }
413
414 /*
415 * First off, drain any detached LWP that is waiting to be
416 * reaped.
417 */
418 while ((l2 = p->p_zomblwp) != NULL) {
419 p->p_zomblwp = NULL;
420 lwp_free(l2, 0, 0); /* releases proc mutex */
421 mutex_enter(&p->p_smutex);
422 }
423
424 /*
425 * Now look for an LWP to collect. If the whole process is
426 * exiting, count detached LWPs as eligible to be collected,
427 * but don't drain them here.
428 */
429 nfound = 0;
430 LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
431 if (l2 == l || (lid != 0 && l2->l_lid != lid))
432 continue;
433 if ((l2->l_prflag & LPR_DETACHED) != 0) {
434 nfound += ((flags & LWPWAIT_EXITCONTROL) != 0);
435 continue;
436 }
437 nfound++;
438
439 /* No need to lock the LWP in order to see LSZOMB. */
440 if (l2->l_stat != LSZOMB)
441 continue;
442
443 if (departed)
444 *departed = l2->l_lid;
445 lwp_free(l2, 0, 0);
446 mutex_enter(&p->p_smutex);
447 p->p_nlwpwait--;
448 return 0;
449 }
450
451 if (nfound == 0) {
452 error = ESRCH;
453 break;
454 }
455 if ((flags & LWPWAIT_EXITCONTROL) != 0) {
456 KASSERT(p->p_nlwps > 1);
457 cv_wait(&p->p_lwpcv, &p->p_smutex);
458 continue;
459 }
460 if ((p->p_sflag & PS_WEXIT) != 0 ||
461 p->p_nrlwps <= p->p_nlwpwait + p->p_ndlwps) {
462 error = EDEADLK;
463 break;
464 }
465 if ((error = cv_wait_sig(&p->p_lwpcv, &p->p_smutex)) != 0)
466 break;
467 }
468
469 p->p_nlwpwait--;
470 return error;
471 }
472
473 /*
474 * Create a new LWP within process 'p2', using LWP 'l1' as a template.
475 * The new LWP is created in state LSIDL and must be set running,
476 * suspended, or stopped by the caller.
477 */
478 int
479 newlwp(struct lwp *l1, struct proc *p2, vaddr_t uaddr, bool inmem,
480 int flags, void *stack, size_t stacksize,
481 void (*func)(void *), void *arg, struct lwp **rnewlwpp)
482 {
483 struct lwp *l2, *isfree;
484 turnstile_t *ts;
485
486 /*
487 * First off, reap any detached LWP waiting to be collected.
488 * We can re-use its LWP structure and turnstile.
489 */
490 isfree = NULL;
491 if (p2->p_zomblwp != NULL) {
492 mutex_enter(&p2->p_smutex);
493 if ((isfree = p2->p_zomblwp) != NULL) {
494 p2->p_zomblwp = NULL;
495 lwp_free(isfree, 1, 0); /* releases proc mutex */
496 } else
497 mutex_exit(&p2->p_smutex);
498 }
499 if (isfree == NULL) {
500 l2 = pool_get(&lwp_pool, PR_WAITOK);
501 memset(l2, 0, sizeof(*l2));
502 l2->l_ts = pool_cache_get(&turnstile_cache, PR_WAITOK);
503 SLIST_INIT(&l2->l_pi_lenders);
504 } else {
505 l2 = isfree;
506 ts = l2->l_ts;
507 KASSERT(l2->l_inheritedprio == MAXPRI);
508 KASSERT(SLIST_EMPTY(&l2->l_pi_lenders));
509 memset(l2, 0, sizeof(*l2));
510 l2->l_ts = ts;
511 }
512
513 l2->l_stat = LSIDL;
514 l2->l_proc = p2;
515 l2->l_refcnt = 1;
516 l2->l_priority = l1->l_priority;
517 l2->l_usrpri = l1->l_usrpri;
518 l2->l_inheritedprio = MAXPRI;
519 l2->l_mutex = &sched_mutex;
520 l2->l_cpu = l1->l_cpu;
521 l2->l_flag = inmem ? LW_INMEM : 0;
522 lwp_initspecific(l2);
523
524 if (p2->p_flag & PK_SYSTEM) {
525 /*
526 * Mark it as a system process and not a candidate for
527 * swapping.
528 */
529 l2->l_flag |= LW_SYSTEM;
530 }
531
532 lwp_update_creds(l2);
533 callout_init(&l2->l_tsleep_ch);
534 mutex_init(&l2->l_swaplock, MUTEX_DEFAULT, IPL_NONE);
535 cv_init(&l2->l_sigcv, "sigwait");
536 l2->l_syncobj = &sched_syncobj;
537
538 if (rnewlwpp != NULL)
539 *rnewlwpp = l2;
540
541 l2->l_addr = UAREA_TO_USER(uaddr);
542 KERNEL_LOCK(1, curlwp);
543 uvm_lwp_fork(l1, l2, stack, stacksize, func,
544 (arg != NULL) ? arg : l2);
545 KERNEL_UNLOCK_ONE(curlwp);
546
547 mutex_enter(&p2->p_smutex);
548
549 if ((flags & LWP_DETACHED) != 0) {
550 l2->l_prflag = LPR_DETACHED;
551 p2->p_ndlwps++;
552 } else
553 l2->l_prflag = 0;
554
555 l2->l_sigmask = l1->l_sigmask;
556 CIRCLEQ_INIT(&l2->l_sigpend.sp_info);
557 sigemptyset(&l2->l_sigpend.sp_set);
558
559 p2->p_nlwpid++;
560 if (p2->p_nlwpid == 0)
561 p2->p_nlwpid++;
562 l2->l_lid = p2->p_nlwpid;
563 LIST_INSERT_HEAD(&p2->p_lwps, l2, l_sibling);
564 p2->p_nlwps++;
565
566 mutex_exit(&p2->p_smutex);
567
568 mutex_enter(&proclist_lock);
569 mutex_enter(&proclist_mutex);
570 LIST_INSERT_HEAD(&alllwp, l2, l_list);
571 mutex_exit(&proclist_mutex);
572 mutex_exit(&proclist_lock);
573
574 SYSCALL_TIME_LWP_INIT(l2);
575
576 if (p2->p_emul->e_lwp_fork)
577 (*p2->p_emul->e_lwp_fork)(l1, l2);
578
579 return (0);
580 }
581
582 /*
583 * Quit the process. This will call cpu_exit, which will call cpu_switch,
584 * so this can only be used meaningfully if you're willing to switch away.
585 * Calling with l!=curlwp would be weird.
586 */
587 void
588 lwp_exit(struct lwp *l)
589 {
590 struct proc *p = l->l_proc;
591 struct lwp *l2;
592
593 DPRINTF(("lwp_exit: %d.%d exiting.\n", p->p_pid, l->l_lid));
594 DPRINTF((" nlwps: %d nzlwps: %d\n", p->p_nlwps, p->p_nzlwps));
595
596 /*
597 * Verify that we hold no locks other than the kernel lock.
598 */
599 #ifdef MULTIPROCESSOR
600 LOCKDEBUG_BARRIER(&kernel_lock, 0);
601 #else
602 LOCKDEBUG_BARRIER(NULL, 0);
603 #endif
604
605 /*
606 * If we are the last live LWP in a process, we need to exit the
607 * entire process. We do so with an exit status of zero, because
608 * it's a "controlled" exit, and because that's what Solaris does.
609 *
610 * We are not quite a zombie yet, but for accounting purposes we
611 * must increment the count of zombies here.
612 *
613 * Note: the last LWP's specificdata will be deleted here.
614 */
615 mutex_enter(&p->p_smutex);
616 if (p->p_nlwps - p->p_nzlwps == 1) {
617 DPRINTF(("lwp_exit: %d.%d calling exit1()\n",
618 p->p_pid, l->l_lid));
619 exit1(l, 0);
620 /* NOTREACHED */
621 }
622 p->p_nzlwps++;
623 mutex_exit(&p->p_smutex);
624
625 if (p->p_emul->e_lwp_exit)
626 (*p->p_emul->e_lwp_exit)(l);
627
628 /* Delete the specificdata while it's still safe to sleep. */
629 specificdata_fini(lwp_specificdata_domain, &l->l_specdataref);
630
631 /*
632 * Release our cached credentials.
633 */
634 kauth_cred_free(l->l_cred);
635
636 /*
637 * While we can still block, mark the LWP as unswappable to
638 * prevent conflicts with the with the swapper.
639 */
640 uvm_lwp_hold(l);
641
642 /*
643 * Remove the LWP from the global list.
644 */
645 mutex_enter(&proclist_lock);
646 mutex_enter(&proclist_mutex);
647 LIST_REMOVE(l, l_list);
648 mutex_exit(&proclist_mutex);
649 mutex_exit(&proclist_lock);
650
651 /*
652 * Get rid of all references to the LWP that others (e.g. procfs)
653 * may have, and mark the LWP as a zombie. If the LWP is detached,
654 * mark it waiting for collection in the proc structure. Note that
655 * before we can do that, we need to free any other dead, deatched
656 * LWP waiting to meet its maker.
657 *
658 * XXXSMP disable preemption.
659 */
660 mutex_enter(&p->p_smutex);
661 lwp_drainrefs(l);
662
663 if ((l->l_prflag & LPR_DETACHED) != 0) {
664 while ((l2 = p->p_zomblwp) != NULL) {
665 p->p_zomblwp = NULL;
666 lwp_free(l2, 0, 0); /* releases proc mutex */
667 mutex_enter(&p->p_smutex);
668 }
669 p->p_zomblwp = l;
670 }
671
672 /*
673 * If we find a pending signal for the process and we have been
674 * asked to check for signals, then we loose: arrange to have
675 * all other LWPs in the process check for signals.
676 */
677 if ((l->l_flag & LW_PENDSIG) != 0 &&
678 firstsig(&p->p_sigpend.sp_set) != 0) {
679 LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
680 lwp_lock(l2);
681 l2->l_flag |= LW_PENDSIG;
682 lwp_unlock(l2);
683 }
684 }
685
686 lwp_lock(l);
687 l->l_stat = LSZOMB;
688 lwp_unlock(l);
689 p->p_nrlwps--;
690 cv_broadcast(&p->p_lwpcv);
691 mutex_exit(&p->p_smutex);
692
693 /*
694 * We can no longer block. At this point, lwp_free() may already
695 * be gunning for us. On a multi-CPU system, we may be off p_lwps.
696 *
697 * Free MD LWP resources.
698 */
699 #ifndef __NO_CPU_LWP_FREE
700 cpu_lwp_free(l, 0);
701 #endif
702 pmap_deactivate(l);
703
704 /*
705 * Release the kernel lock, signal another LWP to collect us,
706 * and switch away into oblivion.
707 */
708 #ifdef notyet
709 /* XXXSMP hold in lwp_userret() */
710 KERNEL_UNLOCK_LAST(l);
711 #else
712 KERNEL_UNLOCK_ALL(l, NULL);
713 #endif
714
715 cpu_exit(l);
716 }
717
718 /*
719 * We are called from cpu_exit() once it is safe to schedule the dead LWP's
720 * resources to be freed (i.e., once we've switched to the idle PCB for the
721 * current CPU).
722 */
723 void
724 lwp_exit2(struct lwp *l)
725 {
726 /* XXXSMP re-enable preemption */
727 }
728
729 /*
730 * Free a dead LWP's remaining resources.
731 *
732 * XXXLWP limits.
733 */
734 void
735 lwp_free(struct lwp *l, int recycle, int last)
736 {
737 struct proc *p = l->l_proc;
738 ksiginfoq_t kq;
739
740 /*
741 * If this was not the last LWP in the process, then adjust
742 * counters and unlock.
743 */
744 if (!last) {
745 /*
746 * Add the LWP's run time to the process' base value.
747 * This needs to co-incide with coming off p_lwps.
748 */
749 timeradd(&l->l_rtime, &p->p_rtime, &p->p_rtime);
750 LIST_REMOVE(l, l_sibling);
751 p->p_nlwps--;
752 p->p_nzlwps--;
753 if ((l->l_prflag & LPR_DETACHED) != 0)
754 p->p_ndlwps--;
755 mutex_exit(&p->p_smutex);
756
757 #ifdef MULTIPROCESSOR
758 /*
759 * In the unlikely event that the LWP is still on the CPU,
760 * then spin until it has switched away. We need to release
761 * all locks to avoid deadlock against interrupt handlers on
762 * the target CPU.
763 */
764 if (l->l_cpu->ci_curlwp == l) {
765 int count;
766 KERNEL_UNLOCK_ALL(curlwp, &count);
767 while (l->l_cpu->ci_curlwp == l)
768 SPINLOCK_BACKOFF_HOOK;
769 KERNEL_LOCK(count, curlwp);
770 }
771 #endif
772 }
773
774 /*
775 * Destroy the LWP's remaining signal information.
776 */
777 ksiginfo_queue_init(&kq);
778 sigclear(&l->l_sigpend, NULL, &kq);
779 ksiginfo_queue_drain(&kq);
780 cv_destroy(&l->l_sigcv);
781 mutex_destroy(&l->l_swaplock);
782
783 /*
784 * Free the LWP's turnstile and the LWP structure itself unless the
785 * caller wants to recycle them.
786 *
787 * We can't return turnstile0 to the pool (it didn't come from it),
788 * so if it comes up just drop it quietly and move on.
789 *
790 * We don't recycle the VM resources at this time.
791 */
792 if (!recycle && l->l_ts != &turnstile0)
793 pool_cache_put(&turnstile_cache, l->l_ts);
794 #ifndef __NO_CPU_LWP_FREE
795 cpu_lwp_free2(l);
796 #endif
797 uvm_lwp_exit(l);
798 KASSERT(SLIST_EMPTY(&l->l_pi_lenders));
799 KASSERT(l->l_inheritedprio == MAXPRI);
800 if (!recycle)
801 pool_put(&lwp_pool, l);
802 }
803
804 /*
805 * Pick a LWP to represent the process for those operations which
806 * want information about a "process" that is actually associated
807 * with a LWP.
808 *
809 * If 'locking' is false, no locking or lock checks are performed.
810 * This is intended for use by DDB.
811 *
812 * We don't bother locking the LWP here, since code that uses this
813 * interface is broken by design and an exact match is not required.
814 */
815 struct lwp *
816 proc_representative_lwp(struct proc *p, int *nrlwps, int locking)
817 {
818 struct lwp *l, *onproc, *running, *sleeping, *stopped, *suspended;
819 struct lwp *signalled;
820 int cnt;
821
822 if (locking) {
823 KASSERT(mutex_owned(&p->p_smutex));
824 }
825
826 /* Trivial case: only one LWP */
827 if (p->p_nlwps == 1) {
828 l = LIST_FIRST(&p->p_lwps);
829 if (nrlwps)
830 *nrlwps = (l->l_stat == LSONPROC || LSRUN);
831 return l;
832 }
833
834 cnt = 0;
835 switch (p->p_stat) {
836 case SSTOP:
837 case SACTIVE:
838 /* Pick the most live LWP */
839 onproc = running = sleeping = stopped = suspended = NULL;
840 signalled = NULL;
841 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
842 if (l->l_lid == p->p_sigctx.ps_lwp)
843 signalled = l;
844 switch (l->l_stat) {
845 case LSONPROC:
846 onproc = l;
847 cnt++;
848 break;
849 case LSRUN:
850 running = l;
851 cnt++;
852 break;
853 case LSSLEEP:
854 sleeping = l;
855 break;
856 case LSSTOP:
857 stopped = l;
858 break;
859 case LSSUSPENDED:
860 suspended = l;
861 break;
862 }
863 }
864 if (nrlwps)
865 *nrlwps = cnt;
866 if (signalled)
867 l = signalled;
868 else if (onproc)
869 l = onproc;
870 else if (running)
871 l = running;
872 else if (sleeping)
873 l = sleeping;
874 else if (stopped)
875 l = stopped;
876 else if (suspended)
877 l = suspended;
878 else
879 break;
880 return l;
881 if (nrlwps)
882 *nrlwps = 0;
883 l = LIST_FIRST(&p->p_lwps);
884 return l;
885 #ifdef DIAGNOSTIC
886 case SIDL:
887 case SZOMB:
888 case SDYING:
889 case SDEAD:
890 if (locking)
891 mutex_exit(&p->p_smutex);
892 /* We have more than one LWP and we're in SIDL?
893 * How'd that happen?
894 */
895 panic("Too many LWPs in idle/dying process %d (%s) stat = %d",
896 p->p_pid, p->p_comm, p->p_stat);
897 break;
898 default:
899 if (locking)
900 mutex_exit(&p->p_smutex);
901 panic("Process %d (%s) in unknown state %d",
902 p->p_pid, p->p_comm, p->p_stat);
903 #endif
904 }
905
906 if (locking)
907 mutex_exit(&p->p_smutex);
908 panic("proc_representative_lwp: couldn't find a lwp for process"
909 " %d (%s)", p->p_pid, p->p_comm);
910 /* NOTREACHED */
911 return NULL;
912 }
913
914 /*
915 * Look up a live LWP within the speicifed process, and return it locked.
916 *
917 * Must be called with p->p_smutex held.
918 */
919 struct lwp *
920 lwp_find(struct proc *p, int id)
921 {
922 struct lwp *l;
923
924 KASSERT(mutex_owned(&p->p_smutex));
925
926 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
927 if (l->l_lid == id)
928 break;
929 }
930
931 /*
932 * No need to lock - all of these conditions will
933 * be visible with the process level mutex held.
934 */
935 if (l != NULL && (l->l_stat == LSIDL || l->l_stat == LSZOMB))
936 l = NULL;
937
938 return l;
939 }
940
941 /*
942 * Update an LWP's cached credentials to mirror the process' master copy.
943 *
944 * This happens early in the syscall path, on user trap, and on LWP
945 * creation. A long-running LWP can also voluntarily choose to update
946 * it's credentials by calling this routine. This may be called from
947 * LWP_CACHE_CREDS(), which checks l->l_cred != p->p_cred beforehand.
948 */
949 void
950 lwp_update_creds(struct lwp *l)
951 {
952 kauth_cred_t oc;
953 struct proc *p;
954
955 p = l->l_proc;
956 oc = l->l_cred;
957
958 mutex_enter(&p->p_mutex);
959 kauth_cred_hold(p->p_cred);
960 l->l_cred = p->p_cred;
961 mutex_exit(&p->p_mutex);
962 if (oc != NULL)
963 kauth_cred_free(oc);
964 }
965
966 /*
967 * Verify that an LWP is locked, and optionally verify that the lock matches
968 * one we specify.
969 */
970 int
971 lwp_locked(struct lwp *l, kmutex_t *mtx)
972 {
973 kmutex_t *cur = l->l_mutex;
974
975 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
976 return mutex_owned(cur) && (mtx == cur || mtx == NULL);
977 #else
978 return mutex_owned(cur);
979 #endif
980 }
981
982 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
983 /*
984 * Lock an LWP.
985 */
986 void
987 lwp_lock_retry(struct lwp *l, kmutex_t *old)
988 {
989
990 /*
991 * XXXgcc ignoring kmutex_t * volatile on i386
992 *
993 * gcc version 4.1.2 20061021 prerelease (NetBSD nb1 20061021)
994 */
995 #if 1
996 while (l->l_mutex != old) {
997 #else
998 for (;;) {
999 #endif
1000 mutex_spin_exit(old);
1001 old = l->l_mutex;
1002 mutex_spin_enter(old);
1003
1004 /*
1005 * mutex_enter() will have posted a read barrier. Re-test
1006 * l->l_mutex. If it has changed, we need to try again.
1007 */
1008 #if 1
1009 }
1010 #else
1011 } while (__predict_false(l->l_mutex != old));
1012 #endif
1013 }
1014 #endif
1015
1016 /*
1017 * Lend a new mutex to an LWP. The old mutex must be held.
1018 */
1019 void
1020 lwp_setlock(struct lwp *l, kmutex_t *new)
1021 {
1022
1023 KASSERT(mutex_owned(l->l_mutex));
1024
1025 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
1026 mb_write();
1027 l->l_mutex = new;
1028 #else
1029 (void)new;
1030 #endif
1031 }
1032
1033 /*
1034 * Lend a new mutex to an LWP, and release the old mutex. The old mutex
1035 * must be held.
1036 */
1037 void
1038 lwp_unlock_to(struct lwp *l, kmutex_t *new)
1039 {
1040 kmutex_t *old;
1041
1042 KASSERT(mutex_owned(l->l_mutex));
1043
1044 old = l->l_mutex;
1045 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
1046 mb_write();
1047 l->l_mutex = new;
1048 #else
1049 (void)new;
1050 #endif
1051 mutex_spin_exit(old);
1052 }
1053
1054 /*
1055 * Acquire a new mutex, and donate it to an LWP. The LWP must already be
1056 * locked.
1057 */
1058 void
1059 lwp_relock(struct lwp *l, kmutex_t *new)
1060 {
1061 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
1062 kmutex_t *old;
1063 #endif
1064
1065 KASSERT(mutex_owned(l->l_mutex));
1066
1067 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
1068 old = l->l_mutex;
1069 if (old != new) {
1070 mutex_spin_enter(new);
1071 l->l_mutex = new;
1072 mutex_spin_exit(old);
1073 }
1074 #else
1075 (void)new;
1076 #endif
1077 }
1078
1079 int
1080 lwp_trylock(struct lwp *l)
1081 {
1082 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
1083 kmutex_t *old;
1084
1085 for (;;) {
1086 if (!mutex_tryenter(old = l->l_mutex))
1087 return 0;
1088 if (__predict_true(l->l_mutex == old))
1089 return 1;
1090 mutex_spin_exit(old);
1091 }
1092 #else
1093 return mutex_tryenter(l->l_mutex);
1094 #endif
1095 }
1096
1097 /*
1098 * Handle exceptions for mi_userret(). Called if a member of LW_USERRET is
1099 * set.
1100 */
1101 void
1102 lwp_userret(struct lwp *l)
1103 {
1104 struct proc *p;
1105 void (*hook)(void);
1106 int sig;
1107
1108 p = l->l_proc;
1109
1110 /*
1111 * It should be safe to do this read unlocked on a multiprocessor
1112 * system..
1113 */
1114 while ((l->l_flag & LW_USERRET) != 0) {
1115 /*
1116 * Process pending signals first, unless the process
1117 * is dumping core or exiting, where we will instead
1118 * enter the L_WSUSPEND case below.
1119 */
1120 if ((l->l_flag & (LW_PENDSIG | LW_WCORE | LW_WEXIT)) ==
1121 LW_PENDSIG) {
1122 KERNEL_LOCK(1, l); /* XXXSMP pool_put() below */
1123 mutex_enter(&p->p_smutex);
1124 while ((sig = issignal(l)) != 0)
1125 postsig(sig);
1126 mutex_exit(&p->p_smutex);
1127 KERNEL_UNLOCK_LAST(l); /* XXXSMP */
1128 }
1129
1130 /*
1131 * Core-dump or suspend pending.
1132 *
1133 * In case of core dump, suspend ourselves, so that the
1134 * kernel stack and therefore the userland registers saved
1135 * in the trapframe are around for coredump() to write them
1136 * out. We issue a wakeup on p->p_lwpcv so that sigexit()
1137 * will write the core file out once all other LWPs are
1138 * suspended.
1139 */
1140 if ((l->l_flag & LW_WSUSPEND) != 0) {
1141 mutex_enter(&p->p_smutex);
1142 p->p_nrlwps--;
1143 cv_broadcast(&p->p_lwpcv);
1144 lwp_lock(l);
1145 l->l_stat = LSSUSPENDED;
1146 mutex_exit(&p->p_smutex);
1147 mi_switch(l, NULL);
1148 }
1149
1150 /* Process is exiting. */
1151 if ((l->l_flag & LW_WEXIT) != 0) {
1152 KERNEL_LOCK(1, l);
1153 lwp_exit(l);
1154 KASSERT(0);
1155 /* NOTREACHED */
1156 }
1157
1158 /* Call userret hook; used by Linux emulation. */
1159 if ((l->l_flag & LW_WUSERRET) != 0) {
1160 lwp_lock(l);
1161 l->l_flag &= ~LW_WUSERRET;
1162 lwp_unlock(l);
1163 hook = p->p_userret;
1164 p->p_userret = NULL;
1165 (*hook)();
1166 }
1167 }
1168 }
1169
1170 /*
1171 * Force an LWP to enter the kernel, to take a trip through lwp_userret().
1172 */
1173 void
1174 lwp_need_userret(struct lwp *l)
1175 {
1176 KASSERT(lwp_locked(l, NULL));
1177
1178 /*
1179 * Since the tests in lwp_userret() are done unlocked, make sure
1180 * that the condition will be seen before forcing the LWP to enter
1181 * kernel mode.
1182 */
1183 mb_write();
1184 cpu_signotify(l);
1185 }
1186
1187 /*
1188 * Add one reference to an LWP. This will prevent the LWP from
1189 * exiting, thus keep the lwp structure and PCB around to inspect.
1190 */
1191 void
1192 lwp_addref(struct lwp *l)
1193 {
1194
1195 KASSERT(mutex_owned(&l->l_proc->p_smutex));
1196 KASSERT(l->l_stat != LSZOMB);
1197 KASSERT(l->l_refcnt != 0);
1198
1199 l->l_refcnt++;
1200 }
1201
1202 /*
1203 * Remove one reference to an LWP. If this is the last reference,
1204 * then we must finalize the LWP's death.
1205 */
1206 void
1207 lwp_delref(struct lwp *l)
1208 {
1209 struct proc *p = l->l_proc;
1210
1211 mutex_enter(&p->p_smutex);
1212 if (--l->l_refcnt == 0)
1213 cv_broadcast(&p->p_refcv);
1214 mutex_exit(&p->p_smutex);
1215 }
1216
1217 /*
1218 * Drain all references to the current LWP.
1219 */
1220 void
1221 lwp_drainrefs(struct lwp *l)
1222 {
1223 struct proc *p = l->l_proc;
1224
1225 KASSERT(mutex_owned(&p->p_smutex));
1226 KASSERT(l->l_refcnt != 0);
1227
1228 l->l_refcnt--;
1229 while (l->l_refcnt != 0)
1230 cv_wait(&p->p_refcv, &p->p_smutex);
1231 }
1232
1233 /*
1234 * lwp_specific_key_create --
1235 * Create a key for subsystem lwp-specific data.
1236 */
1237 int
1238 lwp_specific_key_create(specificdata_key_t *keyp, specificdata_dtor_t dtor)
1239 {
1240
1241 return (specificdata_key_create(lwp_specificdata_domain, keyp, dtor));
1242 }
1243
1244 /*
1245 * lwp_specific_key_delete --
1246 * Delete a key for subsystem lwp-specific data.
1247 */
1248 void
1249 lwp_specific_key_delete(specificdata_key_t key)
1250 {
1251
1252 specificdata_key_delete(lwp_specificdata_domain, key);
1253 }
1254
1255 /*
1256 * lwp_initspecific --
1257 * Initialize an LWP's specificdata container.
1258 */
1259 void
1260 lwp_initspecific(struct lwp *l)
1261 {
1262 int error;
1263
1264 error = specificdata_init(lwp_specificdata_domain, &l->l_specdataref);
1265 KASSERT(error == 0);
1266 }
1267
1268 /*
1269 * lwp_finispecific --
1270 * Finalize an LWP's specificdata container.
1271 */
1272 void
1273 lwp_finispecific(struct lwp *l)
1274 {
1275
1276 specificdata_fini(lwp_specificdata_domain, &l->l_specdataref);
1277 }
1278
1279 /*
1280 * lwp_getspecific --
1281 * Return lwp-specific data corresponding to the specified key.
1282 *
1283 * Note: LWP specific data is NOT INTERLOCKED. An LWP should access
1284 * only its OWN SPECIFIC DATA. If it is necessary to access another
1285 * LWP's specifc data, care must be taken to ensure that doing so
1286 * would not cause internal data structure inconsistency (i.e. caller
1287 * can guarantee that the target LWP is not inside an lwp_getspecific()
1288 * or lwp_setspecific() call).
1289 */
1290 void *
1291 lwp_getspecific(specificdata_key_t key)
1292 {
1293
1294 return (specificdata_getspecific_unlocked(lwp_specificdata_domain,
1295 &curlwp->l_specdataref, key));
1296 }
1297
1298 void *
1299 _lwp_getspecific_by_lwp(struct lwp *l, specificdata_key_t key)
1300 {
1301
1302 return (specificdata_getspecific_unlocked(lwp_specificdata_domain,
1303 &l->l_specdataref, key));
1304 }
1305
1306 /*
1307 * lwp_setspecific --
1308 * Set lwp-specific data corresponding to the specified key.
1309 */
1310 void
1311 lwp_setspecific(specificdata_key_t key, void *data)
1312 {
1313
1314 specificdata_setspecific(lwp_specificdata_domain,
1315 &curlwp->l_specdataref, key, data);
1316 }
1317