2 * Copyright (C) 2001 Julian Elischer <julian@freebsd.org>.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
29 #include "opt_witness.h"
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
38 #include <sys/mutex.h>
40 #include <sys/resourcevar.h>
42 #include <sys/sysctl.h>
43 #include <sys/sched.h>
44 #include <sys/sleepqueue.h>
45 #include <sys/selinfo.h>
46 #include <sys/turnstile.h>
49 #include <sys/cpuset.h>
51 #include <security/audit/audit.h>
54 #include <vm/vm_extern.h>
56 #include <sys/eventhandler.h>
59 * thread related storage.
61 static uma_zone_t thread_zone;
63 SYSCTL_NODE(_kern, OID_AUTO, threads, CTLFLAG_RW, 0, "thread allocation");
65 int max_threads_per_proc = 1500;
66 SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_per_proc, CTLFLAG_RW,
67 &max_threads_per_proc, 0, "Limit on threads per proc");
70 SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_hits, CTLFLAG_RD,
71 &max_threads_hits, 0, "");
73 TAILQ_HEAD(, thread) zombie_threads = TAILQ_HEAD_INITIALIZER(zombie_threads);
74 static struct mtx zombie_lock;
75 MTX_SYSINIT(zombie_lock, &zombie_lock, "zombie lock", MTX_SPIN);
77 static void thread_zombie(struct thread *);
80 static struct unrhdr *tid_unrhdr;
83 * Prepare a thread for use.
86 thread_ctor(void *mem, int size, void *arg, int flags)
90 td = (struct thread *)mem;
91 td->td_state = TDS_INACTIVE;
94 td->td_tid = alloc_unr(tid_unrhdr);
98 * Note that td_critnest begins life as 1 because the thread is not
99 * running and is thereby implicitly waiting to be on the receiving
100 * end of a context switch.
103 EVENTHANDLER_INVOKE(thread_ctor, td);
105 audit_thread_alloc(td);
107 umtx_thread_alloc(td);
112 * Reclaim a thread after use.
115 thread_dtor(void *mem, int size, void *arg)
119 td = (struct thread *)mem;
122 /* Verify that this thread is in a safe state to free. */
123 switch (td->td_state) {
129 * We must never unlink a thread that is in one of
130 * these states, because it is currently active.
132 panic("bad state for thread unlinking");
137 panic("bad thread state");
142 audit_thread_free(td);
144 /* Free all OSD associated to this thread. */
147 EVENTHANDLER_INVOKE(thread_dtor, td);
148 free_unr(tid_unrhdr, td->td_tid);
152 * Initialize type-stable parts of a thread (when newly created).
155 thread_init(void *mem, int size, int flags)
159 td = (struct thread *)mem;
161 td->td_sleepqueue = sleepq_alloc();
162 td->td_turnstile = turnstile_alloc();
163 EVENTHANDLER_INVOKE(thread_init, td);
164 td->td_sched = (struct td_sched *)&td[1];
165 umtx_thread_init(td);
171 * Tear down type-stable parts of a thread (just before being discarded).
174 thread_fini(void *mem, int size)
178 td = (struct thread *)mem;
179 EVENTHANDLER_INVOKE(thread_fini, td);
180 turnstile_free(td->td_turnstile);
181 sleepq_free(td->td_sleepqueue);
182 umtx_thread_fini(td);
187 * For a newly created process,
188 * link up all the structures and its initial threads etc.
190 * {arch}/{arch}/machdep.c ia64_init(), init386() etc.
191 * proc_dtor() (should go away)
195 proc_linkup0(struct proc *p, struct thread *td)
197 TAILQ_INIT(&p->p_threads); /* all threads in proc */
202 proc_linkup(struct proc *p, struct thread *td)
205 sigqueue_init(&p->p_sigqueue, p);
206 p->p_ksi = ksiginfo_alloc(1);
207 if (p->p_ksi != NULL) {
208 /* XXX p_ksi may be null if ksiginfo zone is not ready */
209 p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
211 LIST_INIT(&p->p_mqnotifier);
217 * Initialize global thread allocation resources.
223 mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
224 /* leave one number for thread0 */
225 tid_unrhdr = new_unrhdr(PID_MAX + 2, INT_MAX, &tid_lock);
227 thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
228 thread_ctor, thread_dtor, thread_init, thread_fini,
233 * Place an unused thread on the zombie list.
234 * Use the slpq as that must be unused by now.
237 thread_zombie(struct thread *td)
239 mtx_lock_spin(&zombie_lock);
240 TAILQ_INSERT_HEAD(&zombie_threads, td, td_slpq);
241 mtx_unlock_spin(&zombie_lock);
245 * Release a thread that has exited after cpu_throw().
248 thread_stash(struct thread *td)
250 atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
255 * Reap zombie resources.
260 struct thread *td_first, *td_next;
263 * Don't even bother to lock if none at this instant,
264 * we really don't care about the next instant..
266 if (!TAILQ_EMPTY(&zombie_threads)) {
267 mtx_lock_spin(&zombie_lock);
268 td_first = TAILQ_FIRST(&zombie_threads);
270 TAILQ_INIT(&zombie_threads);
271 mtx_unlock_spin(&zombie_lock);
273 td_next = TAILQ_NEXT(td_first, td_slpq);
274 if (td_first->td_ucred)
275 crfree(td_first->td_ucred);
276 thread_free(td_first);
290 thread_reap(); /* check if any zombies to get */
292 td = (struct thread *)uma_zalloc(thread_zone, M_WAITOK);
293 KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
294 if (!vm_thread_new(td, 0)) {
295 uma_zfree(thread_zone, td);
298 cpu_thread_alloc(td);
304 * Deallocate a thread.
307 thread_free(struct thread *td)
310 lock_profile_thread_exit(td);
312 cpuset_rel(td->td_cpuset);
313 td->td_cpuset = NULL;
315 if (td->td_altkstack != 0)
316 vm_thread_dispose_altkstack(td);
317 if (td->td_kstack != 0)
318 vm_thread_dispose(td);
319 uma_zfree(thread_zone, td);
323 * Discard the current thread and exit from its context.
324 * Always called with scheduler locked.
326 * Because we can't free a thread while we're operating under its context,
327 * push the current thread into our CPU's deadthread holder. This means
328 * we needn't worry about someone else grabbing our context before we
334 uint64_t new_switchtime;
343 PROC_SLOCK_ASSERT(p, MA_OWNED);
344 mtx_assert(&Giant, MA_NOTOWNED);
346 PROC_LOCK_ASSERT(p, MA_OWNED);
347 KASSERT(p != NULL, ("thread exiting without a process"));
348 CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
349 (long)p->p_pid, td->td_name);
350 KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
353 AUDIT_SYSCALL_EXIT(0, td);
355 umtx_thread_exit(td);
357 * drop FPU & debug register state storage, or any other
358 * architecture specific resources that
359 * would not be on a new untouched process.
361 cpu_thread_exit(td); /* XXXSMP */
363 /* Do the same timestamp bookkeeping that mi_switch() would do. */
364 new_switchtime = cpu_ticks();
365 p->p_rux.rux_runtime += (new_switchtime - PCPU_GET(switchtime));
366 PCPU_SET(switchtime, new_switchtime);
367 PCPU_SET(switchticks, ticks);
368 PCPU_INC(cnt.v_swtch);
369 /* Save our resource usage in our process. */
370 td->td_ru.ru_nvcsw++;
371 rucollect(&p->p_ru, &td->td_ru);
373 * The last thread is left attached to the process
374 * So that the whole bundle gets recycled. Skip
375 * all this stuff if we never had threads.
376 * EXIT clears all sign of other threads when
377 * it goes to single threading, so the last thread always
378 * takes the short path.
380 if (p->p_flag & P_HADTHREADS) {
381 if (p->p_numthreads > 1) {
383 td2 = FIRST_THREAD_IN_PROC(p);
384 sched_exit_thread(td2, td);
387 * The test below is NOT true if we are the
388 * sole exiting thread. P_STOPPED_SNGL is unset
389 * in exit1() after it is the only survivor.
391 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
392 if (p->p_numthreads == p->p_suspcount) {
393 thread_lock(p->p_singlethread);
394 wakeup_swapper = thread_unsuspend_one(
396 thread_unlock(p->p_singlethread);
402 atomic_add_int(&td->td_proc->p_exitthreads, 1);
403 PCPU_SET(deadthread, td);
406 * The last thread is exiting.. but not through exit()
408 panic ("thread_exit: Last thread exiting on its own");
413 /* Save our tick information with both the thread and proc locked */
414 ruxagg(&p->p_rux, td);
416 td->td_state = TDS_INACTIVE;
418 witness_thread_exit(td);
420 CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
422 panic("I'm a teapot!");
427 * Do any thread specific cleanups that may be needed in wait()
428 * called with Giant, proc and schedlock not held.
431 thread_wait(struct proc *p)
435 mtx_assert(&Giant, MA_NOTOWNED);
436 KASSERT((p->p_numthreads == 1), ("Multiple threads in wait1()"));
437 td = FIRST_THREAD_IN_PROC(p);
438 /* Lock the last thread so we spin until it exits cpu_throw(). */
441 /* Wait for any remaining threads to exit cpu_throw(). */
442 while (p->p_exitthreads)
443 sched_relinquish(curthread);
444 lock_profile_thread_exit(td);
445 cpuset_rel(td->td_cpuset);
446 td->td_cpuset = NULL;
447 cpu_thread_clean(td);
448 crfree(td->td_ucred);
449 thread_reap(); /* check for zombie threads etc. */
453 * Link a thread to a process.
454 * set up anything that needs to be initialized for it to
455 * be used by the process.
458 thread_link(struct thread *td, struct proc *p)
462 * XXX This can't be enabled because it's called for proc0 before
463 * its lock has been created.
464 * PROC_LOCK_ASSERT(p, MA_OWNED);
466 td->td_state = TDS_INACTIVE;
468 td->td_flags = TDF_INMEM;
470 LIST_INIT(&td->td_contested);
471 LIST_INIT(&td->td_lprof[0]);
472 LIST_INIT(&td->td_lprof[1]);
473 sigqueue_init(&td->td_sigqueue, p);
474 callout_init(&td->td_slpcallout, CALLOUT_MPSAFE);
475 TAILQ_INSERT_HEAD(&p->p_threads, td, td_plist);
480 * Convert a process with one thread to an unthreaded process.
483 thread_unthread(struct thread *td)
485 struct proc *p = td->td_proc;
487 KASSERT((p->p_numthreads == 1), ("Unthreading with >1 threads"));
488 p->p_flag &= ~P_HADTHREADS;
496 thread_unlink(struct thread *td)
498 struct proc *p = td->td_proc;
500 PROC_LOCK_ASSERT(p, MA_OWNED);
501 TAILQ_REMOVE(&p->p_threads, td, td_plist);
503 /* could clear a few other things here */
504 /* Must NOT clear links to proc! */
508 calc_remaining(struct proc *p, int mode)
512 if (mode == SINGLE_EXIT)
513 remaining = p->p_numthreads;
514 else if (mode == SINGLE_BOUNDARY)
515 remaining = p->p_numthreads - p->p_boundary_count;
516 else if (mode == SINGLE_NO_EXIT)
517 remaining = p->p_numthreads - p->p_suspcount;
519 panic("calc_remaining: wrong mode %d", mode);
524 * Enforce single-threading.
526 * Returns 1 if the caller must abort (another thread is waiting to
527 * exit the process or similar). Process is locked!
528 * Returns 0 when you are successfully the only thread running.
529 * A process has successfully single threaded in the suspend mode when
530 * There are no threads in user mode. Threads in the kernel must be
531 * allowed to continue until they get to the user boundary. They may even
532 * copy out their return values and data before suspending. They may however be
533 * accelerated in reaching the user boundary as we will wake up
534 * any sleeping threads that are interruptable. (PCATCH).
537 thread_single(int mode)
542 int remaining, wakeup_swapper;
546 mtx_assert(&Giant, MA_NOTOWNED);
547 PROC_LOCK_ASSERT(p, MA_OWNED);
548 KASSERT((td != NULL), ("curthread is NULL"));
550 if ((p->p_flag & P_HADTHREADS) == 0)
553 /* Is someone already single threading? */
554 if (p->p_singlethread != NULL && p->p_singlethread != td)
557 if (mode == SINGLE_EXIT) {
558 p->p_flag |= P_SINGLE_EXIT;
559 p->p_flag &= ~P_SINGLE_BOUNDARY;
561 p->p_flag &= ~P_SINGLE_EXIT;
562 if (mode == SINGLE_BOUNDARY)
563 p->p_flag |= P_SINGLE_BOUNDARY;
565 p->p_flag &= ~P_SINGLE_BOUNDARY;
567 p->p_flag |= P_STOPPED_SINGLE;
569 p->p_singlethread = td;
570 remaining = calc_remaining(p, mode);
571 while (remaining != 1) {
572 if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
575 FOREACH_THREAD_IN_PROC(p, td2) {
579 td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
580 if (TD_IS_INHIBITED(td2)) {
583 if (TD_IS_SUSPENDED(td2))
585 thread_unsuspend_one(td2);
586 if (TD_ON_SLEEPQ(td2) &&
587 (td2->td_flags & TDF_SINTR))
589 sleepq_abort(td2, EINTR);
591 case SINGLE_BOUNDARY:
592 if (TD_IS_SUSPENDED(td2) &&
593 !(td2->td_flags & TDF_BOUNDARY))
595 thread_unsuspend_one(td2);
596 if (TD_ON_SLEEPQ(td2) &&
597 (td2->td_flags & TDF_SINTR))
599 sleepq_abort(td2, ERESTART);
602 if (TD_IS_SUSPENDED(td2) &&
603 !(td2->td_flags & TDF_BOUNDARY))
605 thread_unsuspend_one(td2);
606 if (TD_ON_SLEEPQ(td2) &&
607 (td2->td_flags & TDF_SINTR))
609 sleepq_abort(td2, ERESTART);
616 else if (TD_IS_RUNNING(td2) && td != td2) {
624 remaining = calc_remaining(p, mode);
627 * Maybe we suspended some threads.. was it enough?
634 * Wake us up when everyone else has suspended.
635 * In the mean time we suspend as well.
637 thread_suspend_switch(td);
638 remaining = calc_remaining(p, mode);
640 if (mode == SINGLE_EXIT) {
642 * We have gotten rid of all the other threads and we
643 * are about to either exit or exec. In either case,
644 * we try our utmost to revert to being a non-threaded
647 p->p_singlethread = NULL;
648 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT);
656 * Called in from locations that can safely check to see
657 * whether we have to suspend or at least throttle for a
658 * single-thread event (e.g. fork).
660 * Such locations include userret().
661 * If the "return_instead" argument is non zero, the thread must be able to
662 * accept 0 (caller may continue), or 1 (caller must abort) as a result.
664 * The 'return_instead' argument tells the function if it may do a
665 * thread_exit() or suspend, or whether the caller must abort and back
668 * If the thread that set the single_threading request has set the
669 * P_SINGLE_EXIT bit in the process flags then this call will never return
670 * if 'return_instead' is false, but will exit.
672 * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
673 *---------------+--------------------+---------------------
674 * 0 | returns 0 | returns 0 or 1
675 * | when ST ends | immediatly
676 *---------------+--------------------+---------------------
677 * 1 | thread exits | returns 1
679 * 0 = thread_exit() or suspension ok,
680 * other = return error instead of stopping the thread.
682 * While a full suspension is under effect, even a single threading
683 * thread would be suspended if it made this call (but it shouldn't).
684 * This call should only be made from places where
685 * thread_exit() would be safe as that may be the outcome unless
686 * return_instead is set.
689 thread_suspend_check(int return_instead)
697 mtx_assert(&Giant, MA_NOTOWNED);
698 PROC_LOCK_ASSERT(p, MA_OWNED);
699 while (P_SHOULDSTOP(p) ||
700 ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_SUSPEND))) {
701 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
702 KASSERT(p->p_singlethread != NULL,
703 ("singlethread not set"));
705 * The only suspension in action is a
706 * single-threading. Single threader need not stop.
707 * XXX Should be safe to access unlocked
708 * as it can only be set to be true by us.
710 if (p->p_singlethread == td)
711 return (0); /* Exempt from stopping. */
713 if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
716 /* Should we goto user boundary if we didn't come from there? */
717 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
718 (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
721 /* If thread will exit, flush its pending signals */
722 if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td))
723 sigqueue_flush(&td->td_sigqueue);
728 * If the process is waiting for us to exit,
729 * this thread should just suicide.
730 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
732 if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td))
734 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
735 if (p->p_numthreads == p->p_suspcount + 1) {
736 thread_lock(p->p_singlethread);
738 thread_unsuspend_one(p->p_singlethread);
739 thread_unlock(p->p_singlethread);
747 * When a thread suspends, it just
748 * gets taken off all queues.
750 thread_suspend_one(td);
751 if (return_instead == 0) {
752 p->p_boundary_count++;
753 td->td_flags |= TDF_BOUNDARY;
756 mi_switch(SW_INVOL | SWT_SUSPEND, NULL);
757 if (return_instead == 0)
758 td->td_flags &= ~TDF_BOUNDARY;
761 if (return_instead == 0)
762 p->p_boundary_count--;
768 thread_suspend_switch(struct thread *td)
773 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
774 PROC_LOCK_ASSERT(p, MA_OWNED);
775 PROC_SLOCK_ASSERT(p, MA_OWNED);
777 * We implement thread_suspend_one in stages here to avoid
778 * dropping the proc lock while the thread lock is owned.
784 td->td_flags &= ~TDF_NEEDSUSPCHK;
785 TD_SET_SUSPENDED(td);
789 mi_switch(SW_VOL | SWT_SUSPEND, NULL);
797 thread_suspend_one(struct thread *td)
799 struct proc *p = td->td_proc;
801 PROC_SLOCK_ASSERT(p, MA_OWNED);
802 THREAD_LOCK_ASSERT(td, MA_OWNED);
803 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
805 td->td_flags &= ~TDF_NEEDSUSPCHK;
806 TD_SET_SUSPENDED(td);
811 thread_unsuspend_one(struct thread *td)
813 struct proc *p = td->td_proc;
815 PROC_SLOCK_ASSERT(p, MA_OWNED);
816 THREAD_LOCK_ASSERT(td, MA_OWNED);
817 KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
818 TD_CLR_SUSPENDED(td);
820 return (setrunnable(td));
824 * Allow all threads blocked by single threading to continue running.
827 thread_unsuspend(struct proc *p)
832 PROC_LOCK_ASSERT(p, MA_OWNED);
833 PROC_SLOCK_ASSERT(p, MA_OWNED);
835 if (!P_SHOULDSTOP(p)) {
836 FOREACH_THREAD_IN_PROC(p, td) {
838 if (TD_IS_SUSPENDED(td)) {
839 wakeup_swapper |= thread_unsuspend_one(td);
843 } else if ((P_SHOULDSTOP(p) == P_STOPPED_SINGLE) &&
844 (p->p_numthreads == p->p_suspcount)) {
846 * Stopping everything also did the job for the single
847 * threading request. Now we've downgraded to single-threaded,
850 thread_lock(p->p_singlethread);
851 wakeup_swapper = thread_unsuspend_one(p->p_singlethread);
852 thread_unlock(p->p_singlethread);
859 * End the single threading mode..
862 thread_single_end(void)
870 PROC_LOCK_ASSERT(p, MA_OWNED);
871 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY);
873 p->p_singlethread = NULL;
876 * If there are other threads they may now run,
877 * unless of course there is a blanket 'stop order'
878 * on the process. The single threader must be allowed
879 * to continue however as this is a bad place to stop.
881 if ((p->p_numthreads != 1) && (!P_SHOULDSTOP(p))) {
882 FOREACH_THREAD_IN_PROC(p, td) {
884 if (TD_IS_SUSPENDED(td)) {
885 wakeup_swapper |= thread_unsuspend_one(td);
896 thread_find(struct proc *p, lwpid_t tid)
900 PROC_LOCK_ASSERT(p, MA_OWNED);
901 FOREACH_THREAD_IN_PROC(p, td) {
902 if (td->td_tid == tid)