kern_lwp.c revision 1.245 1 /* $NetBSD: kern_lwp.c,v 1.245 2021/12/21 19:00:37 thorpej Exp $ */
2
3 /*-
4 * Copyright (c) 2001, 2006, 2007, 2008, 2009, 2019, 2020
5 * The NetBSD Foundation, Inc.
6 * All rights reserved.
7 *
8 * This code is derived from software contributed to The NetBSD Foundation
9 * by Nathan J. Williams, and Andrew Doran.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33 /*
34 * Overview
35 *
36 * Lightweight processes (LWPs) are the basic unit or thread of
37 * execution within the kernel. The core state of an LWP is described
38 * by "struct lwp", also known as lwp_t.
39 *
40 * Each LWP is contained within a process (described by "struct proc"),
41 * Every process contains at least one LWP, but may contain more. The
42 * process describes attributes shared among all of its LWPs such as a
43 * private address space, global execution state (stopped, active,
44 * zombie, ...), signal disposition and so on. On a multiprocessor
45 * machine, multiple LWPs be executing concurrently in the kernel.
46 *
47 * Execution states
48 *
49 * At any given time, an LWP has overall state that is described by
50 * lwp::l_stat. The states are broken into two sets below. The first
51 * set is guaranteed to represent the absolute, current state of the
52 * LWP:
53 *
54 * LSONPROC
55 *
56 * On processor: the LWP is executing on a CPU, either in the
57 * kernel or in user space.
58 *
59 * LSRUN
60 *
61 * Runnable: the LWP is parked on a run queue, and may soon be
62 * chosen to run by an idle processor, or by a processor that
63 * has been asked to preempt a currently runnning but lower
64 * priority LWP.
65 *
66 * LSIDL
67 *
68 * Idle: the LWP has been created but has not yet executed, or
69 * it has ceased executing a unit of work and is waiting to be
70 * started again. This state exists so that the LWP can occupy
71 * a slot in the process & PID table, but without having to
72 * worry about being touched; lookups of the LWP by ID will
73 * fail while in this state. The LWP will become visible for
74 * lookup once its state transitions further. Some special
75 * kernel threads also (ab)use this state to indicate that they
76 * are idle (soft interrupts and idle LWPs).
77 *
78 * LSSUSPENDED:
79 *
80 * Suspended: the LWP has had its execution suspended by
81 * another LWP in the same process using the _lwp_suspend()
82 * system call. User-level LWPs also enter the suspended
83 * state when the system is shutting down.
84 *
85 * The second set represent a "statement of intent" on behalf of the
86 * LWP. The LWP may in fact be executing on a processor, may be
87 * sleeping or idle. It is expected to take the necessary action to
88 * stop executing or become "running" again within a short timeframe.
89 * The LP_RUNNING flag in lwp::l_pflag indicates that an LWP is running.
90 * Importantly, it indicates that its state is tied to a CPU.
91 *
92 * LSZOMB:
93 *
94 * Dead or dying: the LWP has released most of its resources
95 * and is about to switch away into oblivion, or has already
96 * switched away. When it switches away, its few remaining
97 * resources can be collected.
98 *
99 * LSSLEEP:
100 *
101 * Sleeping: the LWP has entered itself onto a sleep queue, and
102 * has switched away or will switch away shortly to allow other
103 * LWPs to run on the CPU.
104 *
105 * LSSTOP:
106 *
107 * Stopped: the LWP has been stopped as a result of a job
108 * control signal, or as a result of the ptrace() interface.
109 *
110 * Stopped LWPs may run briefly within the kernel to handle
111 * signals that they receive, but will not return to user space
112 * until their process' state is changed away from stopped.
113 *
114 * Single LWPs within a process can not be set stopped
115 * selectively: all actions that can stop or continue LWPs
116 * occur at the process level.
117 *
118 * State transitions
119 *
120 * Note that the LSSTOP state may only be set when returning to
121 * user space in userret(), or when sleeping interruptably. The
122 * LSSUSPENDED state may only be set in userret(). Before setting
123 * those states, we try to ensure that the LWPs will release all
124 * locks that they hold, and at a minimum try to ensure that the
125 * LWP can be set runnable again by a signal.
126 *
127 * LWPs may transition states in the following ways:
128 *
129 * RUN -------> ONPROC ONPROC -----> RUN
130 * > SLEEP
131 * > STOPPED
132 * > SUSPENDED
133 * > ZOMB
134 * > IDL (special cases)
135 *
136 * STOPPED ---> RUN SUSPENDED --> RUN
137 * > SLEEP
138 *
139 * SLEEP -----> ONPROC IDL --------> RUN
140 * > RUN > SUSPENDED
141 * > STOPPED > STOPPED
142 * > ONPROC (special cases)
143 *
144 * Some state transitions are only possible with kernel threads (eg
145 * ONPROC -> IDL) and happen under tightly controlled circumstances
146 * free of unwanted side effects.
147 *
148 * Migration
149 *
150 * Migration of threads from one CPU to another could be performed
151 * internally by the scheduler via sched_takecpu() or sched_catchlwp()
152 * functions. The universal lwp_migrate() function should be used for
153 * any other cases. Subsystems in the kernel must be aware that CPU
154 * of LWP may change, while it is not locked.
155 *
156 * Locking
157 *
158 * The majority of fields in 'struct lwp' are covered by a single,
159 * general spin lock pointed to by lwp::l_mutex. The locks covering
160 * each field are documented in sys/lwp.h.
161 *
162 * State transitions must be made with the LWP's general lock held,
163 * and may cause the LWP's lock pointer to change. Manipulation of
164 * the general lock is not performed directly, but through calls to
165 * lwp_lock(), lwp_unlock() and others. It should be noted that the
166 * adaptive locks are not allowed to be released while the LWP's lock
167 * is being held (unlike for other spin-locks).
168 *
169 * States and their associated locks:
170 *
171 * LSIDL, LSONPROC, LSZOMB, LSSUPENDED:
172 *
173 * Always covered by spc_lwplock, which protects LWPs not
174 * associated with any other sync object. This is a per-CPU
175 * lock and matches lwp::l_cpu.
176 *
177 * LSRUN:
178 *
179 * Always covered by spc_mutex, which protects the run queues.
180 * This is a per-CPU lock and matches lwp::l_cpu.
181 *
182 * LSSLEEP:
183 *
184 * Covered by a lock associated with the sleep queue (sometimes
185 * a turnstile sleep queue) that the LWP resides on. This can
186 * be spc_lwplock for SOBJ_SLEEPQ_NULL (an "untracked" sleep).
187 *
188 * LSSTOP:
189 *
190 * If the LWP was previously sleeping (l_wchan != NULL), then
191 * l_mutex references the sleep queue lock. If the LWP was
192 * runnable or on the CPU when halted, or has been removed from
193 * the sleep queue since halted, then the lock is spc_lwplock.
194 *
195 * The lock order is as follows:
196 *
197 * sleepq -> turnstile -> spc_lwplock -> spc_mutex
198 *
199 * Each process has a scheduler state lock (proc::p_lock), and a
200 * number of counters on LWPs and their states: p_nzlwps, p_nrlwps, and
201 * so on. When an LWP is to be entered into or removed from one of the
202 * following states, p_lock must be held and the process wide counters
203 * adjusted:
204 *
205 * LSIDL, LSZOMB, LSSTOP, LSSUSPENDED
206 *
207 * (But not always for kernel threads. There are some special cases
208 * as mentioned above: soft interrupts, and the idle loops.)
209 *
210 * Note that an LWP is considered running or likely to run soon if in
211 * one of the following states. This affects the value of p_nrlwps:
212 *
213 * LSRUN, LSONPROC, LSSLEEP
214 *
215 * p_lock does not need to be held when transitioning among these
216 * three states, hence p_lock is rarely taken for state transitions.
217 */
218
219 #include <sys/cdefs.h>
220 __KERNEL_RCSID(0, "$NetBSD: kern_lwp.c,v 1.245 2021/12/21 19:00:37 thorpej Exp $");
221
222 #include "opt_ddb.h"
223 #include "opt_lockdebug.h"
224 #include "opt_dtrace.h"
225
226 #define _LWP_API_PRIVATE
227
228 #include <sys/param.h>
229 #include <sys/systm.h>
230 #include <sys/cpu.h>
231 #include <sys/pool.h>
232 #include <sys/proc.h>
233 #include <sys/syscallargs.h>
234 #include <sys/syscall_stats.h>
235 #include <sys/kauth.h>
236 #include <sys/sleepq.h>
237 #include <sys/lockdebug.h>
238 #include <sys/kmem.h>
239 #include <sys/pset.h>
240 #include <sys/intr.h>
241 #include <sys/lwpctl.h>
242 #include <sys/atomic.h>
243 #include <sys/filedesc.h>
244 #include <sys/fstrans.h>
245 #include <sys/dtrace_bsd.h>
246 #include <sys/sdt.h>
247 #include <sys/ptrace.h>
248 #include <sys/xcall.h>
249 #include <sys/uidinfo.h>
250 #include <sys/sysctl.h>
251 #include <sys/psref.h>
252 #include <sys/msan.h>
253 #include <sys/kcov.h>
254 #include <sys/cprng.h>
255 #include <sys/futex.h>
256
257 #include <uvm/uvm_extern.h>
258 #include <uvm/uvm_object.h>
259
260 static pool_cache_t lwp_cache __read_mostly;
261 struct lwplist alllwp __cacheline_aligned;
262
263 static int lwp_ctor(void *, void *, int);
264 static void lwp_dtor(void *, void *);
265 static void lwp_pre_dtor(void *);
266
267 /* DTrace proc provider probes */
268 SDT_PROVIDER_DEFINE(proc);
269
270 SDT_PROBE_DEFINE1(proc, kernel, , lwp__create, "struct lwp *");
271 SDT_PROBE_DEFINE1(proc, kernel, , lwp__start, "struct lwp *");
272 SDT_PROBE_DEFINE1(proc, kernel, , lwp__exit, "struct lwp *");
273
274 struct turnstile turnstile0 __cacheline_aligned;
275 struct lwp lwp0 __aligned(MIN_LWP_ALIGNMENT) = {
276 #ifdef LWP0_CPU_INFO
277 .l_cpu = LWP0_CPU_INFO,
278 #endif
279 #ifdef LWP0_MD_INITIALIZER
280 .l_md = LWP0_MD_INITIALIZER,
281 #endif
282 .l_proc = &proc0,
283 .l_lid = 0, /* we own proc0's slot in the pid table */
284 .l_flag = LW_SYSTEM,
285 .l_stat = LSONPROC,
286 .l_ts = &turnstile0,
287 .l_syncobj = &sched_syncobj,
288 .l_refcnt = 0,
289 .l_priority = PRI_USER + NPRI_USER - 1,
290 .l_inheritedprio = -1,
291 .l_class = SCHED_OTHER,
292 .l_psid = PS_NONE,
293 .l_pi_lenders = SLIST_HEAD_INITIALIZER(&lwp0.l_pi_lenders),
294 .l_name = __UNCONST("swapper"),
295 .l_fd = &filedesc0,
296 };
297
298 static int sysctl_kern_maxlwp(SYSCTLFN_PROTO);
299
300 /*
301 * sysctl helper routine for kern.maxlwp. Ensures that the new
302 * values are not too low or too high.
303 */
304 static int
305 sysctl_kern_maxlwp(SYSCTLFN_ARGS)
306 {
307 int error, nmaxlwp;
308 struct sysctlnode node;
309
310 nmaxlwp = maxlwp;
311 node = *rnode;
312 node.sysctl_data = &nmaxlwp;
313 error = sysctl_lookup(SYSCTLFN_CALL(&node));
314 if (error || newp == NULL)
315 return error;
316
317 if (nmaxlwp < 0 || nmaxlwp >= 65536)
318 return EINVAL;
319 if (nmaxlwp > cpu_maxlwp())
320 return EINVAL;
321 maxlwp = nmaxlwp;
322
323 return 0;
324 }
325
326 static void
327 sysctl_kern_lwp_setup(void)
328 {
329 sysctl_createv(NULL, 0, NULL, NULL,
330 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
331 CTLTYPE_INT, "maxlwp",
332 SYSCTL_DESCR("Maximum number of simultaneous threads"),
333 sysctl_kern_maxlwp, 0, NULL, 0,
334 CTL_KERN, CTL_CREATE, CTL_EOL);
335 }
336
337 void
338 lwpinit(void)
339 {
340
341 LIST_INIT(&alllwp);
342 lwpinit_specificdata();
343 lwp_cache = pool_cache_init(sizeof(lwp_t), MIN_LWP_ALIGNMENT, 0, 0,
344 "lwppl", NULL, IPL_NONE, lwp_ctor, lwp_dtor, NULL);
345 pool_cache_setpredestruct(lwp_cache, lwp_pre_dtor);
346
347 maxlwp = cpu_maxlwp();
348 sysctl_kern_lwp_setup();
349 }
350
351 void
352 lwp0_init(void)
353 {
354 struct lwp *l = &lwp0;
355
356 KASSERT((void *)uvm_lwp_getuarea(l) != NULL);
357
358 LIST_INSERT_HEAD(&alllwp, l, l_list);
359
360 callout_init(&l->l_timeout_ch, CALLOUT_MPSAFE);
361 callout_setfunc(&l->l_timeout_ch, sleepq_timeout, l);
362 cv_init(&l->l_sigcv, "sigwait");
363 cv_init(&l->l_waitcv, "vfork");
364
365 kauth_cred_hold(proc0.p_cred);
366 l->l_cred = proc0.p_cred;
367
368 kdtrace_thread_ctor(NULL, l);
369 lwp_initspecific(l);
370
371 SYSCALL_TIME_LWP_INIT(l);
372 }
373
374 /*
375 * Initialize the non-zeroed portion of an lwp_t.
376 */
377 static int
378 lwp_ctor(void *arg, void *obj, int flags)
379 {
380 lwp_t *l = obj;
381
382 l->l_stat = LSIDL;
383 l->l_cpu = curcpu();
384 l->l_mutex = l->l_cpu->ci_schedstate.spc_lwplock;
385 l->l_ts = pool_get(&turnstile_pool, flags);
386
387 if (l->l_ts == NULL) {
388 return ENOMEM;
389 } else {
390 turnstile_ctor(l->l_ts);
391 return 0;
392 }
393 }
394
395 static void
396 lwp_pre_dtor(void *arg __unused)
397 {
398 /*
399 * Provide a barrier to ensure that all mutex_oncpu() and rw_oncpu()
400 * calls will exit before memory of LWPs is returned to the pool, where
401 * KVA of LWP structure might be freed and re-used for other purposes.
402 * Kernel preemption is disabled around mutex_oncpu() and rw_oncpu()
403 * callers, therefore cross-call to all CPUs will do the job.
404 *
405 * XXX should use epoch based reclamation.
406 */
407 xc_barrier(0);
408 }
409
410 static void
411 lwp_dtor(void *arg, void *obj)
412 {
413 lwp_t *l = obj;
414
415 /*
416 * The value of l->l_cpu must still be valid at this point.
417 */
418 KASSERT(l->l_cpu != NULL);
419
420 /*
421 * We can't return turnstile0 to the pool (it didn't come from it),
422 * so if it comes up just drop it quietly and move on.
423 */
424 if (l->l_ts != &turnstile0)
425 pool_put(&turnstile_pool, l->l_ts);
426 }
427
428 /*
429 * Set an LWP suspended.
430 *
431 * Must be called with p_lock held, and the LWP locked. Will unlock the
432 * LWP before return.
433 */
434 int
435 lwp_suspend(struct lwp *curl, struct lwp *t)
436 {
437 int error;
438
439 KASSERT(mutex_owned(t->l_proc->p_lock));
440 KASSERT(lwp_locked(t, NULL));
441
442 KASSERT(curl != t || curl->l_stat == LSONPROC);
443
444 /*
445 * If the current LWP has been told to exit, we must not suspend anyone
446 * else or deadlock could occur. We won't return to userspace.
447 */
448 if ((curl->l_flag & (LW_WEXIT | LW_WCORE)) != 0) {
449 lwp_unlock(t);
450 return (EDEADLK);
451 }
452
453 if ((t->l_flag & LW_DBGSUSPEND) != 0) {
454 lwp_unlock(t);
455 return 0;
456 }
457
458 error = 0;
459
460 switch (t->l_stat) {
461 case LSRUN:
462 case LSONPROC:
463 t->l_flag |= LW_WSUSPEND;
464 lwp_need_userret(t);
465 lwp_unlock(t);
466 break;
467
468 case LSSLEEP:
469 t->l_flag |= LW_WSUSPEND;
470
471 /*
472 * Kick the LWP and try to get it to the kernel boundary
473 * so that it will release any locks that it holds.
474 * setrunnable() will release the lock.
475 */
476 if ((t->l_flag & LW_SINTR) != 0)
477 setrunnable(t);
478 else
479 lwp_unlock(t);
480 break;
481
482 case LSSUSPENDED:
483 lwp_unlock(t);
484 break;
485
486 case LSSTOP:
487 t->l_flag |= LW_WSUSPEND;
488 setrunnable(t);
489 break;
490
491 case LSIDL:
492 case LSZOMB:
493 error = EINTR; /* It's what Solaris does..... */
494 lwp_unlock(t);
495 break;
496 }
497
498 return (error);
499 }
500
501 /*
502 * Restart a suspended LWP.
503 *
504 * Must be called with p_lock held, and the LWP locked. Will unlock the
505 * LWP before return.
506 */
507 void
508 lwp_continue(struct lwp *l)
509 {
510
511 KASSERT(mutex_owned(l->l_proc->p_lock));
512 KASSERT(lwp_locked(l, NULL));
513
514 /* If rebooting or not suspended, then just bail out. */
515 if ((l->l_flag & LW_WREBOOT) != 0) {
516 lwp_unlock(l);
517 return;
518 }
519
520 l->l_flag &= ~LW_WSUSPEND;
521
522 if (l->l_stat != LSSUSPENDED || (l->l_flag & LW_DBGSUSPEND) != 0) {
523 lwp_unlock(l);
524 return;
525 }
526
527 /* setrunnable() will release the lock. */
528 setrunnable(l);
529 }
530
531 /*
532 * Restart a stopped LWP.
533 *
534 * Must be called with p_lock held, and the LWP NOT locked. Will unlock the
535 * LWP before return.
536 */
537 void
538 lwp_unstop(struct lwp *l)
539 {
540 struct proc *p = l->l_proc;
541
542 KASSERT(mutex_owned(&proc_lock));
543 KASSERT(mutex_owned(p->p_lock));
544
545 lwp_lock(l);
546
547 KASSERT((l->l_flag & LW_DBGSUSPEND) == 0);
548
549 /* If not stopped, then just bail out. */
550 if (l->l_stat != LSSTOP) {
551 lwp_unlock(l);
552 return;
553 }
554
555 p->p_stat = SACTIVE;
556 p->p_sflag &= ~PS_STOPPING;
557
558 if (!p->p_waited)
559 p->p_pptr->p_nstopchild--;
560
561 if (l->l_wchan == NULL) {
562 /* setrunnable() will release the lock. */
563 setrunnable(l);
564 } else if (p->p_xsig && (l->l_flag & LW_SINTR) != 0) {
565 /* setrunnable() so we can receive the signal */
566 setrunnable(l);
567 } else {
568 l->l_stat = LSSLEEP;
569 p->p_nrlwps++;
570 lwp_unlock(l);
571 }
572 }
573
574 /*
575 * Wait for an LWP within the current process to exit. If 'lid' is
576 * non-zero, we are waiting for a specific LWP.
577 *
578 * Must be called with p->p_lock held.
579 */
580 int
581 lwp_wait(struct lwp *l, lwpid_t lid, lwpid_t *departed, bool exiting)
582 {
583 const lwpid_t curlid = l->l_lid;
584 proc_t *p = l->l_proc;
585 lwp_t *l2, *next;
586 int error;
587
588 KASSERT(mutex_owned(p->p_lock));
589
590 p->p_nlwpwait++;
591 l->l_waitingfor = lid;
592
593 for (;;) {
594 int nfound;
595
596 /*
597 * Avoid a race between exit1() and sigexit(): if the
598 * process is dumping core, then we need to bail out: call
599 * into lwp_userret() where we will be suspended until the
600 * deed is done.
601 */
602 if ((p->p_sflag & PS_WCORE) != 0) {
603 mutex_exit(p->p_lock);
604 lwp_userret(l);
605 KASSERT(false);
606 }
607
608 /*
609 * First off, drain any detached LWP that is waiting to be
610 * reaped.
611 */
612 while ((l2 = p->p_zomblwp) != NULL) {
613 p->p_zomblwp = NULL;
614 lwp_free(l2, false, false);/* releases proc mutex */
615 mutex_enter(p->p_lock);
616 }
617
618 /*
619 * Now look for an LWP to collect. If the whole process is
620 * exiting, count detached LWPs as eligible to be collected,
621 * but don't drain them here.
622 */
623 nfound = 0;
624 error = 0;
625
626 /*
627 * If given a specific LID, go via pid_table and make sure
628 * it's not detached.
629 */
630 if (lid != 0) {
631 l2 = proc_find_lwp(p, lid);
632 if (l2 == NULL) {
633 error = ESRCH;
634 break;
635 }
636 KASSERT(l2->l_lid == lid);
637 if ((l2->l_prflag & LPR_DETACHED) != 0) {
638 error = EINVAL;
639 break;
640 }
641 } else {
642 l2 = LIST_FIRST(&p->p_lwps);
643 }
644 for (; l2 != NULL; l2 = next) {
645 next = (lid != 0 ? NULL : LIST_NEXT(l2, l_sibling));
646
647 /*
648 * If a specific wait and the target is waiting on
649 * us, then avoid deadlock. This also traps LWPs
650 * that try to wait on themselves.
651 *
652 * Note that this does not handle more complicated
653 * cycles, like: t1 -> t2 -> t3 -> t1. The process
654 * can still be killed so it is not a major problem.
655 */
656 if (l2->l_lid == lid && l2->l_waitingfor == curlid) {
657 error = EDEADLK;
658 break;
659 }
660 if (l2 == l)
661 continue;
662 if ((l2->l_prflag & LPR_DETACHED) != 0) {
663 nfound += exiting;
664 continue;
665 }
666 if (lid != 0) {
667 /*
668 * Mark this LWP as the first waiter, if there
669 * is no other.
670 */
671 if (l2->l_waiter == 0)
672 l2->l_waiter = curlid;
673 } else if (l2->l_waiter != 0) {
674 /*
675 * It already has a waiter - so don't
676 * collect it. If the waiter doesn't
677 * grab it we'll get another chance
678 * later.
679 */
680 nfound++;
681 continue;
682 }
683 nfound++;
684
685 /* No need to lock the LWP in order to see LSZOMB. */
686 if (l2->l_stat != LSZOMB)
687 continue;
688
689 /*
690 * We're no longer waiting. Reset the "first waiter"
691 * pointer on the target, in case it was us.
692 */
693 l->l_waitingfor = 0;
694 l2->l_waiter = 0;
695 p->p_nlwpwait--;
696 if (departed)
697 *departed = l2->l_lid;
698 sched_lwp_collect(l2);
699
700 /* lwp_free() releases the proc lock. */
701 lwp_free(l2, false, false);
702 mutex_enter(p->p_lock);
703 return 0;
704 }
705
706 if (error != 0)
707 break;
708 if (nfound == 0) {
709 error = ESRCH;
710 break;
711 }
712
713 /*
714 * Note: since the lock will be dropped, need to restart on
715 * wakeup to run all LWPs again, e.g. there may be new LWPs.
716 */
717 if (exiting) {
718 KASSERT(p->p_nlwps > 1);
719 error = cv_timedwait(&p->p_lwpcv, p->p_lock, 1);
720 break;
721 }
722
723 /*
724 * Break out if all LWPs are in _lwp_wait(). There are
725 * other ways to hang the process with _lwp_wait(), but the
726 * sleep is interruptable so little point checking for them.
727 */
728 if (p->p_nlwpwait == p->p_nlwps) {
729 error = EDEADLK;
730 break;
731 }
732
733 /*
734 * Sit around and wait for something to happen. We'll be
735 * awoken if any of the conditions examined change: if an
736 * LWP exits, is collected, or is detached.
737 */
738 if ((error = cv_wait_sig(&p->p_lwpcv, p->p_lock)) != 0)
739 break;
740 }
741
742 /*
743 * We didn't find any LWPs to collect, we may have received a
744 * signal, or some other condition has caused us to bail out.
745 *
746 * If waiting on a specific LWP, clear the waiters marker: some
747 * other LWP may want it. Then, kick all the remaining waiters
748 * so that they can re-check for zombies and for deadlock.
749 */
750 if (lid != 0) {
751 l2 = proc_find_lwp(p, lid);
752 KASSERT(l2 == NULL || l2->l_lid == lid);
753
754 if (l2 != NULL && l2->l_waiter == curlid)
755 l2->l_waiter = 0;
756 }
757 p->p_nlwpwait--;
758 l->l_waitingfor = 0;
759 cv_broadcast(&p->p_lwpcv);
760
761 return error;
762 }
763
764 /*
765 * Create a new LWP within process 'p2', using LWP 'l1' as a template.
766 * The new LWP is created in state LSIDL and must be set running,
767 * suspended, or stopped by the caller.
768 */
769 int
770 lwp_create(lwp_t *l1, proc_t *p2, vaddr_t uaddr, int flags,
771 void *stack, size_t stacksize, void (*func)(void *), void *arg,
772 lwp_t **rnewlwpp, int sclass, const sigset_t *sigmask,
773 const stack_t *sigstk)
774 {
775 struct lwp *l2;
776
777 KASSERT(l1 == curlwp || l1->l_proc == &proc0);
778
779 /*
780 * Enforce limits, excluding the first lwp and kthreads. We must
781 * use the process credentials here when adjusting the limit, as
782 * they are what's tied to the accounting entity. However for
783 * authorizing the action, we'll use the LWP's credentials.
784 */
785 mutex_enter(p2->p_lock);
786 if (p2->p_nlwps != 0 && p2 != &proc0) {
787 uid_t uid = kauth_cred_getuid(p2->p_cred);
788 int count = chglwpcnt(uid, 1);
789 if (__predict_false(count >
790 p2->p_rlimit[RLIMIT_NTHR].rlim_cur)) {
791 if (kauth_authorize_process(l1->l_cred,
792 KAUTH_PROCESS_RLIMIT, p2,
793 KAUTH_ARG(KAUTH_REQ_PROCESS_RLIMIT_BYPASS),
794 &p2->p_rlimit[RLIMIT_NTHR], KAUTH_ARG(RLIMIT_NTHR))
795 != 0) {
796 (void)chglwpcnt(uid, -1);
797 mutex_exit(p2->p_lock);
798 return EAGAIN;
799 }
800 }
801 }
802
803 /*
804 * First off, reap any detached LWP waiting to be collected.
805 * We can re-use its LWP structure and turnstile.
806 */
807 if ((l2 = p2->p_zomblwp) != NULL) {
808 p2->p_zomblwp = NULL;
809 lwp_free(l2, true, false);
810 /* p2 now unlocked by lwp_free() */
811 KASSERT(l2->l_ts != NULL);
812 KASSERT(l2->l_inheritedprio == -1);
813 KASSERT(SLIST_EMPTY(&l2->l_pi_lenders));
814 memset(&l2->l_startzero, 0, sizeof(*l2) -
815 offsetof(lwp_t, l_startzero));
816 } else {
817 mutex_exit(p2->p_lock);
818 l2 = pool_cache_get(lwp_cache, PR_WAITOK);
819 memset(&l2->l_startzero, 0, sizeof(*l2) -
820 offsetof(lwp_t, l_startzero));
821 SLIST_INIT(&l2->l_pi_lenders);
822 }
823
824 /*
825 * Because of lockless lookup via pid_table, the LWP can be locked
826 * and inspected briefly even after it's freed, so a few fields are
827 * kept stable.
828 */
829 KASSERT(l2->l_stat == LSIDL);
830 KASSERT(l2->l_cpu != NULL);
831 KASSERT(l2->l_ts != NULL);
832 KASSERT(l2->l_mutex == l2->l_cpu->ci_schedstate.spc_lwplock);
833
834 l2->l_proc = p2;
835 l2->l_refcnt = 0;
836 l2->l_class = sclass;
837
838 /*
839 * Allocate a process ID for this LWP. We need to do this now
840 * while we can still unwind if it fails. Beacuse we're marked
841 * as LSIDL, no lookups by the ID will succeed.
842 *
843 * N.B. this will always succeed for the first LWP in a process,
844 * because proc_alloc_lwpid() will usurp the slot. Also note
845 * that l2->l_proc MUST be valid so that lookups of the proc
846 * will succeed, even if the LWP itself is not visible.
847 */
848 if (__predict_false(proc_alloc_lwpid(p2, l2) == -1)) {
849 pool_cache_put(lwp_cache, l2);
850 return EAGAIN;
851 }
852
853 /*
854 * If vfork(), we want the LWP to run fast and on the same CPU
855 * as its parent, so that it can reuse the VM context and cache
856 * footprint on the local CPU.
857 */
858 l2->l_kpriority = ((flags & LWP_VFORK) ? true : false);
859 l2->l_kpribase = PRI_KERNEL;
860 l2->l_priority = l1->l_priority;
861 l2->l_inheritedprio = -1;
862 l2->l_protectprio = -1;
863 l2->l_auxprio = -1;
864 l2->l_flag = 0;
865 l2->l_pflag = LP_MPSAFE;
866 TAILQ_INIT(&l2->l_ld_locks);
867 l2->l_psrefs = 0;
868 kmsan_lwp_alloc(l2);
869
870 /*
871 * For vfork, borrow parent's lwpctl context if it exists.
872 * This also causes us to return via lwp_userret.
873 */
874 if (flags & LWP_VFORK && l1->l_lwpctl) {
875 l2->l_lwpctl = l1->l_lwpctl;
876 l2->l_flag |= LW_LWPCTL;
877 }
878
879 /*
880 * If not the first LWP in the process, grab a reference to the
881 * descriptor table.
882 */
883 l2->l_fd = p2->p_fd;
884 if (p2->p_nlwps != 0) {
885 KASSERT(l1->l_proc == p2);
886 fd_hold(l2);
887 } else {
888 KASSERT(l1->l_proc != p2);
889 }
890
891 if (p2->p_flag & PK_SYSTEM) {
892 /* Mark it as a system LWP. */
893 l2->l_flag |= LW_SYSTEM;
894 }
895
896 kdtrace_thread_ctor(NULL, l2);
897 lwp_initspecific(l2);
898 sched_lwp_fork(l1, l2);
899 lwp_update_creds(l2);
900 callout_init(&l2->l_timeout_ch, CALLOUT_MPSAFE);
901 callout_setfunc(&l2->l_timeout_ch, sleepq_timeout, l2);
902 cv_init(&l2->l_sigcv, "sigwait");
903 cv_init(&l2->l_waitcv, "vfork");
904 l2->l_syncobj = &sched_syncobj;
905 PSREF_DEBUG_INIT_LWP(l2);
906
907 if (rnewlwpp != NULL)
908 *rnewlwpp = l2;
909
910 /*
911 * PCU state needs to be saved before calling uvm_lwp_fork() so that
912 * the MD cpu_lwp_fork() can copy the saved state to the new LWP.
913 */
914 pcu_save_all(l1);
915 #if PCU_UNIT_COUNT > 0
916 l2->l_pcu_valid = l1->l_pcu_valid;
917 #endif
918
919 uvm_lwp_setuarea(l2, uaddr);
920 uvm_lwp_fork(l1, l2, stack, stacksize, func, (arg != NULL) ? arg : l2);
921
922 mutex_enter(p2->p_lock);
923 if ((flags & LWP_DETACHED) != 0) {
924 l2->l_prflag = LPR_DETACHED;
925 p2->p_ndlwps++;
926 } else
927 l2->l_prflag = 0;
928
929 if (l1->l_proc == p2) {
930 /*
931 * These flags are set while p_lock is held. Copy with
932 * p_lock held too, so the LWP doesn't sneak into the
933 * process without them being set.
934 */
935 l2->l_flag |= (l1->l_flag & (LW_WEXIT | LW_WREBOOT | LW_WCORE));
936 } else {
937 /* fork(): pending core/exit doesn't apply to child. */
938 l2->l_flag |= (l1->l_flag & LW_WREBOOT);
939 }
940
941 l2->l_sigstk = *sigstk;
942 l2->l_sigmask = *sigmask;
943 TAILQ_INIT(&l2->l_sigpend.sp_info);
944 sigemptyset(&l2->l_sigpend.sp_set);
945 LIST_INSERT_HEAD(&p2->p_lwps, l2, l_sibling);
946 p2->p_nlwps++;
947 p2->p_nrlwps++;
948
949 KASSERT(l2->l_affinity == NULL);
950
951 /* Inherit the affinity mask. */
952 if (l1->l_affinity) {
953 /*
954 * Note that we hold the state lock while inheriting
955 * the affinity to avoid race with sched_setaffinity().
956 */
957 lwp_lock(l1);
958 if (l1->l_affinity) {
959 kcpuset_use(l1->l_affinity);
960 l2->l_affinity = l1->l_affinity;
961 }
962 lwp_unlock(l1);
963 }
964
965 /* This marks the end of the "must be atomic" section. */
966 mutex_exit(p2->p_lock);
967
968 SDT_PROBE(proc, kernel, , lwp__create, l2, 0, 0, 0, 0);
969
970 mutex_enter(&proc_lock);
971 LIST_INSERT_HEAD(&alllwp, l2, l_list);
972 /* Inherit a processor-set */
973 l2->l_psid = l1->l_psid;
974 mutex_exit(&proc_lock);
975
976 SYSCALL_TIME_LWP_INIT(l2);
977
978 if (p2->p_emul->e_lwp_fork)
979 (*p2->p_emul->e_lwp_fork)(l1, l2);
980
981 return (0);
982 }
983
984 /*
985 * Set a new LWP running. If the process is stopping, then the LWP is
986 * created stopped.
987 */
988 void
989 lwp_start(lwp_t *l, int flags)
990 {
991 proc_t *p = l->l_proc;
992
993 mutex_enter(p->p_lock);
994 lwp_lock(l);
995 KASSERT(l->l_stat == LSIDL);
996 if ((flags & LWP_SUSPENDED) != 0) {
997 /* It'll suspend itself in lwp_userret(). */
998 l->l_flag |= LW_WSUSPEND;
999 }
1000 if (p->p_stat == SSTOP || (p->p_sflag & PS_STOPPING) != 0) {
1001 KASSERT(l->l_wchan == NULL);
1002 l->l_stat = LSSTOP;
1003 p->p_nrlwps--;
1004 lwp_unlock(l);
1005 } else {
1006 setrunnable(l);
1007 /* LWP now unlocked */
1008 }
1009 mutex_exit(p->p_lock);
1010 }
1011
1012 /*
1013 * Called by MD code when a new LWP begins execution. Must be called
1014 * with the previous LWP locked (so at splsched), or if there is no
1015 * previous LWP, at splsched.
1016 */
1017 void
1018 lwp_startup(struct lwp *prev, struct lwp *new_lwp)
1019 {
1020 kmutex_t *lock;
1021
1022 KASSERTMSG(new_lwp == curlwp, "l %p curlwp %p prevlwp %p", new_lwp, curlwp, prev);
1023 KASSERT(kpreempt_disabled());
1024 KASSERT(prev != NULL);
1025 KASSERT((prev->l_pflag & LP_RUNNING) != 0);
1026 KASSERT(curcpu()->ci_mtx_count == -2);
1027
1028 /*
1029 * Immediately mark the previous LWP as no longer running and unlock
1030 * (to keep lock wait times short as possible). If a zombie, don't
1031 * touch after clearing LP_RUNNING as it could be reaped by another
1032 * CPU. Issue a memory barrier to ensure this.
1033 */
1034 lock = prev->l_mutex;
1035 if (__predict_false(prev->l_stat == LSZOMB)) {
1036 membar_sync();
1037 }
1038 prev->l_pflag &= ~LP_RUNNING;
1039 mutex_spin_exit(lock);
1040
1041 /* Correct spin mutex count after mi_switch(). */
1042 curcpu()->ci_mtx_count = 0;
1043
1044 /* Install new VM context. */
1045 if (__predict_true(new_lwp->l_proc->p_vmspace)) {
1046 pmap_activate(new_lwp);
1047 }
1048
1049 /* We remain at IPL_SCHED from mi_switch() - reset it. */
1050 spl0();
1051
1052 LOCKDEBUG_BARRIER(NULL, 0);
1053 SDT_PROBE(proc, kernel, , lwp__start, new_lwp, 0, 0, 0, 0);
1054
1055 /* For kthreads, acquire kernel lock if not MPSAFE. */
1056 if (__predict_false((new_lwp->l_pflag & LP_MPSAFE) == 0)) {
1057 KERNEL_LOCK(1, new_lwp);
1058 }
1059 }
1060
1061 /*
1062 * Exit an LWP.
1063 *
1064 * *** WARNING *** This can be called with (l != curlwp) in error paths.
1065 */
1066 void
1067 lwp_exit(struct lwp *l)
1068 {
1069 struct proc *p = l->l_proc;
1070 struct lwp *l2;
1071 bool current;
1072
1073 current = (l == curlwp);
1074
1075 KASSERT(current || (l->l_stat == LSIDL && l->l_target_cpu == NULL));
1076 KASSERT(p == curproc);
1077
1078 SDT_PROBE(proc, kernel, , lwp__exit, l, 0, 0, 0, 0);
1079
1080 /* Verify that we hold no locks; for DIAGNOSTIC check kernel_lock. */
1081 LOCKDEBUG_BARRIER(NULL, 0);
1082 KASSERTMSG(curcpu()->ci_biglock_count == 0, "kernel_lock leaked");
1083
1084 /*
1085 * If we are the last live LWP in a process, we need to exit the
1086 * entire process. We do so with an exit status of zero, because
1087 * it's a "controlled" exit, and because that's what Solaris does.
1088 *
1089 * We are not quite a zombie yet, but for accounting purposes we
1090 * must increment the count of zombies here.
1091 *
1092 * Note: the last LWP's specificdata will be deleted here.
1093 */
1094 mutex_enter(p->p_lock);
1095 if (p->p_nlwps - p->p_nzlwps == 1) {
1096 KASSERT(current == true);
1097 KASSERT(p != &proc0);
1098 exit1(l, 0, 0);
1099 /* NOTREACHED */
1100 }
1101 p->p_nzlwps++;
1102
1103 /*
1104 * Perform any required thread cleanup. Do this early so
1105 * anyone wanting to look us up with lwp_getref_lwpid() will
1106 * fail to find us before we become a zombie.
1107 *
1108 * N.B. this will unlock p->p_lock on our behalf.
1109 */
1110 lwp_thread_cleanup(l);
1111
1112 if (p->p_emul->e_lwp_exit)
1113 (*p->p_emul->e_lwp_exit)(l);
1114
1115 /* Drop filedesc reference. */
1116 fd_free();
1117
1118 /* Release fstrans private data. */
1119 fstrans_lwp_dtor(l);
1120
1121 /* Delete the specificdata while it's still safe to sleep. */
1122 lwp_finispecific(l);
1123
1124 /*
1125 * Release our cached credentials.
1126 */
1127 kauth_cred_free(l->l_cred);
1128 callout_destroy(&l->l_timeout_ch);
1129
1130 /*
1131 * If traced, report LWP exit event to the debugger.
1132 *
1133 * Remove the LWP from the global list.
1134 * Free its LID from the PID namespace if needed.
1135 */
1136 mutex_enter(&proc_lock);
1137
1138 if ((p->p_slflag & (PSL_TRACED|PSL_TRACELWP_EXIT)) ==
1139 (PSL_TRACED|PSL_TRACELWP_EXIT)) {
1140 mutex_enter(p->p_lock);
1141 if (ISSET(p->p_sflag, PS_WEXIT)) {
1142 mutex_exit(p->p_lock);
1143 /*
1144 * We are exiting, bail out without informing parent
1145 * about a terminating LWP as it would deadlock.
1146 */
1147 } else {
1148 eventswitch(TRAP_LWP, PTRACE_LWP_EXIT, l->l_lid);
1149 mutex_enter(&proc_lock);
1150 }
1151 }
1152
1153 LIST_REMOVE(l, l_list);
1154 mutex_exit(&proc_lock);
1155
1156 /*
1157 * Get rid of all references to the LWP that others (e.g. procfs)
1158 * may have, and mark the LWP as a zombie. If the LWP is detached,
1159 * mark it waiting for collection in the proc structure. Note that
1160 * before we can do that, we need to free any other dead, deatched
1161 * LWP waiting to meet its maker.
1162 *
1163 * All conditions need to be observed upon under the same hold of
1164 * p_lock, because if the lock is dropped any of them can change.
1165 */
1166 mutex_enter(p->p_lock);
1167 for (;;) {
1168 if (lwp_drainrefs(l))
1169 continue;
1170 if ((l->l_prflag & LPR_DETACHED) != 0) {
1171 if ((l2 = p->p_zomblwp) != NULL) {
1172 p->p_zomblwp = NULL;
1173 lwp_free(l2, false, false);
1174 /* proc now unlocked */
1175 mutex_enter(p->p_lock);
1176 continue;
1177 }
1178 p->p_zomblwp = l;
1179 }
1180 break;
1181 }
1182
1183 /*
1184 * If we find a pending signal for the process and we have been
1185 * asked to check for signals, then we lose: arrange to have
1186 * all other LWPs in the process check for signals.
1187 */
1188 if ((l->l_flag & LW_PENDSIG) != 0 &&
1189 firstsig(&p->p_sigpend.sp_set) != 0) {
1190 LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
1191 lwp_lock(l2);
1192 signotify(l2);
1193 lwp_unlock(l2);
1194 }
1195 }
1196
1197 /*
1198 * Release any PCU resources before becoming a zombie.
1199 */
1200 pcu_discard_all(l);
1201
1202 lwp_lock(l);
1203 l->l_stat = LSZOMB;
1204 if (l->l_name != NULL) {
1205 strcpy(l->l_name, "(zombie)");
1206 }
1207 lwp_unlock(l);
1208 p->p_nrlwps--;
1209 cv_broadcast(&p->p_lwpcv);
1210 if (l->l_lwpctl != NULL)
1211 l->l_lwpctl->lc_curcpu = LWPCTL_CPU_EXITED;
1212 mutex_exit(p->p_lock);
1213
1214 /*
1215 * We can no longer block. At this point, lwp_free() may already
1216 * be gunning for us. On a multi-CPU system, we may be off p_lwps.
1217 *
1218 * Free MD LWP resources.
1219 */
1220 cpu_lwp_free(l, 0);
1221
1222 if (current) {
1223 /* Switch away into oblivion. */
1224 lwp_lock(l);
1225 spc_lock(l->l_cpu);
1226 mi_switch(l);
1227 panic("lwp_exit");
1228 }
1229 }
1230
1231 /*
1232 * Free a dead LWP's remaining resources.
1233 *
1234 * XXXLWP limits.
1235 */
1236 void
1237 lwp_free(struct lwp *l, bool recycle, bool last)
1238 {
1239 struct proc *p = l->l_proc;
1240 struct rusage *ru;
1241 ksiginfoq_t kq;
1242
1243 KASSERT(l != curlwp);
1244 KASSERT(last || mutex_owned(p->p_lock));
1245
1246 /*
1247 * We use the process credentials instead of the lwp credentials here
1248 * because the lwp credentials maybe cached (just after a setuid call)
1249 * and we don't want pay for syncing, since the lwp is going away
1250 * anyway
1251 */
1252 if (p != &proc0 && p->p_nlwps != 1)
1253 (void)chglwpcnt(kauth_cred_getuid(p->p_cred), -1);
1254
1255 /*
1256 * In the unlikely event that the LWP is still on the CPU,
1257 * then spin until it has switched away.
1258 */
1259 membar_consumer();
1260 while (__predict_false((l->l_pflag & LP_RUNNING) != 0)) {
1261 SPINLOCK_BACKOFF_HOOK;
1262 }
1263
1264 /*
1265 * Now that the LWP's known off the CPU, reset its state back to
1266 * LSIDL, which defeats anything that might have gotten a hold on
1267 * the LWP via pid_table before the ID was freed. It's important
1268 * to do this with both the LWP locked and p_lock held.
1269 *
1270 * Also reset the CPU and lock pointer back to curcpu(), since the
1271 * LWP will in all likelyhood be cached with the current CPU in
1272 * lwp_cache when we free it and later allocated from there again
1273 * (avoid incidental lock contention).
1274 */
1275 lwp_lock(l);
1276 l->l_stat = LSIDL;
1277 l->l_cpu = curcpu();
1278 lwp_unlock_to(l, l->l_cpu->ci_schedstate.spc_lwplock);
1279
1280 /*
1281 * If this was not the last LWP in the process, then adjust counters
1282 * and unlock. This is done differently for the last LWP in exit1().
1283 */
1284 if (!last) {
1285 /*
1286 * Add the LWP's run time to the process' base value.
1287 * This needs to co-incide with coming off p_lwps.
1288 */
1289 bintime_add(&p->p_rtime, &l->l_rtime);
1290 p->p_pctcpu += l->l_pctcpu;
1291 ru = &p->p_stats->p_ru;
1292 ruadd(ru, &l->l_ru);
1293 ru->ru_nvcsw += (l->l_ncsw - l->l_nivcsw);
1294 ru->ru_nivcsw += l->l_nivcsw;
1295 LIST_REMOVE(l, l_sibling);
1296 p->p_nlwps--;
1297 p->p_nzlwps--;
1298 if ((l->l_prflag & LPR_DETACHED) != 0)
1299 p->p_ndlwps--;
1300
1301 /*
1302 * Have any LWPs sleeping in lwp_wait() recheck for
1303 * deadlock.
1304 */
1305 cv_broadcast(&p->p_lwpcv);
1306 mutex_exit(p->p_lock);
1307
1308 /* Free the LWP ID. */
1309 mutex_enter(&proc_lock);
1310 proc_free_lwpid(p, l->l_lid);
1311 mutex_exit(&proc_lock);
1312 }
1313
1314 /*
1315 * Destroy the LWP's remaining signal information.
1316 */
1317 ksiginfo_queue_init(&kq);
1318 sigclear(&l->l_sigpend, NULL, &kq);
1319 ksiginfo_queue_drain(&kq);
1320 cv_destroy(&l->l_sigcv);
1321 cv_destroy(&l->l_waitcv);
1322
1323 /*
1324 * Free lwpctl structure and affinity.
1325 */
1326 if (l->l_lwpctl) {
1327 lwp_ctl_free(l);
1328 }
1329 if (l->l_affinity) {
1330 kcpuset_unuse(l->l_affinity, NULL);
1331 l->l_affinity = NULL;
1332 }
1333
1334 /*
1335 * Free remaining data structures and the LWP itself unless the
1336 * caller wants to recycle.
1337 */
1338 if (l->l_name != NULL)
1339 kmem_free(l->l_name, MAXCOMLEN);
1340
1341 kmsan_lwp_free(l);
1342 kcov_lwp_free(l);
1343 cpu_lwp_free2(l);
1344 uvm_lwp_exit(l);
1345
1346 KASSERT(SLIST_EMPTY(&l->l_pi_lenders));
1347 KASSERT(l->l_inheritedprio == -1);
1348 KASSERT(l->l_blcnt == 0);
1349 kdtrace_thread_dtor(NULL, l);
1350 if (!recycle)
1351 pool_cache_put(lwp_cache, l);
1352 }
1353
1354 /*
1355 * Migrate the LWP to the another CPU. Unlocks the LWP.
1356 */
1357 void
1358 lwp_migrate(lwp_t *l, struct cpu_info *tci)
1359 {
1360 struct schedstate_percpu *tspc;
1361 int lstat = l->l_stat;
1362
1363 KASSERT(lwp_locked(l, NULL));
1364 KASSERT(tci != NULL);
1365
1366 /* If LWP is still on the CPU, it must be handled like LSONPROC */
1367 if ((l->l_pflag & LP_RUNNING) != 0) {
1368 lstat = LSONPROC;
1369 }
1370
1371 /*
1372 * The destination CPU could be changed while previous migration
1373 * was not finished.
1374 */
1375 if (l->l_target_cpu != NULL) {
1376 l->l_target_cpu = tci;
1377 lwp_unlock(l);
1378 return;
1379 }
1380
1381 /* Nothing to do if trying to migrate to the same CPU */
1382 if (l->l_cpu == tci) {
1383 lwp_unlock(l);
1384 return;
1385 }
1386
1387 KASSERT(l->l_target_cpu == NULL);
1388 tspc = &tci->ci_schedstate;
1389 switch (lstat) {
1390 case LSRUN:
1391 l->l_target_cpu = tci;
1392 break;
1393 case LSSLEEP:
1394 l->l_cpu = tci;
1395 break;
1396 case LSIDL:
1397 case LSSTOP:
1398 case LSSUSPENDED:
1399 l->l_cpu = tci;
1400 if (l->l_wchan == NULL) {
1401 lwp_unlock_to(l, tspc->spc_lwplock);
1402 return;
1403 }
1404 break;
1405 case LSONPROC:
1406 l->l_target_cpu = tci;
1407 spc_lock(l->l_cpu);
1408 sched_resched_cpu(l->l_cpu, PRI_USER_RT, true);
1409 /* spc now unlocked */
1410 break;
1411 }
1412 lwp_unlock(l);
1413 }
1414
1415 #define lwp_find_exclude(l) \
1416 ((l)->l_stat == LSIDL || (l)->l_stat == LSZOMB)
1417
1418 /*
1419 * Find the LWP in the process. Arguments may be zero, in such case,
1420 * the calling process and first LWP in the list will be used.
1421 * On success - returns proc locked.
1422 *
1423 * => pid == 0 -> look in curproc.
1424 * => pid == -1 -> match any proc.
1425 * => otherwise look up the proc.
1426 *
1427 * => lid == 0 -> first LWP in the proc
1428 * => otherwise specific LWP
1429 */
1430 struct lwp *
1431 lwp_find2(pid_t pid, lwpid_t lid)
1432 {
1433 proc_t *p;
1434 lwp_t *l;
1435
1436 /* First LWP of specified proc. */
1437 if (lid == 0) {
1438 switch (pid) {
1439 case -1:
1440 /* No lookup keys. */
1441 return NULL;
1442 case 0:
1443 p = curproc;
1444 mutex_enter(p->p_lock);
1445 break;
1446 default:
1447 mutex_enter(&proc_lock);
1448 p = proc_find(pid);
1449 if (__predict_false(p == NULL)) {
1450 mutex_exit(&proc_lock);
1451 return NULL;
1452 }
1453 mutex_enter(p->p_lock);
1454 mutex_exit(&proc_lock);
1455 break;
1456 }
1457 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1458 if (__predict_true(!lwp_find_exclude(l)))
1459 break;
1460 }
1461 goto out;
1462 }
1463
1464 l = proc_find_lwp_acquire_proc(lid, &p);
1465 if (l == NULL)
1466 return NULL;
1467 KASSERT(p != NULL);
1468 KASSERT(mutex_owned(p->p_lock));
1469
1470 if (__predict_false(lwp_find_exclude(l))) {
1471 l = NULL;
1472 goto out;
1473 }
1474
1475 /* Apply proc filter, if applicable. */
1476 switch (pid) {
1477 case -1:
1478 /* Match anything. */
1479 break;
1480 case 0:
1481 if (p != curproc)
1482 l = NULL;
1483 break;
1484 default:
1485 if (p->p_pid != pid)
1486 l = NULL;
1487 break;
1488 }
1489
1490 out:
1491 if (__predict_false(l == NULL)) {
1492 mutex_exit(p->p_lock);
1493 }
1494 return l;
1495 }
1496
1497 /*
1498 * Look up a live LWP within the specified process.
1499 *
1500 * Must be called with p->p_lock held (as it looks at the radix tree,
1501 * and also wants to exclude idle and zombie LWPs).
1502 */
1503 struct lwp *
1504 lwp_find(struct proc *p, lwpid_t id)
1505 {
1506 struct lwp *l;
1507
1508 KASSERT(mutex_owned(p->p_lock));
1509
1510 l = proc_find_lwp(p, id);
1511 KASSERT(l == NULL || l->l_lid == id);
1512
1513 /*
1514 * No need to lock - all of these conditions will
1515 * be visible with the process level mutex held.
1516 */
1517 if (__predict_false(l != NULL && lwp_find_exclude(l)))
1518 l = NULL;
1519
1520 return l;
1521 }
1522
1523 /*
1524 * Update an LWP's cached credentials to mirror the process' master copy.
1525 *
1526 * This happens early in the syscall path, on user trap, and on LWP
1527 * creation. A long-running LWP can also voluntarily choose to update
1528 * its credentials by calling this routine. This may be called from
1529 * LWP_CACHE_CREDS(), which checks l->l_cred != p->p_cred beforehand.
1530 */
1531 void
1532 lwp_update_creds(struct lwp *l)
1533 {
1534 kauth_cred_t oc;
1535 struct proc *p;
1536
1537 p = l->l_proc;
1538 oc = l->l_cred;
1539
1540 mutex_enter(p->p_lock);
1541 kauth_cred_hold(p->p_cred);
1542 l->l_cred = p->p_cred;
1543 l->l_prflag &= ~LPR_CRMOD;
1544 mutex_exit(p->p_lock);
1545 if (oc != NULL)
1546 kauth_cred_free(oc);
1547 }
1548
1549 /*
1550 * Verify that an LWP is locked, and optionally verify that the lock matches
1551 * one we specify.
1552 */
1553 int
1554 lwp_locked(struct lwp *l, kmutex_t *mtx)
1555 {
1556 kmutex_t *cur = l->l_mutex;
1557
1558 return mutex_owned(cur) && (mtx == cur || mtx == NULL);
1559 }
1560
1561 /*
1562 * Lend a new mutex to an LWP. The old mutex must be held.
1563 */
1564 kmutex_t *
1565 lwp_setlock(struct lwp *l, kmutex_t *mtx)
1566 {
1567 kmutex_t *oldmtx = l->l_mutex;
1568
1569 KASSERT(mutex_owned(oldmtx));
1570
1571 membar_exit();
1572 l->l_mutex = mtx;
1573 return oldmtx;
1574 }
1575
1576 /*
1577 * Lend a new mutex to an LWP, and release the old mutex. The old mutex
1578 * must be held.
1579 */
1580 void
1581 lwp_unlock_to(struct lwp *l, kmutex_t *mtx)
1582 {
1583 kmutex_t *old;
1584
1585 KASSERT(lwp_locked(l, NULL));
1586
1587 old = l->l_mutex;
1588 membar_exit();
1589 l->l_mutex = mtx;
1590 mutex_spin_exit(old);
1591 }
1592
1593 int
1594 lwp_trylock(struct lwp *l)
1595 {
1596 kmutex_t *old;
1597
1598 for (;;) {
1599 if (!mutex_tryenter(old = l->l_mutex))
1600 return 0;
1601 if (__predict_true(l->l_mutex == old))
1602 return 1;
1603 mutex_spin_exit(old);
1604 }
1605 }
1606
1607 void
1608 lwp_unsleep(lwp_t *l, bool unlock)
1609 {
1610
1611 KASSERT(mutex_owned(l->l_mutex));
1612 (*l->l_syncobj->sobj_unsleep)(l, unlock);
1613 }
1614
1615 /*
1616 * Handle exceptions for mi_userret(). Called if a member of LW_USERRET is
1617 * set.
1618 */
1619 void
1620 lwp_userret(struct lwp *l)
1621 {
1622 struct proc *p;
1623 int sig;
1624
1625 KASSERT(l == curlwp);
1626 KASSERT(l->l_stat == LSONPROC);
1627 p = l->l_proc;
1628
1629 /*
1630 * It is safe to do this read unlocked on a MP system..
1631 */
1632 while ((l->l_flag & LW_USERRET) != 0) {
1633 /*
1634 * Process pending signals first, unless the process
1635 * is dumping core or exiting, where we will instead
1636 * enter the LW_WSUSPEND case below.
1637 */
1638 if ((l->l_flag & (LW_PENDSIG | LW_WCORE | LW_WEXIT)) ==
1639 LW_PENDSIG) {
1640 mutex_enter(p->p_lock);
1641 while ((sig = issignal(l)) != 0)
1642 postsig(sig);
1643 mutex_exit(p->p_lock);
1644 }
1645
1646 /*
1647 * Core-dump or suspend pending.
1648 *
1649 * In case of core dump, suspend ourselves, so that the kernel
1650 * stack and therefore the userland registers saved in the
1651 * trapframe are around for coredump() to write them out.
1652 * We also need to save any PCU resources that we have so that
1653 * they accessible for coredump(). We issue a wakeup on
1654 * p->p_lwpcv so that sigexit() will write the core file out
1655 * once all other LWPs are suspended.
1656 */
1657 if ((l->l_flag & LW_WSUSPEND) != 0) {
1658 pcu_save_all(l);
1659 mutex_enter(p->p_lock);
1660 p->p_nrlwps--;
1661 cv_broadcast(&p->p_lwpcv);
1662 lwp_lock(l);
1663 l->l_stat = LSSUSPENDED;
1664 lwp_unlock(l);
1665 mutex_exit(p->p_lock);
1666 lwp_lock(l);
1667 spc_lock(l->l_cpu);
1668 mi_switch(l);
1669 }
1670
1671 /* Process is exiting. */
1672 if ((l->l_flag & LW_WEXIT) != 0) {
1673 lwp_exit(l);
1674 KASSERT(0);
1675 /* NOTREACHED */
1676 }
1677
1678 /* update lwpctl processor (for vfork child_return) */
1679 if (l->l_flag & LW_LWPCTL) {
1680 lwp_lock(l);
1681 KASSERT(kpreempt_disabled());
1682 l->l_lwpctl->lc_curcpu = (int)cpu_index(l->l_cpu);
1683 l->l_lwpctl->lc_pctr++;
1684 l->l_flag &= ~LW_LWPCTL;
1685 lwp_unlock(l);
1686 }
1687 }
1688 }
1689
1690 /*
1691 * Force an LWP to enter the kernel, to take a trip through lwp_userret().
1692 */
1693 void
1694 lwp_need_userret(struct lwp *l)
1695 {
1696
1697 KASSERT(!cpu_intr_p());
1698 KASSERT(lwp_locked(l, NULL));
1699
1700 /*
1701 * If the LWP is in any state other than LSONPROC, we know that it
1702 * is executing in-kernel and will hit userret() on the way out.
1703 *
1704 * If the LWP is curlwp, then we know we'll be back out to userspace
1705 * soon (can't be called from a hardware interrupt here).
1706 *
1707 * Otherwise, we can't be sure what the LWP is doing, so first make
1708 * sure the update to l_flag will be globally visible, and then
1709 * force the LWP to take a trip through trap() where it will do
1710 * userret().
1711 */
1712 if (l->l_stat == LSONPROC && l != curlwp) {
1713 membar_producer();
1714 cpu_signotify(l);
1715 }
1716 }
1717
1718 /*
1719 * Add one reference to an LWP. This will prevent the LWP from
1720 * exiting, thus keep the lwp structure and PCB around to inspect.
1721 */
1722 void
1723 lwp_addref(struct lwp *l)
1724 {
1725 KASSERT(mutex_owned(l->l_proc->p_lock));
1726 KASSERT(l->l_stat != LSZOMB);
1727 l->l_refcnt++;
1728 }
1729
1730 /*
1731 * Remove one reference to an LWP. If this is the last reference,
1732 * then we must finalize the LWP's death.
1733 */
1734 void
1735 lwp_delref(struct lwp *l)
1736 {
1737 struct proc *p = l->l_proc;
1738
1739 mutex_enter(p->p_lock);
1740 lwp_delref2(l);
1741 mutex_exit(p->p_lock);
1742 }
1743
1744 /*
1745 * Remove one reference to an LWP. If this is the last reference,
1746 * then we must finalize the LWP's death. The proc mutex is held
1747 * on entry.
1748 */
1749 void
1750 lwp_delref2(struct lwp *l)
1751 {
1752 struct proc *p = l->l_proc;
1753
1754 KASSERT(mutex_owned(p->p_lock));
1755 KASSERT(l->l_stat != LSZOMB);
1756 KASSERT(l->l_refcnt > 0);
1757
1758 if (--l->l_refcnt == 0)
1759 cv_broadcast(&p->p_lwpcv);
1760 }
1761
1762 /*
1763 * Drain all references to the current LWP. Returns true if
1764 * we blocked.
1765 */
1766 bool
1767 lwp_drainrefs(struct lwp *l)
1768 {
1769 struct proc *p = l->l_proc;
1770 bool rv = false;
1771
1772 KASSERT(mutex_owned(p->p_lock));
1773
1774 l->l_prflag |= LPR_DRAINING;
1775
1776 while (l->l_refcnt > 0) {
1777 rv = true;
1778 cv_wait(&p->p_lwpcv, p->p_lock);
1779 }
1780 return rv;
1781 }
1782
1783 /*
1784 * Return true if the specified LWP is 'alive'. Only p->p_lock need
1785 * be held.
1786 */
1787 bool
1788 lwp_alive(lwp_t *l)
1789 {
1790
1791 KASSERT(mutex_owned(l->l_proc->p_lock));
1792
1793 switch (l->l_stat) {
1794 case LSSLEEP:
1795 case LSRUN:
1796 case LSONPROC:
1797 case LSSTOP:
1798 case LSSUSPENDED:
1799 return true;
1800 default:
1801 return false;
1802 }
1803 }
1804
1805 /*
1806 * Return first live LWP in the process.
1807 */
1808 lwp_t *
1809 lwp_find_first(proc_t *p)
1810 {
1811 lwp_t *l;
1812
1813 KASSERT(mutex_owned(p->p_lock));
1814
1815 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1816 if (lwp_alive(l)) {
1817 return l;
1818 }
1819 }
1820
1821 return NULL;
1822 }
1823
1824 /*
1825 * Allocate a new lwpctl structure for a user LWP.
1826 */
1827 int
1828 lwp_ctl_alloc(vaddr_t *uaddr)
1829 {
1830 lcproc_t *lp;
1831 u_int bit, i, offset;
1832 struct uvm_object *uao;
1833 int error;
1834 lcpage_t *lcp;
1835 proc_t *p;
1836 lwp_t *l;
1837
1838 l = curlwp;
1839 p = l->l_proc;
1840
1841 /* don't allow a vforked process to create lwp ctls */
1842 if (p->p_lflag & PL_PPWAIT)
1843 return EBUSY;
1844
1845 if (l->l_lcpage != NULL) {
1846 lcp = l->l_lcpage;
1847 *uaddr = lcp->lcp_uaddr + (vaddr_t)l->l_lwpctl - lcp->lcp_kaddr;
1848 return 0;
1849 }
1850
1851 /* First time around, allocate header structure for the process. */
1852 if ((lp = p->p_lwpctl) == NULL) {
1853 lp = kmem_alloc(sizeof(*lp), KM_SLEEP);
1854 mutex_init(&lp->lp_lock, MUTEX_DEFAULT, IPL_NONE);
1855 lp->lp_uao = NULL;
1856 TAILQ_INIT(&lp->lp_pages);
1857 mutex_enter(p->p_lock);
1858 if (p->p_lwpctl == NULL) {
1859 p->p_lwpctl = lp;
1860 mutex_exit(p->p_lock);
1861 } else {
1862 mutex_exit(p->p_lock);
1863 mutex_destroy(&lp->lp_lock);
1864 kmem_free(lp, sizeof(*lp));
1865 lp = p->p_lwpctl;
1866 }
1867 }
1868
1869 /*
1870 * Set up an anonymous memory region to hold the shared pages.
1871 * Map them into the process' address space. The user vmspace
1872 * gets the first reference on the UAO.
1873 */
1874 mutex_enter(&lp->lp_lock);
1875 if (lp->lp_uao == NULL) {
1876 lp->lp_uao = uao_create(LWPCTL_UAREA_SZ, 0);
1877 lp->lp_cur = 0;
1878 lp->lp_max = LWPCTL_UAREA_SZ;
1879 lp->lp_uva = p->p_emul->e_vm_default_addr(p,
1880 (vaddr_t)p->p_vmspace->vm_daddr, LWPCTL_UAREA_SZ,
1881 p->p_vmspace->vm_map.flags & VM_MAP_TOPDOWN);
1882 error = uvm_map(&p->p_vmspace->vm_map, &lp->lp_uva,
1883 LWPCTL_UAREA_SZ, lp->lp_uao, 0, 0, UVM_MAPFLAG(UVM_PROT_RW,
1884 UVM_PROT_RW, UVM_INH_NONE, UVM_ADV_NORMAL, 0));
1885 if (error != 0) {
1886 uao_detach(lp->lp_uao);
1887 lp->lp_uao = NULL;
1888 mutex_exit(&lp->lp_lock);
1889 return error;
1890 }
1891 }
1892
1893 /* Get a free block and allocate for this LWP. */
1894 TAILQ_FOREACH(lcp, &lp->lp_pages, lcp_chain) {
1895 if (lcp->lcp_nfree != 0)
1896 break;
1897 }
1898 if (lcp == NULL) {
1899 /* Nothing available - try to set up a free page. */
1900 if (lp->lp_cur == lp->lp_max) {
1901 mutex_exit(&lp->lp_lock);
1902 return ENOMEM;
1903 }
1904 lcp = kmem_alloc(LWPCTL_LCPAGE_SZ, KM_SLEEP);
1905
1906 /*
1907 * Wire the next page down in kernel space. Since this
1908 * is a new mapping, we must add a reference.
1909 */
1910 uao = lp->lp_uao;
1911 (*uao->pgops->pgo_reference)(uao);
1912 lcp->lcp_kaddr = vm_map_min(kernel_map);
1913 error = uvm_map(kernel_map, &lcp->lcp_kaddr, PAGE_SIZE,
1914 uao, lp->lp_cur, PAGE_SIZE,
1915 UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW,
1916 UVM_INH_NONE, UVM_ADV_RANDOM, 0));
1917 if (error != 0) {
1918 mutex_exit(&lp->lp_lock);
1919 kmem_free(lcp, LWPCTL_LCPAGE_SZ);
1920 (*uao->pgops->pgo_detach)(uao);
1921 return error;
1922 }
1923 error = uvm_map_pageable(kernel_map, lcp->lcp_kaddr,
1924 lcp->lcp_kaddr + PAGE_SIZE, FALSE, 0);
1925 if (error != 0) {
1926 mutex_exit(&lp->lp_lock);
1927 uvm_unmap(kernel_map, lcp->lcp_kaddr,
1928 lcp->lcp_kaddr + PAGE_SIZE);
1929 kmem_free(lcp, LWPCTL_LCPAGE_SZ);
1930 return error;
1931 }
1932 /* Prepare the page descriptor and link into the list. */
1933 lcp->lcp_uaddr = lp->lp_uva + lp->lp_cur;
1934 lp->lp_cur += PAGE_SIZE;
1935 lcp->lcp_nfree = LWPCTL_PER_PAGE;
1936 lcp->lcp_rotor = 0;
1937 memset(lcp->lcp_bitmap, 0xff, LWPCTL_BITMAP_SZ);
1938 TAILQ_INSERT_HEAD(&lp->lp_pages, lcp, lcp_chain);
1939 }
1940 for (i = lcp->lcp_rotor; lcp->lcp_bitmap[i] == 0;) {
1941 if (++i >= LWPCTL_BITMAP_ENTRIES)
1942 i = 0;
1943 }
1944 bit = ffs(lcp->lcp_bitmap[i]) - 1;
1945 lcp->lcp_bitmap[i] ^= (1U << bit);
1946 lcp->lcp_rotor = i;
1947 lcp->lcp_nfree--;
1948 l->l_lcpage = lcp;
1949 offset = (i << 5) + bit;
1950 l->l_lwpctl = (lwpctl_t *)lcp->lcp_kaddr + offset;
1951 *uaddr = lcp->lcp_uaddr + offset * sizeof(lwpctl_t);
1952 mutex_exit(&lp->lp_lock);
1953
1954 KPREEMPT_DISABLE(l);
1955 l->l_lwpctl->lc_curcpu = (int)cpu_index(curcpu());
1956 KPREEMPT_ENABLE(l);
1957
1958 return 0;
1959 }
1960
1961 /*
1962 * Free an lwpctl structure back to the per-process list.
1963 */
1964 void
1965 lwp_ctl_free(lwp_t *l)
1966 {
1967 struct proc *p = l->l_proc;
1968 lcproc_t *lp;
1969 lcpage_t *lcp;
1970 u_int map, offset;
1971
1972 /* don't free a lwp context we borrowed for vfork */
1973 if (p->p_lflag & PL_PPWAIT) {
1974 l->l_lwpctl = NULL;
1975 return;
1976 }
1977
1978 lp = p->p_lwpctl;
1979 KASSERT(lp != NULL);
1980
1981 lcp = l->l_lcpage;
1982 offset = (u_int)((lwpctl_t *)l->l_lwpctl - (lwpctl_t *)lcp->lcp_kaddr);
1983 KASSERT(offset < LWPCTL_PER_PAGE);
1984
1985 mutex_enter(&lp->lp_lock);
1986 lcp->lcp_nfree++;
1987 map = offset >> 5;
1988 lcp->lcp_bitmap[map] |= (1U << (offset & 31));
1989 if (lcp->lcp_bitmap[lcp->lcp_rotor] == 0)
1990 lcp->lcp_rotor = map;
1991 if (TAILQ_FIRST(&lp->lp_pages)->lcp_nfree == 0) {
1992 TAILQ_REMOVE(&lp->lp_pages, lcp, lcp_chain);
1993 TAILQ_INSERT_HEAD(&lp->lp_pages, lcp, lcp_chain);
1994 }
1995 mutex_exit(&lp->lp_lock);
1996 }
1997
1998 /*
1999 * Process is exiting; tear down lwpctl state. This can only be safely
2000 * called by the last LWP in the process.
2001 */
2002 void
2003 lwp_ctl_exit(void)
2004 {
2005 lcpage_t *lcp, *next;
2006 lcproc_t *lp;
2007 proc_t *p;
2008 lwp_t *l;
2009
2010 l = curlwp;
2011 l->l_lwpctl = NULL;
2012 l->l_lcpage = NULL;
2013 p = l->l_proc;
2014 lp = p->p_lwpctl;
2015
2016 KASSERT(lp != NULL);
2017 KASSERT(p->p_nlwps == 1);
2018
2019 for (lcp = TAILQ_FIRST(&lp->lp_pages); lcp != NULL; lcp = next) {
2020 next = TAILQ_NEXT(lcp, lcp_chain);
2021 uvm_unmap(kernel_map, lcp->lcp_kaddr,
2022 lcp->lcp_kaddr + PAGE_SIZE);
2023 kmem_free(lcp, LWPCTL_LCPAGE_SZ);
2024 }
2025
2026 if (lp->lp_uao != NULL) {
2027 uvm_unmap(&p->p_vmspace->vm_map, lp->lp_uva,
2028 lp->lp_uva + LWPCTL_UAREA_SZ);
2029 }
2030
2031 mutex_destroy(&lp->lp_lock);
2032 kmem_free(lp, sizeof(*lp));
2033 p->p_lwpctl = NULL;
2034 }
2035
2036 /*
2037 * Return the current LWP's "preemption counter". Used to detect
2038 * preemption across operations that can tolerate preemption without
2039 * crashing, but which may generate incorrect results if preempted.
2040 */
2041 uint64_t
2042 lwp_pctr(void)
2043 {
2044
2045 return curlwp->l_ncsw;
2046 }
2047
2048 /*
2049 * Set an LWP's private data pointer.
2050 */
2051 int
2052 lwp_setprivate(struct lwp *l, void *ptr)
2053 {
2054 int error = 0;
2055
2056 l->l_private = ptr;
2057 #ifdef __HAVE_CPU_LWP_SETPRIVATE
2058 error = cpu_lwp_setprivate(l, ptr);
2059 #endif
2060 return error;
2061 }
2062
2063 /*
2064 * Perform any thread-related cleanup on LWP exit.
2065 * N.B. l->l_proc->p_lock must be HELD on entry but will
2066 * be released before returning!
2067 */
2068 void
2069 lwp_thread_cleanup(struct lwp *l)
2070 {
2071
2072 KASSERT(mutex_owned(l->l_proc->p_lock));
2073 mutex_exit(l->l_proc->p_lock);
2074
2075 /*
2076 * If the LWP has robust futexes, release them all
2077 * now.
2078 */
2079 if (__predict_false(l->l_robust_head != 0)) {
2080 futex_release_all_lwp(l);
2081 }
2082 }
2083
2084 #if defined(DDB)
2085 #include <machine/pcb.h>
2086
2087 void
2088 lwp_whatis(uintptr_t addr, void (*pr)(const char *, ...))
2089 {
2090 lwp_t *l;
2091
2092 LIST_FOREACH(l, &alllwp, l_list) {
2093 uintptr_t stack = (uintptr_t)KSTACK_LOWEST_ADDR(l);
2094
2095 if (addr < stack || stack + KSTACK_SIZE <= addr) {
2096 continue;
2097 }
2098 (*pr)("%p is %p+%zu, LWP %p's stack\n",
2099 (void *)addr, (void *)stack,
2100 (size_t)(addr - stack), l);
2101 }
2102 }
2103 #endif /* defined(DDB) */
2104