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