2 * Copyright (c) 2003,2004 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@backplane.com>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
17 * 3. Neither the name of The DragonFly Project nor the names of its
18 * contributors may be used to endorse or promote products derived
19 * from this software without specific, prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * $DragonFly: src/sys/kern/lwkt_thread.c,v 1.98 2006/05/29 07:29:14 dillon Exp $
38 * Each cpu in a system has its own self-contained light weight kernel
39 * thread scheduler, which means that generally speaking we only need
40 * to use a critical section to avoid problems. Foreign thread
41 * scheduling is queued via (async) IPIs.
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/kernel.h>
50 #include <sys/rtprio.h>
51 #include <sys/queue.h>
52 #include <sys/sysctl.h>
53 #include <sys/kthread.h>
54 #include <machine/cpu.h>
57 #include <sys/spinlock.h>
60 #include <sys/thread2.h>
61 #include <sys/spinlock2.h>
64 #include <vm/vm_param.h>
65 #include <vm/vm_kern.h>
66 #include <vm/vm_object.h>
67 #include <vm/vm_page.h>
68 #include <vm/vm_map.h>
69 #include <vm/vm_pager.h>
70 #include <vm/vm_extern.h>
71 #include <vm/vm_zone.h>
73 #include <machine/stdarg.h>
74 #include <machine/ipl.h>
75 #include <machine/smp.h>
79 #include <sys/stdint.h>
80 #include <libcaps/thread.h>
81 #include <sys/thread.h>
82 #include <sys/msgport.h>
83 #include <sys/errno.h>
84 #include <libcaps/globaldata.h>
85 #include <machine/cpufunc.h>
86 #include <sys/thread2.h>
87 #include <sys/msgport2.h>
91 #include <machine/lock.h>
92 #include <machine/atomic.h>
93 #include <machine/cpu.h>
97 static int untimely_switch = 0;
99 static int panic_on_cscount = 0;
101 static __int64_t switch_count = 0;
102 static __int64_t preempt_hit = 0;
103 static __int64_t preempt_miss = 0;
104 static __int64_t preempt_weird = 0;
105 static __int64_t token_contention_count = 0;
106 static __int64_t mplock_contention_count = 0;
110 SYSCTL_INT(_lwkt, OID_AUTO, untimely_switch, CTLFLAG_RW, &untimely_switch, 0, "");
112 SYSCTL_INT(_lwkt, OID_AUTO, panic_on_cscount, CTLFLAG_RW, &panic_on_cscount, 0, "");
114 SYSCTL_QUAD(_lwkt, OID_AUTO, switch_count, CTLFLAG_RW, &switch_count, 0, "");
115 SYSCTL_QUAD(_lwkt, OID_AUTO, preempt_hit, CTLFLAG_RW, &preempt_hit, 0, "");
116 SYSCTL_QUAD(_lwkt, OID_AUTO, preempt_miss, CTLFLAG_RW, &preempt_miss, 0, "");
117 SYSCTL_QUAD(_lwkt, OID_AUTO, preempt_weird, CTLFLAG_RW, &preempt_weird, 0, "");
119 SYSCTL_QUAD(_lwkt, OID_AUTO, token_contention_count, CTLFLAG_RW,
120 &token_contention_count, 0, "spinning due to token contention");
121 SYSCTL_QUAD(_lwkt, OID_AUTO, mplock_contention_count, CTLFLAG_RW,
122 &mplock_contention_count, 0, "spinning due to MPLOCK contention");
131 #if !defined(KTR_GIANT_CONTENTION)
132 #define KTR_GIANT_CONTENTION KTR_ALL
135 KTR_INFO_MASTER(giant);
136 KTR_INFO(KTR_GIANT_CONTENTION, giant, beg, 0, "thread=%p", sizeof(void *));
137 KTR_INFO(KTR_GIANT_CONTENTION, giant, end, 1, "thread=%p", sizeof(void *));
139 #define loggiant(name) KTR_LOG(giant_ ## name, curthread)
144 * These helper procedures handle the runq, they can only be called from
145 * within a critical section.
147 * WARNING! Prior to SMP being brought up it is possible to enqueue and
148 * dequeue threads belonging to other cpus, so be sure to use td->td_gd
149 * instead of 'mycpu' when referencing the globaldata structure. Once
150 * SMP live enqueuing and dequeueing only occurs on the current cpu.
154 _lwkt_dequeue(thread_t td)
156 if (td->td_flags & TDF_RUNQ) {
157 int nq = td->td_pri & TDPRI_MASK;
158 struct globaldata *gd = td->td_gd;
160 td->td_flags &= ~TDF_RUNQ;
161 TAILQ_REMOVE(&gd->gd_tdrunq[nq], td, td_threadq);
162 /* runqmask is passively cleaned up by the switcher */
168 _lwkt_enqueue(thread_t td)
170 if ((td->td_flags & (TDF_RUNQ|TDF_MIGRATING|TDF_TSLEEPQ|TDF_BLOCKQ)) == 0) {
171 int nq = td->td_pri & TDPRI_MASK;
172 struct globaldata *gd = td->td_gd;
174 td->td_flags |= TDF_RUNQ;
175 TAILQ_INSERT_TAIL(&gd->gd_tdrunq[nq], td, td_threadq);
176 gd->gd_runqmask |= 1 << nq;
181 * Schedule a thread to run. As the current thread we can always safely
182 * schedule ourselves, and a shortcut procedure is provided for that
185 * (non-blocking, self contained on a per cpu basis)
188 lwkt_schedule_self(thread_t td)
190 crit_enter_quick(td);
191 KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
192 KASSERT(td != &td->td_gd->gd_idlethread, ("lwkt_schedule_self(): scheduling gd_idlethread is illegal!"));
193 KKASSERT(td->td_proc == NULL || (td->td_proc->p_flag & P_ONRUNQ) == 0);
199 * Deschedule a thread.
201 * (non-blocking, self contained on a per cpu basis)
204 lwkt_deschedule_self(thread_t td)
206 crit_enter_quick(td);
207 KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
215 * LWKTs operate on a per-cpu basis
217 * WARNING! Called from early boot, 'mycpu' may not work yet.
220 lwkt_gdinit(struct globaldata *gd)
224 for (i = 0; i < sizeof(gd->gd_tdrunq)/sizeof(gd->gd_tdrunq[0]); ++i)
225 TAILQ_INIT(&gd->gd_tdrunq[i]);
227 TAILQ_INIT(&gd->gd_tdallq);
233 * Initialize a thread wait structure prior to first use.
235 * NOTE! called from low level boot code, we cannot do anything fancy!
238 lwkt_wait_init(lwkt_wait_t w)
240 spin_init(&w->wa_spinlock);
241 TAILQ_INIT(&w->wa_waitq);
247 * Create a new thread. The thread must be associated with a process context
248 * or LWKT start address before it can be scheduled. If the target cpu is
249 * -1 the thread will be created on the current cpu.
251 * If you intend to create a thread without a process context this function
252 * does everything except load the startup and switcher function.
255 lwkt_alloc_thread(struct thread *td, int stksize, int cpu, int flags)
258 globaldata_t gd = mycpu;
262 if (gd->gd_tdfreecount > 0) {
263 --gd->gd_tdfreecount;
264 td = TAILQ_FIRST(&gd->gd_tdfreeq);
265 KASSERT(td != NULL && (td->td_flags & TDF_RUNNING) == 0,
266 ("lwkt_alloc_thread: unexpected NULL or corrupted td"));
267 TAILQ_REMOVE(&gd->gd_tdfreeq, td, td_threadq);
269 flags |= td->td_flags & (TDF_ALLOCATED_STACK|TDF_ALLOCATED_THREAD);
273 td = zalloc(thread_zone);
275 td = malloc(sizeof(struct thread));
277 td->td_kstack = NULL;
278 td->td_kstack_size = 0;
279 flags |= TDF_ALLOCATED_THREAD;
282 if ((stack = td->td_kstack) != NULL && td->td_kstack_size != stksize) {
283 if (flags & TDF_ALLOCATED_STACK) {
285 kmem_free(kernel_map, (vm_offset_t)stack, td->td_kstack_size);
287 libcaps_free_stack(stack, td->td_kstack_size);
294 stack = (void *)kmem_alloc(kernel_map, stksize);
296 stack = libcaps_alloc_stack(stksize);
298 flags |= TDF_ALLOCATED_STACK;
301 lwkt_init_thread(td, stack, stksize, flags, mycpu);
303 lwkt_init_thread(td, stack, stksize, flags, globaldata_find(cpu));
310 * Initialize a preexisting thread structure. This function is used by
311 * lwkt_alloc_thread() and also used to initialize the per-cpu idlethread.
313 * All threads start out in a critical section at a priority of
314 * TDPRI_KERN_DAEMON. Higher level code will modify the priority as
315 * appropriate. This function may send an IPI message when the
316 * requested cpu is not the current cpu and consequently gd_tdallq may
317 * not be initialized synchronously from the point of view of the originating
320 * NOTE! we have to be careful in regards to creating threads for other cpus
321 * if SMP has not yet been activated.
326 lwkt_init_thread_remote(void *arg)
331 * Protected by critical section held by IPI dispatch
333 TAILQ_INSERT_TAIL(&td->td_gd->gd_tdallq, td, td_allq);
339 lwkt_init_thread(thread_t td, void *stack, int stksize, int flags,
340 struct globaldata *gd)
342 globaldata_t mygd = mycpu;
344 bzero(td, sizeof(struct thread));
345 td->td_kstack = stack;
346 td->td_kstack_size = stksize;
347 td->td_flags = flags;
349 td->td_pri = TDPRI_KERN_DAEMON + TDPRI_CRIT;
351 if ((flags & TDF_MPSAFE) == 0)
354 lwkt_initport(&td->td_msgport, td);
355 pmap_init_thread(td);
358 * Normally initializing a thread for a remote cpu requires sending an
359 * IPI. However, the idlethread is setup before the other cpus are
360 * activated so we have to treat it as a special case. XXX manipulation
361 * of gd_tdallq requires the BGL.
363 if (gd == mygd || td == &gd->gd_idlethread) {
365 TAILQ_INSERT_TAIL(&gd->gd_tdallq, td, td_allq);
368 lwkt_send_ipiq(gd, lwkt_init_thread_remote, td);
372 TAILQ_INSERT_TAIL(&gd->gd_tdallq, td, td_allq);
380 lwkt_set_comm(thread_t td, const char *ctl, ...)
385 vsnprintf(td->td_comm, sizeof(td->td_comm), ctl, va);
390 lwkt_hold(thread_t td)
396 lwkt_rele(thread_t td)
398 KKASSERT(td->td_refs > 0);
405 lwkt_wait_free(thread_t td)
408 tsleep(td, 0, "tdreap", hz);
414 lwkt_free_thread(thread_t td)
416 struct globaldata *gd = mycpu;
418 KASSERT((td->td_flags & TDF_RUNNING) == 0,
419 ("lwkt_free_thread: did not exit! %p", td));
422 TAILQ_REMOVE(&td->td_gd->gd_tdallq, td, td_allq); /* Protected by BGL */
423 if (gd->gd_tdfreecount < CACHE_NTHREADS &&
424 (td->td_flags & TDF_ALLOCATED_THREAD)
426 ++gd->gd_tdfreecount;
427 TAILQ_INSERT_HEAD(&gd->gd_tdfreeq, td, td_threadq);
431 if (td->td_kstack && (td->td_flags & TDF_ALLOCATED_STACK)) {
433 kmem_free(kernel_map, (vm_offset_t)td->td_kstack, td->td_kstack_size);
435 libcaps_free_stack(td->td_kstack, td->td_kstack_size);
438 td->td_kstack = NULL;
439 td->td_kstack_size = 0;
441 if (td->td_flags & TDF_ALLOCATED_THREAD) {
443 zfree(thread_zone, td);
453 * Switch to the next runnable lwkt. If no LWKTs are runnable then
454 * switch to the idlethread. Switching must occur within a critical
455 * section to avoid races with the scheduling queue.
457 * We always have full control over our cpu's run queue. Other cpus
458 * that wish to manipulate our queue must use the cpu_*msg() calls to
459 * talk to our cpu, so a critical section is all that is needed and
460 * the result is very, very fast thread switching.
462 * The LWKT scheduler uses a fixed priority model and round-robins at
463 * each priority level. User process scheduling is a totally
464 * different beast and LWKT priorities should not be confused with
465 * user process priorities.
467 * The MP lock may be out of sync with the thread's td_mpcount. lwkt_switch()
468 * cleans it up. Note that the td_switch() function cannot do anything that
469 * requires the MP lock since the MP lock will have already been setup for
470 * the target thread (not the current thread). It's nice to have a scheduler
471 * that does not need the MP lock to work because it allows us to do some
472 * really cool high-performance MP lock optimizations.
474 * PREEMPTION NOTE: Preemption occurs via lwkt_preempt(). lwkt_switch()
475 * is not called by the current thread in the preemption case, only when
476 * the preempting thread blocks (in order to return to the original thread).
481 globaldata_t gd = mycpu;
482 thread_t td = gd->gd_curthread;
489 * Switching from within a 'fast' (non thread switched) interrupt or IPI
490 * is illegal. However, we may have to do it anyway if we hit a fatal
491 * kernel trap or we have paniced.
493 * If this case occurs save and restore the interrupt nesting level.
495 if (gd->gd_intr_nesting_level) {
499 if (gd->gd_trap_nesting_level == 0 && panicstr == NULL) {
500 panic("lwkt_switch: cannot switch from within "
501 "a fast interrupt, yet, td %p\n", td);
503 savegdnest = gd->gd_intr_nesting_level;
504 savegdtrap = gd->gd_trap_nesting_level;
505 gd->gd_intr_nesting_level = 0;
506 gd->gd_trap_nesting_level = 0;
507 if ((td->td_flags & TDF_PANICWARN) == 0) {
508 td->td_flags |= TDF_PANICWARN;
509 printf("Warning: thread switch from interrupt or IPI, "
510 "thread %p (%s)\n", td, td->td_comm);
512 db_print_backtrace();
516 gd->gd_intr_nesting_level = savegdnest;
517 gd->gd_trap_nesting_level = savegdtrap;
523 * Passive release (used to transition from user to kernel mode
524 * when we block or switch rather then when we enter the kernel).
525 * This function is NOT called if we are switching into a preemption
526 * or returning from a preemption. Typically this causes us to lose
527 * our current process designation (if we have one) and become a true
528 * LWKT thread, and may also hand the current process designation to
529 * another process and schedule thread.
537 lwkt_relalltokens(td);
541 * We had better not be holding any spin locks, but don't get into an
542 * endless panic loop.
544 KASSERT(gd->gd_spinlocks_rd == 0 || panicstr != NULL,
545 ("lwkt_switch: still holding %d shared spinlocks!",
546 gd->gd_spinlocks_rd));
547 KASSERT(gd->gd_spinlocks_wr == 0 || panicstr != NULL,
548 ("lwkt_switch: still holding %d exclusive spinlocks!",
549 gd->gd_spinlocks_wr));
554 * td_mpcount cannot be used to determine if we currently hold the
555 * MP lock because get_mplock() will increment it prior to attempting
556 * to get the lock, and switch out if it can't. Our ownership of
557 * the actual lock will remain stable while we are in a critical section
558 * (but, of course, another cpu may own or release the lock so the
559 * actual value of mp_lock is not stable).
561 mpheld = MP_LOCK_HELD();
563 if (td->td_cscount) {
564 printf("Diagnostic: attempt to switch while mastering cpusync: %p\n",
566 if (panic_on_cscount)
567 panic("switching while mastering cpusync");
571 if ((ntd = td->td_preempted) != NULL) {
573 * We had preempted another thread on this cpu, resume the preempted
574 * thread. This occurs transparently, whether the preempted thread
575 * was scheduled or not (it may have been preempted after descheduling
578 * We have to setup the MP lock for the original thread after backing
579 * out the adjustment that was made to curthread when the original
582 KKASSERT(ntd->td_flags & TDF_PREEMPT_LOCK);
584 if (ntd->td_mpcount && mpheld == 0) {
585 panic("MPLOCK NOT HELD ON RETURN: %p %p %d %d",
586 td, ntd, td->td_mpcount, ntd->td_mpcount);
588 if (ntd->td_mpcount) {
589 td->td_mpcount -= ntd->td_mpcount;
590 KKASSERT(td->td_mpcount >= 0);
593 ntd->td_flags |= TDF_PREEMPT_DONE;
596 * XXX. The interrupt may have woken a thread up, we need to properly
597 * set the reschedule flag if the originally interrupted thread is at
600 if (gd->gd_runqmask > (2 << (ntd->td_pri & TDPRI_MASK)) - 1)
602 /* YYY release mp lock on switchback if original doesn't need it */
605 * Priority queue / round-robin at each priority. Note that user
606 * processes run at a fixed, low priority and the user process
607 * scheduler deals with interactions between user processes
608 * by scheduling and descheduling them from the LWKT queue as
611 * We have to adjust the MP lock for the target thread. If we
612 * need the MP lock and cannot obtain it we try to locate a
613 * thread that does not need the MP lock. If we cannot, we spin
616 * A similar issue exists for the tokens held by the target thread.
617 * If we cannot obtain ownership of the tokens we cannot immediately
618 * schedule the thread.
622 * If an LWKT reschedule was requested, well that is what we are
623 * doing now so clear it.
625 clear_lwkt_resched();
627 if (gd->gd_runqmask) {
628 int nq = bsrl(gd->gd_runqmask);
629 if ((ntd = TAILQ_FIRST(&gd->gd_tdrunq[nq])) == NULL) {
630 gd->gd_runqmask &= ~(1 << nq);
635 * THREAD SELECTION FOR AN SMP MACHINE BUILD
637 * If the target needs the MP lock and we couldn't get it,
638 * or if the target is holding tokens and we could not
639 * gain ownership of the tokens, continue looking for a
640 * thread to schedule and spin instead of HLT if we can't.
642 * NOTE: the mpheld variable invalid after this conditional, it
643 * can change due to both cpu_try_mplock() returning success
644 * AND interactions in lwkt_getalltokens() due to the fact that
645 * we are trying to check the mpcount of a thread other then
646 * the current thread. Because of this, if the current thread
647 * is not holding td_mpcount, an IPI indirectly run via
648 * lwkt_getalltokens() can obtain and release the MP lock and
649 * cause the core MP lock to be released.
651 if ((ntd->td_mpcount && mpheld == 0 && !cpu_try_mplock()) ||
652 (ntd->td_toks && lwkt_getalltokens(ntd) == 0)
654 u_int32_t rqmask = gd->gd_runqmask;
656 mpheld = MP_LOCK_HELD();
659 TAILQ_FOREACH(ntd, &gd->gd_tdrunq[nq], td_threadq) {
660 if (ntd->td_mpcount && !mpheld && !cpu_try_mplock()) {
661 /* spinning due to MP lock being held */
663 ++mplock_contention_count;
665 /* mplock still not held, 'mpheld' still valid */
670 * mpheld state invalid after getalltokens call returns
671 * failure, but the variable is only needed for
674 if (ntd->td_toks && !lwkt_getalltokens(ntd)) {
675 /* spinning due to token contention */
677 ++token_contention_count;
679 mpheld = MP_LOCK_HELD();
686 rqmask &= ~(1 << nq);
690 ntd = &gd->gd_idlethread;
691 ntd->td_flags |= TDF_IDLE_NOHLT;
692 goto using_idle_thread;
694 ++gd->gd_cnt.v_swtch;
695 TAILQ_REMOVE(&gd->gd_tdrunq[nq], ntd, td_threadq);
696 TAILQ_INSERT_TAIL(&gd->gd_tdrunq[nq], ntd, td_threadq);
699 ++gd->gd_cnt.v_swtch;
700 TAILQ_REMOVE(&gd->gd_tdrunq[nq], ntd, td_threadq);
701 TAILQ_INSERT_TAIL(&gd->gd_tdrunq[nq], ntd, td_threadq);
705 * THREAD SELECTION FOR A UP MACHINE BUILD. We don't have to
706 * worry about tokens or the BGL.
708 ++gd->gd_cnt.v_swtch;
709 TAILQ_REMOVE(&gd->gd_tdrunq[nq], ntd, td_threadq);
710 TAILQ_INSERT_TAIL(&gd->gd_tdrunq[nq], ntd, td_threadq);
714 * We have nothing to run but only let the idle loop halt
715 * the cpu if there are no pending interrupts.
717 ntd = &gd->gd_idlethread;
718 if (gd->gd_reqflags & RQF_IDLECHECK_MASK)
719 ntd->td_flags |= TDF_IDLE_NOHLT;
723 * The idle thread should not be holding the MP lock unless we
724 * are trapping in the kernel or in a panic. Since we select the
725 * idle thread unconditionally when no other thread is available,
726 * if the MP lock is desired during a panic or kernel trap, we
727 * have to loop in the scheduler until we get it.
729 if (ntd->td_mpcount) {
730 mpheld = MP_LOCK_HELD();
731 if (gd->gd_trap_nesting_level == 0 && panicstr == NULL)
732 panic("Idle thread %p was holding the BGL!", ntd);
733 else if (mpheld == 0)
739 KASSERT(ntd->td_pri >= TDPRI_CRIT,
740 ("priority problem in lwkt_switch %d %d", td->td_pri, ntd->td_pri));
743 * Do the actual switch. If the new target does not need the MP lock
744 * and we are holding it, release the MP lock. If the new target requires
745 * the MP lock we have already acquired it for the target.
748 if (ntd->td_mpcount == 0 ) {
752 ASSERT_MP_LOCK_HELD(ntd);
759 /* NOTE: current cpu may have changed after switch */
764 * Request that the target thread preempt the current thread. Preemption
765 * only works under a specific set of conditions:
767 * - We are not preempting ourselves
768 * - The target thread is owned by the current cpu
769 * - We are not currently being preempted
770 * - The target is not currently being preempted
771 * - We are able to satisfy the target's MP lock requirements (if any).
773 * THE CALLER OF LWKT_PREEMPT() MUST BE IN A CRITICAL SECTION. Typically
774 * this is called via lwkt_schedule() through the td_preemptable callback.
775 * critpri is the managed critical priority that we should ignore in order
776 * to determine whether preemption is possible (aka usually just the crit
777 * priority of lwkt_schedule() itself).
779 * XXX at the moment we run the target thread in a critical section during
780 * the preemption in order to prevent the target from taking interrupts
781 * that *WE* can't. Preemption is strictly limited to interrupt threads
782 * and interrupt-like threads, outside of a critical section, and the
783 * preempted source thread will be resumed the instant the target blocks
784 * whether or not the source is scheduled (i.e. preemption is supposed to
785 * be as transparent as possible).
787 * The target thread inherits our MP count (added to its own) for the
788 * duration of the preemption in order to preserve the atomicy of the
789 * MP lock during the preemption. Therefore, any preempting targets must be
790 * careful in regards to MP assertions. Note that the MP count may be
791 * out of sync with the physical mp_lock, but we do not have to preserve
792 * the original ownership of the lock if it was out of synch (that is, we
793 * can leave it synchronized on return).
796 lwkt_preempt(thread_t ntd, int critpri)
798 struct globaldata *gd = mycpu;
806 * The caller has put us in a critical section. We can only preempt
807 * if the caller of the caller was not in a critical section (basically
808 * a local interrupt), as determined by the 'critpri' parameter. We
809 * also acn't preempt if the caller is holding any spinlocks (even if
810 * he isn't in a critical section). This also handles the tokens test.
812 * YYY The target thread must be in a critical section (else it must
813 * inherit our critical section? I dunno yet).
815 * Set need_lwkt_resched() unconditionally for now YYY.
817 KASSERT(ntd->td_pri >= TDPRI_CRIT, ("BADCRIT0 %d", ntd->td_pri));
819 td = gd->gd_curthread;
820 if ((ntd->td_pri & TDPRI_MASK) <= (td->td_pri & TDPRI_MASK)) {
824 if ((td->td_pri & ~TDPRI_MASK) > critpri) {
830 if (ntd->td_gd != gd) {
837 * Take the easy way out and do not preempt if the target is holding
838 * any spinlocks. We could test whether the thread(s) being
839 * preempted interlock against the target thread's tokens and whether
840 * we can get all the target thread's tokens, but this situation
841 * should not occur very often so its easier to simply not preempt.
842 * Also, plain spinlocks are impossible to figure out at this point so
843 * just don't preempt.
845 if (gd->gd_spinlocks_rd + gd->gd_spinlocks_wr != 0) {
850 if (td == ntd || ((td->td_flags | ntd->td_flags) & TDF_PREEMPT_LOCK)) {
855 if (ntd->td_preempted) {
862 * note: an interrupt might have occured just as we were transitioning
863 * to or from the MP lock. In this case td_mpcount will be pre-disposed
864 * (non-zero) but not actually synchronized with the actual state of the
865 * lock. We can use it to imply an MP lock requirement for the
866 * preemption but we cannot use it to test whether we hold the MP lock
869 savecnt = td->td_mpcount;
870 mpheld = MP_LOCK_HELD();
871 ntd->td_mpcount += td->td_mpcount;
872 if (mpheld == 0 && ntd->td_mpcount && !cpu_try_mplock()) {
873 ntd->td_mpcount -= td->td_mpcount;
881 * Since we are able to preempt the current thread, there is no need to
882 * call need_lwkt_resched().
885 ntd->td_preempted = td;
886 td->td_flags |= TDF_PREEMPT_LOCK;
888 KKASSERT(ntd->td_preempted && (td->td_flags & TDF_PREEMPT_DONE));
890 KKASSERT(savecnt == td->td_mpcount);
891 mpheld = MP_LOCK_HELD();
892 if (mpheld && td->td_mpcount == 0)
894 else if (mpheld == 0 && td->td_mpcount)
895 panic("lwkt_preempt(): MP lock was not held through");
897 ntd->td_preempted = NULL;
898 td->td_flags &= ~(TDF_PREEMPT_LOCK|TDF_PREEMPT_DONE);
902 * Yield our thread while higher priority threads are pending. This is
903 * typically called when we leave a critical section but it can be safely
904 * called while we are in a critical section.
906 * This function will not generally yield to equal priority threads but it
907 * can occur as a side effect. Note that lwkt_switch() is called from
908 * inside the critical section to prevent its own crit_exit() from reentering
909 * lwkt_yield_quick().
911 * gd_reqflags indicates that *something* changed, e.g. an interrupt or softint
912 * came along but was blocked and made pending.
914 * (self contained on a per cpu basis)
917 lwkt_yield_quick(void)
919 globaldata_t gd = mycpu;
920 thread_t td = gd->gd_curthread;
923 * gd_reqflags is cleared in splz if the cpl is 0. If we were to clear
924 * it with a non-zero cpl then we might not wind up calling splz after
925 * a task switch when the critical section is exited even though the
926 * new task could accept the interrupt.
928 * XXX from crit_exit() only called after last crit section is released.
929 * If called directly will run splz() even if in a critical section.
931 * td_nest_count prevent deep nesting via splz() or doreti(). Note that
932 * except for this special case, we MUST call splz() here to handle any
933 * pending ints, particularly after we switch, or we might accidently
934 * halt the cpu with interrupts pending.
936 if (gd->gd_reqflags && td->td_nest_count < 2)
940 * YYY enabling will cause wakeup() to task-switch, which really
941 * confused the old 4.x code. This is a good way to simulate
942 * preemption and MP without actually doing preemption or MP, because a
943 * lot of code assumes that wakeup() does not block.
945 if (untimely_switch && td->td_nest_count == 0 &&
946 gd->gd_intr_nesting_level == 0
948 crit_enter_quick(td);
950 * YYY temporary hacks until we disassociate the userland scheduler
951 * from the LWKT scheduler.
953 if (td->td_flags & TDF_RUNQ) {
954 lwkt_switch(); /* will not reenter yield function */
956 lwkt_schedule_self(td); /* make sure we are scheduled */
957 lwkt_switch(); /* will not reenter yield function */
958 lwkt_deschedule_self(td); /* make sure we are descheduled */
960 crit_exit_noyield(td);
965 * This implements a normal yield which, unlike _quick, will yield to equal
966 * priority threads as well. Note that gd_reqflags tests will be handled by
967 * the crit_exit() call in lwkt_switch().
969 * (self contained on a per cpu basis)
974 lwkt_schedule_self(curthread);
979 * Generic schedule. Possibly schedule threads belonging to other cpus and
980 * deal with threads that might be blocked on a wait queue.
982 * We have a little helper inline function which does additional work after
983 * the thread has been enqueued, including dealing with preemption and
984 * setting need_lwkt_resched() (which prevents the kernel from returning
985 * to userland until it has processed higher priority threads).
987 * It is possible for this routine to be called after a failed _enqueue
988 * (due to the target thread migrating, sleeping, or otherwise blocked).
989 * We have to check that the thread is actually on the run queue!
993 _lwkt_schedule_post(globaldata_t gd, thread_t ntd, int cpri)
995 if (ntd->td_flags & TDF_RUNQ) {
996 if (ntd->td_preemptable) {
997 ntd->td_preemptable(ntd, cpri); /* YYY +token */
998 } else if ((ntd->td_flags & TDF_NORESCHED) == 0 &&
999 (ntd->td_pri & TDPRI_MASK) > (gd->gd_curthread->td_pri & TDPRI_MASK)
1001 need_lwkt_resched();
1007 lwkt_schedule(thread_t td)
1009 globaldata_t mygd = mycpu;
1011 KASSERT(td != &td->td_gd->gd_idlethread, ("lwkt_schedule(): scheduling gd_idlethread is illegal!"));
1012 crit_enter_gd(mygd);
1013 KKASSERT(td->td_proc == NULL || (td->td_proc->p_flag & P_ONRUNQ) == 0);
1014 if (td == mygd->gd_curthread) {
1020 * If the thread is on a wait list we have to send our scheduling
1021 * request to the owner of the wait structure. Otherwise we send
1022 * the scheduling request to the cpu owning the thread. Races
1023 * are ok, the target will forward the message as necessary (the
1024 * message may chase the thread around before it finally gets
1027 * (remember, wait structures use stable storage)
1029 * NOTE: we have to account for the number of critical sections
1030 * under our control when calling _lwkt_schedule_post() so it
1031 * can figure out whether preemption is allowed.
1033 * NOTE: The wait structure algorithms are a mess and need to be
1036 * NOTE: We cannot safely acquire or release a token, even
1037 * non-blocking, because this routine may be called in the context
1038 * of a thread already holding the token and thus not provide any
1039 * interlock protection. We cannot safely manipulate the td_toks
1040 * list for the same reason. Instead we depend on our critical
1041 * section if the token is owned by our cpu.
1043 if ((w = td->td_wait) != NULL) {
1044 spin_lock_wr(&w->wa_spinlock);
1045 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
1048 spin_unlock_wr(&w->wa_spinlock);
1050 if (td->td_gd == mygd) {
1052 _lwkt_schedule_post(mygd, td, TDPRI_CRIT);
1054 lwkt_send_ipiq(td->td_gd, (ipifunc1_t)lwkt_schedule, td);
1058 _lwkt_schedule_post(mygd, td, TDPRI_CRIT);
1062 * If the wait structure is NULL and we own the thread, there
1063 * is no race (since we are in a critical section). If we
1064 * do not own the thread there might be a race but the
1065 * target cpu will deal with it.
1068 if (td->td_gd == mygd) {
1070 _lwkt_schedule_post(mygd, td, TDPRI_CRIT);
1072 lwkt_send_ipiq(td->td_gd, (ipifunc1_t)lwkt_schedule, td);
1076 _lwkt_schedule_post(mygd, td, TDPRI_CRIT);
1086 * Thread migration using a 'Pull' method. The thread may or may not be
1087 * the current thread. It MUST be descheduled and in a stable state.
1088 * lwkt_giveaway() must be called on the cpu owning the thread.
1090 * At any point after lwkt_giveaway() is called, the target cpu may
1091 * 'pull' the thread by calling lwkt_acquire().
1093 * MPSAFE - must be called under very specific conditions.
1096 lwkt_giveaway(thread_t td)
1098 globaldata_t gd = mycpu;
1101 KKASSERT(td->td_gd == gd);
1102 TAILQ_REMOVE(&gd->gd_tdallq, td, td_allq);
1103 td->td_flags |= TDF_MIGRATING;
1108 lwkt_acquire(thread_t td)
1113 KKASSERT(td->td_flags & TDF_MIGRATING);
1118 KKASSERT((td->td_flags & TDF_RUNQ) == 0);
1119 crit_enter_gd(mygd);
1120 while (td->td_flags & (TDF_RUNNING|TDF_PREEMPT_LOCK))
1123 TAILQ_INSERT_TAIL(&mygd->gd_tdallq, td, td_allq);
1124 td->td_flags &= ~TDF_MIGRATING;
1127 crit_enter_gd(mygd);
1128 TAILQ_INSERT_TAIL(&mygd->gd_tdallq, td, td_allq);
1129 td->td_flags &= ~TDF_MIGRATING;
1137 * Generic deschedule. Descheduling threads other then your own should be
1138 * done only in carefully controlled circumstances. Descheduling is
1141 * This function may block if the cpu has run out of messages.
1144 lwkt_deschedule(thread_t td)
1148 if (td == curthread) {
1151 if (td->td_gd == mycpu) {
1154 lwkt_send_ipiq(td->td_gd, (ipifunc1_t)lwkt_deschedule, td);
1164 * Set the target thread's priority. This routine does not automatically
1165 * switch to a higher priority thread, LWKT threads are not designed for
1166 * continuous priority changes. Yield if you want to switch.
1168 * We have to retain the critical section count which uses the high bits
1169 * of the td_pri field. The specified priority may also indicate zero or
1170 * more critical sections by adding TDPRI_CRIT*N.
1172 * Note that we requeue the thread whether it winds up on a different runq
1173 * or not. uio_yield() depends on this and the routine is not normally
1174 * called with the same priority otherwise.
1177 lwkt_setpri(thread_t td, int pri)
1180 KKASSERT(td->td_gd == mycpu);
1182 if (td->td_flags & TDF_RUNQ) {
1184 td->td_pri = (td->td_pri & ~TDPRI_MASK) + pri;
1187 td->td_pri = (td->td_pri & ~TDPRI_MASK) + pri;
1193 lwkt_setpri_self(int pri)
1195 thread_t td = curthread;
1197 KKASSERT(pri >= 0 && pri <= TDPRI_MAX);
1199 if (td->td_flags & TDF_RUNQ) {
1201 td->td_pri = (td->td_pri & ~TDPRI_MASK) + pri;
1204 td->td_pri = (td->td_pri & ~TDPRI_MASK) + pri;
1210 * Determine if there is a runnable thread at a higher priority then
1211 * the current thread. lwkt_setpri() does not check this automatically.
1212 * Return 1 if there is, 0 if there isn't.
1214 * Example: if bit 31 of runqmask is set and the current thread is priority
1215 * 30, then we wind up checking the mask: 0x80000000 against 0x7fffffff.
1217 * If nq reaches 31 the shift operation will overflow to 0 and we will wind
1218 * up comparing against 0xffffffff, a comparison that will always be false.
1221 lwkt_checkpri_self(void)
1223 globaldata_t gd = mycpu;
1224 thread_t td = gd->gd_curthread;
1225 int nq = td->td_pri & TDPRI_MASK;
1227 while (gd->gd_runqmask > (__uint32_t)(2 << nq) - 1) {
1228 if (TAILQ_FIRST(&gd->gd_tdrunq[nq + 1]))
1236 * Migrate the current thread to the specified cpu.
1238 * This is accomplished by descheduling ourselves from the current cpu,
1239 * moving our thread to the tdallq of the target cpu, IPI messaging the
1240 * target cpu, and switching out. TDF_MIGRATING prevents scheduling
1241 * races while the thread is being migrated.
1244 static void lwkt_setcpu_remote(void *arg);
1248 lwkt_setcpu_self(globaldata_t rgd)
1251 thread_t td = curthread;
1253 if (td->td_gd != rgd) {
1254 crit_enter_quick(td);
1255 td->td_flags |= TDF_MIGRATING;
1256 lwkt_deschedule_self(td);
1257 TAILQ_REMOVE(&td->td_gd->gd_tdallq, td, td_allq);
1258 lwkt_send_ipiq(rgd, (ipifunc1_t)lwkt_setcpu_remote, td);
1260 /* we are now on the target cpu */
1261 TAILQ_INSERT_TAIL(&rgd->gd_tdallq, td, td_allq);
1262 crit_exit_quick(td);
1268 lwkt_migratecpu(int cpuid)
1273 rgd = globaldata_find(cpuid);
1274 lwkt_setcpu_self(rgd);
1279 * Remote IPI for cpu migration (called while in a critical section so we
1280 * do not have to enter another one). The thread has already been moved to
1281 * our cpu's allq, but we must wait for the thread to be completely switched
1282 * out on the originating cpu before we schedule it on ours or the stack
1283 * state may be corrupt. We clear TDF_MIGRATING after flushing the GD
1284 * change to main memory.
1286 * XXX The use of TDF_MIGRATING might not be sufficient to avoid races
1287 * against wakeups. It is best if this interface is used only when there
1288 * are no pending events that might try to schedule the thread.
1292 lwkt_setcpu_remote(void *arg)
1295 globaldata_t gd = mycpu;
1297 while (td->td_flags & (TDF_RUNNING|TDF_PREEMPT_LOCK))
1301 td->td_flags &= ~TDF_MIGRATING;
1302 KKASSERT(td->td_proc == NULL || (td->td_proc->p_flag & P_ONRUNQ) == 0);
1308 lwkt_preempted_proc(void)
1310 thread_t td = curthread;
1311 while (td->td_preempted)
1312 td = td->td_preempted;
1317 * Block on the specified wait queue until signaled. A generation number
1318 * must be supplied to interlock the wait queue. The function will
1319 * return immediately if the generation number does not match the wait
1320 * structure's generation number.
1323 lwkt_block(lwkt_wait_t w, const char *wmesg, int *gen)
1325 thread_t td = curthread;
1327 spin_lock_wr(&w->wa_spinlock);
1328 if (w->wa_gen == *gen) {
1330 td->td_flags |= TDF_BLOCKQ;
1331 TAILQ_INSERT_TAIL(&w->wa_waitq, td, td_threadq);
1334 td->td_wmesg = wmesg;
1335 spin_unlock_wr(&w->wa_spinlock);
1337 KKASSERT((td->td_flags & TDF_BLOCKQ) == 0);
1338 td->td_wmesg = NULL;
1342 spin_unlock_wr(&w->wa_spinlock);
1347 * Signal a wait queue. We gain ownership of the wait queue in order to
1348 * signal it. Once a thread is removed from the wait queue we have to
1349 * deal with the cpu owning the thread.
1351 * Note: alternatively we could message the target cpu owning the wait
1352 * queue. YYY implement as sysctl.
1355 lwkt_signal(lwkt_wait_t w, int count)
1359 spin_lock_wr(&w->wa_spinlock);
1362 count = w->wa_count;
1363 while ((td = TAILQ_FIRST(&w->wa_waitq)) != NULL && count) {
1366 KKASSERT(td->td_flags & TDF_BLOCKQ);
1367 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
1368 td->td_flags &= ~TDF_BLOCKQ;
1370 spin_unlock_wr(&w->wa_spinlock);
1371 KKASSERT(td->td_proc == NULL || (td->td_proc->p_flag & P_ONRUNQ) == 0);
1373 if (td->td_gd == mycpu) {
1376 lwkt_send_ipiq(td->td_gd, (ipifunc1_t)lwkt_schedule, td);
1381 spin_lock_wr(&w->wa_spinlock);
1383 spin_unlock_wr(&w->wa_spinlock);
1387 * Create a kernel process/thread/whatever. It shares it's address space
1388 * with proc0 - ie: kernel only.
1390 * NOTE! By default new threads are created with the MP lock held. A
1391 * thread which does not require the MP lock should release it by calling
1392 * rel_mplock() at the start of the new thread.
1395 lwkt_create(void (*func)(void *), void *arg,
1396 struct thread **tdp, thread_t template, int tdflags, int cpu,
1397 const char *fmt, ...)
1402 td = lwkt_alloc_thread(template, LWKT_THREAD_STACK, cpu,
1403 tdflags | TDF_VERBOSE);
1406 cpu_set_thread_handler(td, lwkt_exit, func, arg);
1409 * Set up arg0 for 'ps' etc
1411 __va_start(ap, fmt);
1412 vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
1416 * Schedule the thread to run
1418 if ((td->td_flags & TDF_STOPREQ) == 0)
1421 td->td_flags &= ~TDF_STOPREQ;
1426 * kthread_* is specific to the kernel and is not needed by userland.
1431 * Destroy an LWKT thread. Warning! This function is not called when
1432 * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
1433 * uses a different reaping mechanism.
1438 thread_t td = curthread;
1441 if (td->td_flags & TDF_VERBOSE)
1442 printf("kthread %p %s has exited\n", td, td->td_comm);
1444 crit_enter_quick(td);
1445 lwkt_deschedule_self(td);
1447 KKASSERT(gd == td->td_gd);
1448 TAILQ_REMOVE(&gd->gd_tdallq, td, td_allq);
1449 if (td->td_flags & TDF_ALLOCATED_THREAD) {
1450 ++gd->gd_tdfreecount;
1451 TAILQ_INSERT_TAIL(&gd->gd_tdfreeq, td, td_threadq);
1456 #endif /* _KERNEL */
1461 thread_t td = curthread;
1462 int lpri = td->td_pri;
1465 panic("td_pri is/would-go negative! %p %d", td, lpri);
1471 * Called from debugger/panic on cpus which have been stopped. We must still
1472 * process the IPIQ while stopped, even if we were stopped while in a critical
1475 * If we are dumping also try to process any pending interrupts. This may
1476 * or may not work depending on the state of the cpu at the point it was
1480 lwkt_smp_stopped(void)
1482 globaldata_t gd = mycpu;
1486 lwkt_process_ipiq();
1489 lwkt_process_ipiq();
1495 * get_mplock() calls this routine if it is unable to obtain the MP lock.
1496 * get_mplock() has already incremented td_mpcount. We must block and
1497 * not return until giant is held.
1499 * All we have to do is lwkt_switch() away. The LWKT scheduler will not
1500 * reschedule the thread until it can obtain the giant lock for it.
1503 lwkt_mp_lock_contested(void)