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.113 2008/05/18 20:57:56 nth 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.
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
48 #include <sys/rtprio.h>
49 #include <sys/queue.h>
50 #include <sys/sysctl.h>
51 #include <sys/kthread.h>
52 #include <machine/cpu.h>
55 #include <sys/spinlock.h>
58 #include <sys/thread2.h>
59 #include <sys/spinlock2.h>
62 #include <vm/vm_param.h>
63 #include <vm/vm_kern.h>
64 #include <vm/vm_object.h>
65 #include <vm/vm_page.h>
66 #include <vm/vm_map.h>
67 #include <vm/vm_pager.h>
68 #include <vm/vm_extern.h>
69 #include <vm/vm_zone.h>
71 #include <machine/stdarg.h>
72 #include <machine/smp.h>
74 static int untimely_switch
= 0;
76 static int panic_on_cscount
= 0;
78 static __int64_t switch_count
= 0;
79 static __int64_t preempt_hit
= 0;
80 static __int64_t preempt_miss
= 0;
81 static __int64_t preempt_weird
= 0;
82 static __int64_t token_contention_count
= 0;
83 static __int64_t mplock_contention_count
= 0;
84 static int lwkt_use_spin_port
;
87 * We can make all thread ports use the spin backend instead of the thread
88 * backend. This should only be set to debug the spin backend.
90 TUNABLE_INT("lwkt.use_spin_port", &lwkt_use_spin_port
);
92 SYSCTL_INT(_lwkt
, OID_AUTO
, untimely_switch
, CTLFLAG_RW
, &untimely_switch
, 0, "");
94 SYSCTL_INT(_lwkt
, OID_AUTO
, panic_on_cscount
, CTLFLAG_RW
, &panic_on_cscount
, 0, "");
96 SYSCTL_QUAD(_lwkt
, OID_AUTO
, switch_count
, CTLFLAG_RW
, &switch_count
, 0, "");
97 SYSCTL_QUAD(_lwkt
, OID_AUTO
, preempt_hit
, CTLFLAG_RW
, &preempt_hit
, 0, "");
98 SYSCTL_QUAD(_lwkt
, OID_AUTO
, preempt_miss
, CTLFLAG_RW
, &preempt_miss
, 0, "");
99 SYSCTL_QUAD(_lwkt
, OID_AUTO
, preempt_weird
, CTLFLAG_RW
, &preempt_weird
, 0, "");
101 SYSCTL_QUAD(_lwkt
, OID_AUTO
, token_contention_count
, CTLFLAG_RW
,
102 &token_contention_count
, 0, "spinning due to token contention");
103 SYSCTL_QUAD(_lwkt
, OID_AUTO
, mplock_contention_count
, CTLFLAG_RW
,
104 &mplock_contention_count
, 0, "spinning due to MPLOCK contention");
110 #if !defined(KTR_GIANT_CONTENTION)
111 #define KTR_GIANT_CONTENTION KTR_ALL
114 KTR_INFO_MASTER(giant
);
115 KTR_INFO(KTR_GIANT_CONTENTION
, giant
, beg
, 0, "thread=%p", sizeof(void *));
116 KTR_INFO(KTR_GIANT_CONTENTION
, giant
, end
, 1, "thread=%p", sizeof(void *));
118 #define loggiant(name) KTR_LOG(giant_ ## name, curthread)
121 * These helper procedures handle the runq, they can only be called from
122 * within a critical section.
124 * WARNING! Prior to SMP being brought up it is possible to enqueue and
125 * dequeue threads belonging to other cpus, so be sure to use td->td_gd
126 * instead of 'mycpu' when referencing the globaldata structure. Once
127 * SMP live enqueuing and dequeueing only occurs on the current cpu.
131 _lwkt_dequeue(thread_t td
)
133 if (td
->td_flags
& TDF_RUNQ
) {
134 int nq
= td
->td_pri
& TDPRI_MASK
;
135 struct globaldata
*gd
= td
->td_gd
;
137 td
->td_flags
&= ~TDF_RUNQ
;
138 TAILQ_REMOVE(&gd
->gd_tdrunq
[nq
], td
, td_threadq
);
139 /* runqmask is passively cleaned up by the switcher */
145 _lwkt_enqueue(thread_t td
)
147 if ((td
->td_flags
& (TDF_RUNQ
|TDF_MIGRATING
|TDF_TSLEEPQ
|TDF_BLOCKQ
)) == 0) {
148 int nq
= td
->td_pri
& TDPRI_MASK
;
149 struct globaldata
*gd
= td
->td_gd
;
151 td
->td_flags
|= TDF_RUNQ
;
152 TAILQ_INSERT_TAIL(&gd
->gd_tdrunq
[nq
], td
, td_threadq
);
153 gd
->gd_runqmask
|= 1 << nq
;
158 * Schedule a thread to run. As the current thread we can always safely
159 * schedule ourselves, and a shortcut procedure is provided for that
162 * (non-blocking, self contained on a per cpu basis)
165 lwkt_schedule_self(thread_t td
)
167 crit_enter_quick(td
);
168 KASSERT(td
!= &td
->td_gd
->gd_idlethread
, ("lwkt_schedule_self(): scheduling gd_idlethread is illegal!"));
169 KKASSERT(td
->td_lwp
== NULL
|| (td
->td_lwp
->lwp_flag
& LWP_ONRUNQ
) == 0);
175 * Deschedule a thread.
177 * (non-blocking, self contained on a per cpu basis)
180 lwkt_deschedule_self(thread_t td
)
182 crit_enter_quick(td
);
188 * LWKTs operate on a per-cpu basis
190 * WARNING! Called from early boot, 'mycpu' may not work yet.
193 lwkt_gdinit(struct globaldata
*gd
)
197 for (i
= 0; i
< sizeof(gd
->gd_tdrunq
)/sizeof(gd
->gd_tdrunq
[0]); ++i
)
198 TAILQ_INIT(&gd
->gd_tdrunq
[i
]);
200 TAILQ_INIT(&gd
->gd_tdallq
);
204 * Create a new thread. The thread must be associated with a process context
205 * or LWKT start address before it can be scheduled. If the target cpu is
206 * -1 the thread will be created on the current cpu.
208 * If you intend to create a thread without a process context this function
209 * does everything except load the startup and switcher function.
212 lwkt_alloc_thread(struct thread
*td
, int stksize
, int cpu
, int flags
)
215 globaldata_t gd
= mycpu
;
219 if (gd
->gd_tdfreecount
> 0) {
220 --gd
->gd_tdfreecount
;
221 td
= TAILQ_FIRST(&gd
->gd_tdfreeq
);
222 KASSERT(td
!= NULL
&& (td
->td_flags
& TDF_RUNNING
) == 0,
223 ("lwkt_alloc_thread: unexpected NULL or corrupted td"));
224 TAILQ_REMOVE(&gd
->gd_tdfreeq
, td
, td_threadq
);
226 flags
|= td
->td_flags
& (TDF_ALLOCATED_STACK
|TDF_ALLOCATED_THREAD
);
229 td
= zalloc(thread_zone
);
230 td
->td_kstack
= NULL
;
231 td
->td_kstack_size
= 0;
232 flags
|= TDF_ALLOCATED_THREAD
;
235 if ((stack
= td
->td_kstack
) != NULL
&& td
->td_kstack_size
!= stksize
) {
236 if (flags
& TDF_ALLOCATED_STACK
) {
237 kmem_free(&kernel_map
, (vm_offset_t
)stack
, td
->td_kstack_size
);
242 stack
= (void *)kmem_alloc(&kernel_map
, stksize
);
243 flags
|= TDF_ALLOCATED_STACK
;
246 lwkt_init_thread(td
, stack
, stksize
, flags
, mycpu
);
248 lwkt_init_thread(td
, stack
, stksize
, flags
, globaldata_find(cpu
));
253 * Initialize a preexisting thread structure. This function is used by
254 * lwkt_alloc_thread() and also used to initialize the per-cpu idlethread.
256 * All threads start out in a critical section at a priority of
257 * TDPRI_KERN_DAEMON. Higher level code will modify the priority as
258 * appropriate. This function may send an IPI message when the
259 * requested cpu is not the current cpu and consequently gd_tdallq may
260 * not be initialized synchronously from the point of view of the originating
263 * NOTE! we have to be careful in regards to creating threads for other cpus
264 * if SMP has not yet been activated.
269 lwkt_init_thread_remote(void *arg
)
274 * Protected by critical section held by IPI dispatch
276 TAILQ_INSERT_TAIL(&td
->td_gd
->gd_tdallq
, td
, td_allq
);
282 lwkt_init_thread(thread_t td
, void *stack
, int stksize
, int flags
,
283 struct globaldata
*gd
)
285 globaldata_t mygd
= mycpu
;
287 bzero(td
, sizeof(struct thread
));
288 td
->td_kstack
= stack
;
289 td
->td_kstack_size
= stksize
;
290 td
->td_flags
= flags
;
292 td
->td_pri
= TDPRI_KERN_DAEMON
+ TDPRI_CRIT
;
294 if ((flags
& TDF_MPSAFE
) == 0)
297 if (lwkt_use_spin_port
)
298 lwkt_initport_spin(&td
->td_msgport
);
300 lwkt_initport_thread(&td
->td_msgport
, td
);
301 pmap_init_thread(td
);
304 * Normally initializing a thread for a remote cpu requires sending an
305 * IPI. However, the idlethread is setup before the other cpus are
306 * activated so we have to treat it as a special case. XXX manipulation
307 * of gd_tdallq requires the BGL.
309 if (gd
== mygd
|| td
== &gd
->gd_idlethread
) {
311 TAILQ_INSERT_TAIL(&gd
->gd_tdallq
, td
, td_allq
);
314 lwkt_send_ipiq(gd
, lwkt_init_thread_remote
, td
);
318 TAILQ_INSERT_TAIL(&gd
->gd_tdallq
, td
, td_allq
);
324 lwkt_set_comm(thread_t td
, const char *ctl
, ...)
329 kvsnprintf(td
->td_comm
, sizeof(td
->td_comm
), ctl
, va
);
334 lwkt_hold(thread_t td
)
340 lwkt_rele(thread_t td
)
342 KKASSERT(td
->td_refs
> 0);
347 lwkt_wait_free(thread_t td
)
350 tsleep(td
, 0, "tdreap", hz
);
354 lwkt_free_thread(thread_t td
)
356 struct globaldata
*gd
= mycpu
;
358 KASSERT((td
->td_flags
& TDF_RUNNING
) == 0,
359 ("lwkt_free_thread: did not exit! %p", td
));
362 if (gd
->gd_tdfreecount
< CACHE_NTHREADS
&&
363 (td
->td_flags
& TDF_ALLOCATED_THREAD
)
365 ++gd
->gd_tdfreecount
;
366 TAILQ_INSERT_HEAD(&gd
->gd_tdfreeq
, td
, td_threadq
);
370 if (td
->td_kstack
&& (td
->td_flags
& TDF_ALLOCATED_STACK
)) {
371 kmem_free(&kernel_map
, (vm_offset_t
)td
->td_kstack
, td
->td_kstack_size
);
373 td
->td_kstack
= NULL
;
374 td
->td_kstack_size
= 0;
376 if (td
->td_flags
& TDF_ALLOCATED_THREAD
) {
377 zfree(thread_zone
, td
);
384 * Switch to the next runnable lwkt. If no LWKTs are runnable then
385 * switch to the idlethread. Switching must occur within a critical
386 * section to avoid races with the scheduling queue.
388 * We always have full control over our cpu's run queue. Other cpus
389 * that wish to manipulate our queue must use the cpu_*msg() calls to
390 * talk to our cpu, so a critical section is all that is needed and
391 * the result is very, very fast thread switching.
393 * The LWKT scheduler uses a fixed priority model and round-robins at
394 * each priority level. User process scheduling is a totally
395 * different beast and LWKT priorities should not be confused with
396 * user process priorities.
398 * The MP lock may be out of sync with the thread's td_mpcount. lwkt_switch()
399 * cleans it up. Note that the td_switch() function cannot do anything that
400 * requires the MP lock since the MP lock will have already been setup for
401 * the target thread (not the current thread). It's nice to have a scheduler
402 * that does not need the MP lock to work because it allows us to do some
403 * really cool high-performance MP lock optimizations.
405 * PREEMPTION NOTE: Preemption occurs via lwkt_preempt(). lwkt_switch()
406 * is not called by the current thread in the preemption case, only when
407 * the preempting thread blocks (in order to return to the original thread).
412 globaldata_t gd
= mycpu
;
413 thread_t td
= gd
->gd_curthread
;
420 * Switching from within a 'fast' (non thread switched) interrupt or IPI
421 * is illegal. However, we may have to do it anyway if we hit a fatal
422 * kernel trap or we have paniced.
424 * If this case occurs save and restore the interrupt nesting level.
426 if (gd
->gd_intr_nesting_level
) {
430 if (gd
->gd_trap_nesting_level
== 0 && panicstr
== NULL
) {
431 panic("lwkt_switch: cannot switch from within "
432 "a fast interrupt, yet, td %p\n", td
);
434 savegdnest
= gd
->gd_intr_nesting_level
;
435 savegdtrap
= gd
->gd_trap_nesting_level
;
436 gd
->gd_intr_nesting_level
= 0;
437 gd
->gd_trap_nesting_level
= 0;
438 if ((td
->td_flags
& TDF_PANICWARN
) == 0) {
439 td
->td_flags
|= TDF_PANICWARN
;
440 kprintf("Warning: thread switch from interrupt or IPI, "
441 "thread %p (%s)\n", td
, td
->td_comm
);
443 db_print_backtrace();
447 gd
->gd_intr_nesting_level
= savegdnest
;
448 gd
->gd_trap_nesting_level
= savegdtrap
;
454 * Passive release (used to transition from user to kernel mode
455 * when we block or switch rather then when we enter the kernel).
456 * This function is NOT called if we are switching into a preemption
457 * or returning from a preemption. Typically this causes us to lose
458 * our current process designation (if we have one) and become a true
459 * LWKT thread, and may also hand the current process designation to
460 * another process and schedule thread.
467 lwkt_relalltokens(td
);
470 * We had better not be holding any spin locks, but don't get into an
471 * endless panic loop.
473 KASSERT(gd
->gd_spinlock_rd
== NULL
|| panicstr
!= NULL
,
474 ("lwkt_switch: still holding a shared spinlock %p!",
475 gd
->gd_spinlock_rd
));
476 KASSERT(gd
->gd_spinlocks_wr
== 0 || panicstr
!= NULL
,
477 ("lwkt_switch: still holding %d exclusive spinlocks!",
478 gd
->gd_spinlocks_wr
));
483 * td_mpcount cannot be used to determine if we currently hold the
484 * MP lock because get_mplock() will increment it prior to attempting
485 * to get the lock, and switch out if it can't. Our ownership of
486 * the actual lock will remain stable while we are in a critical section
487 * (but, of course, another cpu may own or release the lock so the
488 * actual value of mp_lock is not stable).
490 mpheld
= MP_LOCK_HELD();
492 if (td
->td_cscount
) {
493 kprintf("Diagnostic: attempt to switch while mastering cpusync: %p\n",
495 if (panic_on_cscount
)
496 panic("switching while mastering cpusync");
500 if ((ntd
= td
->td_preempted
) != NULL
) {
502 * We had preempted another thread on this cpu, resume the preempted
503 * thread. This occurs transparently, whether the preempted thread
504 * was scheduled or not (it may have been preempted after descheduling
507 * We have to setup the MP lock for the original thread after backing
508 * out the adjustment that was made to curthread when the original
511 KKASSERT(ntd
->td_flags
& TDF_PREEMPT_LOCK
);
513 if (ntd
->td_mpcount
&& mpheld
== 0) {
514 panic("MPLOCK NOT HELD ON RETURN: %p %p %d %d",
515 td
, ntd
, td
->td_mpcount
, ntd
->td_mpcount
);
517 if (ntd
->td_mpcount
) {
518 td
->td_mpcount
-= ntd
->td_mpcount
;
519 KKASSERT(td
->td_mpcount
>= 0);
522 ntd
->td_flags
|= TDF_PREEMPT_DONE
;
525 * XXX. The interrupt may have woken a thread up, we need to properly
526 * set the reschedule flag if the originally interrupted thread is at
529 if (gd
->gd_runqmask
> (2 << (ntd
->td_pri
& TDPRI_MASK
)) - 1)
531 /* YYY release mp lock on switchback if original doesn't need it */
534 * Priority queue / round-robin at each priority. Note that user
535 * processes run at a fixed, low priority and the user process
536 * scheduler deals with interactions between user processes
537 * by scheduling and descheduling them from the LWKT queue as
540 * We have to adjust the MP lock for the target thread. If we
541 * need the MP lock and cannot obtain it we try to locate a
542 * thread that does not need the MP lock. If we cannot, we spin
545 * A similar issue exists for the tokens held by the target thread.
546 * If we cannot obtain ownership of the tokens we cannot immediately
547 * schedule the thread.
551 * If an LWKT reschedule was requested, well that is what we are
552 * doing now so clear it.
554 clear_lwkt_resched();
556 if (gd
->gd_runqmask
) {
557 int nq
= bsrl(gd
->gd_runqmask
);
558 if ((ntd
= TAILQ_FIRST(&gd
->gd_tdrunq
[nq
])) == NULL
) {
559 gd
->gd_runqmask
&= ~(1 << nq
);
564 * THREAD SELECTION FOR AN SMP MACHINE BUILD
566 * If the target needs the MP lock and we couldn't get it,
567 * or if the target is holding tokens and we could not
568 * gain ownership of the tokens, continue looking for a
569 * thread to schedule and spin instead of HLT if we can't.
571 * NOTE: the mpheld variable invalid after this conditional, it
572 * can change due to both cpu_try_mplock() returning success
573 * AND interactions in lwkt_getalltokens() due to the fact that
574 * we are trying to check the mpcount of a thread other then
575 * the current thread. Because of this, if the current thread
576 * is not holding td_mpcount, an IPI indirectly run via
577 * lwkt_getalltokens() can obtain and release the MP lock and
578 * cause the core MP lock to be released.
580 if ((ntd
->td_mpcount
&& mpheld
== 0 && !cpu_try_mplock()) ||
581 (ntd
->td_toks
&& lwkt_getalltokens(ntd
) == 0)
583 u_int32_t rqmask
= gd
->gd_runqmask
;
585 mpheld
= MP_LOCK_HELD();
588 TAILQ_FOREACH(ntd
, &gd
->gd_tdrunq
[nq
], td_threadq
) {
589 if (ntd
->td_mpcount
&& !mpheld
&& !cpu_try_mplock()) {
590 /* spinning due to MP lock being held */
592 ++mplock_contention_count
;
594 /* mplock still not held, 'mpheld' still valid */
599 * mpheld state invalid after getalltokens call returns
600 * failure, but the variable is only needed for
603 if (ntd
->td_toks
&& !lwkt_getalltokens(ntd
)) {
604 /* spinning due to token contention */
606 ++token_contention_count
;
608 mpheld
= MP_LOCK_HELD();
615 rqmask
&= ~(1 << nq
);
619 cpu_mplock_contested();
620 ntd
= &gd
->gd_idlethread
;
621 ntd
->td_flags
|= TDF_IDLE_NOHLT
;
622 goto using_idle_thread
;
624 ++gd
->gd_cnt
.v_swtch
;
625 TAILQ_REMOVE(&gd
->gd_tdrunq
[nq
], ntd
, td_threadq
);
626 TAILQ_INSERT_TAIL(&gd
->gd_tdrunq
[nq
], ntd
, td_threadq
);
629 ++gd
->gd_cnt
.v_swtch
;
630 TAILQ_REMOVE(&gd
->gd_tdrunq
[nq
], ntd
, td_threadq
);
631 TAILQ_INSERT_TAIL(&gd
->gd_tdrunq
[nq
], ntd
, td_threadq
);
635 * THREAD SELECTION FOR A UP MACHINE BUILD. We don't have to
636 * worry about tokens or the BGL. However, we still have
637 * to call lwkt_getalltokens() in order to properly detect
638 * stale tokens. This call cannot fail for a UP build!
640 lwkt_getalltokens(ntd
);
641 ++gd
->gd_cnt
.v_swtch
;
642 TAILQ_REMOVE(&gd
->gd_tdrunq
[nq
], ntd
, td_threadq
);
643 TAILQ_INSERT_TAIL(&gd
->gd_tdrunq
[nq
], ntd
, td_threadq
);
647 * We have nothing to run but only let the idle loop halt
648 * the cpu if there are no pending interrupts.
650 ntd
= &gd
->gd_idlethread
;
651 if (gd
->gd_reqflags
& RQF_IDLECHECK_MASK
)
652 ntd
->td_flags
|= TDF_IDLE_NOHLT
;
656 * The idle thread should not be holding the MP lock unless we
657 * are trapping in the kernel or in a panic. Since we select the
658 * idle thread unconditionally when no other thread is available,
659 * if the MP lock is desired during a panic or kernel trap, we
660 * have to loop in the scheduler until we get it.
662 if (ntd
->td_mpcount
) {
663 mpheld
= MP_LOCK_HELD();
664 if (gd
->gd_trap_nesting_level
== 0 && panicstr
== NULL
) {
665 panic("Idle thread %p was holding the BGL!", ntd
);
666 } else if (mpheld
== 0) {
667 cpu_mplock_contested();
674 KASSERT(ntd
->td_pri
>= TDPRI_CRIT
,
675 ("priority problem in lwkt_switch %d %d", td
->td_pri
, ntd
->td_pri
));
678 * Do the actual switch. If the new target does not need the MP lock
679 * and we are holding it, release the MP lock. If the new target requires
680 * the MP lock we have already acquired it for the target.
683 if (ntd
->td_mpcount
== 0 ) {
687 ASSERT_MP_LOCK_HELD(ntd
);
694 /* NOTE: current cpu may have changed after switch */
699 * Request that the target thread preempt the current thread. Preemption
700 * only works under a specific set of conditions:
702 * - We are not preempting ourselves
703 * - The target thread is owned by the current cpu
704 * - We are not currently being preempted
705 * - The target is not currently being preempted
706 * - We are not holding any spin locks
707 * - The target thread is not holding any tokens
708 * - We are able to satisfy the target's MP lock requirements (if any).
710 * THE CALLER OF LWKT_PREEMPT() MUST BE IN A CRITICAL SECTION. Typically
711 * this is called via lwkt_schedule() through the td_preemptable callback.
712 * critpri is the managed critical priority that we should ignore in order
713 * to determine whether preemption is possible (aka usually just the crit
714 * priority of lwkt_schedule() itself).
716 * XXX at the moment we run the target thread in a critical section during
717 * the preemption in order to prevent the target from taking interrupts
718 * that *WE* can't. Preemption is strictly limited to interrupt threads
719 * and interrupt-like threads, outside of a critical section, and the
720 * preempted source thread will be resumed the instant the target blocks
721 * whether or not the source is scheduled (i.e. preemption is supposed to
722 * be as transparent as possible).
724 * The target thread inherits our MP count (added to its own) for the
725 * duration of the preemption in order to preserve the atomicy of the
726 * MP lock during the preemption. Therefore, any preempting targets must be
727 * careful in regards to MP assertions. Note that the MP count may be
728 * out of sync with the physical mp_lock, but we do not have to preserve
729 * the original ownership of the lock if it was out of synch (that is, we
730 * can leave it synchronized on return).
733 lwkt_preempt(thread_t ntd
, int critpri
)
735 struct globaldata
*gd
= mycpu
;
743 * The caller has put us in a critical section. We can only preempt
744 * if the caller of the caller was not in a critical section (basically
745 * a local interrupt), as determined by the 'critpri' parameter. We
746 * also can't preempt if the caller is holding any spinlocks (even if
747 * he isn't in a critical section). This also handles the tokens test.
749 * YYY The target thread must be in a critical section (else it must
750 * inherit our critical section? I dunno yet).
752 * Set need_lwkt_resched() unconditionally for now YYY.
754 KASSERT(ntd
->td_pri
>= TDPRI_CRIT
, ("BADCRIT0 %d", ntd
->td_pri
));
756 td
= gd
->gd_curthread
;
757 if ((ntd
->td_pri
& TDPRI_MASK
) <= (td
->td_pri
& TDPRI_MASK
)) {
761 if ((td
->td_pri
& ~TDPRI_MASK
) > critpri
) {
767 if (ntd
->td_gd
!= gd
) {
774 * Take the easy way out and do not preempt if we are holding
775 * any spinlocks. We could test whether the thread(s) being
776 * preempted interlock against the target thread's tokens and whether
777 * we can get all the target thread's tokens, but this situation
778 * should not occur very often so its easier to simply not preempt.
779 * Also, plain spinlocks are impossible to figure out at this point so
780 * just don't preempt.
782 * Do not try to preempt if the target thread is holding any tokens.
783 * We could try to acquire the tokens but this case is so rare there
784 * is no need to support it.
786 if (gd
->gd_spinlock_rd
|| gd
->gd_spinlocks_wr
) {
796 if (td
== ntd
|| ((td
->td_flags
| ntd
->td_flags
) & TDF_PREEMPT_LOCK
)) {
801 if (ntd
->td_preempted
) {
808 * note: an interrupt might have occured just as we were transitioning
809 * to or from the MP lock. In this case td_mpcount will be pre-disposed
810 * (non-zero) but not actually synchronized with the actual state of the
811 * lock. We can use it to imply an MP lock requirement for the
812 * preemption but we cannot use it to test whether we hold the MP lock
815 savecnt
= td
->td_mpcount
;
816 mpheld
= MP_LOCK_HELD();
817 ntd
->td_mpcount
+= td
->td_mpcount
;
818 if (mpheld
== 0 && ntd
->td_mpcount
&& !cpu_try_mplock()) {
819 ntd
->td_mpcount
-= td
->td_mpcount
;
827 * Since we are able to preempt the current thread, there is no need to
828 * call need_lwkt_resched().
831 ntd
->td_preempted
= td
;
832 td
->td_flags
|= TDF_PREEMPT_LOCK
;
834 KKASSERT(ntd
->td_preempted
&& (td
->td_flags
& TDF_PREEMPT_DONE
));
836 KKASSERT(savecnt
== td
->td_mpcount
);
837 mpheld
= MP_LOCK_HELD();
838 if (mpheld
&& td
->td_mpcount
== 0)
840 else if (mpheld
== 0 && td
->td_mpcount
)
841 panic("lwkt_preempt(): MP lock was not held through");
843 ntd
->td_preempted
= NULL
;
844 td
->td_flags
&= ~(TDF_PREEMPT_LOCK
|TDF_PREEMPT_DONE
);
848 * Yield our thread while higher priority threads are pending. This is
849 * typically called when we leave a critical section but it can be safely
850 * called while we are in a critical section.
852 * This function will not generally yield to equal priority threads but it
853 * can occur as a side effect. Note that lwkt_switch() is called from
854 * inside the critical section to prevent its own crit_exit() from reentering
855 * lwkt_yield_quick().
857 * gd_reqflags indicates that *something* changed, e.g. an interrupt or softint
858 * came along but was blocked and made pending.
860 * (self contained on a per cpu basis)
863 lwkt_yield_quick(void)
865 globaldata_t gd
= mycpu
;
866 thread_t td
= gd
->gd_curthread
;
869 * gd_reqflags is cleared in splz if the cpl is 0. If we were to clear
870 * it with a non-zero cpl then we might not wind up calling splz after
871 * a task switch when the critical section is exited even though the
872 * new task could accept the interrupt.
874 * XXX from crit_exit() only called after last crit section is released.
875 * If called directly will run splz() even if in a critical section.
877 * td_nest_count prevent deep nesting via splz() or doreti(). Note that
878 * except for this special case, we MUST call splz() here to handle any
879 * pending ints, particularly after we switch, or we might accidently
880 * halt the cpu with interrupts pending.
882 if (gd
->gd_reqflags
&& td
->td_nest_count
< 2)
886 * YYY enabling will cause wakeup() to task-switch, which really
887 * confused the old 4.x code. This is a good way to simulate
888 * preemption and MP without actually doing preemption or MP, because a
889 * lot of code assumes that wakeup() does not block.
891 if (untimely_switch
&& td
->td_nest_count
== 0 &&
892 gd
->gd_intr_nesting_level
== 0
894 crit_enter_quick(td
);
896 * YYY temporary hacks until we disassociate the userland scheduler
897 * from the LWKT scheduler.
899 if (td
->td_flags
& TDF_RUNQ
) {
900 lwkt_switch(); /* will not reenter yield function */
902 lwkt_schedule_self(td
); /* make sure we are scheduled */
903 lwkt_switch(); /* will not reenter yield function */
904 lwkt_deschedule_self(td
); /* make sure we are descheduled */
906 crit_exit_noyield(td
);
911 * This implements a normal yield which, unlike _quick, will yield to equal
912 * priority threads as well. Note that gd_reqflags tests will be handled by
913 * the crit_exit() call in lwkt_switch().
915 * (self contained on a per cpu basis)
920 lwkt_schedule_self(curthread
);
925 * Generic schedule. Possibly schedule threads belonging to other cpus and
926 * deal with threads that might be blocked on a wait queue.
928 * We have a little helper inline function which does additional work after
929 * the thread has been enqueued, including dealing with preemption and
930 * setting need_lwkt_resched() (which prevents the kernel from returning
931 * to userland until it has processed higher priority threads).
933 * It is possible for this routine to be called after a failed _enqueue
934 * (due to the target thread migrating, sleeping, or otherwise blocked).
935 * We have to check that the thread is actually on the run queue!
939 _lwkt_schedule_post(globaldata_t gd
, thread_t ntd
, int cpri
)
941 if (ntd
->td_flags
& TDF_RUNQ
) {
942 if (ntd
->td_preemptable
) {
943 ntd
->td_preemptable(ntd
, cpri
); /* YYY +token */
944 } else if ((ntd
->td_flags
& TDF_NORESCHED
) == 0 &&
945 (ntd
->td_pri
& TDPRI_MASK
) > (gd
->gd_curthread
->td_pri
& TDPRI_MASK
)
953 lwkt_schedule(thread_t td
)
955 globaldata_t mygd
= mycpu
;
957 KASSERT(td
!= &td
->td_gd
->gd_idlethread
, ("lwkt_schedule(): scheduling gd_idlethread is illegal!"));
959 KKASSERT(td
->td_lwp
== NULL
|| (td
->td_lwp
->lwp_flag
& LWP_ONRUNQ
) == 0);
960 if (td
== mygd
->gd_curthread
) {
964 * If we own the thread, there is no race (since we are in a
965 * critical section). If we do not own the thread there might
966 * be a race but the target cpu will deal with it.
969 if (td
->td_gd
== mygd
) {
971 _lwkt_schedule_post(mygd
, td
, TDPRI_CRIT
);
973 lwkt_send_ipiq(td
->td_gd
, (ipifunc1_t
)lwkt_schedule
, td
);
977 _lwkt_schedule_post(mygd
, td
, TDPRI_CRIT
);
986 * Thread migration using a 'Pull' method. The thread may or may not be
987 * the current thread. It MUST be descheduled and in a stable state.
988 * lwkt_giveaway() must be called on the cpu owning the thread.
990 * At any point after lwkt_giveaway() is called, the target cpu may
991 * 'pull' the thread by calling lwkt_acquire().
993 * MPSAFE - must be called under very specific conditions.
996 lwkt_giveaway(thread_t td
)
998 globaldata_t gd
= mycpu
;
1001 KKASSERT(td
->td_gd
== gd
);
1002 TAILQ_REMOVE(&gd
->gd_tdallq
, td
, td_allq
);
1003 td
->td_flags
|= TDF_MIGRATING
;
1008 lwkt_acquire(thread_t td
)
1013 KKASSERT(td
->td_flags
& TDF_MIGRATING
);
1018 KKASSERT((td
->td_flags
& TDF_RUNQ
) == 0);
1019 crit_enter_gd(mygd
);
1020 while (td
->td_flags
& (TDF_RUNNING
|TDF_PREEMPT_LOCK
))
1023 TAILQ_INSERT_TAIL(&mygd
->gd_tdallq
, td
, td_allq
);
1024 td
->td_flags
&= ~TDF_MIGRATING
;
1027 crit_enter_gd(mygd
);
1028 TAILQ_INSERT_TAIL(&mygd
->gd_tdallq
, td
, td_allq
);
1029 td
->td_flags
&= ~TDF_MIGRATING
;
1037 * Generic deschedule. Descheduling threads other then your own should be
1038 * done only in carefully controlled circumstances. Descheduling is
1041 * This function may block if the cpu has run out of messages.
1044 lwkt_deschedule(thread_t td
)
1048 if (td
== curthread
) {
1051 if (td
->td_gd
== mycpu
) {
1054 lwkt_send_ipiq(td
->td_gd
, (ipifunc1_t
)lwkt_deschedule
, td
);
1064 * Set the target thread's priority. This routine does not automatically
1065 * switch to a higher priority thread, LWKT threads are not designed for
1066 * continuous priority changes. Yield if you want to switch.
1068 * We have to retain the critical section count which uses the high bits
1069 * of the td_pri field. The specified priority may also indicate zero or
1070 * more critical sections by adding TDPRI_CRIT*N.
1072 * Note that we requeue the thread whether it winds up on a different runq
1073 * or not. uio_yield() depends on this and the routine is not normally
1074 * called with the same priority otherwise.
1077 lwkt_setpri(thread_t td
, int pri
)
1080 KKASSERT(td
->td_gd
== mycpu
);
1082 if (td
->td_flags
& TDF_RUNQ
) {
1084 td
->td_pri
= (td
->td_pri
& ~TDPRI_MASK
) + pri
;
1087 td
->td_pri
= (td
->td_pri
& ~TDPRI_MASK
) + pri
;
1093 lwkt_setpri_self(int pri
)
1095 thread_t td
= curthread
;
1097 KKASSERT(pri
>= 0 && pri
<= TDPRI_MAX
);
1099 if (td
->td_flags
& TDF_RUNQ
) {
1101 td
->td_pri
= (td
->td_pri
& ~TDPRI_MASK
) + pri
;
1104 td
->td_pri
= (td
->td_pri
& ~TDPRI_MASK
) + pri
;
1110 * Determine if there is a runnable thread at a higher priority then
1111 * the current thread. lwkt_setpri() does not check this automatically.
1112 * Return 1 if there is, 0 if there isn't.
1114 * Example: if bit 31 of runqmask is set and the current thread is priority
1115 * 30, then we wind up checking the mask: 0x80000000 against 0x7fffffff.
1117 * If nq reaches 31 the shift operation will overflow to 0 and we will wind
1118 * up comparing against 0xffffffff, a comparison that will always be false.
1121 lwkt_checkpri_self(void)
1123 globaldata_t gd
= mycpu
;
1124 thread_t td
= gd
->gd_curthread
;
1125 int nq
= td
->td_pri
& TDPRI_MASK
;
1127 while (gd
->gd_runqmask
> (__uint32_t
)(2 << nq
) - 1) {
1128 if (TAILQ_FIRST(&gd
->gd_tdrunq
[nq
+ 1]))
1136 * Migrate the current thread to the specified cpu.
1138 * This is accomplished by descheduling ourselves from the current cpu,
1139 * moving our thread to the tdallq of the target cpu, IPI messaging the
1140 * target cpu, and switching out. TDF_MIGRATING prevents scheduling
1141 * races while the thread is being migrated.
1144 static void lwkt_setcpu_remote(void *arg
);
1148 lwkt_setcpu_self(globaldata_t rgd
)
1151 thread_t td
= curthread
;
1153 if (td
->td_gd
!= rgd
) {
1154 crit_enter_quick(td
);
1155 td
->td_flags
|= TDF_MIGRATING
;
1156 lwkt_deschedule_self(td
);
1157 TAILQ_REMOVE(&td
->td_gd
->gd_tdallq
, td
, td_allq
);
1158 lwkt_send_ipiq(rgd
, (ipifunc1_t
)lwkt_setcpu_remote
, td
);
1160 /* we are now on the target cpu */
1161 TAILQ_INSERT_TAIL(&rgd
->gd_tdallq
, td
, td_allq
);
1162 crit_exit_quick(td
);
1168 lwkt_migratecpu(int cpuid
)
1173 rgd
= globaldata_find(cpuid
);
1174 lwkt_setcpu_self(rgd
);
1179 * Remote IPI for cpu migration (called while in a critical section so we
1180 * do not have to enter another one). The thread has already been moved to
1181 * our cpu's allq, but we must wait for the thread to be completely switched
1182 * out on the originating cpu before we schedule it on ours or the stack
1183 * state may be corrupt. We clear TDF_MIGRATING after flushing the GD
1184 * change to main memory.
1186 * XXX The use of TDF_MIGRATING might not be sufficient to avoid races
1187 * against wakeups. It is best if this interface is used only when there
1188 * are no pending events that might try to schedule the thread.
1192 lwkt_setcpu_remote(void *arg
)
1195 globaldata_t gd
= mycpu
;
1197 while (td
->td_flags
& (TDF_RUNNING
|TDF_PREEMPT_LOCK
))
1201 td
->td_flags
&= ~TDF_MIGRATING
;
1202 KKASSERT(td
->td_lwp
== NULL
|| (td
->td_lwp
->lwp_flag
& LWP_ONRUNQ
) == 0);
1208 lwkt_preempted_proc(void)
1210 thread_t td
= curthread
;
1211 while (td
->td_preempted
)
1212 td
= td
->td_preempted
;
1217 * Create a kernel process/thread/whatever. It shares it's address space
1218 * with proc0 - ie: kernel only.
1220 * NOTE! By default new threads are created with the MP lock held. A
1221 * thread which does not require the MP lock should release it by calling
1222 * rel_mplock() at the start of the new thread.
1225 lwkt_create(void (*func
)(void *), void *arg
,
1226 struct thread
**tdp
, thread_t
template, int tdflags
, int cpu
,
1227 const char *fmt
, ...)
1232 td
= lwkt_alloc_thread(template, LWKT_THREAD_STACK
, cpu
,
1236 cpu_set_thread_handler(td
, lwkt_exit
, func
, arg
);
1239 * Set up arg0 for 'ps' etc
1241 __va_start(ap
, fmt
);
1242 kvsnprintf(td
->td_comm
, sizeof(td
->td_comm
), fmt
, ap
);
1246 * Schedule the thread to run
1248 if ((td
->td_flags
& TDF_STOPREQ
) == 0)
1251 td
->td_flags
&= ~TDF_STOPREQ
;
1256 * Destroy an LWKT thread. Warning! This function is not called when
1257 * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
1258 * uses a different reaping mechanism.
1263 thread_t td
= curthread
;
1266 if (td
->td_flags
& TDF_VERBOSE
)
1267 kprintf("kthread %p %s has exited\n", td
, td
->td_comm
);
1269 crit_enter_quick(td
);
1270 lwkt_deschedule_self(td
);
1272 lwkt_remove_tdallq(td
);
1273 if (td
->td_flags
& TDF_ALLOCATED_THREAD
) {
1274 ++gd
->gd_tdfreecount
;
1275 TAILQ_INSERT_TAIL(&gd
->gd_tdfreeq
, td
, td_threadq
);
1281 lwkt_remove_tdallq(thread_t td
)
1283 KKASSERT(td
->td_gd
== mycpu
);
1284 TAILQ_REMOVE(&td
->td_gd
->gd_tdallq
, td
, td_allq
);
1290 thread_t td
= curthread
;
1291 int lpri
= td
->td_pri
;
1294 panic("td_pri is/would-go negative! %p %d", td
, lpri
);
1300 * Called from debugger/panic on cpus which have been stopped. We must still
1301 * process the IPIQ while stopped, even if we were stopped while in a critical
1304 * If we are dumping also try to process any pending interrupts. This may
1305 * or may not work depending on the state of the cpu at the point it was
1309 lwkt_smp_stopped(void)
1311 globaldata_t gd
= mycpu
;
1315 lwkt_process_ipiq();
1318 lwkt_process_ipiq();
1324 * get_mplock() calls this routine if it is unable to obtain the MP lock.
1325 * get_mplock() has already incremented td_mpcount. We must block and
1326 * not return until giant is held.
1328 * All we have to do is lwkt_switch() away. The LWKT scheduler will not
1329 * reschedule the thread until it can obtain the giant lock for it.
1332 lwkt_mp_lock_contested(void)