xref: /freebsd/sys/kern/kern_thread.c (revision d2387d42b8da231a5b95cbc313825fb2aadf26f6)
1 /*
2  * Copyright (C) 2001 Julian Elischer <julian@freebsd.org>.
3  *  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice(s), this list of conditions and the following disclaimer as
10  *    the first lines of this file unmodified other than the possible
11  *    addition of one or more copyright notices.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice(s), this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
17  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  * DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
20  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
26  * DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/kernel.h>
35 #include <sys/lock.h>
36 #include <sys/malloc.h>
37 #include <sys/mutex.h>
38 #include <sys/proc.h>
39 #include <sys/smp.h>
40 #include <sys/sysctl.h>
41 #include <sys/sysproto.h>
42 #include <sys/filedesc.h>
43 #include <sys/sched.h>
44 #include <sys/signalvar.h>
45 #include <sys/sleepqueue.h>
46 #include <sys/sx.h>
47 #include <sys/tty.h>
48 #include <sys/turnstile.h>
49 #include <sys/user.h>
50 #include <sys/kse.h>
51 #include <sys/ktr.h>
52 #include <sys/ucontext.h>
53 
54 #include <vm/vm.h>
55 #include <vm/vm_extern.h>
56 #include <vm/vm_object.h>
57 #include <vm/pmap.h>
58 #include <vm/uma.h>
59 #include <vm/vm_map.h>
60 
61 #include <machine/frame.h>
62 
63 /*
64  * KSEGRP related storage.
65  */
66 static uma_zone_t ksegrp_zone;
67 static uma_zone_t kse_zone;
68 static uma_zone_t thread_zone;
69 static uma_zone_t upcall_zone;
70 
71 /* DEBUG ONLY */
72 SYSCTL_NODE(_kern, OID_AUTO, threads, CTLFLAG_RW, 0, "thread allocation");
73 static int thread_debug = 0;
74 SYSCTL_INT(_kern_threads, OID_AUTO, debug, CTLFLAG_RW,
75 	&thread_debug, 0, "thread debug");
76 
77 static int max_threads_per_proc = 1500;
78 SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_per_proc, CTLFLAG_RW,
79 	&max_threads_per_proc, 0, "Limit on threads per proc");
80 
81 static int max_groups_per_proc = 500;
82 SYSCTL_INT(_kern_threads, OID_AUTO, max_groups_per_proc, CTLFLAG_RW,
83 	&max_groups_per_proc, 0, "Limit on thread groups per proc");
84 
85 static int max_threads_hits;
86 SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_hits, CTLFLAG_RD,
87 	&max_threads_hits, 0, "");
88 
89 static int virtual_cpu;
90 
91 #define RANGEOF(type, start, end) (offsetof(type, end) - offsetof(type, start))
92 
93 TAILQ_HEAD(, thread) zombie_threads = TAILQ_HEAD_INITIALIZER(zombie_threads);
94 TAILQ_HEAD(, kse) zombie_kses = TAILQ_HEAD_INITIALIZER(zombie_kses);
95 TAILQ_HEAD(, ksegrp) zombie_ksegrps = TAILQ_HEAD_INITIALIZER(zombie_ksegrps);
96 TAILQ_HEAD(, kse_upcall) zombie_upcalls =
97 	TAILQ_HEAD_INITIALIZER(zombie_upcalls);
98 struct mtx kse_zombie_lock;
99 MTX_SYSINIT(kse_zombie_lock, &kse_zombie_lock, "kse zombie lock", MTX_SPIN);
100 
101 static void kse_purge(struct proc *p, struct thread *td);
102 static void kse_purge_group(struct thread *td);
103 static int thread_update_usr_ticks(struct thread *td, int user);
104 static void thread_alloc_spare(struct thread *td, struct thread *spare);
105 
106 static int
107 sysctl_kse_virtual_cpu(SYSCTL_HANDLER_ARGS)
108 {
109 	int error, new_val;
110 	int def_val;
111 
112 #ifdef SMP
113 	def_val = mp_ncpus;
114 #else
115 	def_val = 1;
116 #endif
117 	if (virtual_cpu == 0)
118 		new_val = def_val;
119 	else
120 		new_val = virtual_cpu;
121 	error = sysctl_handle_int(oidp, &new_val, 0, req);
122         if (error != 0 || req->newptr == NULL)
123 		return (error);
124 	if (new_val < 0)
125 		return (EINVAL);
126 	virtual_cpu = new_val;
127 	return (0);
128 }
129 
130 /* DEBUG ONLY */
131 SYSCTL_PROC(_kern_threads, OID_AUTO, virtual_cpu, CTLTYPE_INT|CTLFLAG_RW,
132 	0, sizeof(virtual_cpu), sysctl_kse_virtual_cpu, "I",
133 	"debug virtual cpus");
134 
135 /*
136  * Thread ID allocator. The allocator keeps track of assigned IDs by
137  * using a bitmap. The bitmap is created in parts. The parts are linked
138  * together.
139  */
140 typedef u_long tid_bitmap_word;
141 
142 #define	TID_IDS_PER_PART	1024
143 #define	TID_IDS_PER_IDX		(sizeof(tid_bitmap_word) << 3)
144 #define	TID_BITMAP_SIZE		(TID_IDS_PER_PART / TID_IDS_PER_IDX)
145 #define	TID_MIN			(PID_MAX + 1)
146 
147 struct tid_bitmap_part {
148 	STAILQ_ENTRY(tid_bitmap_part) bmp_next;
149 	tid_bitmap_word	bmp_bitmap[TID_BITMAP_SIZE];
150 	int		bmp_base;
151 	int		bmp_free;
152 };
153 
154 static STAILQ_HEAD(, tid_bitmap_part) tid_bitmap =
155     STAILQ_HEAD_INITIALIZER(tid_bitmap);
156 static uma_zone_t tid_zone;
157 
158 struct mtx tid_lock;
159 MTX_SYSINIT(tid_lock, &tid_lock, "TID lock", MTX_DEF);
160 
161 /*
162  * Prepare a thread for use.
163  */
164 static void
165 thread_ctor(void *mem, int size, void *arg)
166 {
167 	struct thread	*td;
168 
169 	td = (struct thread *)mem;
170 	td->td_tid = 0;
171 	td->td_state = TDS_INACTIVE;
172 	td->td_oncpu	= NOCPU;
173 	td->td_critnest = 1;
174 }
175 
176 /*
177  * Reclaim a thread after use.
178  */
179 static void
180 thread_dtor(void *mem, int size, void *arg)
181 {
182 	struct thread *td;
183 	struct tid_bitmap_part *bmp;
184 	int bit, idx, tid;
185 
186 	td = (struct thread *)mem;
187 
188 	if (td->td_tid > PID_MAX) {
189 		STAILQ_FOREACH(bmp, &tid_bitmap, bmp_next) {
190 			if (td->td_tid >= bmp->bmp_base &&
191 			    td->td_tid < bmp->bmp_base + TID_IDS_PER_PART)
192 				break;
193 		}
194 		KASSERT(bmp != NULL, ("No TID bitmap?"));
195 		mtx_lock(&tid_lock);
196 		tid = td->td_tid - bmp->bmp_base;
197 		idx = tid / TID_IDS_PER_IDX;
198 		bit = 1UL << (tid % TID_IDS_PER_IDX);
199 		bmp->bmp_bitmap[idx] |= bit;
200 		bmp->bmp_free++;
201 		mtx_unlock(&tid_lock);
202 	}
203 
204 #ifdef INVARIANTS
205 	/* Verify that this thread is in a safe state to free. */
206 	switch (td->td_state) {
207 	case TDS_INHIBITED:
208 	case TDS_RUNNING:
209 	case TDS_CAN_RUN:
210 	case TDS_RUNQ:
211 		/*
212 		 * We must never unlink a thread that is in one of
213 		 * these states, because it is currently active.
214 		 */
215 		panic("bad state for thread unlinking");
216 		/* NOTREACHED */
217 	case TDS_INACTIVE:
218 		break;
219 	default:
220 		panic("bad thread state");
221 		/* NOTREACHED */
222 	}
223 #endif
224 }
225 
226 /*
227  * Initialize type-stable parts of a thread (when newly created).
228  */
229 static void
230 thread_init(void *mem, int size)
231 {
232 	struct thread	*td;
233 
234 	td = (struct thread *)mem;
235 	vm_thread_new(td, 0);
236 	cpu_thread_setup(td);
237 	td->td_sleepqueue = sleepq_alloc();
238 	td->td_turnstile = turnstile_alloc();
239 	td->td_sched = (struct td_sched *)&td[1];
240 }
241 
242 /*
243  * Tear down type-stable parts of a thread (just before being discarded).
244  */
245 static void
246 thread_fini(void *mem, int size)
247 {
248 	struct thread	*td;
249 
250 	td = (struct thread *)mem;
251 	turnstile_free(td->td_turnstile);
252 	sleepq_free(td->td_sleepqueue);
253 	vm_thread_dispose(td);
254 }
255 
256 /*
257  * Initialize type-stable parts of a kse (when newly created).
258  */
259 static void
260 kse_init(void *mem, int size)
261 {
262 	struct kse	*ke;
263 
264 	ke = (struct kse *)mem;
265 	ke->ke_sched = (struct ke_sched *)&ke[1];
266 }
267 
268 /*
269  * Initialize type-stable parts of a ksegrp (when newly created).
270  */
271 static void
272 ksegrp_init(void *mem, int size)
273 {
274 	struct ksegrp	*kg;
275 
276 	kg = (struct ksegrp *)mem;
277 	kg->kg_sched = (struct kg_sched *)&kg[1];
278 }
279 
280 /*
281  * KSE is linked into kse group.
282  */
283 void
284 kse_link(struct kse *ke, struct ksegrp *kg)
285 {
286 	struct proc *p = kg->kg_proc;
287 
288 	TAILQ_INSERT_HEAD(&kg->kg_kseq, ke, ke_kglist);
289 	kg->kg_kses++;
290 	ke->ke_state	= KES_UNQUEUED;
291 	ke->ke_proc	= p;
292 	ke->ke_ksegrp	= kg;
293 	ke->ke_thread	= NULL;
294 	ke->ke_oncpu	= NOCPU;
295 	ke->ke_flags	= 0;
296 }
297 
298 void
299 kse_unlink(struct kse *ke)
300 {
301 	struct ksegrp *kg;
302 
303 	mtx_assert(&sched_lock, MA_OWNED);
304 	kg = ke->ke_ksegrp;
305 	TAILQ_REMOVE(&kg->kg_kseq, ke, ke_kglist);
306 	if (ke->ke_state == KES_IDLE) {
307 		TAILQ_REMOVE(&kg->kg_iq, ke, ke_kgrlist);
308 		kg->kg_idle_kses--;
309 	}
310 	--kg->kg_kses;
311 	/*
312 	 * Aggregate stats from the KSE
313 	 */
314 	kse_stash(ke);
315 }
316 
317 void
318 ksegrp_link(struct ksegrp *kg, struct proc *p)
319 {
320 
321 	TAILQ_INIT(&kg->kg_threads);
322 	TAILQ_INIT(&kg->kg_runq);	/* links with td_runq */
323 	TAILQ_INIT(&kg->kg_slpq);	/* links with td_runq */
324 	TAILQ_INIT(&kg->kg_kseq);	/* all kses in ksegrp */
325 	TAILQ_INIT(&kg->kg_iq);		/* all idle kses in ksegrp */
326 	TAILQ_INIT(&kg->kg_upcalls);	/* all upcall structure in ksegrp */
327 	kg->kg_proc = p;
328 	/*
329 	 * the following counters are in the -zero- section
330 	 * and may not need clearing
331 	 */
332 	kg->kg_numthreads = 0;
333 	kg->kg_runnable   = 0;
334 	kg->kg_kses       = 0;
335 	kg->kg_runq_kses  = 0; /* XXXKSE change name */
336 	kg->kg_idle_kses  = 0;
337 	kg->kg_numupcalls = 0;
338 	/* link it in now that it's consistent */
339 	p->p_numksegrps++;
340 	TAILQ_INSERT_HEAD(&p->p_ksegrps, kg, kg_ksegrp);
341 }
342 
343 void
344 ksegrp_unlink(struct ksegrp *kg)
345 {
346 	struct proc *p;
347 
348 	mtx_assert(&sched_lock, MA_OWNED);
349 	KASSERT((kg->kg_numthreads == 0), ("ksegrp_unlink: residual threads"));
350 	KASSERT((kg->kg_kses == 0), ("ksegrp_unlink: residual kses"));
351 	KASSERT((kg->kg_numupcalls == 0), ("ksegrp_unlink: residual upcalls"));
352 
353 	p = kg->kg_proc;
354 	TAILQ_REMOVE(&p->p_ksegrps, kg, kg_ksegrp);
355 	p->p_numksegrps--;
356 	/*
357 	 * Aggregate stats from the KSE
358 	 */
359 	ksegrp_stash(kg);
360 }
361 
362 struct kse_upcall *
363 upcall_alloc(void)
364 {
365 	struct kse_upcall *ku;
366 
367 	ku = uma_zalloc(upcall_zone, M_WAITOK);
368 	bzero(ku, sizeof(*ku));
369 	return (ku);
370 }
371 
372 void
373 upcall_free(struct kse_upcall *ku)
374 {
375 
376 	uma_zfree(upcall_zone, ku);
377 }
378 
379 void
380 upcall_link(struct kse_upcall *ku, struct ksegrp *kg)
381 {
382 
383 	mtx_assert(&sched_lock, MA_OWNED);
384 	TAILQ_INSERT_TAIL(&kg->kg_upcalls, ku, ku_link);
385 	ku->ku_ksegrp = kg;
386 	kg->kg_numupcalls++;
387 }
388 
389 void
390 upcall_unlink(struct kse_upcall *ku)
391 {
392 	struct ksegrp *kg = ku->ku_ksegrp;
393 
394 	mtx_assert(&sched_lock, MA_OWNED);
395 	KASSERT(ku->ku_owner == NULL, ("%s: have owner", __func__));
396 	TAILQ_REMOVE(&kg->kg_upcalls, ku, ku_link);
397 	kg->kg_numupcalls--;
398 	upcall_stash(ku);
399 }
400 
401 void
402 upcall_remove(struct thread *td)
403 {
404 
405 	if (td->td_upcall) {
406 		td->td_upcall->ku_owner = NULL;
407 		upcall_unlink(td->td_upcall);
408 		td->td_upcall = 0;
409 	}
410 }
411 
412 /*
413  * For a newly created process,
414  * link up all the structures and its initial threads etc.
415  */
416 void
417 proc_linkup(struct proc *p, struct ksegrp *kg,
418 	    struct kse *ke, struct thread *td)
419 {
420 
421 	TAILQ_INIT(&p->p_ksegrps);	     /* all ksegrps in proc */
422 	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
423 	TAILQ_INIT(&p->p_suspended);	     /* Threads suspended */
424 	p->p_numksegrps = 0;
425 	p->p_numthreads = 0;
426 
427 	ksegrp_link(kg, p);
428 	kse_link(ke, kg);
429 	thread_link(td, kg);
430 }
431 
432 #ifndef _SYS_SYSPROTO_H_
433 struct kse_switchin_args {
434 	const struct __mcontext *mcp;
435 	long val;
436 	long *loc;
437 };
438 #endif
439 
440 int
441 kse_switchin(struct thread *td, struct kse_switchin_args *uap)
442 {
443 	mcontext_t mc;
444 	int error;
445 
446 	error = (uap->mcp == NULL) ? EINVAL : 0;
447 	if (!error)
448 		error = copyin(uap->mcp, &mc, sizeof(mc));
449 	if (!error && uap->loc != NULL)
450 		error = (suword(uap->loc, uap->val) != 0) ? EINVAL : 0;
451 	if (!error)
452 		error = set_mcontext(td, &mc);
453 	return ((error == 0) ? EJUSTRETURN : error);
454 }
455 
456 /*
457 struct kse_thr_interrupt_args {
458 	struct kse_thr_mailbox * tmbx;
459 	int cmd;
460 	long data;
461 };
462 */
463 int
464 kse_thr_interrupt(struct thread *td, struct kse_thr_interrupt_args *uap)
465 {
466 	struct proc *p;
467 	struct thread *td2;
468 
469 	p = td->td_proc;
470 
471 	if (!(p->p_flag & P_SA))
472 		return (EINVAL);
473 
474 	switch (uap->cmd) {
475 	case KSE_INTR_SENDSIG:
476 		if (uap->data < 0 || uap->data > _SIG_MAXSIG)
477 			return (EINVAL);
478 	case KSE_INTR_INTERRUPT:
479 	case KSE_INTR_RESTART:
480 		PROC_LOCK(p);
481 		mtx_lock_spin(&sched_lock);
482 		FOREACH_THREAD_IN_PROC(p, td2) {
483 			if (td2->td_mailbox == uap->tmbx)
484 				break;
485 		}
486 		if (td2 == NULL) {
487 			mtx_unlock_spin(&sched_lock);
488 			PROC_UNLOCK(p);
489 			return (ESRCH);
490 		}
491 		if (uap->cmd == KSE_INTR_SENDSIG) {
492 			if (uap->data > 0) {
493 				td2->td_flags &= ~TDF_INTERRUPT;
494 				mtx_unlock_spin(&sched_lock);
495 				tdsignal(td2, (int)uap->data, SIGTARGET_TD);
496 			} else {
497 				mtx_unlock_spin(&sched_lock);
498 			}
499 		} else {
500 			td2->td_flags |= TDF_INTERRUPT | TDF_ASTPENDING;
501 			if (TD_CAN_UNBIND(td2))
502 				td2->td_upcall->ku_flags |= KUF_DOUPCALL;
503 			if (uap->cmd == KSE_INTR_INTERRUPT)
504 				td2->td_intrval = EINTR;
505 			else
506 				td2->td_intrval = ERESTART;
507 			if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR))
508 				sleepq_abort(td2);
509 			mtx_unlock_spin(&sched_lock);
510 		}
511 		PROC_UNLOCK(p);
512 		break;
513 	case KSE_INTR_SIGEXIT:
514 		if (uap->data < 1 || uap->data > _SIG_MAXSIG)
515 			return (EINVAL);
516 		PROC_LOCK(p);
517 		sigexit(td, (int)uap->data);
518 		break;
519 	default:
520 		return (EINVAL);
521 	}
522 	return (0);
523 }
524 
525 /*
526 struct kse_exit_args {
527 	register_t dummy;
528 };
529 */
530 int
531 kse_exit(struct thread *td, struct kse_exit_args *uap)
532 {
533 	struct proc *p;
534 	struct ksegrp *kg;
535 	struct kse *ke;
536 	struct kse_upcall *ku, *ku2;
537 	int    error, count;
538 
539 	p = td->td_proc;
540 	if ((ku = td->td_upcall) == NULL || TD_CAN_UNBIND(td))
541 		return (EINVAL);
542 	kg = td->td_ksegrp;
543 	count = 0;
544 	PROC_LOCK(p);
545 	mtx_lock_spin(&sched_lock);
546 	FOREACH_UPCALL_IN_GROUP(kg, ku2) {
547 		if (ku2->ku_flags & KUF_EXITING)
548 			count++;
549 	}
550 	if ((kg->kg_numupcalls - count) == 1 &&
551 	    (kg->kg_numthreads > 1)) {
552 		mtx_unlock_spin(&sched_lock);
553 		PROC_UNLOCK(p);
554 		return (EDEADLK);
555 	}
556 	ku->ku_flags |= KUF_EXITING;
557 	mtx_unlock_spin(&sched_lock);
558 	PROC_UNLOCK(p);
559 	error = suword(&ku->ku_mailbox->km_flags, ku->ku_mflags|KMF_DONE);
560 	PROC_LOCK(p);
561 	if (error)
562 		psignal(p, SIGSEGV);
563 	mtx_lock_spin(&sched_lock);
564 	upcall_remove(td);
565 	ke = td->td_kse;
566 	if (p->p_numthreads == 1) {
567 		kse_purge(p, td);
568 		p->p_flag &= ~P_SA;
569 		mtx_unlock_spin(&sched_lock);
570 		PROC_UNLOCK(p);
571 	} else {
572 		if (kg->kg_numthreads == 1) { /* Shutdown a group */
573 			kse_purge_group(td);
574 			ke->ke_flags |= KEF_EXIT;
575 		}
576 		thread_stopped(p);
577 		thread_exit();
578 		/* NOTREACHED */
579 	}
580 	return (0);
581 }
582 
583 /*
584  * Either becomes an upcall or waits for an awakening event and
585  * then becomes an upcall. Only error cases return.
586  */
587 /*
588 struct kse_release_args {
589 	struct timespec *timeout;
590 };
591 */
592 int
593 kse_release(struct thread *td, struct kse_release_args *uap)
594 {
595 	struct proc *p;
596 	struct ksegrp *kg;
597 	struct kse_upcall *ku;
598 	struct timespec timeout;
599 	struct timeval tv;
600 	sigset_t sigset;
601 	int error;
602 
603 	p = td->td_proc;
604 	kg = td->td_ksegrp;
605 	if ((ku = td->td_upcall) == NULL || TD_CAN_UNBIND(td))
606 		return (EINVAL);
607 	if (uap->timeout != NULL) {
608 		if ((error = copyin(uap->timeout, &timeout, sizeof(timeout))))
609 			return (error);
610 		TIMESPEC_TO_TIMEVAL(&tv, &timeout);
611 	}
612 	if (td->td_flags & TDF_SA)
613 		td->td_pflags |= TDP_UPCALLING;
614 	else {
615 		ku->ku_mflags = fuword(&ku->ku_mailbox->km_flags);
616 		if (ku->ku_mflags == -1) {
617 			PROC_LOCK(p);
618 			sigexit(td, SIGSEGV);
619 		}
620 	}
621 	PROC_LOCK(p);
622 	if (ku->ku_mflags & KMF_WAITSIGEVENT) {
623 		/* UTS wants to wait for signal event */
624 		if (!(p->p_flag & P_SIGEVENT) && !(ku->ku_flags & KUF_DOUPCALL))
625 			error = msleep(&p->p_siglist, &p->p_mtx, PPAUSE|PCATCH,
626 			    "ksesigwait", (uap->timeout ? tvtohz(&tv) : 0));
627 		p->p_flag &= ~P_SIGEVENT;
628 		sigset = p->p_siglist;
629 		PROC_UNLOCK(p);
630 		error = copyout(&sigset, &ku->ku_mailbox->km_sigscaught,
631 		    sizeof(sigset));
632 	} else {
633 		 if (! kg->kg_completed && !(ku->ku_flags & KUF_DOUPCALL)) {
634 			kg->kg_upsleeps++;
635 			error = msleep(&kg->kg_completed, &p->p_mtx,
636 				PPAUSE|PCATCH, "kserel",
637 				(uap->timeout ? tvtohz(&tv) : 0));
638 			kg->kg_upsleeps--;
639 		}
640 		PROC_UNLOCK(p);
641 	}
642 	if (ku->ku_flags & KUF_DOUPCALL) {
643 		mtx_lock_spin(&sched_lock);
644 		ku->ku_flags &= ~KUF_DOUPCALL;
645 		mtx_unlock_spin(&sched_lock);
646 	}
647 	return (0);
648 }
649 
650 /* struct kse_wakeup_args {
651 	struct kse_mailbox *mbx;
652 }; */
653 int
654 kse_wakeup(struct thread *td, struct kse_wakeup_args *uap)
655 {
656 	struct proc *p;
657 	struct ksegrp *kg;
658 	struct kse_upcall *ku;
659 	struct thread *td2;
660 
661 	p = td->td_proc;
662 	td2 = NULL;
663 	ku = NULL;
664 	/* KSE-enabled processes only, please. */
665 	if (!(p->p_flag & P_SA))
666 		return (EINVAL);
667 	PROC_LOCK(p);
668 	mtx_lock_spin(&sched_lock);
669 	if (uap->mbx) {
670 		FOREACH_KSEGRP_IN_PROC(p, kg) {
671 			FOREACH_UPCALL_IN_GROUP(kg, ku) {
672 				if (ku->ku_mailbox == uap->mbx)
673 					break;
674 			}
675 			if (ku)
676 				break;
677 		}
678 	} else {
679 		kg = td->td_ksegrp;
680 		if (kg->kg_upsleeps) {
681 			wakeup_one(&kg->kg_completed);
682 			mtx_unlock_spin(&sched_lock);
683 			PROC_UNLOCK(p);
684 			return (0);
685 		}
686 		ku = TAILQ_FIRST(&kg->kg_upcalls);
687 	}
688 	if (ku) {
689 		if ((td2 = ku->ku_owner) == NULL) {
690 			panic("%s: no owner", __func__);
691 		} else if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) &&
692 		           ((td2->td_wchan == &kg->kg_completed) ||
693 			    (td2->td_wchan == &p->p_siglist &&
694 			     (ku->ku_mflags & KMF_WAITSIGEVENT)))) {
695 			sleepq_abort(td2);
696 		} else {
697 			ku->ku_flags |= KUF_DOUPCALL;
698 		}
699 		mtx_unlock_spin(&sched_lock);
700 		PROC_UNLOCK(p);
701 		return (0);
702 	}
703 	mtx_unlock_spin(&sched_lock);
704 	PROC_UNLOCK(p);
705 	return (ESRCH);
706 }
707 
708 /*
709  * No new KSEG: first call: use current KSE, don't schedule an upcall
710  * All other situations, do allocate max new KSEs and schedule an upcall.
711  */
712 /* struct kse_create_args {
713 	struct kse_mailbox *mbx;
714 	int newgroup;
715 }; */
716 int
717 kse_create(struct thread *td, struct kse_create_args *uap)
718 {
719 	struct kse *newke;
720 	struct ksegrp *newkg;
721 	struct ksegrp *kg;
722 	struct proc *p;
723 	struct kse_mailbox mbx;
724 	struct kse_upcall *newku;
725 	int err, ncpus, sa = 0, first = 0;
726 	struct thread *newtd;
727 
728 	p = td->td_proc;
729 	if ((err = copyin(uap->mbx, &mbx, sizeof(mbx))))
730 		return (err);
731 
732 	/* Too bad, why hasn't kernel always a cpu counter !? */
733 #ifdef SMP
734 	ncpus = mp_ncpus;
735 #else
736 	ncpus = 1;
737 #endif
738 	if (virtual_cpu != 0)
739 		ncpus = virtual_cpu;
740 	if (!(mbx.km_flags & KMF_BOUND))
741 		sa = TDF_SA;
742 	else
743 		ncpus = 1;
744 	PROC_LOCK(p);
745 	if (!(p->p_flag & P_SA)) {
746 		first = 1;
747 		p->p_flag |= P_SA;
748 	}
749 	PROC_UNLOCK(p);
750 	if (!sa && !uap->newgroup && !first)
751 		return (EINVAL);
752 	kg = td->td_ksegrp;
753 	if (uap->newgroup) {
754 		/* Have race condition but it is cheap */
755 		if (p->p_numksegrps >= max_groups_per_proc)
756 			return (EPROCLIM);
757 		/*
758 		 * If we want a new KSEGRP it doesn't matter whether
759 		 * we have already fired up KSE mode before or not.
760 		 * We put the process in KSE mode and create a new KSEGRP.
761 		 */
762 		newkg = ksegrp_alloc();
763 		bzero(&newkg->kg_startzero, RANGEOF(struct ksegrp,
764 		      kg_startzero, kg_endzero));
765 		bcopy(&kg->kg_startcopy, &newkg->kg_startcopy,
766 		      RANGEOF(struct ksegrp, kg_startcopy, kg_endcopy));
767 		PROC_LOCK(p);
768 		mtx_lock_spin(&sched_lock);
769 		if (p->p_numksegrps >= max_groups_per_proc) {
770 			mtx_unlock_spin(&sched_lock);
771 			PROC_UNLOCK(p);
772 			ksegrp_free(newkg);
773 			return (EPROCLIM);
774 		}
775 		ksegrp_link(newkg, p);
776 		sched_fork_ksegrp(kg, newkg);
777 		mtx_unlock_spin(&sched_lock);
778 		PROC_UNLOCK(p);
779 	} else {
780 		if (!first && ((td->td_flags & TDF_SA) ^ sa) != 0)
781 			return (EINVAL);
782 		newkg = kg;
783 	}
784 
785 	/*
786 	 * Creating upcalls more than number of physical cpu does
787 	 * not help performance.
788 	 */
789 	if (newkg->kg_numupcalls >= ncpus)
790 		return (EPROCLIM);
791 
792 	if (newkg->kg_numupcalls == 0) {
793 		/*
794 		 * Initialize KSE group
795 		 *
796 		 * For multiplxed group, create KSEs as many as physical
797 		 * cpus. This increases concurrent even if userland
798 		 * is not MP safe and can only run on single CPU.
799 		 * In ideal world, every physical cpu should execute a thread.
800 		 * If there is enough KSEs, threads in kernel can be
801 		 * executed parallel on different cpus with full speed,
802 		 * Concurrent in kernel shouldn't be restricted by number of
803 		 * upcalls userland provides. Adding more upcall structures
804 		 * only increases concurrent in userland.
805 		 *
806 		 * For bound thread group, because there is only thread in the
807 		 * group, we only create one KSE for the group. Thread in this
808 		 * kind of group will never schedule an upcall when blocked,
809 		 * this intends to simulate pthread system scope thread.
810 		 */
811 		while (newkg->kg_kses < ncpus) {
812 			newke = kse_alloc();
813 			bzero(&newke->ke_startzero, RANGEOF(struct kse,
814 			      ke_startzero, ke_endzero));
815 #if 0
816 			mtx_lock_spin(&sched_lock);
817 			bcopy(&ke->ke_startcopy, &newke->ke_startcopy,
818 			      RANGEOF(struct kse, ke_startcopy, ke_endcopy));
819 			mtx_unlock_spin(&sched_lock);
820 #endif
821 			mtx_lock_spin(&sched_lock);
822 			kse_link(newke, newkg);
823 			sched_fork_kse(td->td_kse, newke);
824 			/* Add engine */
825 			kse_reassign(newke);
826 			mtx_unlock_spin(&sched_lock);
827 		}
828 	}
829 	newku = upcall_alloc();
830 	newku->ku_mailbox = uap->mbx;
831 	newku->ku_func = mbx.km_func;
832 	bcopy(&mbx.km_stack, &newku->ku_stack, sizeof(stack_t));
833 
834 	/* For the first call this may not have been set */
835 	if (td->td_standin == NULL)
836 		thread_alloc_spare(td, NULL);
837 
838 	PROC_LOCK(p);
839 	if (newkg->kg_numupcalls >= ncpus) {
840 		PROC_UNLOCK(p);
841 		upcall_free(newku);
842 		return (EPROCLIM);
843 	}
844 	if (first && sa) {
845 		SIGSETOR(p->p_siglist, td->td_siglist);
846 		SIGEMPTYSET(td->td_siglist);
847 		SIGFILLSET(td->td_sigmask);
848 		SIG_CANTMASK(td->td_sigmask);
849 	}
850 	mtx_lock_spin(&sched_lock);
851 	PROC_UNLOCK(p);
852 	upcall_link(newku, newkg);
853 	if (mbx.km_quantum)
854 		newkg->kg_upquantum = max(1, mbx.km_quantum/tick);
855 
856 	/*
857 	 * Each upcall structure has an owner thread, find which
858 	 * one owns it.
859 	 */
860 	if (uap->newgroup) {
861 		/*
862 		 * Because new ksegrp hasn't thread,
863 		 * create an initial upcall thread to own it.
864 		 */
865 		newtd = thread_schedule_upcall(td, newku);
866 	} else {
867 		/*
868 		 * If current thread hasn't an upcall structure,
869 		 * just assign the upcall to it.
870 		 */
871 		if (td->td_upcall == NULL) {
872 			newku->ku_owner = td;
873 			td->td_upcall = newku;
874 			newtd = td;
875 		} else {
876 			/*
877 			 * Create a new upcall thread to own it.
878 			 */
879 			newtd = thread_schedule_upcall(td, newku);
880 		}
881 	}
882 	if (!sa) {
883 		newtd->td_mailbox = mbx.km_curthread;
884 		newtd->td_flags &= ~TDF_SA;
885 		if (newtd != td) {
886 			mtx_unlock_spin(&sched_lock);
887 			cpu_set_upcall_kse(newtd, newku);
888 			mtx_lock_spin(&sched_lock);
889 		}
890 	} else {
891 		newtd->td_flags |= TDF_SA;
892 	}
893 	if (newtd != td)
894 		setrunqueue(newtd);
895 	mtx_unlock_spin(&sched_lock);
896 	return (0);
897 }
898 
899 /*
900  * Initialize global thread allocation resources.
901  */
902 void
903 threadinit(void)
904 {
905 
906 	thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
907 	    thread_ctor, thread_dtor, thread_init, thread_fini,
908 	    UMA_ALIGN_CACHE, 0);
909 	tid_zone = uma_zcreate("TID", sizeof(struct tid_bitmap_part),
910 	    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
911 	ksegrp_zone = uma_zcreate("KSEGRP", sched_sizeof_ksegrp(),
912 	    NULL, NULL, ksegrp_init, NULL,
913 	    UMA_ALIGN_CACHE, 0);
914 	kse_zone = uma_zcreate("KSE", sched_sizeof_kse(),
915 	    NULL, NULL, kse_init, NULL,
916 	    UMA_ALIGN_CACHE, 0);
917 	upcall_zone = uma_zcreate("UPCALL", sizeof(struct kse_upcall),
918 	    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
919 }
920 
921 /*
922  * Stash an embarasingly extra thread into the zombie thread queue.
923  */
924 void
925 thread_stash(struct thread *td)
926 {
927 	mtx_lock_spin(&kse_zombie_lock);
928 	TAILQ_INSERT_HEAD(&zombie_threads, td, td_runq);
929 	mtx_unlock_spin(&kse_zombie_lock);
930 }
931 
932 /*
933  * Stash an embarasingly extra kse into the zombie kse queue.
934  */
935 void
936 kse_stash(struct kse *ke)
937 {
938 	mtx_lock_spin(&kse_zombie_lock);
939 	TAILQ_INSERT_HEAD(&zombie_kses, ke, ke_procq);
940 	mtx_unlock_spin(&kse_zombie_lock);
941 }
942 
943 /*
944  * Stash an embarasingly extra upcall into the zombie upcall queue.
945  */
946 
947 void
948 upcall_stash(struct kse_upcall *ku)
949 {
950 	mtx_lock_spin(&kse_zombie_lock);
951 	TAILQ_INSERT_HEAD(&zombie_upcalls, ku, ku_link);
952 	mtx_unlock_spin(&kse_zombie_lock);
953 }
954 
955 /*
956  * Stash an embarasingly extra ksegrp into the zombie ksegrp queue.
957  */
958 void
959 ksegrp_stash(struct ksegrp *kg)
960 {
961 	mtx_lock_spin(&kse_zombie_lock);
962 	TAILQ_INSERT_HEAD(&zombie_ksegrps, kg, kg_ksegrp);
963 	mtx_unlock_spin(&kse_zombie_lock);
964 }
965 
966 /*
967  * Reap zombie kse resource.
968  */
969 void
970 thread_reap(void)
971 {
972 	struct thread *td_first, *td_next;
973 	struct kse *ke_first, *ke_next;
974 	struct ksegrp *kg_first, * kg_next;
975 	struct kse_upcall *ku_first, *ku_next;
976 
977 	/*
978 	 * Don't even bother to lock if none at this instant,
979 	 * we really don't care about the next instant..
980 	 */
981 	if ((!TAILQ_EMPTY(&zombie_threads))
982 	    || (!TAILQ_EMPTY(&zombie_kses))
983 	    || (!TAILQ_EMPTY(&zombie_ksegrps))
984 	    || (!TAILQ_EMPTY(&zombie_upcalls))) {
985 		mtx_lock_spin(&kse_zombie_lock);
986 		td_first = TAILQ_FIRST(&zombie_threads);
987 		ke_first = TAILQ_FIRST(&zombie_kses);
988 		kg_first = TAILQ_FIRST(&zombie_ksegrps);
989 		ku_first = TAILQ_FIRST(&zombie_upcalls);
990 		if (td_first)
991 			TAILQ_INIT(&zombie_threads);
992 		if (ke_first)
993 			TAILQ_INIT(&zombie_kses);
994 		if (kg_first)
995 			TAILQ_INIT(&zombie_ksegrps);
996 		if (ku_first)
997 			TAILQ_INIT(&zombie_upcalls);
998 		mtx_unlock_spin(&kse_zombie_lock);
999 		while (td_first) {
1000 			td_next = TAILQ_NEXT(td_first, td_runq);
1001 			if (td_first->td_ucred)
1002 				crfree(td_first->td_ucred);
1003 			thread_free(td_first);
1004 			td_first = td_next;
1005 		}
1006 		while (ke_first) {
1007 			ke_next = TAILQ_NEXT(ke_first, ke_procq);
1008 			kse_free(ke_first);
1009 			ke_first = ke_next;
1010 		}
1011 		while (kg_first) {
1012 			kg_next = TAILQ_NEXT(kg_first, kg_ksegrp);
1013 			ksegrp_free(kg_first);
1014 			kg_first = kg_next;
1015 		}
1016 		while (ku_first) {
1017 			ku_next = TAILQ_NEXT(ku_first, ku_link);
1018 			upcall_free(ku_first);
1019 			ku_first = ku_next;
1020 		}
1021 	}
1022 }
1023 
1024 /*
1025  * Allocate a ksegrp.
1026  */
1027 struct ksegrp *
1028 ksegrp_alloc(void)
1029 {
1030 	return (uma_zalloc(ksegrp_zone, M_WAITOK));
1031 }
1032 
1033 /*
1034  * Allocate a kse.
1035  */
1036 struct kse *
1037 kse_alloc(void)
1038 {
1039 	return (uma_zalloc(kse_zone, M_WAITOK));
1040 }
1041 
1042 /*
1043  * Allocate a thread.
1044  */
1045 struct thread *
1046 thread_alloc(void)
1047 {
1048 	thread_reap(); /* check if any zombies to get */
1049 	return (uma_zalloc(thread_zone, M_WAITOK));
1050 }
1051 
1052 /*
1053  * Deallocate a ksegrp.
1054  */
1055 void
1056 ksegrp_free(struct ksegrp *td)
1057 {
1058 	uma_zfree(ksegrp_zone, td);
1059 }
1060 
1061 /*
1062  * Deallocate a kse.
1063  */
1064 void
1065 kse_free(struct kse *td)
1066 {
1067 	uma_zfree(kse_zone, td);
1068 }
1069 
1070 /*
1071  * Deallocate a thread.
1072  */
1073 void
1074 thread_free(struct thread *td)
1075 {
1076 
1077 	cpu_thread_clean(td);
1078 	uma_zfree(thread_zone, td);
1079 }
1080 
1081 /*
1082  * Assign a thread ID.
1083  */
1084 int
1085 thread_new_tid(void)
1086 {
1087 	struct tid_bitmap_part *bmp, *new;
1088 	int bit, idx, tid;
1089 
1090 	mtx_lock(&tid_lock);
1091 	STAILQ_FOREACH(bmp, &tid_bitmap, bmp_next) {
1092 		if (bmp->bmp_free)
1093 			break;
1094 	}
1095 	/* Create a new bitmap if we run out of free bits. */
1096 	if (bmp == NULL) {
1097 		mtx_unlock(&tid_lock);
1098 		new = uma_zalloc(tid_zone, M_WAITOK);
1099 		mtx_lock(&tid_lock);
1100 		bmp = STAILQ_LAST(&tid_bitmap, tid_bitmap_part, bmp_next);
1101 		if (bmp == NULL || bmp->bmp_free < TID_IDS_PER_PART/2) {
1102 			/* 1=free, 0=assigned. This way we can use ffsl(). */
1103 			memset(new->bmp_bitmap, ~0U, sizeof(new->bmp_bitmap));
1104 			new->bmp_base = (bmp == NULL) ? TID_MIN :
1105 			    bmp->bmp_base + TID_IDS_PER_PART;
1106 			new->bmp_free = TID_IDS_PER_PART;
1107 			STAILQ_INSERT_TAIL(&tid_bitmap, new, bmp_next);
1108 			bmp = new;
1109 			new = NULL;
1110 		}
1111 	} else
1112 		new = NULL;
1113 	/* We have a bitmap with available IDs. */
1114 	idx = 0;
1115 	while (idx < TID_BITMAP_SIZE && bmp->bmp_bitmap[idx] == 0UL)
1116 		idx++;
1117 	bit = ffsl(bmp->bmp_bitmap[idx]) - 1;
1118 	tid = bmp->bmp_base + idx * TID_IDS_PER_IDX + bit;
1119 	bmp->bmp_bitmap[idx] &= ~(1UL << bit);
1120 	bmp->bmp_free--;
1121 	mtx_unlock(&tid_lock);
1122 
1123 	if (new != NULL)
1124 		uma_zfree(tid_zone, new);
1125 	return (tid);
1126 }
1127 
1128 /*
1129  * Store the thread context in the UTS's mailbox.
1130  * then add the mailbox at the head of a list we are building in user space.
1131  * The list is anchored in the ksegrp structure.
1132  */
1133 int
1134 thread_export_context(struct thread *td, int willexit)
1135 {
1136 	struct proc *p;
1137 	struct ksegrp *kg;
1138 	uintptr_t mbx;
1139 	void *addr;
1140 	int error = 0, temp, sig;
1141 	mcontext_t mc;
1142 
1143 	p = td->td_proc;
1144 	kg = td->td_ksegrp;
1145 
1146 	/* Export the user/machine context. */
1147 	get_mcontext(td, &mc, 0);
1148 	addr = (void *)(&td->td_mailbox->tm_context.uc_mcontext);
1149 	error = copyout(&mc, addr, sizeof(mcontext_t));
1150 	if (error)
1151 		goto bad;
1152 
1153 	/* Exports clock ticks in kernel mode */
1154 	addr = (caddr_t)(&td->td_mailbox->tm_sticks);
1155 	temp = fuword32(addr) + td->td_usticks;
1156 	if (suword32(addr, temp)) {
1157 		error = EFAULT;
1158 		goto bad;
1159 	}
1160 
1161 	/*
1162 	 * Post sync signal, or process SIGKILL and SIGSTOP.
1163 	 * For sync signal, it is only possible when the signal is not
1164 	 * caught by userland or process is being debugged.
1165 	 */
1166 	PROC_LOCK(p);
1167 	if (td->td_flags & TDF_NEEDSIGCHK) {
1168 		mtx_lock_spin(&sched_lock);
1169 		td->td_flags &= ~TDF_NEEDSIGCHK;
1170 		mtx_unlock_spin(&sched_lock);
1171 		mtx_lock(&p->p_sigacts->ps_mtx);
1172 		while ((sig = cursig(td)) != 0)
1173 			postsig(sig);
1174 		mtx_unlock(&p->p_sigacts->ps_mtx);
1175 	}
1176 	if (willexit)
1177 		SIGFILLSET(td->td_sigmask);
1178 	PROC_UNLOCK(p);
1179 
1180 	/* Get address in latest mbox of list pointer */
1181 	addr = (void *)(&td->td_mailbox->tm_next);
1182 	/*
1183 	 * Put the saved address of the previous first
1184 	 * entry into this one
1185 	 */
1186 	for (;;) {
1187 		mbx = (uintptr_t)kg->kg_completed;
1188 		if (suword(addr, mbx)) {
1189 			error = EFAULT;
1190 			goto bad;
1191 		}
1192 		PROC_LOCK(p);
1193 		if (mbx == (uintptr_t)kg->kg_completed) {
1194 			kg->kg_completed = td->td_mailbox;
1195 			/*
1196 			 * The thread context may be taken away by
1197 			 * other upcall threads when we unlock
1198 			 * process lock. it's no longer valid to
1199 			 * use it again in any other places.
1200 			 */
1201 			td->td_mailbox = NULL;
1202 			PROC_UNLOCK(p);
1203 			break;
1204 		}
1205 		PROC_UNLOCK(p);
1206 	}
1207 	td->td_usticks = 0;
1208 	return (0);
1209 
1210 bad:
1211 	PROC_LOCK(p);
1212 	sigexit(td, SIGILL);
1213 	return (error);
1214 }
1215 
1216 /*
1217  * Take the list of completed mailboxes for this KSEGRP and put them on this
1218  * upcall's mailbox as it's the next one going up.
1219  */
1220 static int
1221 thread_link_mboxes(struct ksegrp *kg, struct kse_upcall *ku)
1222 {
1223 	struct proc *p = kg->kg_proc;
1224 	void *addr;
1225 	uintptr_t mbx;
1226 
1227 	addr = (void *)(&ku->ku_mailbox->km_completed);
1228 	for (;;) {
1229 		mbx = (uintptr_t)kg->kg_completed;
1230 		if (suword(addr, mbx)) {
1231 			PROC_LOCK(p);
1232 			psignal(p, SIGSEGV);
1233 			PROC_UNLOCK(p);
1234 			return (EFAULT);
1235 		}
1236 		PROC_LOCK(p);
1237 		if (mbx == (uintptr_t)kg->kg_completed) {
1238 			kg->kg_completed = NULL;
1239 			PROC_UNLOCK(p);
1240 			break;
1241 		}
1242 		PROC_UNLOCK(p);
1243 	}
1244 	return (0);
1245 }
1246 
1247 /*
1248  * This function should be called at statclock interrupt time
1249  */
1250 int
1251 thread_statclock(int user)
1252 {
1253 	struct thread *td = curthread;
1254 	struct ksegrp *kg = td->td_ksegrp;
1255 
1256 	if (kg->kg_numupcalls == 0 || !(td->td_flags & TDF_SA))
1257 		return (0);
1258 	if (user) {
1259 		/* Current always do via ast() */
1260 		mtx_lock_spin(&sched_lock);
1261 		td->td_flags |= (TDF_USTATCLOCK|TDF_ASTPENDING);
1262 		mtx_unlock_spin(&sched_lock);
1263 		td->td_uuticks++;
1264 	} else {
1265 		if (td->td_mailbox != NULL)
1266 			td->td_usticks++;
1267 		else {
1268 			/* XXXKSE
1269 		 	 * We will call thread_user_enter() for every
1270 			 * kernel entry in future, so if the thread mailbox
1271 			 * is NULL, it must be a UTS kernel, don't account
1272 			 * clock ticks for it.
1273 			 */
1274 		}
1275 	}
1276 	return (0);
1277 }
1278 
1279 /*
1280  * Export state clock ticks for userland
1281  */
1282 static int
1283 thread_update_usr_ticks(struct thread *td, int user)
1284 {
1285 	struct proc *p = td->td_proc;
1286 	struct kse_thr_mailbox *tmbx;
1287 	struct kse_upcall *ku;
1288 	struct ksegrp *kg;
1289 	caddr_t addr;
1290 	u_int uticks;
1291 
1292 	if ((ku = td->td_upcall) == NULL)
1293 		return (-1);
1294 
1295 	tmbx = (void *)fuword((void *)&ku->ku_mailbox->km_curthread);
1296 	if ((tmbx == NULL) || (tmbx == (void *)-1))
1297 		return (-1);
1298 	if (user) {
1299 		uticks = td->td_uuticks;
1300 		td->td_uuticks = 0;
1301 		addr = (caddr_t)&tmbx->tm_uticks;
1302 	} else {
1303 		uticks = td->td_usticks;
1304 		td->td_usticks = 0;
1305 		addr = (caddr_t)&tmbx->tm_sticks;
1306 	}
1307 	if (uticks) {
1308 		if (suword32(addr, uticks+fuword32(addr))) {
1309 			PROC_LOCK(p);
1310 			psignal(p, SIGSEGV);
1311 			PROC_UNLOCK(p);
1312 			return (-2);
1313 		}
1314 	}
1315 	kg = td->td_ksegrp;
1316 	if (kg->kg_upquantum && ticks >= kg->kg_nextupcall) {
1317 		mtx_lock_spin(&sched_lock);
1318 		td->td_upcall->ku_flags |= KUF_DOUPCALL;
1319 		mtx_unlock_spin(&sched_lock);
1320 	}
1321 	return (0);
1322 }
1323 
1324 /*
1325  * Discard the current thread and exit from its context.
1326  *
1327  * Because we can't free a thread while we're operating under its context,
1328  * push the current thread into our CPU's deadthread holder. This means
1329  * we needn't worry about someone else grabbing our context before we
1330  * do a cpu_throw().
1331  */
1332 void
1333 thread_exit(void)
1334 {
1335 	struct thread *td;
1336 	struct kse *ke;
1337 	struct proc *p;
1338 	struct ksegrp	*kg;
1339 
1340 	td = curthread;
1341 	kg = td->td_ksegrp;
1342 	p = td->td_proc;
1343 	ke = td->td_kse;
1344 
1345 	mtx_assert(&sched_lock, MA_OWNED);
1346 	KASSERT(p != NULL, ("thread exiting without a process"));
1347 	KASSERT(ke != NULL, ("thread exiting without a kse"));
1348 	KASSERT(kg != NULL, ("thread exiting without a kse group"));
1349 	PROC_LOCK_ASSERT(p, MA_OWNED);
1350 	CTR1(KTR_PROC, "thread_exit: thread %p", td);
1351 	mtx_assert(&Giant, MA_NOTOWNED);
1352 
1353 	if (td->td_standin != NULL) {
1354 		thread_stash(td->td_standin);
1355 		td->td_standin = NULL;
1356 	}
1357 
1358 	cpu_thread_exit(td);	/* XXXSMP */
1359 
1360 	/*
1361 	 * The last thread is left attached to the process
1362 	 * So that the whole bundle gets recycled. Skip
1363 	 * all this stuff.
1364 	 */
1365 	if (p->p_numthreads > 1) {
1366 		thread_unlink(td);
1367 		if (p->p_maxthrwaits)
1368 			wakeup(&p->p_numthreads);
1369 		/*
1370 		 * The test below is NOT true if we are the
1371 		 * sole exiting thread. P_STOPPED_SNGL is unset
1372 		 * in exit1() after it is the only survivor.
1373 		 */
1374 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1375 			if (p->p_numthreads == p->p_suspcount) {
1376 				thread_unsuspend_one(p->p_singlethread);
1377 			}
1378 		}
1379 
1380 		/*
1381 		 * Because each upcall structure has an owner thread,
1382 		 * owner thread exits only when process is in exiting
1383 		 * state, so upcall to userland is no longer needed,
1384 		 * deleting upcall structure is safe here.
1385 		 * So when all threads in a group is exited, all upcalls
1386 		 * in the group should be automatically freed.
1387 		 */
1388 		if (td->td_upcall)
1389 			upcall_remove(td);
1390 
1391 		sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
1392 		sched_exit_kse(FIRST_KSE_IN_PROC(p), ke);
1393 		ke->ke_state = KES_UNQUEUED;
1394 		ke->ke_thread = NULL;
1395 		/*
1396 		 * Decide what to do with the KSE attached to this thread.
1397 		 */
1398 		if (ke->ke_flags & KEF_EXIT) {
1399 			kse_unlink(ke);
1400 			if (kg->kg_kses == 0) {
1401 				sched_exit_ksegrp(FIRST_KSEGRP_IN_PROC(p), kg);
1402 				ksegrp_unlink(kg);
1403 			}
1404 		}
1405 		else
1406 			kse_reassign(ke);
1407 		PROC_UNLOCK(p);
1408 		td->td_kse	= NULL;
1409 		td->td_state	= TDS_INACTIVE;
1410 #if 0
1411 		td->td_proc	= NULL;
1412 #endif
1413 		td->td_ksegrp	= NULL;
1414 		td->td_last_kse	= NULL;
1415 		PCPU_SET(deadthread, td);
1416 	} else {
1417 		PROC_UNLOCK(p);
1418 	}
1419 	/* XXX Shouldn't cpu_throw() here. */
1420 	mtx_assert(&sched_lock, MA_OWNED);
1421 	cpu_throw(td, choosethread());
1422 	panic("I'm a teapot!");
1423 	/* NOTREACHED */
1424 }
1425 
1426 /*
1427  * Do any thread specific cleanups that may be needed in wait()
1428  * called with Giant, proc and schedlock not held.
1429  */
1430 void
1431 thread_wait(struct proc *p)
1432 {
1433 	struct thread *td;
1434 
1435 	mtx_assert(&Giant, MA_NOTOWNED);
1436 	KASSERT((p->p_numthreads == 1), ("Multiple threads in wait1()"));
1437 	KASSERT((p->p_numksegrps == 1), ("Multiple ksegrps in wait1()"));
1438 	FOREACH_THREAD_IN_PROC(p, td) {
1439 		if (td->td_standin != NULL) {
1440 			thread_free(td->td_standin);
1441 			td->td_standin = NULL;
1442 		}
1443 		cpu_thread_clean(td);
1444 	}
1445 	thread_reap();	/* check for zombie threads etc. */
1446 }
1447 
1448 /*
1449  * Link a thread to a process.
1450  * set up anything that needs to be initialized for it to
1451  * be used by the process.
1452  *
1453  * Note that we do not link to the proc's ucred here.
1454  * The thread is linked as if running but no KSE assigned.
1455  */
1456 void
1457 thread_link(struct thread *td, struct ksegrp *kg)
1458 {
1459 	struct proc *p;
1460 
1461 	p = kg->kg_proc;
1462 	td->td_state    = TDS_INACTIVE;
1463 	td->td_proc     = p;
1464 	td->td_ksegrp   = kg;
1465 	td->td_last_kse = NULL;
1466 	td->td_flags    = 0;
1467 	td->td_kse      = NULL;
1468 
1469 	LIST_INIT(&td->td_contested);
1470 	callout_init(&td->td_slpcallout, CALLOUT_MPSAFE);
1471 	TAILQ_INSERT_HEAD(&p->p_threads, td, td_plist);
1472 	TAILQ_INSERT_HEAD(&kg->kg_threads, td, td_kglist);
1473 	p->p_numthreads++;
1474 	kg->kg_numthreads++;
1475 }
1476 
1477 void
1478 thread_unlink(struct thread *td)
1479 {
1480 	struct proc *p = td->td_proc;
1481 	struct ksegrp *kg = td->td_ksegrp;
1482 
1483 	mtx_assert(&sched_lock, MA_OWNED);
1484 	TAILQ_REMOVE(&p->p_threads, td, td_plist);
1485 	p->p_numthreads--;
1486 	TAILQ_REMOVE(&kg->kg_threads, td, td_kglist);
1487 	kg->kg_numthreads--;
1488 	/* could clear a few other things here */
1489 }
1490 
1491 /*
1492  * Purge a ksegrp resource. When a ksegrp is preparing to
1493  * exit, it calls this function.
1494  */
1495 static void
1496 kse_purge_group(struct thread *td)
1497 {
1498 	struct ksegrp *kg;
1499 	struct kse *ke;
1500 
1501 	kg = td->td_ksegrp;
1502  	KASSERT(kg->kg_numthreads == 1, ("%s: bad thread number", __func__));
1503 	while ((ke = TAILQ_FIRST(&kg->kg_iq)) != NULL) {
1504 		KASSERT(ke->ke_state == KES_IDLE,
1505 			("%s: wrong idle KSE state", __func__));
1506 		kse_unlink(ke);
1507 	}
1508 	KASSERT((kg->kg_kses == 1),
1509 		("%s: ksegrp still has %d KSEs", __func__, kg->kg_kses));
1510 	KASSERT((kg->kg_numupcalls == 0),
1511 	        ("%s: ksegrp still has %d upcall datas",
1512 		__func__, kg->kg_numupcalls));
1513 }
1514 
1515 /*
1516  * Purge a process's KSE resource. When a process is preparing to
1517  * exit, it calls kse_purge to release any extra KSE resources in
1518  * the process.
1519  */
1520 static void
1521 kse_purge(struct proc *p, struct thread *td)
1522 {
1523 	struct ksegrp *kg;
1524 	struct kse *ke;
1525 
1526  	KASSERT(p->p_numthreads == 1, ("bad thread number"));
1527 	while ((kg = TAILQ_FIRST(&p->p_ksegrps)) != NULL) {
1528 		TAILQ_REMOVE(&p->p_ksegrps, kg, kg_ksegrp);
1529 		p->p_numksegrps--;
1530 		/*
1531 		 * There is no ownership for KSE, after all threads
1532 		 * in the group exited, it is possible that some KSEs
1533 		 * were left in idle queue, gc them now.
1534 		 */
1535 		while ((ke = TAILQ_FIRST(&kg->kg_iq)) != NULL) {
1536 			KASSERT(ke->ke_state == KES_IDLE,
1537 			   ("%s: wrong idle KSE state", __func__));
1538 			TAILQ_REMOVE(&kg->kg_iq, ke, ke_kgrlist);
1539 			kg->kg_idle_kses--;
1540 			TAILQ_REMOVE(&kg->kg_kseq, ke, ke_kglist);
1541 			kg->kg_kses--;
1542 			kse_stash(ke);
1543 		}
1544 		KASSERT(((kg->kg_kses == 0) && (kg != td->td_ksegrp)) ||
1545 		        ((kg->kg_kses == 1) && (kg == td->td_ksegrp)),
1546 		        ("ksegrp has wrong kg_kses: %d", kg->kg_kses));
1547 		KASSERT((kg->kg_numupcalls == 0),
1548 		        ("%s: ksegrp still has %d upcall datas",
1549 			__func__, kg->kg_numupcalls));
1550 
1551 		if (kg != td->td_ksegrp)
1552 			ksegrp_stash(kg);
1553 	}
1554 	TAILQ_INSERT_HEAD(&p->p_ksegrps, td->td_ksegrp, kg_ksegrp);
1555 	p->p_numksegrps++;
1556 }
1557 
1558 /*
1559  * This function is intended to be used to initialize a spare thread
1560  * for upcall. Initialize thread's large data area outside sched_lock
1561  * for thread_schedule_upcall().
1562  */
1563 void
1564 thread_alloc_spare(struct thread *td, struct thread *spare)
1565 {
1566 
1567 	if (td->td_standin)
1568 		return;
1569 	if (spare == NULL) {
1570 		spare = thread_alloc();
1571 		spare->td_tid = thread_new_tid();
1572 	}
1573 	td->td_standin = spare;
1574 	bzero(&spare->td_startzero,
1575 	    (unsigned)RANGEOF(struct thread, td_startzero, td_endzero));
1576 	spare->td_proc = td->td_proc;
1577 	spare->td_ucred = crhold(td->td_ucred);
1578 }
1579 
1580 /*
1581  * Create a thread and schedule it for upcall on the KSE given.
1582  * Use our thread's standin so that we don't have to allocate one.
1583  */
1584 struct thread *
1585 thread_schedule_upcall(struct thread *td, struct kse_upcall *ku)
1586 {
1587 	struct thread *td2;
1588 
1589 	mtx_assert(&sched_lock, MA_OWNED);
1590 
1591 	/*
1592 	 * Schedule an upcall thread on specified kse_upcall,
1593 	 * the kse_upcall must be free.
1594 	 * td must have a spare thread.
1595 	 */
1596 	KASSERT(ku->ku_owner == NULL, ("%s: upcall has owner", __func__));
1597 	if ((td2 = td->td_standin) != NULL) {
1598 		td->td_standin = NULL;
1599 	} else {
1600 		panic("no reserve thread when scheduling an upcall");
1601 		return (NULL);
1602 	}
1603 	CTR3(KTR_PROC, "thread_schedule_upcall: thread %p (pid %d, %s)",
1604 	     td2, td->td_proc->p_pid, td->td_proc->p_comm);
1605 	bcopy(&td->td_startcopy, &td2->td_startcopy,
1606 	    (unsigned) RANGEOF(struct thread, td_startcopy, td_endcopy));
1607 	thread_link(td2, ku->ku_ksegrp);
1608 	/* inherit blocked thread's context */
1609 	cpu_set_upcall(td2, td);
1610 	/* Let the new thread become owner of the upcall */
1611 	ku->ku_owner   = td2;
1612 	td2->td_upcall = ku;
1613 	td2->td_flags  = TDF_SA;
1614 	td2->td_pflags = TDP_UPCALLING;
1615 	td2->td_kse    = NULL;
1616 	td2->td_state  = TDS_CAN_RUN;
1617 	td2->td_inhibitors = 0;
1618 	SIGFILLSET(td2->td_sigmask);
1619 	SIG_CANTMASK(td2->td_sigmask);
1620 	sched_fork_thread(td, td2);
1621 	return (td2);	/* bogus.. should be a void function */
1622 }
1623 
1624 /*
1625  * It is only used when thread generated a trap and process is being
1626  * debugged.
1627  */
1628 void
1629 thread_signal_add(struct thread *td, int sig)
1630 {
1631 	struct proc *p;
1632 	siginfo_t siginfo;
1633 	struct sigacts *ps;
1634 	int error;
1635 
1636 	p = td->td_proc;
1637 	PROC_LOCK_ASSERT(p, MA_OWNED);
1638 	ps = p->p_sigacts;
1639 	mtx_assert(&ps->ps_mtx, MA_OWNED);
1640 
1641 	cpu_thread_siginfo(sig, 0, &siginfo);
1642 	mtx_unlock(&ps->ps_mtx);
1643 	PROC_UNLOCK(p);
1644 	error = copyout(&siginfo, &td->td_mailbox->tm_syncsig, sizeof(siginfo));
1645 	if (error) {
1646 		PROC_LOCK(p);
1647 		sigexit(td, SIGILL);
1648 	}
1649 	PROC_LOCK(p);
1650 	SIGADDSET(td->td_sigmask, sig);
1651 	mtx_lock(&ps->ps_mtx);
1652 }
1653 
1654 void
1655 thread_switchout(struct thread *td)
1656 {
1657 	struct kse_upcall *ku;
1658 	struct thread *td2;
1659 
1660 	mtx_assert(&sched_lock, MA_OWNED);
1661 
1662 	/*
1663 	 * If the outgoing thread is in threaded group and has never
1664 	 * scheduled an upcall, decide whether this is a short
1665 	 * or long term event and thus whether or not to schedule
1666 	 * an upcall.
1667 	 * If it is a short term event, just suspend it in
1668 	 * a way that takes its KSE with it.
1669 	 * Select the events for which we want to schedule upcalls.
1670 	 * For now it's just sleep.
1671 	 * XXXKSE eventually almost any inhibition could do.
1672 	 */
1673 	if (TD_CAN_UNBIND(td) && (td->td_standin) && TD_ON_SLEEPQ(td)) {
1674 		/*
1675 		 * Release ownership of upcall, and schedule an upcall
1676 		 * thread, this new upcall thread becomes the owner of
1677 		 * the upcall structure.
1678 		 */
1679 		ku = td->td_upcall;
1680 		ku->ku_owner = NULL;
1681 		td->td_upcall = NULL;
1682 		td->td_flags &= ~TDF_CAN_UNBIND;
1683 		td2 = thread_schedule_upcall(td, ku);
1684 		setrunqueue(td2);
1685 	}
1686 }
1687 
1688 /*
1689  * Setup done on the thread when it enters the kernel.
1690  * XXXKSE Presently only for syscalls but eventually all kernel entries.
1691  */
1692 void
1693 thread_user_enter(struct proc *p, struct thread *td)
1694 {
1695 	struct ksegrp *kg;
1696 	struct kse_upcall *ku;
1697 	struct kse_thr_mailbox *tmbx;
1698 	uint32_t tflags;
1699 
1700 	kg = td->td_ksegrp;
1701 
1702 	/*
1703 	 * First check that we shouldn't just abort.
1704 	 * But check if we are the single thread first!
1705 	 */
1706 	if (p->p_flag & P_SINGLE_EXIT) {
1707 		PROC_LOCK(p);
1708 		mtx_lock_spin(&sched_lock);
1709 		thread_stopped(p);
1710 		thread_exit();
1711 		/* NOTREACHED */
1712 	}
1713 
1714 	/*
1715 	 * If we are doing a syscall in a KSE environment,
1716 	 * note where our mailbox is. There is always the
1717 	 * possibility that we could do this lazily (in kse_reassign()),
1718 	 * but for now do it every time.
1719 	 */
1720 	kg = td->td_ksegrp;
1721 	if (td->td_flags & TDF_SA) {
1722 		ku = td->td_upcall;
1723 		KASSERT(ku, ("%s: no upcall owned", __func__));
1724 		KASSERT((ku->ku_owner == td), ("%s: wrong owner", __func__));
1725 		KASSERT(!TD_CAN_UNBIND(td), ("%s: can unbind", __func__));
1726 		ku->ku_mflags = fuword32((void *)&ku->ku_mailbox->km_flags);
1727 		tmbx = (void *)fuword((void *)&ku->ku_mailbox->km_curthread);
1728 		if ((tmbx == NULL) || (tmbx == (void *)-1L) ||
1729 		    (ku->ku_mflags & KMF_NOUPCALL)) {
1730 			td->td_mailbox = NULL;
1731 		} else {
1732 			if (td->td_standin == NULL)
1733 				thread_alloc_spare(td, NULL);
1734 			tflags = fuword32(&tmbx->tm_flags);
1735 			/*
1736 			 * On some architectures, TP register points to thread
1737 			 * mailbox but not points to kse mailbox, and userland
1738 			 * can not atomically clear km_curthread, but can
1739 			 * use TP register, and set TMF_NOUPCALL in thread
1740 			 * flag	to indicate a critical region.
1741 			 */
1742 			if (tflags & TMF_NOUPCALL) {
1743 				td->td_mailbox = NULL;
1744 			} else {
1745 				td->td_mailbox = tmbx;
1746 				mtx_lock_spin(&sched_lock);
1747 				td->td_flags |= TDF_CAN_UNBIND;
1748 				mtx_unlock_spin(&sched_lock);
1749 			}
1750 		}
1751 	}
1752 }
1753 
1754 /*
1755  * The extra work we go through if we are a threaded process when we
1756  * return to userland.
1757  *
1758  * If we are a KSE process and returning to user mode, check for
1759  * extra work to do before we return (e.g. for more syscalls
1760  * to complete first).  If we were in a critical section, we should
1761  * just return to let it finish. Same if we were in the UTS (in
1762  * which case the mailbox's context's busy indicator will be set).
1763  * The only traps we suport will have set the mailbox.
1764  * We will clear it here.
1765  */
1766 int
1767 thread_userret(struct thread *td, struct trapframe *frame)
1768 {
1769 	int error = 0, upcalls, uts_crit;
1770 	struct kse_upcall *ku;
1771 	struct ksegrp *kg, *kg2;
1772 	struct proc *p;
1773 	struct timespec ts;
1774 
1775 	p = td->td_proc;
1776 	kg = td->td_ksegrp;
1777 	ku = td->td_upcall;
1778 
1779 	/* Nothing to do with bound thread */
1780 	if (!(td->td_flags & TDF_SA))
1781 		return (0);
1782 
1783 	/*
1784 	 * Stat clock interrupt hit in userland, it
1785 	 * is returning from interrupt, charge thread's
1786 	 * userland time for UTS.
1787 	 */
1788 	if (td->td_flags & TDF_USTATCLOCK) {
1789 		thread_update_usr_ticks(td, 1);
1790 		mtx_lock_spin(&sched_lock);
1791 		td->td_flags &= ~TDF_USTATCLOCK;
1792 		mtx_unlock_spin(&sched_lock);
1793 		if (kg->kg_completed ||
1794 		    (td->td_upcall->ku_flags & KUF_DOUPCALL))
1795 			thread_user_enter(p, td);
1796 	}
1797 
1798 	uts_crit = (td->td_mailbox == NULL);
1799 	/*
1800 	 * Optimisation:
1801 	 * This thread has not started any upcall.
1802 	 * If there is no work to report other than ourself,
1803 	 * then it can return direct to userland.
1804 	 */
1805 	if (TD_CAN_UNBIND(td)) {
1806 		mtx_lock_spin(&sched_lock);
1807 		td->td_flags &= ~TDF_CAN_UNBIND;
1808 		if ((td->td_flags & TDF_NEEDSIGCHK) == 0 &&
1809 		    (kg->kg_completed == NULL) &&
1810 		    (ku->ku_flags & KUF_DOUPCALL) == 0 &&
1811 		    (kg->kg_upquantum && ticks < kg->kg_nextupcall)) {
1812 			mtx_unlock_spin(&sched_lock);
1813 			thread_update_usr_ticks(td, 0);
1814 			nanotime(&ts);
1815 			error = copyout(&ts,
1816 				(caddr_t)&ku->ku_mailbox->km_timeofday,
1817 				sizeof(ts));
1818 			td->td_mailbox = 0;
1819 			ku->ku_mflags = 0;
1820 			if (error)
1821 				goto out;
1822 			return (0);
1823 		}
1824 		mtx_unlock_spin(&sched_lock);
1825 		thread_export_context(td, 0);
1826 		/*
1827 		 * There is something to report, and we own an upcall
1828 		 * strucuture, we can go to userland.
1829 		 * Turn ourself into an upcall thread.
1830 		 */
1831 		td->td_pflags |= TDP_UPCALLING;
1832 	} else if (td->td_mailbox && (ku == NULL)) {
1833 		thread_export_context(td, 1);
1834 		PROC_LOCK(p);
1835 		/*
1836 		 * There are upcall threads waiting for
1837 		 * work to do, wake one of them up.
1838 		 * XXXKSE Maybe wake all of them up.
1839 		 */
1840 		if (kg->kg_upsleeps)
1841 			wakeup_one(&kg->kg_completed);
1842 		mtx_lock_spin(&sched_lock);
1843 		thread_stopped(p);
1844 		thread_exit();
1845 		/* NOTREACHED */
1846 	}
1847 
1848 	KASSERT(ku != NULL, ("upcall is NULL\n"));
1849 	KASSERT(TD_CAN_UNBIND(td) == 0, ("can unbind"));
1850 
1851 	if (p->p_numthreads > max_threads_per_proc) {
1852 		max_threads_hits++;
1853 		PROC_LOCK(p);
1854 		mtx_lock_spin(&sched_lock);
1855 		p->p_maxthrwaits++;
1856 		while (p->p_numthreads > max_threads_per_proc) {
1857 			upcalls = 0;
1858 			FOREACH_KSEGRP_IN_PROC(p, kg2) {
1859 				if (kg2->kg_numupcalls == 0)
1860 					upcalls++;
1861 				else
1862 					upcalls += kg2->kg_numupcalls;
1863 			}
1864 			if (upcalls >= max_threads_per_proc)
1865 				break;
1866 			mtx_unlock_spin(&sched_lock);
1867 			if (msleep(&p->p_numthreads, &p->p_mtx, PPAUSE|PCATCH,
1868 			    "maxthreads", 0)) {
1869 				mtx_lock_spin(&sched_lock);
1870 				break;
1871 			} else {
1872 				mtx_lock_spin(&sched_lock);
1873 			}
1874 		}
1875 		p->p_maxthrwaits--;
1876 		mtx_unlock_spin(&sched_lock);
1877 		PROC_UNLOCK(p);
1878 	}
1879 
1880 	if (td->td_pflags & TDP_UPCALLING) {
1881 		uts_crit = 0;
1882 		kg->kg_nextupcall = ticks+kg->kg_upquantum;
1883 		/*
1884 		 * There is no more work to do and we are going to ride
1885 		 * this thread up to userland as an upcall.
1886 		 * Do the last parts of the setup needed for the upcall.
1887 		 */
1888 		CTR3(KTR_PROC, "userret: upcall thread %p (pid %d, %s)",
1889 		    td, td->td_proc->p_pid, td->td_proc->p_comm);
1890 
1891 		td->td_pflags &= ~TDP_UPCALLING;
1892 		if (ku->ku_flags & KUF_DOUPCALL) {
1893 			mtx_lock_spin(&sched_lock);
1894 			ku->ku_flags &= ~KUF_DOUPCALL;
1895 			mtx_unlock_spin(&sched_lock);
1896 		}
1897 		/*
1898 		 * Set user context to the UTS
1899 		 */
1900 		if (!(ku->ku_mflags & KMF_NOUPCALL)) {
1901 			cpu_set_upcall_kse(td, ku);
1902 			error = suword(&ku->ku_mailbox->km_curthread, 0);
1903 			if (error)
1904 				goto out;
1905 		}
1906 
1907 		/*
1908 		 * Unhook the list of completed threads.
1909 		 * anything that completes after this gets to
1910 		 * come in next time.
1911 		 * Put the list of completed thread mailboxes on
1912 		 * this KSE's mailbox.
1913 		 */
1914 		if (!(ku->ku_mflags & KMF_NOCOMPLETED) &&
1915 		    (error = thread_link_mboxes(kg, ku)) != 0)
1916 			goto out;
1917 	}
1918 	if (!uts_crit) {
1919 		nanotime(&ts);
1920 		error = copyout(&ts, &ku->ku_mailbox->km_timeofday, sizeof(ts));
1921 	}
1922 
1923 out:
1924 	if (error) {
1925 		/*
1926 		 * Things are going to be so screwed we should just kill
1927 		 * the process.
1928 		 * how do we do that?
1929 		 */
1930 		PROC_LOCK(td->td_proc);
1931 		psignal(td->td_proc, SIGSEGV);
1932 		PROC_UNLOCK(td->td_proc);
1933 	} else {
1934 		/*
1935 		 * Optimisation:
1936 		 * Ensure that we have a spare thread available,
1937 		 * for when we re-enter the kernel.
1938 		 */
1939 		if (td->td_standin == NULL)
1940 			thread_alloc_spare(td, NULL);
1941 	}
1942 
1943 	ku->ku_mflags = 0;
1944 	/*
1945 	 * Clear thread mailbox first, then clear system tick count.
1946 	 * The order is important because thread_statclock() use
1947 	 * mailbox pointer to see if it is an userland thread or
1948 	 * an UTS kernel thread.
1949 	 */
1950 	td->td_mailbox = NULL;
1951 	td->td_usticks = 0;
1952 	return (error);	/* go sync */
1953 }
1954 
1955 /*
1956  * Enforce single-threading.
1957  *
1958  * Returns 1 if the caller must abort (another thread is waiting to
1959  * exit the process or similar). Process is locked!
1960  * Returns 0 when you are successfully the only thread running.
1961  * A process has successfully single threaded in the suspend mode when
1962  * There are no threads in user mode. Threads in the kernel must be
1963  * allowed to continue until they get to the user boundary. They may even
1964  * copy out their return values and data before suspending. They may however be
1965  * accellerated in reaching the user boundary as we will wake up
1966  * any sleeping threads that are interruptable. (PCATCH).
1967  */
1968 int
1969 thread_single(int force_exit)
1970 {
1971 	struct thread *td;
1972 	struct thread *td2;
1973 	struct proc *p;
1974 
1975 	td = curthread;
1976 	p = td->td_proc;
1977 	mtx_assert(&Giant, MA_NOTOWNED);
1978 	PROC_LOCK_ASSERT(p, MA_OWNED);
1979 	KASSERT((td != NULL), ("curthread is NULL"));
1980 
1981 	if ((p->p_flag & P_SA) == 0 && p->p_numthreads == 1)
1982 		return (0);
1983 
1984 	/* Is someone already single threading? */
1985 	if (p->p_singlethread)
1986 		return (1);
1987 
1988 	if (force_exit == SINGLE_EXIT) {
1989 		p->p_flag |= P_SINGLE_EXIT;
1990 	} else
1991 		p->p_flag &= ~P_SINGLE_EXIT;
1992 	p->p_flag |= P_STOPPED_SINGLE;
1993 	mtx_lock_spin(&sched_lock);
1994 	p->p_singlethread = td;
1995 	while ((p->p_numthreads - p->p_suspcount) != 1) {
1996 		FOREACH_THREAD_IN_PROC(p, td2) {
1997 			if (td2 == td)
1998 				continue;
1999 			td2->td_flags |= TDF_ASTPENDING;
2000 			if (TD_IS_INHIBITED(td2)) {
2001 				if (force_exit == SINGLE_EXIT) {
2002 					if (TD_IS_SUSPENDED(td2)) {
2003 						thread_unsuspend_one(td2);
2004 					}
2005 					if (TD_ON_SLEEPQ(td2) &&
2006 					    (td2->td_flags & TDF_SINTR)) {
2007 						sleepq_abort(td2);
2008 					}
2009 				} else {
2010 					if (TD_IS_SUSPENDED(td2))
2011 						continue;
2012 					/*
2013 					 * maybe other inhibitted states too?
2014 					 * XXXKSE Is it totally safe to
2015 					 * suspend a non-interruptable thread?
2016 					 */
2017 					if (td2->td_inhibitors &
2018 					    (TDI_SLEEPING | TDI_SWAPPED))
2019 						thread_suspend_one(td2);
2020 				}
2021 			}
2022 		}
2023 		/*
2024 		 * Maybe we suspended some threads.. was it enough?
2025 		 */
2026 		if ((p->p_numthreads - p->p_suspcount) == 1)
2027 			break;
2028 
2029 		/*
2030 		 * Wake us up when everyone else has suspended.
2031 		 * In the mean time we suspend as well.
2032 		 */
2033 		thread_suspend_one(td);
2034 		PROC_UNLOCK(p);
2035 		mi_switch(SW_VOL);
2036 		mtx_unlock_spin(&sched_lock);
2037 		PROC_LOCK(p);
2038 		mtx_lock_spin(&sched_lock);
2039 	}
2040 	if (force_exit == SINGLE_EXIT) {
2041 		if (td->td_upcall)
2042 			upcall_remove(td);
2043 		kse_purge(p, td);
2044 	}
2045 	mtx_unlock_spin(&sched_lock);
2046 	return (0);
2047 }
2048 
2049 /*
2050  * Called in from locations that can safely check to see
2051  * whether we have to suspend or at least throttle for a
2052  * single-thread event (e.g. fork).
2053  *
2054  * Such locations include userret().
2055  * If the "return_instead" argument is non zero, the thread must be able to
2056  * accept 0 (caller may continue), or 1 (caller must abort) as a result.
2057  *
2058  * The 'return_instead' argument tells the function if it may do a
2059  * thread_exit() or suspend, or whether the caller must abort and back
2060  * out instead.
2061  *
2062  * If the thread that set the single_threading request has set the
2063  * P_SINGLE_EXIT bit in the process flags then this call will never return
2064  * if 'return_instead' is false, but will exit.
2065  *
2066  * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
2067  *---------------+--------------------+---------------------
2068  *       0       | returns 0          |   returns 0 or 1
2069  *               | when ST ends       |   immediatly
2070  *---------------+--------------------+---------------------
2071  *       1       | thread exits       |   returns 1
2072  *               |                    |  immediatly
2073  * 0 = thread_exit() or suspension ok,
2074  * other = return error instead of stopping the thread.
2075  *
2076  * While a full suspension is under effect, even a single threading
2077  * thread would be suspended if it made this call (but it shouldn't).
2078  * This call should only be made from places where
2079  * thread_exit() would be safe as that may be the outcome unless
2080  * return_instead is set.
2081  */
2082 int
2083 thread_suspend_check(int return_instead)
2084 {
2085 	struct thread *td;
2086 	struct proc *p;
2087 
2088 	td = curthread;
2089 	p = td->td_proc;
2090 	mtx_assert(&Giant, MA_NOTOWNED);
2091 	PROC_LOCK_ASSERT(p, MA_OWNED);
2092 	while (P_SHOULDSTOP(p)) {
2093 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
2094 			KASSERT(p->p_singlethread != NULL,
2095 			    ("singlethread not set"));
2096 			/*
2097 			 * The only suspension in action is a
2098 			 * single-threading. Single threader need not stop.
2099 			 * XXX Should be safe to access unlocked
2100 			 * as it can only be set to be true by us.
2101 			 */
2102 			if (p->p_singlethread == td)
2103 				return (0);	/* Exempt from stopping. */
2104 		}
2105 		if (return_instead)
2106 			return (1);
2107 
2108 		mtx_lock_spin(&sched_lock);
2109 		thread_stopped(p);
2110 		/*
2111 		 * If the process is waiting for us to exit,
2112 		 * this thread should just suicide.
2113 		 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
2114 		 */
2115 		if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
2116 			if (p->p_flag & P_SA)
2117 				thread_exit();
2118 			else
2119 				thr_exit1();
2120 		}
2121 
2122 		/*
2123 		 * When a thread suspends, it just
2124 		 * moves to the processes's suspend queue
2125 		 * and stays there.
2126 		 */
2127 		thread_suspend_one(td);
2128 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
2129 			if (p->p_numthreads == p->p_suspcount) {
2130 				thread_unsuspend_one(p->p_singlethread);
2131 			}
2132 		}
2133 		PROC_UNLOCK(p);
2134 		mi_switch(SW_INVOL);
2135 		mtx_unlock_spin(&sched_lock);
2136 		PROC_LOCK(p);
2137 	}
2138 	return (0);
2139 }
2140 
2141 void
2142 thread_suspend_one(struct thread *td)
2143 {
2144 	struct proc *p = td->td_proc;
2145 
2146 	mtx_assert(&sched_lock, MA_OWNED);
2147 	PROC_LOCK_ASSERT(p, MA_OWNED);
2148 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
2149 	p->p_suspcount++;
2150 	TD_SET_SUSPENDED(td);
2151 	TAILQ_INSERT_TAIL(&p->p_suspended, td, td_runq);
2152 	/*
2153 	 * Hack: If we are suspending but are on the sleep queue
2154 	 * then we are in msleep or the cv equivalent. We
2155 	 * want to look like we have two Inhibitors.
2156 	 * May already be set.. doesn't matter.
2157 	 */
2158 	if (TD_ON_SLEEPQ(td))
2159 		TD_SET_SLEEPING(td);
2160 }
2161 
2162 void
2163 thread_unsuspend_one(struct thread *td)
2164 {
2165 	struct proc *p = td->td_proc;
2166 
2167 	mtx_assert(&sched_lock, MA_OWNED);
2168 	PROC_LOCK_ASSERT(p, MA_OWNED);
2169 	TAILQ_REMOVE(&p->p_suspended, td, td_runq);
2170 	TD_CLR_SUSPENDED(td);
2171 	p->p_suspcount--;
2172 	setrunnable(td);
2173 }
2174 
2175 /*
2176  * Allow all threads blocked by single threading to continue running.
2177  */
2178 void
2179 thread_unsuspend(struct proc *p)
2180 {
2181 	struct thread *td;
2182 
2183 	mtx_assert(&sched_lock, MA_OWNED);
2184 	PROC_LOCK_ASSERT(p, MA_OWNED);
2185 	if (!P_SHOULDSTOP(p)) {
2186 		while (( td = TAILQ_FIRST(&p->p_suspended))) {
2187 			thread_unsuspend_one(td);
2188 		}
2189 	} else if ((P_SHOULDSTOP(p) == P_STOPPED_SINGLE) &&
2190 	    (p->p_numthreads == p->p_suspcount)) {
2191 		/*
2192 		 * Stopping everything also did the job for the single
2193 		 * threading request. Now we've downgraded to single-threaded,
2194 		 * let it continue.
2195 		 */
2196 		thread_unsuspend_one(p->p_singlethread);
2197 	}
2198 }
2199 
2200 void
2201 thread_single_end(void)
2202 {
2203 	struct thread *td;
2204 	struct proc *p;
2205 
2206 	td = curthread;
2207 	p = td->td_proc;
2208 	PROC_LOCK_ASSERT(p, MA_OWNED);
2209 	p->p_flag &= ~P_STOPPED_SINGLE;
2210 	mtx_lock_spin(&sched_lock);
2211 	p->p_singlethread = NULL;
2212 	/*
2213 	 * If there are other threads they mey now run,
2214 	 * unless of course there is a blanket 'stop order'
2215 	 * on the process. The single threader must be allowed
2216 	 * to continue however as this is a bad place to stop.
2217 	 */
2218 	if ((p->p_numthreads != 1) && (!P_SHOULDSTOP(p))) {
2219 		while (( td = TAILQ_FIRST(&p->p_suspended))) {
2220 			thread_unsuspend_one(td);
2221 		}
2222 	}
2223 	mtx_unlock_spin(&sched_lock);
2224 }
2225