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.9 2003/06/29 03:28:44 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)
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 ntd->td_flags &= ~TDF_PREEMPTED;
220 } else if ((ntd = TAILQ_FIRST(&mycpu->gd_tdrunq)) != NULL) {
221 TAILQ_REMOVE(&mycpu->gd_tdrunq, ntd, td_threadq);
222 TAILQ_INSERT_TAIL(&mycpu->gd_tdrunq, ntd, td_threadq);
224 ntd = mycpu->gd_idletd;
232 * Yield our thread while higher priority threads are pending. This is
233 * typically called when we leave a critical section but it can be safely
234 * called while we are in a critical section.
236 * This function will not generally yield to equal priority threads but it
237 * can occur as a side effect. Note that lwkt_switch() is called from
238 * inside the critical section to pervent its own crit_exit() from reentering
239 * lwkt_yield_quick().
241 * gd_reqpri indicates that *something* changed, e.g. an interrupt or softint
242 * came along but was blocked and made pending.
244 * (self contained on a per cpu basis)
247 lwkt_yield_quick(void)
249 thread_t td = curthread;
251 if ((td->td_pri & TDPRI_MASK) < mycpu->gd_reqpri) {
252 mycpu->gd_reqpri = 0;
257 * YYY enabling will cause wakeup() to task-switch, which really
258 * confused the old 4.x code. This is a good way to simulate
259 * preemption and MP without actually doing preemption or MP, because a
260 * lot of code assumes that wakeup() does not block.
262 if (untimely_switch && mycpu->gd_intr_nesting_level == 0) {
265 * YYY temporary hacks until we disassociate the userland scheduler
266 * from the LWKT scheduler.
268 if (td->td_flags & TDF_RUNQ) {
269 lwkt_switch(); /* will not reenter yield function */
271 lwkt_schedule_self(); /* make sure we are scheduled */
272 lwkt_switch(); /* will not reenter yield function */
273 lwkt_deschedule_self(); /* make sure we are descheduled */
280 * This implements a normal yield which, unlike _quick, will yield to equal
281 * priority threads as well. Note that gd_reqpri tests will be handled by
282 * the crit_exit() call in lwkt_switch().
284 * (self contained on a per cpu basis)
289 lwkt_schedule_self();
294 * Schedule a thread to run. As the current thread we can always safely
295 * schedule ourselves, and a shortcut procedure is provided for that
298 * (non-blocking, self contained on a per cpu basis)
301 lwkt_schedule_self(void)
303 thread_t td = curthread;
306 KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
312 * Generic schedule. Possibly schedule threads belonging to other cpus and
313 * deal with threads that might be blocked on a wait queue.
315 * This function will queue requests asynchronously when possible, but may
316 * block if no request structures are available. Upon return the caller
317 * should note that the scheduling request may not yet have been processed
320 * YYY this is one of the best places to implement any load balancing code.
321 * Load balancing can be accomplished by requesting other sorts of actions
322 * for the thread in question.
325 lwkt_schedule(thread_t td)
328 if (td == curthread) {
334 * If the thread is on a wait list we have to send our scheduling
335 * request to the owner of the wait structure. Otherwise we send
336 * the scheduling request to the cpu owning the thread. Races
337 * are ok, the target will forward the message as necessary (the
338 * message may chase the thread around before it finally gets
341 * (remember, wait structures use stable storage)
343 if ((w = td->td_wait) != NULL) {
344 if (lwkt_havetoken(&w->wa_token)) {
345 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
348 if (td->td_cpu == mycpu->gd_cpuid) {
351 panic("lwkt_schedule: cpu mismatch1");
353 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
354 initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
355 cpu_sendnormsg(&msg.mu_Msg);
359 panic("lwkt_schedule: cpu mismatch2");
361 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
362 initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
363 cpu_sendnormsg(&msg.mu_Msg);
368 * If the wait structure is NULL and we own the thread, there
369 * is no race (since we are in a critical section). If we
370 * do not own the thread there might be a race but the
371 * target cpu will deal with it.
373 if (td->td_cpu == mycpu->gd_cpuid) {
376 panic("lwkt_schedule: cpu mismatch3");
378 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
379 initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
380 cpu_sendnormsg(&msg.mu_Msg);
389 * Deschedule a thread.
391 * (non-blocking, self contained on a per cpu basis)
394 lwkt_deschedule_self(void)
396 thread_t td = curthread;
399 KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
405 * Generic deschedule. Descheduling threads other then your own should be
406 * done only in carefully controlled circumstances. Descheduling is
409 * This function may block if the cpu has run out of messages.
412 lwkt_deschedule(thread_t td)
415 if (td == curthread) {
418 if (td->td_cpu == mycpu->gd_cpuid) {
421 panic("lwkt_deschedule: cpu mismatch");
423 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
424 initDescheduleReqMsg_Thread(&msg.mu_DeschedReq, td);
425 cpu_sendnormsg(&msg.mu_Msg);
433 * This function deschedules the current thread and blocks on the specified
434 * wait queue. We obtain ownership of the wait queue in order to block
435 * on it. A generation number is used to interlock the wait queue in case
436 * it gets signalled while we are blocked waiting on the token.
438 * Note: alternatively we could dequeue our thread and then message the
439 * target cpu owning the wait queue. YYY implement as sysctl.
441 * Note: wait queue signals normally ping-pong the cpu as an optimization.
444 lwkt_block(lwkt_wait_t w, const char *wmesg, int *gen)
446 thread_t td = curthread;
448 lwkt_gettoken(&w->wa_token);
449 if (w->wa_gen == *gen) {
451 TAILQ_INSERT_TAIL(&w->wa_waitq, td, td_threadq);
454 td->td_wmesg = wmesg;
457 /* token might be lost, doesn't matter for gen update */
459 lwkt_reltoken(&w->wa_token);
463 * Signal a wait queue. We gain ownership of the wait queue in order to
464 * signal it. Once a thread is removed from the wait queue we have to
465 * deal with the cpu owning the thread.
467 * Note: alternatively we could message the target cpu owning the wait
468 * queue. YYY implement as sysctl.
471 lwkt_signal(lwkt_wait_t w)
476 lwkt_gettoken(&w->wa_token);
479 while ((td = TAILQ_FIRST(&w->wa_waitq)) != NULL && count) {
482 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
485 if (td->td_cpu == mycpu->gd_cpuid) {
489 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
490 initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
491 cpu_sendnormsg(&msg.mu_Msg);
493 panic("lwkt_signal: cpu mismatch");
495 lwkt_regettoken(&w->wa_token);
497 lwkt_reltoken(&w->wa_token);
501 * Aquire ownership of a token
503 * Aquire ownership of a token. The token may have spl and/or critical
504 * section side effects, depending on its purpose. These side effects
505 * guarentee that you will maintain ownership of the token as long as you
506 * do not block. If you block you may lose access to the token (but you
507 * must still release it even if you lose your access to it).
509 * Note that the spl and critical section characteristics of a token
510 * may not be changed once the token has been initialized.
513 lwkt_gettoken(lwkt_token_t tok)
516 * Prevent preemption so the token can't be taken away from us once
517 * we gain ownership of it. Use a synchronous request which might
518 * block. The request will be forwarded as necessary playing catchup
523 while (tok->t_cpu != mycpu->gd_cpuid) {
524 lwkt_cpu_msg_union msg;
525 initTokenReqMsg(&msg.mu_TokenReq);
530 * leave us in a critical section on return. This will be undone
536 * Release your ownership of a token. Releases must occur in reverse
537 * order to aquisitions, eventually so priorities can be unwound properly
538 * like SPLs. At the moment the actual implemention doesn't care.
540 * We can safely hand a token that we own to another cpu without notifying
541 * it, but once we do we can't get it back without requesting it (unless
542 * the other cpu hands it back to us before we check).
544 * We might have lost the token, so check that.
547 lwkt_reltoken(lwkt_token_t tok)
549 if (tok->t_cpu == mycpu->gd_cpuid) {
550 tok->t_cpu = tok->t_reqcpu;
556 * Reaquire a token that might have been lost. Returns 1 if we blocked
557 * while reaquiring the token (meaning that you might have lost other
558 * tokens you held when you made this call), return 0 if we did not block.
561 lwkt_regettoken(lwkt_token_t tok)
564 if (tok->t_cpu != mycpu->gd_cpuid) {
565 while (tok->t_cpu != mycpu->gd_cpuid) {
566 lwkt_cpu_msg_union msg;
567 initTokenReqMsg(&msg.mu_TokenReq);
577 * Create a kernel process/thread/whatever. It shares it's address space
578 * with proc0 - ie: kernel only.
580 * XXX should be renamed to lwkt_create()
583 lwkt_create(void (*func)(void *), void *arg,
584 struct thread **tdp, struct thread *template, int tdflags,
585 const char *fmt, ...)
590 td = *tdp = lwkt_alloc_thread(template);
591 cpu_set_thread_handler(td, kthread_exit, func, arg);
592 td->td_flags |= TDF_VERBOSE | tdflags;
595 * Set up arg0 for 'ps' etc
598 vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
602 * Schedule the thread to run
604 if ((td->td_flags & TDF_STOPREQ) == 0)
607 td->td_flags &= ~TDF_STOPREQ;
612 * Destroy an LWKT thread. Warning! This function is not called when
613 * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
614 * uses a different reaping mechanism.
619 thread_t td = curthread;
621 if (td->td_flags & TDF_VERBOSE)
622 printf("kthread %p %s has exited\n", td, td->td_comm);
624 lwkt_deschedule_self();
625 ++mycpu->gd_tdfreecount;
626 TAILQ_INSERT_TAIL(&mycpu->gd_tdfreeq, td, td_threadq);
631 * Create a kernel process/thread/whatever. It shares it's address space
632 * with proc0 - ie: kernel only. 5.x compatible.
635 kthread_create(void (*func)(void *), void *arg,
636 struct thread **tdp, const char *fmt, ...)
641 td = *tdp = lwkt_alloc_thread(NULL);
642 cpu_set_thread_handler(td, kthread_exit, func, arg);
643 td->td_flags |= TDF_VERBOSE;
646 * Set up arg0 for 'ps' etc
649 vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
653 * Schedule the thread to run
660 * Destroy an LWKT thread. Warning! This function is not called when
661 * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
662 * uses a different reaping mechanism.
664 * XXX duplicates lwkt_exit()