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.10 2003/06/29 05:29:31 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(struct thread *td)
118 if (mycpu->gd_tdfreecount > 0) {
119 --mycpu->gd_tdfreecount;
120 td = TAILQ_FIRST(&mycpu->gd_tdfreeq);
121 KASSERT(td != NULL && (td->td_flags & TDF_EXITED),
122 ("lwkt_alloc_thread: unexpected NULL or corrupted td"));
123 TAILQ_REMOVE(&mycpu->gd_tdfreeq, td, td_threadq);
125 stack = td->td_kstack;
126 flags = td->td_flags & (TDF_ALLOCATED_STACK|TDF_ALLOCATED_THREAD);
129 td = zalloc(thread_zone);
130 td->td_kstack = NULL;
131 flags |= TDF_ALLOCATED_THREAD;
134 if ((stack = td->td_kstack) == NULL) {
135 stack = (void *)kmem_alloc(kernel_map, UPAGES * PAGE_SIZE);
136 flags |= TDF_ALLOCATED_STACK;
138 lwkt_init_thread(td, stack, flags);
143 * Initialize a preexisting thread structure. This function is used by
144 * lwkt_alloc_thread() and also used to initialize the per-cpu idlethread.
146 * NOTE! called from low level boot code, we cannot do anything fancy!
149 lwkt_init_thread(thread_t td, void *stack, int flags)
151 bzero(td, sizeof(struct thread));
152 td->td_kstack = stack;
153 td->td_flags |= flags;
154 pmap_init_thread(td);
158 lwkt_free_thread(struct thread *td)
160 KASSERT(td->td_flags & TDF_EXITED,
161 ("lwkt_free_thread: did not exit! %p", td));
164 if (mycpu->gd_tdfreecount < CACHE_NTHREADS &&
165 (td->td_flags & TDF_ALLOCATED_THREAD)
167 ++mycpu->gd_tdfreecount;
168 TAILQ_INSERT_HEAD(&mycpu->gd_tdfreeq, td, td_threadq);
172 if (td->td_kstack && (td->td_flags & TDF_ALLOCATED_STACK)) {
173 kmem_free(kernel_map,
174 (vm_offset_t)td->td_kstack, UPAGES * PAGE_SIZE);
175 td->td_kstack = NULL;
177 if (td->td_flags & TDF_ALLOCATED_THREAD)
178 zfree(thread_zone, td);
184 * Switch to the next runnable lwkt. If no LWKTs are runnable then
185 * switch to the idlethread. Switching must occur within a critical
186 * section to avoid races with the scheduling queue.
188 * We always have full control over our cpu's run queue. Other cpus
189 * that wish to manipulate our queue must use the cpu_*msg() calls to
190 * talk to our cpu, so a critical section is all that is needed and
191 * the result is very, very fast thread switching.
193 * We always 'own' our own thread and the threads on our run queue,l
194 * due to TDF_RUNNING or TDF_RUNQ being set. We can safely clear
195 * TDF_RUNNING while in a critical section.
197 * The td_switch() function must be called while in the critical section.
198 * This function saves as much state as is appropriate for the type of
201 * (self contained on a per cpu basis)
206 thread_t td = curthread;
209 if (mycpu->gd_intr_nesting_level && td->td_preempted == NULL)
210 panic("lwkt_switch: cannot switch from within an interrupt\n");
213 if ((ntd = td->td_preempted) != NULL) {
215 * We had preempted another thread on this cpu, resume the preempted
218 td->td_preempted = NULL;
219 td->td_pri -= TDPRI_CRIT;
220 ntd->td_flags &= ~TDF_PREEMPTED;
221 } else if ((ntd = TAILQ_FIRST(&mycpu->gd_tdrunq)) != NULL) {
222 TAILQ_REMOVE(&mycpu->gd_tdrunq, ntd, td_threadq);
223 TAILQ_INSERT_TAIL(&mycpu->gd_tdrunq, ntd, td_threadq);
225 ntd = mycpu->gd_idletd;
233 * The target thread preempts the current thread. The target thread
234 * structure must be stable and preempt-safe (e.g. an interrupt thread).
235 * When the target thread blocks the current thread will be resumed.
237 * XXX the target runs in a critical section so it does not open the original
238 * thread up to additional interrupts that the original thread believes it
241 * Normal kernel threads should not preempt other normal kernel threads
242 * as it breaks the assumptions kernel threads are allowed to make. Note
243 * that preemption does not mess around with the current thread's RUNQ
247 lwkt_preempt(struct thread *ntd, int id)
249 struct thread *td = curthread;
252 if (ntd->td_preempted == NULL) {
253 ntd->td_preempted = curthread;
254 td->td_flags |= TDF_PREEMPTED;
255 ntd->td_pri += TDPRI_CRIT;
256 while (td->td_flags & TDF_PREEMPTED)
263 * Yield our thread while higher priority threads are pending. This is
264 * typically called when we leave a critical section but it can be safely
265 * called while we are in a critical section.
267 * This function will not generally yield to equal priority threads but it
268 * can occur as a side effect. Note that lwkt_switch() is called from
269 * inside the critical section to pervent its own crit_exit() from reentering
270 * lwkt_yield_quick().
272 * gd_reqpri indicates that *something* changed, e.g. an interrupt or softint
273 * came along but was blocked and made pending.
275 * (self contained on a per cpu basis)
278 lwkt_yield_quick(void)
280 thread_t td = curthread;
282 if ((td->td_pri & TDPRI_MASK) < mycpu->gd_reqpri) {
283 mycpu->gd_reqpri = 0;
288 * YYY enabling will cause wakeup() to task-switch, which really
289 * confused the old 4.x code. This is a good way to simulate
290 * preemption and MP without actually doing preemption or MP, because a
291 * lot of code assumes that wakeup() does not block.
293 if (untimely_switch && mycpu->gd_intr_nesting_level == 0) {
296 * YYY temporary hacks until we disassociate the userland scheduler
297 * from the LWKT scheduler.
299 if (td->td_flags & TDF_RUNQ) {
300 lwkt_switch(); /* will not reenter yield function */
302 lwkt_schedule_self(); /* make sure we are scheduled */
303 lwkt_switch(); /* will not reenter yield function */
304 lwkt_deschedule_self(); /* make sure we are descheduled */
311 * This implements a normal yield which, unlike _quick, will yield to equal
312 * priority threads as well. Note that gd_reqpri tests will be handled by
313 * the crit_exit() call in lwkt_switch().
315 * (self contained on a per cpu basis)
320 lwkt_schedule_self();
325 * Schedule a thread to run. As the current thread we can always safely
326 * schedule ourselves, and a shortcut procedure is provided for that
329 * (non-blocking, self contained on a per cpu basis)
332 lwkt_schedule_self(void)
334 thread_t td = curthread;
337 KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
343 * Generic schedule. Possibly schedule threads belonging to other cpus and
344 * deal with threads that might be blocked on a wait queue.
346 * This function will queue requests asynchronously when possible, but may
347 * block if no request structures are available. Upon return the caller
348 * should note that the scheduling request may not yet have been processed
351 * YYY this is one of the best places to implement any load balancing code.
352 * Load balancing can be accomplished by requesting other sorts of actions
353 * for the thread in question.
356 lwkt_schedule(thread_t td)
359 if (td == curthread) {
365 * If the thread is on a wait list we have to send our scheduling
366 * request to the owner of the wait structure. Otherwise we send
367 * the scheduling request to the cpu owning the thread. Races
368 * are ok, the target will forward the message as necessary (the
369 * message may chase the thread around before it finally gets
372 * (remember, wait structures use stable storage)
374 if ((w = td->td_wait) != NULL) {
375 if (lwkt_havetoken(&w->wa_token)) {
376 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
379 if (td->td_cpu == mycpu->gd_cpuid) {
382 panic("lwkt_schedule: cpu mismatch1");
384 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
385 initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
386 cpu_sendnormsg(&msg.mu_Msg);
390 panic("lwkt_schedule: cpu mismatch2");
392 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
393 initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
394 cpu_sendnormsg(&msg.mu_Msg);
399 * If the wait structure is NULL and we own the thread, there
400 * is no race (since we are in a critical section). If we
401 * do not own the thread there might be a race but the
402 * target cpu will deal with it.
404 if (td->td_cpu == mycpu->gd_cpuid) {
407 panic("lwkt_schedule: cpu mismatch3");
409 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
410 initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
411 cpu_sendnormsg(&msg.mu_Msg);
420 * Deschedule a thread.
422 * (non-blocking, self contained on a per cpu basis)
425 lwkt_deschedule_self(void)
427 thread_t td = curthread;
430 KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
436 * Generic deschedule. Descheduling threads other then your own should be
437 * done only in carefully controlled circumstances. Descheduling is
440 * This function may block if the cpu has run out of messages.
443 lwkt_deschedule(thread_t td)
446 if (td == curthread) {
449 if (td->td_cpu == mycpu->gd_cpuid) {
452 panic("lwkt_deschedule: cpu mismatch");
454 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
455 initDescheduleReqMsg_Thread(&msg.mu_DeschedReq, td);
456 cpu_sendnormsg(&msg.mu_Msg);
464 * This function deschedules the current thread and blocks on the specified
465 * wait queue. We obtain ownership of the wait queue in order to block
466 * on it. A generation number is used to interlock the wait queue in case
467 * it gets signalled while we are blocked waiting on the token.
469 * Note: alternatively we could dequeue our thread and then message the
470 * target cpu owning the wait queue. YYY implement as sysctl.
472 * Note: wait queue signals normally ping-pong the cpu as an optimization.
475 lwkt_block(lwkt_wait_t w, const char *wmesg, int *gen)
477 thread_t td = curthread;
479 lwkt_gettoken(&w->wa_token);
480 if (w->wa_gen == *gen) {
482 TAILQ_INSERT_TAIL(&w->wa_waitq, td, td_threadq);
485 td->td_wmesg = wmesg;
488 /* token might be lost, doesn't matter for gen update */
490 lwkt_reltoken(&w->wa_token);
494 * Signal a wait queue. We gain ownership of the wait queue in order to
495 * signal it. Once a thread is removed from the wait queue we have to
496 * deal with the cpu owning the thread.
498 * Note: alternatively we could message the target cpu owning the wait
499 * queue. YYY implement as sysctl.
502 lwkt_signal(lwkt_wait_t w)
507 lwkt_gettoken(&w->wa_token);
510 while ((td = TAILQ_FIRST(&w->wa_waitq)) != NULL && count) {
513 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
516 if (td->td_cpu == mycpu->gd_cpuid) {
520 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
521 initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
522 cpu_sendnormsg(&msg.mu_Msg);
524 panic("lwkt_signal: cpu mismatch");
526 lwkt_regettoken(&w->wa_token);
528 lwkt_reltoken(&w->wa_token);
532 * Aquire ownership of a token
534 * Aquire ownership of a token. The token may have spl and/or critical
535 * section side effects, depending on its purpose. These side effects
536 * guarentee that you will maintain ownership of the token as long as you
537 * do not block. If you block you may lose access to the token (but you
538 * must still release it even if you lose your access to it).
540 * Note that the spl and critical section characteristics of a token
541 * may not be changed once the token has been initialized.
544 lwkt_gettoken(lwkt_token_t tok)
547 * Prevent preemption so the token can't be taken away from us once
548 * we gain ownership of it. Use a synchronous request which might
549 * block. The request will be forwarded as necessary playing catchup
554 while (tok->t_cpu != mycpu->gd_cpuid) {
555 lwkt_cpu_msg_union msg;
556 initTokenReqMsg(&msg.mu_TokenReq);
561 * leave us in a critical section on return. This will be undone
567 * Release your ownership of a token. Releases must occur in reverse
568 * order to aquisitions, eventually so priorities can be unwound properly
569 * like SPLs. At the moment the actual implemention doesn't care.
571 * We can safely hand a token that we own to another cpu without notifying
572 * it, but once we do we can't get it back without requesting it (unless
573 * the other cpu hands it back to us before we check).
575 * We might have lost the token, so check that.
578 lwkt_reltoken(lwkt_token_t tok)
580 if (tok->t_cpu == mycpu->gd_cpuid) {
581 tok->t_cpu = tok->t_reqcpu;
587 * Reaquire a token that might have been lost. Returns 1 if we blocked
588 * while reaquiring the token (meaning that you might have lost other
589 * tokens you held when you made this call), return 0 if we did not block.
592 lwkt_regettoken(lwkt_token_t tok)
595 if (tok->t_cpu != mycpu->gd_cpuid) {
596 while (tok->t_cpu != mycpu->gd_cpuid) {
597 lwkt_cpu_msg_union msg;
598 initTokenReqMsg(&msg.mu_TokenReq);
608 * Create a kernel process/thread/whatever. It shares it's address space
609 * with proc0 - ie: kernel only.
611 * XXX should be renamed to lwkt_create()
614 lwkt_create(void (*func)(void *), void *arg,
615 struct thread **tdp, struct thread *template, int tdflags,
616 const char *fmt, ...)
621 td = *tdp = lwkt_alloc_thread(template);
622 cpu_set_thread_handler(td, kthread_exit, func, arg);
623 td->td_flags |= TDF_VERBOSE | tdflags;
626 * Set up arg0 for 'ps' etc
629 vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
633 * Schedule the thread to run
635 if ((td->td_flags & TDF_STOPREQ) == 0)
638 td->td_flags &= ~TDF_STOPREQ;
643 * Destroy an LWKT thread. Warning! This function is not called when
644 * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
645 * uses a different reaping mechanism.
650 thread_t td = curthread;
652 if (td->td_flags & TDF_VERBOSE)
653 printf("kthread %p %s has exited\n", td, td->td_comm);
655 lwkt_deschedule_self();
656 ++mycpu->gd_tdfreecount;
657 TAILQ_INSERT_TAIL(&mycpu->gd_tdfreeq, td, td_threadq);
662 * Create a kernel process/thread/whatever. It shares it's address space
663 * with proc0 - ie: kernel only. 5.x compatible.
666 kthread_create(void (*func)(void *), void *arg,
667 struct thread **tdp, const char *fmt, ...)
672 td = *tdp = lwkt_alloc_thread(NULL);
673 cpu_set_thread_handler(td, kthread_exit, func, arg);
674 td->td_flags |= TDF_VERBOSE;
677 * Set up arg0 for 'ps' etc
680 vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
684 * Schedule the thread to run
691 * Destroy an LWKT thread. Warning! This function is not called when
692 * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
693 * uses a different reaping mechanism.
695 * XXX duplicates lwkt_exit()