kern_lwp.c revision 1.262 1 /* $NetBSD: kern_lwp.c,v 1.262 2023/10/04 20:46:33 ad Exp $ */
2
3 /*-
4 * Copyright (c) 2001, 2006, 2007, 2008, 2009, 2019, 2020, 2023
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.262 2023/10/04 20:46:33 ad 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
266 /* DTrace proc provider probes */
267 SDT_PROVIDER_DEFINE(proc);
268
269 SDT_PROBE_DEFINE1(proc, kernel, , lwp__create, "struct lwp *");
270 SDT_PROBE_DEFINE1(proc, kernel, , lwp__start, "struct lwp *");
271 SDT_PROBE_DEFINE1(proc, kernel, , lwp__exit, "struct lwp *");
272
273 struct turnstile turnstile0 __cacheline_aligned;
274 struct lwp lwp0 __aligned(MIN_LWP_ALIGNMENT) = {
275 #ifdef LWP0_CPU_INFO
276 .l_cpu = LWP0_CPU_INFO,
277 #endif
278 #ifdef LWP0_MD_INITIALIZER
279 .l_md = LWP0_MD_INITIALIZER,
280 #endif
281 .l_proc = &proc0,
282 .l_lid = 0, /* we own proc0's slot in the pid table */
283 .l_flag = LW_SYSTEM,
284 .l_stat = LSONPROC,
285 .l_ts = &turnstile0,
286 .l_syncobj = &sched_syncobj,
287 .l_refcnt = 0,
288 .l_priority = PRI_USER + NPRI_USER - 1,
289 .l_inheritedprio = -1,
290 .l_class = SCHED_OTHER,
291 .l_psid = PS_NONE,
292 .l_pi_lenders = SLIST_HEAD_INITIALIZER(&lwp0.l_pi_lenders),
293 .l_name = __UNCONST("swapper"),
294 .l_fd = &filedesc0,
295 };
296
297 static int
298 lwp_maxlwp(void)
299 {
300 /* Assume 1 LWP per 1MiB. */
301 uint64_t lwps_per = ctob(physmem) / (1024 * 1024);
302
303 return MAX(MIN(MAXMAXLWP, lwps_per), MAXLWP);
304 }
305
306 static int sysctl_kern_maxlwp(SYSCTLFN_PROTO);
307
308 /*
309 * sysctl helper routine for kern.maxlwp. Ensures that the new
310 * values are not too low or too high.
311 */
312 static int
313 sysctl_kern_maxlwp(SYSCTLFN_ARGS)
314 {
315 int error, nmaxlwp;
316 struct sysctlnode node;
317
318 nmaxlwp = maxlwp;
319 node = *rnode;
320 node.sysctl_data = &nmaxlwp;
321 error = sysctl_lookup(SYSCTLFN_CALL(&node));
322 if (error || newp == NULL)
323 return error;
324
325 if (nmaxlwp < 0 || nmaxlwp >= MAXMAXLWP)
326 return EINVAL;
327 if (nmaxlwp > lwp_maxlwp())
328 return EINVAL;
329 maxlwp = nmaxlwp;
330
331 return 0;
332 }
333
334 static void
335 sysctl_kern_lwp_setup(void)
336 {
337 sysctl_createv(NULL, 0, NULL, NULL,
338 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
339 CTLTYPE_INT, "maxlwp",
340 SYSCTL_DESCR("Maximum number of simultaneous threads"),
341 sysctl_kern_maxlwp, 0, NULL, 0,
342 CTL_KERN, CTL_CREATE, CTL_EOL);
343 }
344
345 void
346 lwpinit(void)
347 {
348
349 LIST_INIT(&alllwp);
350 lwpinit_specificdata();
351 /*
352 * Provide a barrier to ensure that all mutex_oncpu() and rw_oncpu()
353 * calls will exit before memory of LWPs is returned to the pool, where
354 * KVA of LWP structure might be freed and re-used for other purposes.
355 * Kernel preemption is disabled around mutex_oncpu() and rw_oncpu()
356 * callers, therefore a regular passive serialization barrier will
357 * do the job.
358 */
359 lwp_cache = pool_cache_init(sizeof(lwp_t), MIN_LWP_ALIGNMENT, 0,
360 PR_PSERIALIZE, "lwppl", NULL, IPL_NONE, lwp_ctor, lwp_dtor, NULL);
361
362 maxlwp = lwp_maxlwp();
363 sysctl_kern_lwp_setup();
364 }
365
366 void
367 lwp0_init(void)
368 {
369 struct lwp *l = &lwp0;
370
371 KASSERT((void *)uvm_lwp_getuarea(l) != NULL);
372
373 LIST_INSERT_HEAD(&alllwp, l, l_list);
374
375 callout_init(&l->l_timeout_ch, CALLOUT_MPSAFE);
376 callout_setfunc(&l->l_timeout_ch, sleepq_timeout, l);
377 cv_init(&l->l_sigcv, "sigwait");
378 cv_init(&l->l_waitcv, "vfork");
379
380 kauth_cred_hold(proc0.p_cred);
381 l->l_cred = proc0.p_cred;
382
383 kdtrace_thread_ctor(NULL, l);
384 lwp_initspecific(l);
385
386 SYSCALL_TIME_LWP_INIT(l);
387 }
388
389 /*
390 * Initialize the non-zeroed portion of an lwp_t.
391 */
392 static int
393 lwp_ctor(void *arg, void *obj, int flags)
394 {
395 lwp_t *l = obj;
396
397 l->l_stat = LSIDL;
398 l->l_cpu = curcpu();
399 l->l_mutex = l->l_cpu->ci_schedstate.spc_lwplock;
400 l->l_ts = kmem_alloc(sizeof(*l->l_ts), flags == PR_WAITOK ?
401 KM_SLEEP : KM_NOSLEEP);
402
403 if (l->l_ts == NULL) {
404 return ENOMEM;
405 } else {
406 turnstile_ctor(l->l_ts);
407 return 0;
408 }
409 }
410
411 static void
412 lwp_dtor(void *arg, void *obj)
413 {
414 lwp_t *l = obj;
415
416 /*
417 * The value of l->l_cpu must still be valid at this point.
418 */
419 KASSERT(l->l_cpu != NULL);
420
421 /*
422 * We can't return turnstile0 to the pool (it didn't come from it),
423 * so if it comes up just drop it quietly and move on.
424 */
425 if (l->l_ts != &turnstile0)
426 kmem_free(l->l_ts, sizeof(*l->l_ts));
427 }
428
429 /*
430 * Set an LWP suspended.
431 *
432 * Must be called with p_lock held, and the LWP locked. Will unlock the
433 * LWP before return.
434 */
435 int
436 lwp_suspend(struct lwp *curl, struct lwp *t)
437 {
438 int error;
439
440 KASSERT(mutex_owned(t->l_proc->p_lock));
441 KASSERT(lwp_locked(t, NULL));
442
443 KASSERT(curl != t || curl->l_stat == LSONPROC);
444
445 /*
446 * If the current LWP has been told to exit, we must not suspend anyone
447 * else or deadlock could occur. We won't return to userspace.
448 */
449 if ((curl->l_flag & (LW_WEXIT | LW_WCORE)) != 0) {
450 lwp_unlock(t);
451 return (EDEADLK);
452 }
453
454 if ((t->l_flag & LW_DBGSUSPEND) != 0) {
455 lwp_unlock(t);
456 return 0;
457 }
458
459 error = 0;
460
461 switch (t->l_stat) {
462 case LSRUN:
463 case LSONPROC:
464 t->l_flag |= LW_WSUSPEND;
465 lwp_need_userret(t);
466 lwp_unlock(t);
467 break;
468
469 case LSSLEEP:
470 t->l_flag |= LW_WSUSPEND;
471 lwp_need_userret(t);
472
473 /*
474 * Kick the LWP and try to get it to the kernel boundary
475 * so that it will release any locks that it holds.
476 * setrunnable() will release the lock.
477 */
478 if ((t->l_flag & LW_SINTR) != 0)
479 setrunnable(t);
480 else
481 lwp_unlock(t);
482 break;
483
484 case LSSUSPENDED:
485 lwp_unlock(t);
486 break;
487
488 case LSSTOP:
489 t->l_flag |= LW_WSUSPEND;
490 lwp_need_userret(t);
491 setrunnable(t);
492 break;
493
494 case LSIDL:
495 case LSZOMB:
496 error = EINTR; /* It's what Solaris does..... */
497 lwp_unlock(t);
498 break;
499 }
500
501 return (error);
502 }
503
504 /*
505 * Restart a suspended LWP.
506 *
507 * Must be called with p_lock held, and the LWP locked. Will unlock the
508 * LWP before return.
509 */
510 void
511 lwp_continue(struct lwp *l)
512 {
513
514 KASSERT(mutex_owned(l->l_proc->p_lock));
515 KASSERT(lwp_locked(l, NULL));
516
517 /* If rebooting or not suspended, then just bail out. */
518 if ((l->l_flag & LW_WREBOOT) != 0) {
519 lwp_unlock(l);
520 return;
521 }
522
523 l->l_flag &= ~LW_WSUSPEND;
524
525 if (l->l_stat != LSSUSPENDED || (l->l_flag & LW_DBGSUSPEND) != 0) {
526 lwp_unlock(l);
527 return;
528 }
529
530 /* setrunnable() will release the lock. */
531 setrunnable(l);
532 }
533
534 /*
535 * Restart a stopped LWP.
536 *
537 * Must be called with p_lock held, and the LWP NOT locked. Will unlock the
538 * LWP before return.
539 */
540 void
541 lwp_unstop(struct lwp *l)
542 {
543 struct proc *p = l->l_proc;
544
545 KASSERT(mutex_owned(&proc_lock));
546 KASSERT(mutex_owned(p->p_lock));
547
548 lwp_lock(l);
549
550 KASSERT((l->l_flag & LW_DBGSUSPEND) == 0);
551
552 /* If not stopped, then just bail out. */
553 if (l->l_stat != LSSTOP) {
554 lwp_unlock(l);
555 return;
556 }
557
558 p->p_stat = SACTIVE;
559 p->p_sflag &= ~PS_STOPPING;
560
561 if (!p->p_waited)
562 p->p_pptr->p_nstopchild--;
563
564 if (l->l_wchan == NULL) {
565 /* setrunnable() will release the lock. */
566 setrunnable(l);
567 } else if (p->p_xsig && (l->l_flag & LW_SINTR) != 0) {
568 /* setrunnable() so we can receive the signal */
569 setrunnable(l);
570 } else {
571 l->l_stat = LSSLEEP;
572 p->p_nrlwps++;
573 lwp_unlock(l);
574 }
575 }
576
577 /*
578 * Wait for an LWP within the current process to exit. If 'lid' is
579 * non-zero, we are waiting for a specific LWP.
580 *
581 * Must be called with p->p_lock held.
582 */
583 int
584 lwp_wait(struct lwp *l, lwpid_t lid, lwpid_t *departed, bool exiting)
585 {
586 const lwpid_t curlid = l->l_lid;
587 proc_t *p = l->l_proc;
588 lwp_t *l2, *next;
589 int error;
590
591 KASSERT(mutex_owned(p->p_lock));
592
593 p->p_nlwpwait++;
594 l->l_waitingfor = lid;
595
596 for (;;) {
597 int nfound;
598
599 /*
600 * Avoid a race between exit1() and sigexit(): if the
601 * process is dumping core, then we need to bail out: call
602 * into lwp_userret() where we will be suspended until the
603 * deed is done.
604 */
605 if ((p->p_sflag & PS_WCORE) != 0) {
606 mutex_exit(p->p_lock);
607 lwp_userret(l);
608 KASSERT(false);
609 }
610
611 /*
612 * First off, drain any detached LWP that is waiting to be
613 * reaped.
614 */
615 if ((l2 = p->p_zomblwp) != NULL) {
616 p->p_zomblwp = NULL;
617 lwp_free(l2, false, false);/* releases proc mutex */
618 mutex_enter(p->p_lock);
619 continue;
620 }
621
622 /*
623 * Now look for an LWP to collect. If the whole process is
624 * exiting, count detached LWPs as eligible to be collected,
625 * but don't drain them here.
626 */
627 nfound = 0;
628 error = 0;
629
630 /*
631 * If given a specific LID, go via pid_table and make sure
632 * it's not detached.
633 */
634 if (lid != 0) {
635 l2 = proc_find_lwp(p, lid);
636 if (l2 == NULL) {
637 error = ESRCH;
638 break;
639 }
640 KASSERT(l2->l_lid == lid);
641 if ((l2->l_prflag & LPR_DETACHED) != 0) {
642 error = EINVAL;
643 break;
644 }
645 } else {
646 l2 = LIST_FIRST(&p->p_lwps);
647 }
648 for (; l2 != NULL; l2 = next) {
649 next = (lid != 0 ? NULL : LIST_NEXT(l2, l_sibling));
650
651 /*
652 * If a specific wait and the target is waiting on
653 * us, then avoid deadlock. This also traps LWPs
654 * that try to wait on themselves.
655 *
656 * Note that this does not handle more complicated
657 * cycles, like: t1 -> t2 -> t3 -> t1. The process
658 * can still be killed so it is not a major problem.
659 */
660 if (l2->l_lid == lid && l2->l_waitingfor == curlid) {
661 error = EDEADLK;
662 break;
663 }
664 if (l2 == l)
665 continue;
666 if ((l2->l_prflag & LPR_DETACHED) != 0) {
667 nfound += exiting;
668 continue;
669 }
670 if (lid != 0) {
671 /*
672 * Mark this LWP as the first waiter, if there
673 * is no other.
674 */
675 if (l2->l_waiter == 0)
676 l2->l_waiter = curlid;
677 } else if (l2->l_waiter != 0) {
678 /*
679 * It already has a waiter - so don't
680 * collect it. If the waiter doesn't
681 * grab it we'll get another chance
682 * later.
683 */
684 nfound++;
685 continue;
686 }
687 nfound++;
688
689 /* No need to lock the LWP in order to see LSZOMB. */
690 if (l2->l_stat != LSZOMB)
691 continue;
692
693 /*
694 * We're no longer waiting. Reset the "first waiter"
695 * pointer on the target, in case it was us.
696 */
697 l->l_waitingfor = 0;
698 l2->l_waiter = 0;
699 p->p_nlwpwait--;
700 if (departed)
701 *departed = l2->l_lid;
702 sched_lwp_collect(l2);
703
704 /* lwp_free() releases the proc lock. */
705 lwp_free(l2, false, false);
706 mutex_enter(p->p_lock);
707 return 0;
708 }
709
710 if (error != 0)
711 break;
712 if (nfound == 0) {
713 error = ESRCH;
714 break;
715 }
716
717 /*
718 * Note: since the lock will be dropped, need to restart on
719 * wakeup to run all LWPs again, e.g. there may be new LWPs.
720 */
721 if (exiting) {
722 KASSERT(p->p_nlwps > 1);
723 error = cv_timedwait(&p->p_lwpcv, p->p_lock, 1);
724 break;
725 }
726
727 /*
728 * Break out if all LWPs are in _lwp_wait(). There are
729 * other ways to hang the process with _lwp_wait(), but the
730 * sleep is interruptable so little point checking for them.
731 */
732 if (p->p_nlwpwait == p->p_nlwps) {
733 error = EDEADLK;
734 break;
735 }
736
737 /*
738 * Sit around and wait for something to happen. We'll be
739 * awoken if any of the conditions examined change: if an
740 * LWP exits, is collected, or is detached.
741 */
742 if ((error = cv_wait_sig(&p->p_lwpcv, p->p_lock)) != 0)
743 break;
744 }
745
746 /*
747 * We didn't find any LWPs to collect, we may have received a
748 * signal, or some other condition has caused us to bail out.
749 *
750 * If waiting on a specific LWP, clear the waiters marker: some
751 * other LWP may want it. Then, kick all the remaining waiters
752 * so that they can re-check for zombies and for deadlock.
753 */
754 if (lid != 0) {
755 l2 = proc_find_lwp(p, lid);
756 KASSERT(l2 == NULL || l2->l_lid == lid);
757
758 if (l2 != NULL && l2->l_waiter == curlid)
759 l2->l_waiter = 0;
760 }
761 p->p_nlwpwait--;
762 l->l_waitingfor = 0;
763 cv_broadcast(&p->p_lwpcv);
764
765 return error;
766 }
767
768 /*
769 * Create a new LWP within process 'p2', using LWP 'l1' as a template.
770 * The new LWP is created in state LSIDL and must be set running,
771 * suspended, or stopped by the caller.
772 */
773 int
774 lwp_create(lwp_t *l1, proc_t *p2, vaddr_t uaddr, int flags,
775 void *stack, size_t stacksize, void (*func)(void *), void *arg,
776 lwp_t **rnewlwpp, int sclass, const sigset_t *sigmask,
777 const stack_t *sigstk)
778 {
779 struct lwp *l2;
780
781 KASSERT(l1 == curlwp || l1->l_proc == &proc0);
782
783 /*
784 * Enforce limits, excluding the first lwp and kthreads. We must
785 * use the process credentials here when adjusting the limit, as
786 * they are what's tied to the accounting entity. However for
787 * authorizing the action, we'll use the LWP's credentials.
788 */
789 mutex_enter(p2->p_lock);
790 if (p2->p_nlwps != 0 && p2 != &proc0) {
791 uid_t uid = kauth_cred_getuid(p2->p_cred);
792 int count = chglwpcnt(uid, 1);
793 if (__predict_false(count >
794 p2->p_rlimit[RLIMIT_NTHR].rlim_cur)) {
795 if (kauth_authorize_process(l1->l_cred,
796 KAUTH_PROCESS_RLIMIT, p2,
797 KAUTH_ARG(KAUTH_REQ_PROCESS_RLIMIT_BYPASS),
798 &p2->p_rlimit[RLIMIT_NTHR], KAUTH_ARG(RLIMIT_NTHR))
799 != 0) {
800 (void)chglwpcnt(uid, -1);
801 mutex_exit(p2->p_lock);
802 return EAGAIN;
803 }
804 }
805 }
806
807 /*
808 * First off, reap any detached LWP waiting to be collected.
809 * We can re-use its LWP structure and turnstile.
810 */
811 if ((l2 = p2->p_zomblwp) != NULL) {
812 p2->p_zomblwp = NULL;
813 lwp_free(l2, true, false);
814 /* p2 now unlocked by lwp_free() */
815 KASSERT(l2->l_ts != NULL);
816 KASSERT(l2->l_inheritedprio == -1);
817 KASSERT(SLIST_EMPTY(&l2->l_pi_lenders));
818 memset(&l2->l_startzero, 0, sizeof(*l2) -
819 offsetof(lwp_t, l_startzero));
820 } else {
821 mutex_exit(p2->p_lock);
822 l2 = pool_cache_get(lwp_cache, PR_WAITOK);
823 memset(&l2->l_startzero, 0, sizeof(*l2) -
824 offsetof(lwp_t, l_startzero));
825 SLIST_INIT(&l2->l_pi_lenders);
826 }
827
828 /*
829 * Because of lockless lookup via pid_table, the LWP can be locked
830 * and inspected briefly even after it's freed, so a few fields are
831 * kept stable.
832 */
833 KASSERT(l2->l_stat == LSIDL);
834 KASSERT(l2->l_cpu != NULL);
835 KASSERT(l2->l_ts != NULL);
836 KASSERT(l2->l_mutex == l2->l_cpu->ci_schedstate.spc_lwplock);
837
838 l2->l_proc = p2;
839 l2->l_refcnt = 0;
840 l2->l_class = sclass;
841
842 /*
843 * Allocate a process ID for this LWP. We need to do this now
844 * while we can still unwind if it fails. Because we're marked
845 * as LSIDL, no lookups by the ID will succeed.
846 *
847 * N.B. this will always succeed for the first LWP in a process,
848 * because proc_alloc_lwpid() will usurp the slot. Also note
849 * that l2->l_proc MUST be valid so that lookups of the proc
850 * will succeed, even if the LWP itself is not visible.
851 */
852 if (__predict_false(proc_alloc_lwpid(p2, l2) == -1)) {
853 pool_cache_put(lwp_cache, l2);
854 return EAGAIN;
855 }
856
857 /*
858 * If vfork(), we want the LWP to run fast and on the same CPU
859 * as its parent, so that it can reuse the VM context and cache
860 * footprint on the local CPU.
861 */
862 l2->l_boostpri = ((flags & LWP_VFORK) ? PRI_KERNEL : PRI_USER);
863 l2->l_priority = l1->l_priority;
864 l2->l_inheritedprio = -1;
865 l2->l_protectprio = -1;
866 l2->l_auxprio = -1;
867 l2->l_flag = 0;
868 l2->l_pflag = LP_MPSAFE;
869 TAILQ_INIT(&l2->l_ld_locks);
870 l2->l_psrefs = 0;
871 kmsan_lwp_alloc(l2);
872
873 /*
874 * For vfork, borrow parent's lwpctl context if it exists.
875 * This also causes us to return via lwp_userret.
876 */
877 if (flags & LWP_VFORK && l1->l_lwpctl) {
878 l2->l_lwpctl = l1->l_lwpctl;
879 l2->l_flag |= LW_LWPCTL;
880 }
881
882 /*
883 * If not the first LWP in the process, grab a reference to the
884 * descriptor table.
885 */
886 l2->l_fd = p2->p_fd;
887 if (p2->p_nlwps != 0) {
888 KASSERT(l1->l_proc == p2);
889 fd_hold(l2);
890 } else {
891 KASSERT(l1->l_proc != p2);
892 }
893
894 if (p2->p_flag & PK_SYSTEM) {
895 /* Mark it as a system LWP. */
896 l2->l_flag |= LW_SYSTEM;
897 }
898
899 kdtrace_thread_ctor(NULL, l2);
900 lwp_initspecific(l2);
901 sched_lwp_fork(l1, l2);
902 lwp_update_creds(l2);
903 callout_init(&l2->l_timeout_ch, CALLOUT_MPSAFE);
904 callout_setfunc(&l2->l_timeout_ch, sleepq_timeout, l2);
905 cv_init(&l2->l_sigcv, "sigwait");
906 cv_init(&l2->l_waitcv, "vfork");
907 l2->l_syncobj = &sched_syncobj;
908 PSREF_DEBUG_INIT_LWP(l2);
909
910 if (rnewlwpp != NULL)
911 *rnewlwpp = l2;
912
913 /*
914 * PCU state needs to be saved before calling uvm_lwp_fork() so that
915 * the MD cpu_lwp_fork() can copy the saved state to the new LWP.
916 */
917 pcu_save_all(l1);
918 #if PCU_UNIT_COUNT > 0
919 l2->l_pcu_valid = l1->l_pcu_valid;
920 #endif
921
922 uvm_lwp_setuarea(l2, uaddr);
923 uvm_lwp_fork(l1, l2, stack, stacksize, func, (arg != NULL) ? arg : l2);
924
925 mutex_enter(p2->p_lock);
926 if ((flags & LWP_DETACHED) != 0) {
927 l2->l_prflag = LPR_DETACHED;
928 p2->p_ndlwps++;
929 } else
930 l2->l_prflag = 0;
931
932 if (l1->l_proc == p2) {
933 /*
934 * These flags are set while p_lock is held. Copy with
935 * p_lock held too, so the LWP doesn't sneak into the
936 * process without them being set.
937 */
938 l2->l_flag |= (l1->l_flag & (LW_WEXIT | LW_WREBOOT | LW_WCORE));
939 } else {
940 /* fork(): pending core/exit doesn't apply to child. */
941 l2->l_flag |= (l1->l_flag & LW_WREBOOT);
942 }
943
944 l2->l_sigstk = *sigstk;
945 l2->l_sigmask = *sigmask;
946 TAILQ_INIT(&l2->l_sigpend.sp_info);
947 sigemptyset(&l2->l_sigpend.sp_set);
948 LIST_INSERT_HEAD(&p2->p_lwps, l2, l_sibling);
949 p2->p_nlwps++;
950 p2->p_nrlwps++;
951
952 KASSERT(l2->l_affinity == NULL);
953
954 /* Inherit the affinity mask. */
955 if (l1->l_affinity) {
956 /*
957 * Note that we hold the state lock while inheriting
958 * the affinity to avoid race with sched_setaffinity().
959 */
960 lwp_lock(l1);
961 if (l1->l_affinity) {
962 kcpuset_use(l1->l_affinity);
963 l2->l_affinity = l1->l_affinity;
964 }
965 lwp_unlock(l1);
966 }
967
968 /* Ensure a trip through lwp_userret() if needed. */
969 if ((l2->l_flag & LW_USERRET) != 0) {
970 lwp_need_userret(l2);
971 }
972
973 /* This marks the end of the "must be atomic" section. */
974 mutex_exit(p2->p_lock);
975
976 SDT_PROBE(proc, kernel, , lwp__create, l2, 0, 0, 0, 0);
977
978 mutex_enter(&proc_lock);
979 LIST_INSERT_HEAD(&alllwp, l2, l_list);
980 /* Inherit a processor-set */
981 l2->l_psid = l1->l_psid;
982 mutex_exit(&proc_lock);
983
984 SYSCALL_TIME_LWP_INIT(l2);
985
986 if (p2->p_emul->e_lwp_fork)
987 (*p2->p_emul->e_lwp_fork)(l1, l2);
988
989 return (0);
990 }
991
992 /*
993 * Set a new LWP running. If the process is stopping, then the LWP is
994 * created stopped.
995 */
996 void
997 lwp_start(lwp_t *l, int flags)
998 {
999 proc_t *p = l->l_proc;
1000
1001 mutex_enter(p->p_lock);
1002 lwp_lock(l);
1003 KASSERT(l->l_stat == LSIDL);
1004 if ((flags & LWP_SUSPENDED) != 0) {
1005 /* It'll suspend itself in lwp_userret(). */
1006 l->l_flag |= LW_WSUSPEND;
1007 lwp_need_userret(l);
1008 }
1009 if (p->p_stat == SSTOP || (p->p_sflag & PS_STOPPING) != 0) {
1010 KASSERT(l->l_wchan == NULL);
1011 l->l_stat = LSSTOP;
1012 p->p_nrlwps--;
1013 lwp_unlock(l);
1014 } else {
1015 setrunnable(l);
1016 /* LWP now unlocked */
1017 }
1018 mutex_exit(p->p_lock);
1019 }
1020
1021 /*
1022 * Called by MD code when a new LWP begins execution. Must be called
1023 * with the previous LWP locked (so at splsched), or if there is no
1024 * previous LWP, at splsched.
1025 */
1026 void
1027 lwp_startup(struct lwp *prev, struct lwp *new_lwp)
1028 {
1029 kmutex_t *lock;
1030
1031 KASSERTMSG(new_lwp == curlwp, "l %p curlwp %p prevlwp %p", new_lwp, curlwp, prev);
1032 KASSERT(kpreempt_disabled());
1033 KASSERT(prev != NULL);
1034 KASSERT((prev->l_pflag & LP_RUNNING) != 0);
1035 KASSERT(curcpu()->ci_mtx_count == -2);
1036
1037 /*
1038 * Immediately mark the previous LWP as no longer running and
1039 * unlock (to keep lock wait times short as possible). If a
1040 * zombie, don't touch after clearing LP_RUNNING as it could be
1041 * reaped by another CPU. Use atomic_store_release to ensure
1042 * this -- matches atomic_load_acquire in lwp_free.
1043 */
1044 lock = prev->l_mutex;
1045 if (__predict_false(prev->l_stat == LSZOMB)) {
1046 atomic_store_release(&prev->l_pflag,
1047 prev->l_pflag & ~LP_RUNNING);
1048 } else {
1049 prev->l_pflag &= ~LP_RUNNING;
1050 }
1051 mutex_spin_exit(lock);
1052
1053 /* Correct spin mutex count after mi_switch(). */
1054 curcpu()->ci_mtx_count = 0;
1055
1056 /* Install new VM context. */
1057 if (__predict_true(new_lwp->l_proc->p_vmspace)) {
1058 pmap_activate(new_lwp);
1059 }
1060
1061 /* We remain at IPL_SCHED from mi_switch() - reset it. */
1062 spl0();
1063
1064 LOCKDEBUG_BARRIER(NULL, 0);
1065 SDT_PROBE(proc, kernel, , lwp__start, new_lwp, 0, 0, 0, 0);
1066
1067 /* For kthreads, acquire kernel lock if not MPSAFE. */
1068 if (__predict_false((new_lwp->l_pflag & LP_MPSAFE) == 0)) {
1069 KERNEL_LOCK(1, new_lwp);
1070 }
1071 }
1072
1073 /*
1074 * Exit an LWP.
1075 *
1076 * *** WARNING *** This can be called with (l != curlwp) in error paths.
1077 */
1078 void
1079 lwp_exit(struct lwp *l)
1080 {
1081 struct proc *p = l->l_proc;
1082 struct lwp *l2;
1083 bool current;
1084
1085 current = (l == curlwp);
1086
1087 KASSERT(current || l->l_stat == LSIDL);
1088 KASSERT(current || l->l_target_cpu == NULL);
1089 KASSERT(p == curproc);
1090
1091 SDT_PROBE(proc, kernel, , lwp__exit, l, 0, 0, 0, 0);
1092
1093 /* Verify that we hold no locks; for DIAGNOSTIC check kernel_lock. */
1094 LOCKDEBUG_BARRIER(NULL, 0);
1095 KASSERTMSG(curcpu()->ci_biglock_count == 0, "kernel_lock leaked");
1096
1097 /*
1098 * If we are the last live LWP in a process, we need to exit the
1099 * entire process. We do so with an exit status of zero, because
1100 * it's a "controlled" exit, and because that's what Solaris does.
1101 *
1102 * We are not quite a zombie yet, but for accounting purposes we
1103 * must increment the count of zombies here.
1104 *
1105 * Note: the last LWP's specificdata will be deleted here.
1106 */
1107 mutex_enter(p->p_lock);
1108 if (p->p_nlwps - p->p_nzlwps == 1) {
1109 KASSERT(current == true);
1110 KASSERT(p != &proc0);
1111 exit1(l, 0, 0);
1112 /* NOTREACHED */
1113 }
1114 p->p_nzlwps++;
1115
1116 /*
1117 * Perform any required thread cleanup. Do this early so
1118 * anyone wanting to look us up with lwp_getref_lwpid() will
1119 * fail to find us before we become a zombie.
1120 *
1121 * N.B. this will unlock p->p_lock on our behalf.
1122 */
1123 lwp_thread_cleanup(l);
1124
1125 if (p->p_emul->e_lwp_exit)
1126 (*p->p_emul->e_lwp_exit)(l);
1127
1128 /* Drop filedesc reference. */
1129 fd_free();
1130
1131 /* Release fstrans private data. */
1132 fstrans_lwp_dtor(l);
1133
1134 /* Delete the specificdata while it's still safe to sleep. */
1135 lwp_finispecific(l);
1136
1137 /*
1138 * Release our cached credentials.
1139 */
1140 kauth_cred_free(l->l_cred);
1141 callout_destroy(&l->l_timeout_ch);
1142
1143 /*
1144 * If traced, report LWP exit event to the debugger.
1145 *
1146 * Remove the LWP from the global list.
1147 * Free its LID from the PID namespace if needed.
1148 */
1149 mutex_enter(&proc_lock);
1150
1151 if ((p->p_slflag & (PSL_TRACED|PSL_TRACELWP_EXIT)) ==
1152 (PSL_TRACED|PSL_TRACELWP_EXIT)) {
1153 mutex_enter(p->p_lock);
1154 if (ISSET(p->p_sflag, PS_WEXIT)) {
1155 mutex_exit(p->p_lock);
1156 /*
1157 * We are exiting, bail out without informing parent
1158 * about a terminating LWP as it would deadlock.
1159 */
1160 } else {
1161 eventswitch(TRAP_LWP, PTRACE_LWP_EXIT, l->l_lid);
1162 mutex_enter(&proc_lock);
1163 }
1164 }
1165
1166 LIST_REMOVE(l, l_list);
1167 mutex_exit(&proc_lock);
1168
1169 /*
1170 * Get rid of all references to the LWP that others (e.g. procfs)
1171 * may have, and mark the LWP as a zombie. If the LWP is detached,
1172 * mark it waiting for collection in the proc structure. Note that
1173 * before we can do that, we need to free any other dead, deatched
1174 * LWP waiting to meet its maker.
1175 *
1176 * All conditions need to be observed upon under the same hold of
1177 * p_lock, because if the lock is dropped any of them can change.
1178 */
1179 mutex_enter(p->p_lock);
1180 for (;;) {
1181 if (lwp_drainrefs(l))
1182 continue;
1183 if ((l->l_prflag & LPR_DETACHED) != 0) {
1184 if ((l2 = p->p_zomblwp) != NULL) {
1185 p->p_zomblwp = NULL;
1186 lwp_free(l2, false, false);
1187 /* proc now unlocked */
1188 mutex_enter(p->p_lock);
1189 continue;
1190 }
1191 p->p_zomblwp = l;
1192 }
1193 break;
1194 }
1195
1196 /*
1197 * If we find a pending signal for the process and we have been
1198 * asked to check for signals, then we lose: arrange to have
1199 * all other LWPs in the process check for signals.
1200 */
1201 if ((l->l_flag & LW_PENDSIG) != 0 &&
1202 firstsig(&p->p_sigpend.sp_set) != 0) {
1203 LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
1204 lwp_lock(l2);
1205 signotify(l2);
1206 lwp_unlock(l2);
1207 }
1208 }
1209
1210 /*
1211 * Release any PCU resources before becoming a zombie.
1212 */
1213 pcu_discard_all(l);
1214
1215 lwp_lock(l);
1216 l->l_stat = LSZOMB;
1217 if (l->l_name != NULL) {
1218 strcpy(l->l_name, "(zombie)");
1219 }
1220 lwp_unlock(l);
1221 p->p_nrlwps--;
1222 if (l->l_lwpctl != NULL)
1223 l->l_lwpctl->lc_curcpu = LWPCTL_CPU_EXITED;
1224 mutex_exit(p->p_lock);
1225 cv_broadcast(&p->p_lwpcv);
1226
1227 /*
1228 * We can no longer block. At this point, lwp_free() may already
1229 * be gunning for us. On a multi-CPU system, we may be off p_lwps.
1230 *
1231 * Free MD LWP resources.
1232 */
1233 cpu_lwp_free(l, 0);
1234
1235 if (current) {
1236 /* Switch away into oblivion. */
1237 lwp_lock(l);
1238 spc_lock(l->l_cpu);
1239 mi_switch(l);
1240 panic("lwp_exit");
1241 }
1242 }
1243
1244 /*
1245 * Free a dead LWP's remaining resources.
1246 *
1247 * XXXLWP limits.
1248 */
1249 void
1250 lwp_free(struct lwp *l, bool recycle, bool last)
1251 {
1252 struct proc *p = l->l_proc;
1253 struct rusage *ru;
1254 ksiginfoq_t kq;
1255
1256 KASSERT(l != curlwp);
1257 KASSERT(last || mutex_owned(p->p_lock));
1258
1259 /*
1260 * We use the process credentials instead of the lwp credentials here
1261 * because the lwp credentials maybe cached (just after a setuid call)
1262 * and we don't want pay for syncing, since the lwp is going away
1263 * anyway
1264 */
1265 if (p != &proc0 && p->p_nlwps != 1)
1266 (void)chglwpcnt(kauth_cred_getuid(p->p_cred), -1);
1267
1268 /*
1269 * In the unlikely event that the LWP is still on the CPU,
1270 * then spin until it has switched away.
1271 *
1272 * atomic_load_acquire matches atomic_store_release in
1273 * lwp_startup and mi_switch.
1274 */
1275 while (__predict_false((atomic_load_acquire(&l->l_pflag) & LP_RUNNING)
1276 != 0)) {
1277 SPINLOCK_BACKOFF_HOOK;
1278 }
1279
1280 /*
1281 * Now that the LWP's known off the CPU, reset its state back to
1282 * LSIDL, which defeats anything that might have gotten a hold on
1283 * the LWP via pid_table before the ID was freed. It's important
1284 * to do this with both the LWP locked and p_lock held.
1285 *
1286 * Also reset the CPU and lock pointer back to curcpu(), since the
1287 * LWP will in all likelyhood be cached with the current CPU in
1288 * lwp_cache when we free it and later allocated from there again
1289 * (avoid incidental lock contention).
1290 */
1291 lwp_lock(l);
1292 l->l_stat = LSIDL;
1293 l->l_cpu = curcpu();
1294 lwp_unlock_to(l, l->l_cpu->ci_schedstate.spc_lwplock);
1295
1296 /*
1297 * If this was not the last LWP in the process, then adjust counters
1298 * and unlock. This is done differently for the last LWP in exit1().
1299 */
1300 if (!last) {
1301 /*
1302 * Add the LWP's run time to the process' base value.
1303 * This needs to co-incide with coming off p_lwps.
1304 */
1305 bintime_add(&p->p_rtime, &l->l_rtime);
1306 p->p_pctcpu += l->l_pctcpu;
1307 ru = &p->p_stats->p_ru;
1308 ruadd(ru, &l->l_ru);
1309 LIST_REMOVE(l, l_sibling);
1310 p->p_nlwps--;
1311 p->p_nzlwps--;
1312 if ((l->l_prflag & LPR_DETACHED) != 0)
1313 p->p_ndlwps--;
1314 mutex_exit(p->p_lock);
1315
1316 /*
1317 * Have any LWPs sleeping in lwp_wait() recheck for
1318 * deadlock.
1319 */
1320 cv_broadcast(&p->p_lwpcv);
1321
1322 /* Free the LWP ID. */
1323 mutex_enter(&proc_lock);
1324 proc_free_lwpid(p, l->l_lid);
1325 mutex_exit(&proc_lock);
1326 }
1327
1328 /*
1329 * Destroy the LWP's remaining signal information.
1330 */
1331 ksiginfo_queue_init(&kq);
1332 sigclear(&l->l_sigpend, NULL, &kq);
1333 ksiginfo_queue_drain(&kq);
1334 cv_destroy(&l->l_sigcv);
1335 cv_destroy(&l->l_waitcv);
1336
1337 /*
1338 * Free lwpctl structure and affinity.
1339 */
1340 if (l->l_lwpctl) {
1341 lwp_ctl_free(l);
1342 }
1343 if (l->l_affinity) {
1344 kcpuset_unuse(l->l_affinity, NULL);
1345 l->l_affinity = NULL;
1346 }
1347
1348 /*
1349 * Free remaining data structures and the LWP itself unless the
1350 * caller wants to recycle.
1351 */
1352 if (l->l_name != NULL)
1353 kmem_free(l->l_name, MAXCOMLEN);
1354
1355 kmsan_lwp_free(l);
1356 kcov_lwp_free(l);
1357 cpu_lwp_free2(l);
1358 uvm_lwp_exit(l);
1359
1360 KASSERT(SLIST_EMPTY(&l->l_pi_lenders));
1361 KASSERT(l->l_inheritedprio == -1);
1362 KASSERT(l->l_blcnt == 0);
1363 kdtrace_thread_dtor(NULL, l);
1364 if (!recycle)
1365 pool_cache_put(lwp_cache, l);
1366 }
1367
1368 /*
1369 * Migrate the LWP to the another CPU. Unlocks the LWP.
1370 */
1371 void
1372 lwp_migrate(lwp_t *l, struct cpu_info *tci)
1373 {
1374 struct schedstate_percpu *tspc;
1375 int lstat = l->l_stat;
1376
1377 KASSERT(lwp_locked(l, NULL));
1378 KASSERT(tci != NULL);
1379
1380 /* If LWP is still on the CPU, it must be handled like LSONPROC */
1381 if ((l->l_pflag & LP_RUNNING) != 0) {
1382 lstat = LSONPROC;
1383 }
1384
1385 /*
1386 * The destination CPU could be changed while previous migration
1387 * was not finished.
1388 */
1389 if (l->l_target_cpu != NULL) {
1390 l->l_target_cpu = tci;
1391 lwp_unlock(l);
1392 return;
1393 }
1394
1395 /* Nothing to do if trying to migrate to the same CPU */
1396 if (l->l_cpu == tci) {
1397 lwp_unlock(l);
1398 return;
1399 }
1400
1401 KASSERT(l->l_target_cpu == NULL);
1402 tspc = &tci->ci_schedstate;
1403 switch (lstat) {
1404 case LSRUN:
1405 l->l_target_cpu = tci;
1406 break;
1407 case LSSLEEP:
1408 l->l_cpu = tci;
1409 break;
1410 case LSIDL:
1411 case LSSTOP:
1412 case LSSUSPENDED:
1413 l->l_cpu = tci;
1414 if (l->l_wchan == NULL) {
1415 lwp_unlock_to(l, tspc->spc_lwplock);
1416 return;
1417 }
1418 break;
1419 case LSONPROC:
1420 l->l_target_cpu = tci;
1421 spc_lock(l->l_cpu);
1422 sched_resched_cpu(l->l_cpu, PRI_USER_RT, true);
1423 /* spc now unlocked */
1424 break;
1425 }
1426 lwp_unlock(l);
1427 }
1428
1429 #define lwp_find_exclude(l) \
1430 ((l)->l_stat == LSIDL || (l)->l_stat == LSZOMB)
1431
1432 /*
1433 * Find the LWP in the process. Arguments may be zero, in such case,
1434 * the calling process and first LWP in the list will be used.
1435 * On success - returns proc locked.
1436 *
1437 * => pid == 0 -> look in curproc.
1438 * => pid == -1 -> match any proc.
1439 * => otherwise look up the proc.
1440 *
1441 * => lid == 0 -> first LWP in the proc
1442 * => otherwise specific LWP
1443 */
1444 struct lwp *
1445 lwp_find2(pid_t pid, lwpid_t lid)
1446 {
1447 proc_t *p;
1448 lwp_t *l;
1449
1450 /* First LWP of specified proc. */
1451 if (lid == 0) {
1452 switch (pid) {
1453 case -1:
1454 /* No lookup keys. */
1455 return NULL;
1456 case 0:
1457 p = curproc;
1458 mutex_enter(p->p_lock);
1459 break;
1460 default:
1461 mutex_enter(&proc_lock);
1462 p = proc_find(pid);
1463 if (__predict_false(p == NULL)) {
1464 mutex_exit(&proc_lock);
1465 return NULL;
1466 }
1467 mutex_enter(p->p_lock);
1468 mutex_exit(&proc_lock);
1469 break;
1470 }
1471 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1472 if (__predict_true(!lwp_find_exclude(l)))
1473 break;
1474 }
1475 goto out;
1476 }
1477
1478 l = proc_find_lwp_acquire_proc(lid, &p);
1479 if (l == NULL)
1480 return NULL;
1481 KASSERT(p != NULL);
1482 KASSERT(mutex_owned(p->p_lock));
1483
1484 if (__predict_false(lwp_find_exclude(l))) {
1485 l = NULL;
1486 goto out;
1487 }
1488
1489 /* Apply proc filter, if applicable. */
1490 switch (pid) {
1491 case -1:
1492 /* Match anything. */
1493 break;
1494 case 0:
1495 if (p != curproc)
1496 l = NULL;
1497 break;
1498 default:
1499 if (p->p_pid != pid)
1500 l = NULL;
1501 break;
1502 }
1503
1504 out:
1505 if (__predict_false(l == NULL)) {
1506 mutex_exit(p->p_lock);
1507 }
1508 return l;
1509 }
1510
1511 /*
1512 * Look up a live LWP within the specified process.
1513 *
1514 * Must be called with p->p_lock held (as it looks at the radix tree,
1515 * and also wants to exclude idle and zombie LWPs).
1516 */
1517 struct lwp *
1518 lwp_find(struct proc *p, lwpid_t id)
1519 {
1520 struct lwp *l;
1521
1522 KASSERT(mutex_owned(p->p_lock));
1523
1524 l = proc_find_lwp(p, id);
1525 KASSERT(l == NULL || l->l_lid == id);
1526
1527 /*
1528 * No need to lock - all of these conditions will
1529 * be visible with the process level mutex held.
1530 */
1531 if (__predict_false(l != NULL && lwp_find_exclude(l)))
1532 l = NULL;
1533
1534 return l;
1535 }
1536
1537 /*
1538 * Update an LWP's cached credentials to mirror the process' master copy.
1539 *
1540 * This happens early in the syscall path, on user trap, and on LWP
1541 * creation. A long-running LWP can also voluntarily choose to update
1542 * its credentials by calling this routine. This may be called from
1543 * LWP_CACHE_CREDS(), which checks l->l_prflag & LPR_CRMOD beforehand.
1544 */
1545 void
1546 lwp_update_creds(struct lwp *l)
1547 {
1548 kauth_cred_t oc;
1549 struct proc *p;
1550
1551 p = l->l_proc;
1552 oc = l->l_cred;
1553
1554 mutex_enter(p->p_lock);
1555 kauth_cred_hold(p->p_cred);
1556 l->l_cred = p->p_cred;
1557 l->l_prflag &= ~LPR_CRMOD;
1558 mutex_exit(p->p_lock);
1559 if (oc != NULL)
1560 kauth_cred_free(oc);
1561 }
1562
1563 /*
1564 * Verify that an LWP is locked, and optionally verify that the lock matches
1565 * one we specify.
1566 */
1567 int
1568 lwp_locked(struct lwp *l, kmutex_t *mtx)
1569 {
1570 kmutex_t *cur = l->l_mutex;
1571
1572 return mutex_owned(cur) && (mtx == cur || mtx == NULL);
1573 }
1574
1575 /*
1576 * Lend a new mutex to an LWP. The old mutex must be held.
1577 */
1578 kmutex_t *
1579 lwp_setlock(struct lwp *l, kmutex_t *mtx)
1580 {
1581 kmutex_t *oldmtx = l->l_mutex;
1582
1583 KASSERT(mutex_owned(oldmtx));
1584
1585 atomic_store_release(&l->l_mutex, mtx);
1586 return oldmtx;
1587 }
1588
1589 /*
1590 * Lend a new mutex to an LWP, and release the old mutex. The old mutex
1591 * must be held.
1592 */
1593 void
1594 lwp_unlock_to(struct lwp *l, kmutex_t *mtx)
1595 {
1596 kmutex_t *old;
1597
1598 KASSERT(lwp_locked(l, NULL));
1599
1600 old = l->l_mutex;
1601 atomic_store_release(&l->l_mutex, mtx);
1602 mutex_spin_exit(old);
1603 }
1604
1605 int
1606 lwp_trylock(struct lwp *l)
1607 {
1608 kmutex_t *old;
1609
1610 for (;;) {
1611 if (!mutex_tryenter(old = atomic_load_consume(&l->l_mutex)))
1612 return 0;
1613 if (__predict_true(atomic_load_relaxed(&l->l_mutex) == old))
1614 return 1;
1615 mutex_spin_exit(old);
1616 }
1617 }
1618
1619 void
1620 lwp_unsleep(lwp_t *l, bool unlock)
1621 {
1622
1623 KASSERT(mutex_owned(l->l_mutex));
1624 (*l->l_syncobj->sobj_unsleep)(l, unlock);
1625 }
1626
1627 /*
1628 * Lock an LWP.
1629 */
1630 void
1631 lwp_lock(lwp_t *l)
1632 {
1633 kmutex_t *old = atomic_load_consume(&l->l_mutex);
1634
1635 /*
1636 * Note: mutex_spin_enter() will have posted a read barrier.
1637 * Re-test l->l_mutex. If it has changed, we need to try again.
1638 */
1639 mutex_spin_enter(old);
1640 while (__predict_false(atomic_load_relaxed(&l->l_mutex) != old)) {
1641 mutex_spin_exit(old);
1642 old = atomic_load_consume(&l->l_mutex);
1643 mutex_spin_enter(old);
1644 }
1645 }
1646
1647 /*
1648 * Unlock an LWP.
1649 */
1650 void
1651 lwp_unlock(lwp_t *l)
1652 {
1653
1654 mutex_spin_exit(l->l_mutex);
1655 }
1656
1657 void
1658 lwp_changepri(lwp_t *l, pri_t pri)
1659 {
1660
1661 KASSERT(mutex_owned(l->l_mutex));
1662
1663 if (l->l_priority == pri)
1664 return;
1665
1666 (*l->l_syncobj->sobj_changepri)(l, pri);
1667 KASSERT(l->l_priority == pri);
1668 }
1669
1670 void
1671 lwp_lendpri(lwp_t *l, pri_t pri)
1672 {
1673 KASSERT(mutex_owned(l->l_mutex));
1674
1675 (*l->l_syncobj->sobj_lendpri)(l, pri);
1676 KASSERT(l->l_inheritedprio == pri);
1677 }
1678
1679 pri_t
1680 lwp_eprio(lwp_t *l)
1681 {
1682 pri_t pri = l->l_priority;
1683
1684 KASSERT(mutex_owned(l->l_mutex));
1685
1686 /*
1687 * Timeshared/user LWPs get a temporary priority boost for blocking
1688 * in kernel. This is key to good interactive response on a loaded
1689 * system: without it, things will seem very sluggish to the user.
1690 *
1691 * The function of the boost is to get the LWP onto a CPU and
1692 * running quickly. Once that happens the LWP loses the priority
1693 * boost and could be preempted very quickly by another LWP but that
1694 * won't happen often enough to be a annoyance.
1695 */
1696 if (pri <= MAXPRI_USER && l->l_boostpri > MAXPRI_USER)
1697 pri = (pri >> 1) + l->l_boostpri;
1698
1699 return MAX(l->l_auxprio, pri);
1700 }
1701
1702 /*
1703 * Handle exceptions for mi_userret(). Called if a member of LW_USERRET is
1704 * set or a preemption is required.
1705 */
1706 void
1707 lwp_userret(struct lwp *l)
1708 {
1709 struct proc *p;
1710 int sig, f;
1711
1712 KASSERT(l == curlwp);
1713 KASSERT(l->l_stat == LSONPROC);
1714 p = l->l_proc;
1715
1716 for (;;) {
1717 /*
1718 * This is the main location that user preemptions are
1719 * processed.
1720 */
1721 preempt_point();
1722
1723 /*
1724 * It is safe to do this unlocked and without raised SPL,
1725 * since whenever a flag of interest is added to l_flag the
1726 * LWP will take an AST and come down this path again. If a
1727 * remote CPU posts the AST, it will be done with an IPI
1728 * (strongly synchronising).
1729 */
1730 if ((f = atomic_load_relaxed(&l->l_flag) & LW_USERRET) == 0) {
1731 return;
1732 }
1733
1734 /*
1735 * Process pending signals first, unless the process
1736 * is dumping core or exiting, where we will instead
1737 * enter the LW_WSUSPEND case below.
1738 */
1739 if ((f & (LW_PENDSIG | LW_WCORE | LW_WEXIT)) == LW_PENDSIG) {
1740 mutex_enter(p->p_lock);
1741 while ((sig = issignal(l)) != 0)
1742 postsig(sig);
1743 mutex_exit(p->p_lock);
1744 continue;
1745 }
1746
1747 /*
1748 * Core-dump or suspend pending.
1749 *
1750 * In case of core dump, suspend ourselves, so that the kernel
1751 * stack and therefore the userland registers saved in the
1752 * trapframe are around for coredump() to write them out.
1753 * We also need to save any PCU resources that we have so that
1754 * they accessible for coredump(). We issue a wakeup on
1755 * p->p_lwpcv so that sigexit() will write the core file out
1756 * once all other LWPs are suspended.
1757 */
1758 if ((f & LW_WSUSPEND) != 0) {
1759 pcu_save_all(l);
1760 mutex_enter(p->p_lock);
1761 p->p_nrlwps--;
1762 lwp_lock(l);
1763 l->l_stat = LSSUSPENDED;
1764 lwp_unlock(l);
1765 mutex_exit(p->p_lock);
1766 cv_broadcast(&p->p_lwpcv);
1767 lwp_lock(l);
1768 spc_lock(l->l_cpu);
1769 mi_switch(l);
1770 continue;
1771 }
1772
1773 /*
1774 * Process is exiting. The core dump and signal cases must
1775 * be handled first.
1776 */
1777 if ((f & LW_WEXIT) != 0) {
1778 lwp_exit(l);
1779 KASSERT(0);
1780 /* NOTREACHED */
1781 }
1782
1783 /*
1784 * Update lwpctl processor (for vfork child_return).
1785 */
1786 if ((f & LW_LWPCTL) != 0) {
1787 lwp_lock(l);
1788 KASSERT(kpreempt_disabled());
1789 l->l_lwpctl->lc_curcpu = (int)cpu_index(l->l_cpu);
1790 l->l_lwpctl->lc_pctr++;
1791 l->l_flag &= ~LW_LWPCTL;
1792 lwp_unlock(l);
1793 continue;
1794 }
1795 }
1796 }
1797
1798 /*
1799 * Force an LWP to enter the kernel, to take a trip through lwp_userret().
1800 */
1801 void
1802 lwp_need_userret(struct lwp *l)
1803 {
1804
1805 KASSERT(!cpu_intr_p());
1806 KASSERT(lwp_locked(l, NULL) || l->l_stat == LSIDL);
1807
1808 /*
1809 * If the LWP is in any state other than LSONPROC, we know that it
1810 * is executing in-kernel and will hit userret() on the way out.
1811 *
1812 * If the LWP is curlwp, then we know we'll be back out to userspace
1813 * soon (can't be called from a hardware interrupt here).
1814 *
1815 * Otherwise, we can't be sure what the LWP is doing, so first make
1816 * sure the update to l_flag will be globally visible, and then
1817 * force the LWP to take a trip through trap() where it will do
1818 * userret().
1819 */
1820 if (l->l_stat == LSONPROC && l != curlwp) {
1821 membar_producer();
1822 cpu_signotify(l);
1823 }
1824 }
1825
1826 /*
1827 * Add one reference to an LWP. This will prevent the LWP from
1828 * exiting, thus keep the lwp structure and PCB around to inspect.
1829 */
1830 void
1831 lwp_addref(struct lwp *l)
1832 {
1833 KASSERT(mutex_owned(l->l_proc->p_lock));
1834 KASSERT(l->l_stat != LSZOMB);
1835 l->l_refcnt++;
1836 }
1837
1838 /*
1839 * Remove one reference to an LWP. If this is the last reference,
1840 * then we must finalize the LWP's death.
1841 */
1842 void
1843 lwp_delref(struct lwp *l)
1844 {
1845 struct proc *p = l->l_proc;
1846
1847 mutex_enter(p->p_lock);
1848 lwp_delref2(l);
1849 mutex_exit(p->p_lock);
1850 }
1851
1852 /*
1853 * Remove one reference to an LWP. If this is the last reference,
1854 * then we must finalize the LWP's death. The proc mutex is held
1855 * on entry.
1856 */
1857 void
1858 lwp_delref2(struct lwp *l)
1859 {
1860 struct proc *p = l->l_proc;
1861
1862 KASSERT(mutex_owned(p->p_lock));
1863 KASSERT(l->l_stat != LSZOMB);
1864 KASSERT(l->l_refcnt > 0);
1865
1866 if (--l->l_refcnt == 0)
1867 cv_broadcast(&p->p_lwpcv);
1868 }
1869
1870 /*
1871 * Drain all references to the current LWP. Returns true if
1872 * we blocked.
1873 */
1874 bool
1875 lwp_drainrefs(struct lwp *l)
1876 {
1877 struct proc *p = l->l_proc;
1878 bool rv = false;
1879
1880 KASSERT(mutex_owned(p->p_lock));
1881
1882 l->l_prflag |= LPR_DRAINING;
1883
1884 while (l->l_refcnt > 0) {
1885 rv = true;
1886 cv_wait(&p->p_lwpcv, p->p_lock);
1887 }
1888 return rv;
1889 }
1890
1891 /*
1892 * Return true if the specified LWP is 'alive'. Only p->p_lock need
1893 * be held.
1894 */
1895 bool
1896 lwp_alive(lwp_t *l)
1897 {
1898
1899 KASSERT(mutex_owned(l->l_proc->p_lock));
1900
1901 switch (l->l_stat) {
1902 case LSSLEEP:
1903 case LSRUN:
1904 case LSONPROC:
1905 case LSSTOP:
1906 case LSSUSPENDED:
1907 return true;
1908 default:
1909 return false;
1910 }
1911 }
1912
1913 /*
1914 * Return first live LWP in the process.
1915 */
1916 lwp_t *
1917 lwp_find_first(proc_t *p)
1918 {
1919 lwp_t *l;
1920
1921 KASSERT(mutex_owned(p->p_lock));
1922
1923 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1924 if (lwp_alive(l)) {
1925 return l;
1926 }
1927 }
1928
1929 return NULL;
1930 }
1931
1932 /*
1933 * Allocate a new lwpctl structure for a user LWP.
1934 */
1935 int
1936 lwp_ctl_alloc(vaddr_t *uaddr)
1937 {
1938 lcproc_t *lp;
1939 u_int bit, i, offset;
1940 struct uvm_object *uao;
1941 int error;
1942 lcpage_t *lcp;
1943 proc_t *p;
1944 lwp_t *l;
1945
1946 l = curlwp;
1947 p = l->l_proc;
1948
1949 /* don't allow a vforked process to create lwp ctls */
1950 if (p->p_lflag & PL_PPWAIT)
1951 return EBUSY;
1952
1953 if (l->l_lcpage != NULL) {
1954 lcp = l->l_lcpage;
1955 *uaddr = lcp->lcp_uaddr + (vaddr_t)l->l_lwpctl - lcp->lcp_kaddr;
1956 return 0;
1957 }
1958
1959 /* First time around, allocate header structure for the process. */
1960 if ((lp = p->p_lwpctl) == NULL) {
1961 lp = kmem_alloc(sizeof(*lp), KM_SLEEP);
1962 mutex_init(&lp->lp_lock, MUTEX_DEFAULT, IPL_NONE);
1963 lp->lp_uao = NULL;
1964 TAILQ_INIT(&lp->lp_pages);
1965 mutex_enter(p->p_lock);
1966 if (p->p_lwpctl == NULL) {
1967 p->p_lwpctl = lp;
1968 mutex_exit(p->p_lock);
1969 } else {
1970 mutex_exit(p->p_lock);
1971 mutex_destroy(&lp->lp_lock);
1972 kmem_free(lp, sizeof(*lp));
1973 lp = p->p_lwpctl;
1974 }
1975 }
1976
1977 /*
1978 * Set up an anonymous memory region to hold the shared pages.
1979 * Map them into the process' address space. The user vmspace
1980 * gets the first reference on the UAO.
1981 */
1982 mutex_enter(&lp->lp_lock);
1983 if (lp->lp_uao == NULL) {
1984 lp->lp_uao = uao_create(LWPCTL_UAREA_SZ, 0);
1985 lp->lp_cur = 0;
1986 lp->lp_max = LWPCTL_UAREA_SZ;
1987 lp->lp_uva = p->p_emul->e_vm_default_addr(p,
1988 (vaddr_t)p->p_vmspace->vm_daddr, LWPCTL_UAREA_SZ,
1989 p->p_vmspace->vm_map.flags & VM_MAP_TOPDOWN);
1990 error = uvm_map(&p->p_vmspace->vm_map, &lp->lp_uva,
1991 LWPCTL_UAREA_SZ, lp->lp_uao, 0, 0, UVM_MAPFLAG(UVM_PROT_RW,
1992 UVM_PROT_RW, UVM_INH_NONE, UVM_ADV_NORMAL, 0));
1993 if (error != 0) {
1994 uao_detach(lp->lp_uao);
1995 lp->lp_uao = NULL;
1996 mutex_exit(&lp->lp_lock);
1997 return error;
1998 }
1999 }
2000
2001 /* Get a free block and allocate for this LWP. */
2002 TAILQ_FOREACH(lcp, &lp->lp_pages, lcp_chain) {
2003 if (lcp->lcp_nfree != 0)
2004 break;
2005 }
2006 if (lcp == NULL) {
2007 /* Nothing available - try to set up a free page. */
2008 if (lp->lp_cur == lp->lp_max) {
2009 mutex_exit(&lp->lp_lock);
2010 return ENOMEM;
2011 }
2012 lcp = kmem_alloc(LWPCTL_LCPAGE_SZ, KM_SLEEP);
2013
2014 /*
2015 * Wire the next page down in kernel space. Since this
2016 * is a new mapping, we must add a reference.
2017 */
2018 uao = lp->lp_uao;
2019 (*uao->pgops->pgo_reference)(uao);
2020 lcp->lcp_kaddr = vm_map_min(kernel_map);
2021 error = uvm_map(kernel_map, &lcp->lcp_kaddr, PAGE_SIZE,
2022 uao, lp->lp_cur, PAGE_SIZE,
2023 UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW,
2024 UVM_INH_NONE, UVM_ADV_RANDOM, 0));
2025 if (error != 0) {
2026 mutex_exit(&lp->lp_lock);
2027 kmem_free(lcp, LWPCTL_LCPAGE_SZ);
2028 (*uao->pgops->pgo_detach)(uao);
2029 return error;
2030 }
2031 error = uvm_map_pageable(kernel_map, lcp->lcp_kaddr,
2032 lcp->lcp_kaddr + PAGE_SIZE, FALSE, 0);
2033 if (error != 0) {
2034 mutex_exit(&lp->lp_lock);
2035 uvm_unmap(kernel_map, lcp->lcp_kaddr,
2036 lcp->lcp_kaddr + PAGE_SIZE);
2037 kmem_free(lcp, LWPCTL_LCPAGE_SZ);
2038 return error;
2039 }
2040 /* Prepare the page descriptor and link into the list. */
2041 lcp->lcp_uaddr = lp->lp_uva + lp->lp_cur;
2042 lp->lp_cur += PAGE_SIZE;
2043 lcp->lcp_nfree = LWPCTL_PER_PAGE;
2044 lcp->lcp_rotor = 0;
2045 memset(lcp->lcp_bitmap, 0xff, LWPCTL_BITMAP_SZ);
2046 TAILQ_INSERT_HEAD(&lp->lp_pages, lcp, lcp_chain);
2047 }
2048 for (i = lcp->lcp_rotor; lcp->lcp_bitmap[i] == 0;) {
2049 if (++i >= LWPCTL_BITMAP_ENTRIES)
2050 i = 0;
2051 }
2052 bit = ffs(lcp->lcp_bitmap[i]) - 1;
2053 lcp->lcp_bitmap[i] ^= (1U << bit);
2054 lcp->lcp_rotor = i;
2055 lcp->lcp_nfree--;
2056 l->l_lcpage = lcp;
2057 offset = (i << 5) + bit;
2058 l->l_lwpctl = (lwpctl_t *)lcp->lcp_kaddr + offset;
2059 *uaddr = lcp->lcp_uaddr + offset * sizeof(lwpctl_t);
2060 mutex_exit(&lp->lp_lock);
2061
2062 KPREEMPT_DISABLE(l);
2063 l->l_lwpctl->lc_curcpu = (int)cpu_index(curcpu());
2064 KPREEMPT_ENABLE(l);
2065
2066 return 0;
2067 }
2068
2069 /*
2070 * Free an lwpctl structure back to the per-process list.
2071 */
2072 void
2073 lwp_ctl_free(lwp_t *l)
2074 {
2075 struct proc *p = l->l_proc;
2076 lcproc_t *lp;
2077 lcpage_t *lcp;
2078 u_int map, offset;
2079
2080 /* don't free a lwp context we borrowed for vfork */
2081 if (p->p_lflag & PL_PPWAIT) {
2082 l->l_lwpctl = NULL;
2083 return;
2084 }
2085
2086 lp = p->p_lwpctl;
2087 KASSERT(lp != NULL);
2088
2089 lcp = l->l_lcpage;
2090 offset = (u_int)((lwpctl_t *)l->l_lwpctl - (lwpctl_t *)lcp->lcp_kaddr);
2091 KASSERT(offset < LWPCTL_PER_PAGE);
2092
2093 mutex_enter(&lp->lp_lock);
2094 lcp->lcp_nfree++;
2095 map = offset >> 5;
2096 lcp->lcp_bitmap[map] |= (1U << (offset & 31));
2097 if (lcp->lcp_bitmap[lcp->lcp_rotor] == 0)
2098 lcp->lcp_rotor = map;
2099 if (TAILQ_FIRST(&lp->lp_pages)->lcp_nfree == 0) {
2100 TAILQ_REMOVE(&lp->lp_pages, lcp, lcp_chain);
2101 TAILQ_INSERT_HEAD(&lp->lp_pages, lcp, lcp_chain);
2102 }
2103 mutex_exit(&lp->lp_lock);
2104 }
2105
2106 /*
2107 * Process is exiting; tear down lwpctl state. This can only be safely
2108 * called by the last LWP in the process.
2109 */
2110 void
2111 lwp_ctl_exit(void)
2112 {
2113 lcpage_t *lcp, *next;
2114 lcproc_t *lp;
2115 proc_t *p;
2116 lwp_t *l;
2117
2118 l = curlwp;
2119 l->l_lwpctl = NULL;
2120 l->l_lcpage = NULL;
2121 p = l->l_proc;
2122 lp = p->p_lwpctl;
2123
2124 KASSERT(lp != NULL);
2125 KASSERT(p->p_nlwps == 1);
2126
2127 for (lcp = TAILQ_FIRST(&lp->lp_pages); lcp != NULL; lcp = next) {
2128 next = TAILQ_NEXT(lcp, lcp_chain);
2129 uvm_unmap(kernel_map, lcp->lcp_kaddr,
2130 lcp->lcp_kaddr + PAGE_SIZE);
2131 kmem_free(lcp, LWPCTL_LCPAGE_SZ);
2132 }
2133
2134 if (lp->lp_uao != NULL) {
2135 uvm_unmap(&p->p_vmspace->vm_map, lp->lp_uva,
2136 lp->lp_uva + LWPCTL_UAREA_SZ);
2137 }
2138
2139 mutex_destroy(&lp->lp_lock);
2140 kmem_free(lp, sizeof(*lp));
2141 p->p_lwpctl = NULL;
2142 }
2143
2144 /*
2145 * Return the current LWP's "preemption counter". Used to detect
2146 * preemption across operations that can tolerate preemption without
2147 * crashing, but which may generate incorrect results if preempted.
2148 */
2149 long
2150 lwp_pctr(void)
2151 {
2152
2153 return curlwp->l_ru.ru_nvcsw + curlwp->l_ru.ru_nivcsw;
2154 }
2155
2156 /*
2157 * Set an LWP's private data pointer.
2158 */
2159 int
2160 lwp_setprivate(struct lwp *l, void *ptr)
2161 {
2162 int error = 0;
2163
2164 l->l_private = ptr;
2165 #ifdef __HAVE_CPU_LWP_SETPRIVATE
2166 error = cpu_lwp_setprivate(l, ptr);
2167 #endif
2168 return error;
2169 }
2170
2171 /*
2172 * Perform any thread-related cleanup on LWP exit.
2173 * N.B. l->l_proc->p_lock must be HELD on entry but will
2174 * be released before returning!
2175 */
2176 void
2177 lwp_thread_cleanup(struct lwp *l)
2178 {
2179
2180 KASSERT(mutex_owned(l->l_proc->p_lock));
2181 mutex_exit(l->l_proc->p_lock);
2182
2183 /*
2184 * If the LWP has robust futexes, release them all
2185 * now.
2186 */
2187 if (__predict_false(l->l_robust_head != 0)) {
2188 futex_release_all_lwp(l);
2189 }
2190 }
2191
2192 #if defined(DDB)
2193 #include <machine/pcb.h>
2194
2195 void
2196 lwp_whatis(uintptr_t addr, void (*pr)(const char *, ...))
2197 {
2198 lwp_t *l;
2199
2200 LIST_FOREACH(l, &alllwp, l_list) {
2201 uintptr_t stack = (uintptr_t)KSTACK_LOWEST_ADDR(l);
2202
2203 if (addr < stack || stack + KSTACK_SIZE <= addr) {
2204 continue;
2205 }
2206 (*pr)("%p is %p+%zu, LWP %p's stack\n",
2207 (void *)addr, (void *)stack,
2208 (size_t)(addr - stack), l);
2209 }
2210 }
2211 #endif /* defined(DDB) */
2212