2 * Copyright (c) 2003 Matthew Dillon <dillon@backplane.com>
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, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * Each cpu in a system has its own self-contained light weight kernel
27 * thread scheduler, which means that generally speaking we only need
28 * to use a critical section to prevent hicups.
30 * $DragonFly: src/sys/kern/lwkt_thread.c,v 1.7 2003/06/27 20:27:18 dillon Exp $
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/kernel.h>
37 #include <sys/rtprio.h>
38 #include <sys/queue.h>
39 #include <sys/thread2.h>
40 #include <sys/sysctl.h>
41 #include <sys/kthread.h>
42 #include <machine/cpu.h>
46 #include <vm/vm_param.h>
47 #include <vm/vm_kern.h>
48 #include <vm/vm_object.h>
49 #include <vm/vm_page.h>
50 #include <vm/vm_map.h>
51 #include <vm/vm_pager.h>
52 #include <vm/vm_extern.h>
53 #include <vm/vm_zone.h>
55 #include <machine/stdarg.h>
57 static int untimely_switch = 0;
58 SYSCTL_INT(_debug, OID_AUTO, untimely_switch, CTLFLAG_RW, &untimely_switch, 0, "");
63 _lwkt_dequeue(thread_t td)
65 if (td->td_flags & TDF_RUNQ) {
66 td->td_flags &= ~TDF_RUNQ;
67 TAILQ_REMOVE(&mycpu->gd_tdrunq, td, td_threadq);
73 _lwkt_enqueue(thread_t td)
75 if ((td->td_flags & TDF_RUNQ) == 0) {
76 td->td_flags |= TDF_RUNQ;
77 TAILQ_INSERT_TAIL(&mycpu->gd_tdrunq, td, td_threadq);
82 * LWKTs operate on a per-cpu basis
84 * YYY implement strict priorities & round-robin at the same priority
87 lwkt_gdinit(struct globaldata *gd)
89 TAILQ_INIT(&gd->gd_tdrunq);
93 * Initialize a thread wait structure prior to first use.
95 * NOTE! called from low level boot code, we cannot do anything fancy!
98 lwkt_init_wait(lwkt_wait_t w)
100 TAILQ_INIT(&w->wa_waitq);
104 * Create a new thread. The thread must be associated with a process context
105 * or LWKT start address before it can be scheduled.
107 * If you intend to create a thread without a process context this function
108 * does everything except load the startup and switcher function.
111 lwkt_alloc_thread(void)
117 if (mycpu->gd_tdfreecount > 0) {
118 --mycpu->gd_tdfreecount;
119 td = TAILQ_FIRST(&mycpu->gd_tdfreeq);
120 KASSERT(td != NULL && (td->td_flags & TDF_EXITED),
121 ("lwkt_alloc_thread: unexpected NULL or corrupted td"));
122 TAILQ_REMOVE(&mycpu->gd_tdfreeq, td, td_threadq);
124 stack = td->td_kstack;
127 td = zalloc(thread_zone);
128 stack = (void *)kmem_alloc(kernel_map, UPAGES * PAGE_SIZE);
130 lwkt_init_thread(td, stack, TDF_ALLOCATED_STACK|TDF_ALLOCATED_THREAD);
135 * Initialize a preexisting thread structure. This function is used by
136 * lwkt_alloc_thread() and also used to initialize the per-cpu idlethread.
138 * NOTE! called from low level boot code, we cannot do anything fancy!
141 lwkt_init_thread(thread_t td, void *stack, int flags)
143 bzero(td, sizeof(struct thread));
144 td->td_kstack = stack;
145 td->td_flags |= flags;
146 pmap_init_thread(td);
150 lwkt_free_thread(struct thread *td)
152 KASSERT(td->td_flags & TDF_EXITED,
153 ("lwkt_free_thread: did not exit! %p", td));
156 if (mycpu->gd_tdfreecount < CACHE_NTHREADS &&
157 (td->td_flags & TDF_ALLOCATED_THREAD)
159 ++mycpu->gd_tdfreecount;
160 TAILQ_INSERT_HEAD(&mycpu->gd_tdfreeq, td, td_threadq);
164 if (td->td_kstack && (td->td_flags & TDF_ALLOCATED_STACK)) {
165 kmem_free(kernel_map,
166 (vm_offset_t)td->td_kstack, UPAGES * PAGE_SIZE);
167 td->td_kstack = NULL;
169 if (td->td_flags & TDF_ALLOCATED_THREAD)
170 zfree(thread_zone, td);
176 * Switch to the next runnable lwkt. If no LWKTs are runnable then
177 * switch to the idlethread. Switching must occur within a critical
178 * section to avoid races with the scheduling queue.
180 * We always have full control over our cpu's run queue. Other cpus
181 * that wish to manipulate our queue must use the cpu_*msg() calls to
182 * talk to our cpu, so a critical section is all that is needed and
183 * the result is very, very fast thread switching.
185 * We always 'own' our own thread and the threads on our run queue,l
186 * due to TDF_RUNNING or TDF_RUNQ being set. We can safely clear
187 * TDF_RUNNING while in a critical section.
189 * The td_switch() function must be called while in the critical section.
190 * This function saves as much state as is appropriate for the type of
193 * (self contained on a per cpu basis)
198 thread_t td = curthread;
202 if ((ntd = td->td_preempted) != NULL) {
204 * We had preempted another thread on this cpu, resume the preempted
207 td->td_preempted = NULL;
208 ntd->td_flags &= ~TDF_PREEMPTED;
209 } else if ((ntd = TAILQ_FIRST(&mycpu->gd_tdrunq)) != NULL) {
210 TAILQ_REMOVE(&mycpu->gd_tdrunq, ntd, td_threadq);
211 TAILQ_INSERT_TAIL(&mycpu->gd_tdrunq, ntd, td_threadq);
213 ntd = &mycpu->gd_idlethread;
221 * Yield our thread while higher priority threads are pending. This is
222 * typically called when we leave a critical section but it can be safely
223 * called while we are in a critical section.
225 * This function will not generally yield to equal priority threads but it
226 * can occur as a side effect. Note that lwkt_switch() is called from
227 * inside the critical section to pervent its own crit_exit() from reentering
228 * lwkt_yield_quick().
230 * (self contained on a per cpu basis)
233 lwkt_yield_quick(void)
235 thread_t td = curthread;
236 while ((td->td_pri & TDPRI_MASK) < mycpu->gd_reqpri) {
238 cpu_schedule_reqs(); /* resets gd_reqpri */
244 * YYY enabling will cause wakeup() to task-switch, which really
245 * confused the old 4.x code. This is a good way to simulate
246 * preemption and MP without actually doing preemption or MP, because a
247 * lot of code assumes that wakeup() does not block.
249 if (untimely_switch && intr_nesting_level == 0) {
252 * YYY temporary hacks until we disassociate the userland scheduler
253 * from the LWKT scheduler.
255 if (td->td_flags & TDF_RUNQ) {
256 lwkt_switch(); /* will not reenter yield function */
258 lwkt_schedule_self(); /* make sure we are scheduled */
259 lwkt_switch(); /* will not reenter yield function */
260 lwkt_deschedule_self(); /* make sure we are descheduled */
267 * This implements a normal yield which, unlike _quick, will yield to equal
268 * priority threads as well. Note that gd_reqpri tests will be handled by
269 * the crit_exit() call in lwkt_switch().
271 * (self contained on a per cpu basis)
276 lwkt_schedule_self();
281 * Schedule a thread to run. As the current thread we can always safely
282 * schedule ourselves, and a shortcut procedure is provided for that
285 * (non-blocking, self contained on a per cpu basis)
288 lwkt_schedule_self(void)
290 thread_t td = curthread;
293 KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
299 * Generic schedule. Possibly schedule threads belonging to other cpus and
300 * deal with threads that might be blocked on a wait queue.
302 * This function will queue requests asynchronously when possible, but may
303 * block if no request structures are available. Upon return the caller
304 * should note that the scheduling request may not yet have been processed
307 * YYY this is one of the best places to implement any load balancing code.
308 * Load balancing can be accomplished by requesting other sorts of actions
309 * for the thread in question.
312 lwkt_schedule(thread_t td)
315 if (td == curthread) {
321 * If the thread is on a wait list we have to send our scheduling
322 * request to the owner of the wait structure. Otherwise we send
323 * the scheduling request to the cpu owning the thread. Races
324 * are ok, the target will forward the message as necessary (the
325 * message may chase the thread around before it finally gets
328 * (remember, wait structures use stable storage)
330 if ((w = td->td_wait) != NULL) {
331 if (lwkt_havetoken(&w->wa_token)) {
332 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
335 if (td->td_cpu == mycpu->gd_cpuid) {
338 panic("lwkt_schedule: cpu mismatch1");
340 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
341 initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
342 cpu_sendnormsg(&msg.mu_Msg);
346 panic("lwkt_schedule: cpu mismatch2");
348 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
349 initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
350 cpu_sendnormsg(&msg.mu_Msg);
355 * If the wait structure is NULL and we own the thread, there
356 * is no race (since we are in a critical section). If we
357 * do not own the thread there might be a race but the
358 * target cpu will deal with it.
360 if (td->td_cpu == mycpu->gd_cpuid) {
363 panic("lwkt_schedule: cpu mismatch3");
365 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
366 initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
367 cpu_sendnormsg(&msg.mu_Msg);
376 * Deschedule a thread.
378 * (non-blocking, self contained on a per cpu basis)
381 lwkt_deschedule_self(void)
383 thread_t td = curthread;
386 KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
392 * Generic deschedule. Descheduling threads other then your own should be
393 * done only in carefully controlled circumstances. Descheduling is
396 * This function may block if the cpu has run out of messages.
399 lwkt_deschedule(thread_t td)
402 if (td == curthread) {
405 if (td->td_cpu == mycpu->gd_cpuid) {
408 panic("lwkt_deschedule: cpu mismatch");
410 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
411 initDescheduleReqMsg_Thread(&msg.mu_DeschedReq, td);
412 cpu_sendnormsg(&msg.mu_Msg);
420 * This function deschedules the current thread and blocks on the specified
421 * wait queue. We obtain ownership of the wait queue in order to block
422 * on it. A generation number is used to interlock the wait queue in case
423 * it gets signalled while we are blocked waiting on the token.
425 * Note: alternatively we could dequeue our thread and then message the
426 * target cpu owning the wait queue. YYY implement as sysctl.
428 * Note: wait queue signals normally ping-pong the cpu as an optimization.
431 lwkt_block(lwkt_wait_t w, const char *wmesg, int *gen)
433 thread_t td = curthread;
435 lwkt_gettoken(&w->wa_token);
436 if (w->wa_gen == *gen) {
438 TAILQ_INSERT_TAIL(&w->wa_waitq, td, td_threadq);
441 td->td_wmesg = wmesg;
444 /* token might be lost, doesn't matter for gen update */
446 lwkt_reltoken(&w->wa_token);
450 * Signal a wait queue. We gain ownership of the wait queue in order to
451 * signal it. Once a thread is removed from the wait queue we have to
452 * deal with the cpu owning the thread.
454 * Note: alternatively we could message the target cpu owning the wait
455 * queue. YYY implement as sysctl.
458 lwkt_signal(lwkt_wait_t w)
463 lwkt_gettoken(&w->wa_token);
466 while ((td = TAILQ_FIRST(&w->wa_waitq)) != NULL && count) {
469 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
472 if (td->td_cpu == mycpu->gd_cpuid) {
476 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
477 initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
478 cpu_sendnormsg(&msg.mu_Msg);
480 panic("lwkt_signal: cpu mismatch");
482 lwkt_regettoken(&w->wa_token);
484 lwkt_reltoken(&w->wa_token);
488 * Aquire ownership of a token
490 * Aquire ownership of a token. The token may have spl and/or critical
491 * section side effects, depending on its purpose. These side effects
492 * guarentee that you will maintain ownership of the token as long as you
493 * do not block. If you block you may lose access to the token (but you
494 * must still release it even if you lose your access to it).
496 * Note that the spl and critical section characteristics of a token
497 * may not be changed once the token has been initialized.
500 lwkt_gettoken(lwkt_token_t tok)
503 * Prevent preemption so the token can't be taken away from us once
504 * we gain ownership of it. Use a synchronous request which might
505 * block. The request will be forwarded as necessary playing catchup
510 while (tok->t_cpu != mycpu->gd_cpuid) {
511 lwkt_cpu_msg_union msg;
512 initTokenReqMsg(&msg.mu_TokenReq);
517 * leave us in a critical section on return. This will be undone
523 * Release your ownership of a token. Releases must occur in reverse
524 * order to aquisitions, eventually so priorities can be unwound properly
525 * like SPLs. At the moment the actual implemention doesn't care.
527 * We can safely hand a token that we own to another cpu without notifying
528 * it, but once we do we can't get it back without requesting it (unless
529 * the other cpu hands it back to us before we check).
531 * We might have lost the token, so check that.
534 lwkt_reltoken(lwkt_token_t tok)
536 if (tok->t_cpu == mycpu->gd_cpuid) {
537 tok->t_cpu = tok->t_reqcpu;
543 * Reaquire a token that might have been lost. Returns 1 if we blocked
544 * while reaquiring the token (meaning that you might have lost other
545 * tokens you held when you made this call), return 0 if we did not block.
548 lwkt_regettoken(lwkt_token_t tok)
551 if (tok->t_cpu != mycpu->gd_cpuid) {
552 while (tok->t_cpu != mycpu->gd_cpuid) {
553 lwkt_cpu_msg_union msg;
554 initTokenReqMsg(&msg.mu_TokenReq);
564 * Create a kernel process/thread/whatever. It shares it's address space
565 * with proc0 - ie: kernel only.
567 * XXX should be renamed to lwkt_create()
570 lwkt_create(void (*func)(void *), void *arg,
571 struct thread **tdp, const char *fmt, ...)
576 td = *tdp = lwkt_alloc_thread();
577 cpu_set_thread_handler(td, kthread_exit, func, arg);
578 td->td_flags |= TDF_VERBOSE;
581 * Set up arg0 for 'ps' etc
584 vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
588 * Schedule the thread to run
595 * Destroy an LWKT thread. Warning! This function is not called when
596 * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
597 * uses a different reaping mechanism.
602 thread_t td = curthread;
604 if (td->td_flags & TDF_VERBOSE)
605 printf("kthread %p %s has exited\n", td, td->td_comm);
607 lwkt_deschedule_self();
608 ++mycpu->gd_tdfreecount;
609 TAILQ_INSERT_TAIL(&mycpu->gd_tdfreeq, td, td_threadq);
614 * Create a kernel process/thread/whatever. It shares it's address space
615 * with proc0 - ie: kernel only.
617 * XXX exact duplicate of lwkt_create().
620 kthread_create(void (*func)(void *), void *arg,
621 struct thread **tdp, const char *fmt, ...)
626 td = *tdp = lwkt_alloc_thread();
627 cpu_set_thread_handler(td, kthread_exit, func, arg);
628 td->td_flags |= TDF_VERBOSE;
631 * Set up arg0 for 'ps' etc
634 vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
638 * Schedule the thread to run
645 * Destroy an LWKT thread. Warning! This function is not called when
646 * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
647 * uses a different reaping mechanism.
649 * XXX duplicates lwkt_exit()