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