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