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.11 2003/06/29 07:37:06 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(_lwkt, OID_AUTO, untimely_switch, CTLFLAG_RW, &untimely_switch, 0, "");
59 static quad_t switch_count = 0;
60 SYSCTL_QUAD(_lwkt, OID_AUTO, switch_count, CTLFLAG_RW, &switch_count, 0, "");
61 static quad_t preempt_hit = 0;
62 SYSCTL_QUAD(_lwkt, OID_AUTO, preempt_hit, CTLFLAG_RW, &preempt_hit, 0, "");
63 static quad_t preempt_miss = 0;
64 SYSCTL_QUAD(_lwkt, OID_AUTO, preempt_miss, CTLFLAG_RW, &preempt_miss, 0, "");
67 * These helper procedures handle the runq, they can only be called from
68 * within a critical section.
72 _lwkt_dequeue(thread_t td)
74 if (td->td_flags & TDF_RUNQ) {
75 int nq = td->td_pri & TDPRI_MASK;
76 struct globaldata *gd = mycpu;
78 td->td_flags &= ~TDF_RUNQ;
79 TAILQ_REMOVE(&gd->gd_tdrunq[nq], td, td_threadq);
80 /* runqmask is passively cleaned up by the switcher */
86 _lwkt_enqueue(thread_t td)
88 if ((td->td_flags & TDF_RUNQ) == 0) {
89 int nq = td->td_pri & TDPRI_MASK;
90 struct globaldata *gd = mycpu;
92 td->td_flags |= TDF_RUNQ;
93 TAILQ_INSERT_TAIL(&gd->gd_tdrunq[nq], td, td_threadq);
94 gd->gd_runqmask |= 1 << nq;
99 * LWKTs operate on a per-cpu basis
101 * YYY implement strict priorities & round-robin at the same priority
104 lwkt_gdinit(struct globaldata *gd)
108 for (i = 0; i < sizeof(gd->gd_tdrunq)/sizeof(gd->gd_tdrunq[0]); ++i)
109 TAILQ_INIT(&gd->gd_tdrunq[i]);
114 * Initialize a thread wait structure prior to first use.
116 * NOTE! called from low level boot code, we cannot do anything fancy!
119 lwkt_init_wait(lwkt_wait_t w)
121 TAILQ_INIT(&w->wa_waitq);
125 * Create a new thread. The thread must be associated with a process context
126 * or LWKT start address before it can be scheduled.
128 * If you intend to create a thread without a process context this function
129 * does everything except load the startup and switcher function.
132 lwkt_alloc_thread(struct thread *td)
139 if (mycpu->gd_tdfreecount > 0) {
140 --mycpu->gd_tdfreecount;
141 td = TAILQ_FIRST(&mycpu->gd_tdfreeq);
142 KASSERT(td != NULL && (td->td_flags & TDF_EXITED),
143 ("lwkt_alloc_thread: unexpected NULL or corrupted td"));
144 TAILQ_REMOVE(&mycpu->gd_tdfreeq, td, td_threadq);
146 stack = td->td_kstack;
147 flags = td->td_flags & (TDF_ALLOCATED_STACK|TDF_ALLOCATED_THREAD);
150 td = zalloc(thread_zone);
151 td->td_kstack = NULL;
152 flags |= TDF_ALLOCATED_THREAD;
155 if ((stack = td->td_kstack) == NULL) {
156 stack = (void *)kmem_alloc(kernel_map, UPAGES * PAGE_SIZE);
157 flags |= TDF_ALLOCATED_STACK;
159 lwkt_init_thread(td, stack, flags);
164 * Initialize a preexisting thread structure. This function is used by
165 * lwkt_alloc_thread() and also used to initialize the per-cpu idlethread.
167 * NOTE! called from low level boot code, we cannot do anything fancy!
170 lwkt_init_thread(thread_t td, void *stack, int flags)
172 bzero(td, sizeof(struct thread));
173 td->td_kstack = stack;
174 td->td_flags |= flags;
175 pmap_init_thread(td);
179 lwkt_free_thread(struct thread *td)
181 KASSERT(td->td_flags & TDF_EXITED,
182 ("lwkt_free_thread: did not exit! %p", td));
185 if (mycpu->gd_tdfreecount < CACHE_NTHREADS &&
186 (td->td_flags & TDF_ALLOCATED_THREAD)
188 ++mycpu->gd_tdfreecount;
189 TAILQ_INSERT_HEAD(&mycpu->gd_tdfreeq, td, td_threadq);
193 if (td->td_kstack && (td->td_flags & TDF_ALLOCATED_STACK)) {
194 kmem_free(kernel_map,
195 (vm_offset_t)td->td_kstack, UPAGES * PAGE_SIZE);
196 td->td_kstack = NULL;
198 if (td->td_flags & TDF_ALLOCATED_THREAD)
199 zfree(thread_zone, td);
205 * Switch to the next runnable lwkt. If no LWKTs are runnable then
206 * switch to the idlethread. Switching must occur within a critical
207 * section to avoid races with the scheduling queue.
209 * We always have full control over our cpu's run queue. Other cpus
210 * that wish to manipulate our queue must use the cpu_*msg() calls to
211 * talk to our cpu, so a critical section is all that is needed and
212 * the result is very, very fast thread switching.
214 * We always 'own' our own thread and the threads on our run queue,l
215 * due to TDF_RUNNING or TDF_RUNQ being set. We can safely clear
216 * TDF_RUNNING while in a critical section.
218 * The td_switch() function must be called while in the critical section.
219 * This function saves as much state as is appropriate for the type of
222 * (self contained on a per cpu basis)
227 struct globaldata *gd;
228 thread_t td = curthread;
231 if (mycpu->gd_intr_nesting_level && td->td_preempted == NULL)
232 panic("lwkt_switch: cannot switch from within an interrupt\n");
236 if ((ntd = td->td_preempted) != NULL) {
238 * We had preempted another thread on this cpu, resume the preempted
241 td->td_preempted = NULL;
242 td->td_pri -= TDPRI_CRIT;
243 ntd->td_flags &= ~TDF_PREEMPTED;
246 * Priority queue / round-robin at each priority. Note that user
247 * processes run at a fixed, low priority and the user process
248 * scheduler deals with interactions between user processes
249 * by scheduling and descheduling them from the LWKT queue as
255 if (gd->gd_runqmask) {
256 int nq = bsrl(gd->gd_runqmask);
257 if ((ntd = TAILQ_FIRST(&gd->gd_tdrunq[nq])) == NULL) {
258 gd->gd_runqmask &= ~(1 << nq);
261 TAILQ_REMOVE(&gd->gd_tdrunq[nq], ntd, td_threadq);
262 TAILQ_INSERT_TAIL(&gd->gd_tdrunq[nq], ntd, td_threadq);
273 * The target thread preempts the current thread. The target thread
274 * structure must be stable and preempt-safe (e.g. an interrupt thread).
275 * When the target thread blocks the current thread will be resumed.
277 * XXX the target runs in a critical section so it does not open the original
278 * thread up to additional interrupts that the original thread believes it
281 * Normal kernel threads should not preempt other normal kernel threads
282 * as it breaks the assumptions kernel threads are allowed to make. Note
283 * that preemption does not mess around with the current thread's RUNQ
286 * This call is typically made from an interrupt handler like sched_ithd()
287 * which will only run if the current thread is not in a critical section,
288 * so we optimize the priority check a bit.
291 lwkt_preempt(struct thread *ntd, int id)
293 struct thread *td = curthread;
295 crit_enter(); /* YYY token */
296 if (ntd->td_preempted == NULL &&
297 (ntd->td_pri & TDPRI_MASK) > (td->td_pri & TDPRI_MASK)
300 ntd->td_preempted = td;
301 td->td_flags |= TDF_PREEMPTED;
302 ntd->td_pri += TDPRI_CRIT;
303 while (td->td_flags & TDF_PREEMPTED)
312 * Yield our thread while higher priority threads are pending. This is
313 * typically called when we leave a critical section but it can be safely
314 * called while we are in a critical section.
316 * This function will not generally yield to equal priority threads but it
317 * can occur as a side effect. Note that lwkt_switch() is called from
318 * inside the critical section to pervent its own crit_exit() from reentering
319 * lwkt_yield_quick().
321 * gd_reqpri indicates that *something* changed, e.g. an interrupt or softint
322 * came along but was blocked and made pending.
324 * (self contained on a per cpu basis)
327 lwkt_yield_quick(void)
329 thread_t td = curthread;
331 if ((td->td_pri & TDPRI_MASK) < mycpu->gd_reqpri) {
332 mycpu->gd_reqpri = 0;
337 * YYY enabling will cause wakeup() to task-switch, which really
338 * confused the old 4.x code. This is a good way to simulate
339 * preemption and MP without actually doing preemption or MP, because a
340 * lot of code assumes that wakeup() does not block.
342 if (untimely_switch && mycpu->gd_intr_nesting_level == 0) {
345 * YYY temporary hacks until we disassociate the userland scheduler
346 * from the LWKT scheduler.
348 if (td->td_flags & TDF_RUNQ) {
349 lwkt_switch(); /* will not reenter yield function */
351 lwkt_schedule_self(); /* make sure we are scheduled */
352 lwkt_switch(); /* will not reenter yield function */
353 lwkt_deschedule_self(); /* make sure we are descheduled */
360 * This implements a normal yield which, unlike _quick, will yield to equal
361 * priority threads as well. Note that gd_reqpri tests will be handled by
362 * the crit_exit() call in lwkt_switch().
364 * (self contained on a per cpu basis)
369 lwkt_schedule_self();
374 * Schedule a thread to run. As the current thread we can always safely
375 * schedule ourselves, and a shortcut procedure is provided for that
378 * (non-blocking, self contained on a per cpu basis)
381 lwkt_schedule_self(void)
383 thread_t td = curthread;
386 KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
392 * Generic schedule. Possibly schedule threads belonging to other cpus and
393 * deal with threads that might be blocked on a wait queue.
395 * This function will queue requests asynchronously when possible, but may
396 * block if no request structures are available. Upon return the caller
397 * should note that the scheduling request may not yet have been processed
400 * YYY this is one of the best places to implement any load balancing code.
401 * Load balancing can be accomplished by requesting other sorts of actions
402 * for the thread in question.
405 lwkt_schedule(thread_t td)
408 if (td == curthread) {
414 * If the thread is on a wait list we have to send our scheduling
415 * request to the owner of the wait structure. Otherwise we send
416 * the scheduling request to the cpu owning the thread. Races
417 * are ok, the target will forward the message as necessary (the
418 * message may chase the thread around before it finally gets
421 * (remember, wait structures use stable storage)
423 if ((w = td->td_wait) != NULL) {
424 if (lwkt_havetoken(&w->wa_token)) {
425 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
428 if (td->td_cpu == mycpu->gd_cpuid) {
431 panic("lwkt_schedule: cpu mismatch1");
433 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
434 initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
435 cpu_sendnormsg(&msg.mu_Msg);
439 panic("lwkt_schedule: cpu mismatch2");
441 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
442 initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
443 cpu_sendnormsg(&msg.mu_Msg);
448 * If the wait structure is NULL and we own the thread, there
449 * is no race (since we are in a critical section). If we
450 * do not own the thread there might be a race but the
451 * target cpu will deal with it.
453 if (td->td_cpu == mycpu->gd_cpuid) {
456 panic("lwkt_schedule: cpu mismatch3");
458 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
459 initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
460 cpu_sendnormsg(&msg.mu_Msg);
469 * Deschedule a thread.
471 * (non-blocking, self contained on a per cpu basis)
474 lwkt_deschedule_self(void)
476 thread_t td = curthread;
479 KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
485 * Generic deschedule. Descheduling threads other then your own should be
486 * done only in carefully controlled circumstances. Descheduling is
489 * This function may block if the cpu has run out of messages.
492 lwkt_deschedule(thread_t td)
495 if (td == curthread) {
498 if (td->td_cpu == mycpu->gd_cpuid) {
501 panic("lwkt_deschedule: cpu mismatch");
503 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
504 initDescheduleReqMsg_Thread(&msg.mu_DeschedReq, td);
505 cpu_sendnormsg(&msg.mu_Msg);
513 * Set the target thread's priority. This routine does not automatically
514 * switch to a higher priority thread, LWKT threads are not designed for
515 * continuous priority changes. Yield if you want to switch.
517 * We have to retain the critical section count which uses the high bits
518 * of the td_pri field.
521 lwkt_setpri(thread_t td, int pri)
523 KKASSERT(pri >= 0 && pri <= TDPRI_MAX);
525 if (td->td_flags & TDF_RUNQ) {
527 td->td_pri = (td->td_pri & ~TDPRI_MASK) + pri;
530 td->td_pri = (td->td_pri & ~TDPRI_MASK) + pri;
536 lwkt_preempted_proc(void)
538 struct thread *td = curthread;
539 while (td->td_preempted)
540 td = td->td_preempted;
546 * This function deschedules the current thread and blocks on the specified
547 * wait queue. We obtain ownership of the wait queue in order to block
548 * on it. A generation number is used to interlock the wait queue in case
549 * it gets signalled while we are blocked waiting on the token.
551 * Note: alternatively we could dequeue our thread and then message the
552 * target cpu owning the wait queue. YYY implement as sysctl.
554 * Note: wait queue signals normally ping-pong the cpu as an optimization.
557 lwkt_block(lwkt_wait_t w, const char *wmesg, int *gen)
559 thread_t td = curthread;
561 lwkt_gettoken(&w->wa_token);
562 if (w->wa_gen == *gen) {
564 TAILQ_INSERT_TAIL(&w->wa_waitq, td, td_threadq);
567 td->td_wmesg = wmesg;
570 /* token might be lost, doesn't matter for gen update */
572 lwkt_reltoken(&w->wa_token);
576 * Signal a wait queue. We gain ownership of the wait queue in order to
577 * signal it. Once a thread is removed from the wait queue we have to
578 * deal with the cpu owning the thread.
580 * Note: alternatively we could message the target cpu owning the wait
581 * queue. YYY implement as sysctl.
584 lwkt_signal(lwkt_wait_t w)
589 lwkt_gettoken(&w->wa_token);
592 while ((td = TAILQ_FIRST(&w->wa_waitq)) != NULL && count) {
595 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
598 if (td->td_cpu == mycpu->gd_cpuid) {
602 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
603 initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
604 cpu_sendnormsg(&msg.mu_Msg);
606 panic("lwkt_signal: cpu mismatch");
608 lwkt_regettoken(&w->wa_token);
610 lwkt_reltoken(&w->wa_token);
614 * Aquire ownership of a token
616 * Aquire ownership of a token. The token may have spl and/or critical
617 * section side effects, depending on its purpose. These side effects
618 * guarentee that you will maintain ownership of the token as long as you
619 * do not block. If you block you may lose access to the token (but you
620 * must still release it even if you lose your access to it).
622 * Note that the spl and critical section characteristics of a token
623 * may not be changed once the token has been initialized.
626 lwkt_gettoken(lwkt_token_t tok)
629 * Prevent preemption so the token can't be taken away from us once
630 * we gain ownership of it. Use a synchronous request which might
631 * block. The request will be forwarded as necessary playing catchup
636 while (tok->t_cpu != mycpu->gd_cpuid) {
637 lwkt_cpu_msg_union msg;
638 initTokenReqMsg(&msg.mu_TokenReq);
643 * leave us in a critical section on return. This will be undone
649 * Release your ownership of a token. Releases must occur in reverse
650 * order to aquisitions, eventually so priorities can be unwound properly
651 * like SPLs. At the moment the actual implemention doesn't care.
653 * We can safely hand a token that we own to another cpu without notifying
654 * it, but once we do we can't get it back without requesting it (unless
655 * the other cpu hands it back to us before we check).
657 * We might have lost the token, so check that.
660 lwkt_reltoken(lwkt_token_t tok)
662 if (tok->t_cpu == mycpu->gd_cpuid) {
663 tok->t_cpu = tok->t_reqcpu;
669 * Reaquire a token that might have been lost. Returns 1 if we blocked
670 * while reaquiring the token (meaning that you might have lost other
671 * tokens you held when you made this call), return 0 if we did not block.
674 lwkt_regettoken(lwkt_token_t tok)
677 if (tok->t_cpu != mycpu->gd_cpuid) {
678 while (tok->t_cpu != mycpu->gd_cpuid) {
679 lwkt_cpu_msg_union msg;
680 initTokenReqMsg(&msg.mu_TokenReq);
690 * Create a kernel process/thread/whatever. It shares it's address space
691 * with proc0 - ie: kernel only.
693 * XXX should be renamed to lwkt_create()
696 lwkt_create(void (*func)(void *), void *arg,
697 struct thread **tdp, struct thread *template, int tdflags,
698 const char *fmt, ...)
703 td = *tdp = lwkt_alloc_thread(template);
704 cpu_set_thread_handler(td, kthread_exit, func, arg);
705 td->td_flags |= TDF_VERBOSE | tdflags;
708 * Set up arg0 for 'ps' etc
711 vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
715 * Schedule the thread to run
717 if ((td->td_flags & TDF_STOPREQ) == 0)
720 td->td_flags &= ~TDF_STOPREQ;
725 * Destroy an LWKT thread. Warning! This function is not called when
726 * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
727 * uses a different reaping mechanism.
732 thread_t td = curthread;
734 if (td->td_flags & TDF_VERBOSE)
735 printf("kthread %p %s has exited\n", td, td->td_comm);
737 lwkt_deschedule_self();
738 ++mycpu->gd_tdfreecount;
739 TAILQ_INSERT_TAIL(&mycpu->gd_tdfreeq, td, td_threadq);
744 * Create a kernel process/thread/whatever. It shares it's address space
745 * with proc0 - ie: kernel only. 5.x compatible.
748 kthread_create(void (*func)(void *), void *arg,
749 struct thread **tdp, const char *fmt, ...)
754 td = *tdp = lwkt_alloc_thread(NULL);
755 cpu_set_thread_handler(td, kthread_exit, func, arg);
756 td->td_flags |= TDF_VERBOSE;
759 * Set up arg0 for 'ps' etc
762 vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
766 * Schedule the thread to run
773 * Destroy an LWKT thread. Warning! This function is not called when
774 * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
775 * uses a different reaping mechanism.
777 * XXX duplicates lwkt_exit()