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