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.4 2003/06/22 04:30:42 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>
41 #include <sys/sysctl.h>
42 #include <machine/cpu.h>
45 #include <vm/vm_param.h>
46 #include <vm/vm_kern.h>
47 #include <vm/vm_object.h>
48 #include <vm/vm_page.h>
49 #include <vm/vm_map.h>
50 #include <vm/vm_pager.h>
51 #include <vm/vm_extern.h>
52 #include <vm/vm_zone.h>
54 static int untimely_switch = 0;
55 SYSCTL_INT(_debug, OID_AUTO, untimely_switch, CTLFLAG_RW, &untimely_switch, 0, "");
60 _lwkt_dequeue(thread_t td)
62 if (td->td_flags & TDF_RUNQ) {
63 td->td_flags &= ~TDF_RUNQ;
64 TAILQ_REMOVE(&mycpu->gd_tdrunq, td, td_threadq);
70 _lwkt_enqueue(thread_t td)
72 if ((td->td_flags & TDF_RUNQ) == 0) {
73 td->td_flags |= TDF_RUNQ;
74 TAILQ_INSERT_TAIL(&mycpu->gd_tdrunq, td, td_threadq);
79 * LWKTs operate on a per-cpu basis
81 * YYY implement strict priorities & round-robin at the same priority
84 lwkt_gdinit(struct globaldata *gd)
86 TAILQ_INIT(&gd->gd_tdrunq);
90 * Initialize a thread wait structure prior to first use.
92 * NOTE! called from low level boot code, we cannot do anything fancy!
95 lwkt_init_wait(lwkt_wait_t w)
97 TAILQ_INIT(&w->wa_waitq);
101 * Create a new thread. The thread must be associated with a process context
102 * or LWKT start address before it can be scheduled.
105 lwkt_alloc_thread(void)
111 if (mycpu->gd_tdfreecount > 0) {
112 --mycpu->gd_tdfreecount;
113 td = TAILQ_FIRST(&mycpu->gd_tdfreeq);
114 KASSERT(td != NULL, ("unexpected null cache td"));
115 TAILQ_REMOVE(&mycpu->gd_tdfreeq, td, td_threadq);
117 stack = td->td_kstack;
120 td = zalloc(thread_zone);
121 stack = (void *)kmem_alloc(kernel_map, UPAGES * PAGE_SIZE);
123 lwkt_init_thread(td, stack);
128 * Initialize a preexisting thread structure. This function is used by
129 * lwkt_alloc_thread() and also used to initialize the per-cpu idlethread.
131 * NOTE! called from low level boot code, we cannot do anything fancy!
134 lwkt_init_thread(thread_t td, void *stack)
136 bzero(td, sizeof(struct thread));
137 lwkt_rwlock_init(&td->td_rwlock);
138 td->td_kstack = stack;
139 pmap_init_thread(td);
143 * Switch to the next runnable lwkt. If no LWKTs are runnable then
144 * switch to the idlethread. Switching must occur within a critical
145 * section to avoid races with the scheduling queue.
147 * We always have full control over our cpu's run queue. Other cpus
148 * that wish to manipulate our queue must use the cpu_*msg() calls to
149 * talk to our cpu, so a critical section is all that is needed and
150 * the result is very, very fast thread switching.
152 * We always 'own' our own thread and the threads on our run queue,l
153 * due to TDF_RUNNING or TDF_RUNQ being set. We can safely clear
154 * TDF_RUNNING while in a critical section.
156 * The td_switch() function must be called while in the critical section.
157 * This function saves as much state as is appropriate for the type of
160 * (self contained on a per cpu basis)
165 thread_t td = curthread;
169 if ((ntd = TAILQ_FIRST(&mycpu->gd_tdrunq)) != NULL) {
170 TAILQ_REMOVE(&mycpu->gd_tdrunq, ntd, td_threadq);
171 TAILQ_INSERT_TAIL(&mycpu->gd_tdrunq, ntd, td_threadq);
173 ntd = &mycpu->gd_idlethread;
176 td->td_flags &= ~TDF_RUNNING;
177 ntd->td_flags |= TDF_RUNNING;
184 * Yield our thread while higher priority threads are pending. This is
185 * typically called when we leave a critical section but it can be safely
186 * called while we are in a critical section.
188 * This function will not generally yield to equal priority threads but it
189 * can occur as a side effect. Note that lwkt_switch() is called from
190 * inside the critical section to pervent its own crit_exit() from reentering
191 * lwkt_yield_quick().
193 * (self contained on a per cpu basis)
196 lwkt_yield_quick(void)
198 thread_t td = curthread;
199 while ((td->td_pri & TDPRI_MASK) < mycpu->gd_reqpri) {
201 cpu_schedule_reqs(); /* resets gd_reqpri */
207 * YYY enabling will cause wakeup() to task-switch, which really
208 * confused the old 4.x code. This is a good way to simulate
209 * preemption and MP without actually doing preemption or MP, because a
210 * lot of code assumes that wakeup() does not block.
212 if (untimely_switch && intr_nesting_level == 0) {
215 * YYY temporary hacks until we disassociate the userland scheduler
216 * from the LWKT scheduler.
218 if (td->td_flags & TDF_RUNQ) {
219 lwkt_switch(); /* will not reenter yield function */
221 lwkt_schedule_self(); /* make sure we are scheduled */
222 lwkt_switch(); /* will not reenter yield function */
223 lwkt_deschedule_self(); /* make sure we are descheduled */
230 * This implements a normal yield which, unlike _quick, will yield to equal
231 * priority threads as well. Note that gd_reqpri tests will be handled by
232 * the crit_exit() call in lwkt_switch().
234 * (self contained on a per cpu basis)
239 lwkt_schedule_self();
244 * Schedule a thread to run. As the current thread we can always safely
245 * schedule ourselves, and a shortcut procedure is provided for that
248 * (non-blocking, self contained on a per cpu basis)
251 lwkt_schedule_self(void)
253 thread_t td = curthread;
256 KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
257 KASSERT(td->td_flags & TDF_RUNNING, ("lwkt_schedule_self(): TDF_RUNNING not set!"));
263 * Generic schedule. Possibly schedule threads belonging to other cpus and
264 * deal with threads that might be blocked on a wait queue.
266 * This function will queue requests asynchronously when possible, but may
267 * block if no request structures are available. Upon return the caller
268 * should note that the scheduling request may not yet have been processed
271 * YYY this is one of the best places to implement any load balancing code.
272 * Load balancing can be accomplished by requesting other sorts of actions
273 * for the thread in question.
276 lwkt_schedule(thread_t td)
279 if (td == curthread) {
285 * If the thread is on a wait list we have to send our scheduling
286 * request to the owner of the wait structure. Otherwise we send
287 * the scheduling request to the cpu owning the thread. Races
288 * are ok, the target will forward the message as necessary (the
289 * message may chase the thread around before it finally gets
292 * (remember, wait structures use stable storage)
294 if ((w = td->td_wait) != NULL) {
295 if (lwkt_havetoken(&w->wa_token)) {
296 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
299 if (td->td_cpu == mycpu->gd_cpu) {
302 panic("lwkt_schedule: cpu mismatch1");
304 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
305 initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
306 cpu_sendnormsg(&msg.mu_Msg);
310 panic("lwkt_schedule: cpu mismatch2");
312 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
313 initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
314 cpu_sendnormsg(&msg.mu_Msg);
319 * If the wait structure is NULL and we own the thread, there
320 * is no race (since we are in a critical section). If we
321 * do not own the thread there might be a race but the
322 * target cpu will deal with it.
324 if (td->td_cpu == mycpu->gd_cpu) {
327 panic("lwkt_schedule: cpu mismatch3");
329 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
330 initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
331 cpu_sendnormsg(&msg.mu_Msg);
340 * Deschedule a thread.
342 * (non-blocking, self contained on a per cpu basis)
345 lwkt_deschedule_self(void)
347 thread_t td = curthread;
350 KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
351 KASSERT(td->td_flags & TDF_RUNNING, ("lwkt_schedule_self(): TDF_RUNNING not set!"));
357 * Generic deschedule. Descheduling threads other then your own should be
358 * done only in carefully controlled circumstances. Descheduling is
361 * This function may block if the cpu has run out of messages.
364 lwkt_deschedule(thread_t td)
367 if (td == curthread) {
370 if (td->td_cpu == mycpu->gd_cpu) {
373 panic("lwkt_deschedule: cpu mismatch");
375 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
376 initDescheduleReqMsg_Thread(&msg.mu_DeschedReq, td);
377 cpu_sendnormsg(&msg.mu_Msg);
385 * This function deschedules the current thread and blocks on the specified
386 * wait queue. We obtain ownership of the wait queue in order to block
387 * on it. A generation number is used to interlock the wait queue in case
388 * it gets signalled while we are blocked waiting on the token.
390 * Note: alternatively we could dequeue our thread and then message the
391 * target cpu owning the wait queue. YYY implement as sysctl.
393 * Note: wait queue signals normally ping-pong the cpu as an optimization.
396 lwkt_block(lwkt_wait_t w, const char *wmesg, int *gen)
398 thread_t td = curthread;
400 lwkt_gettoken(&w->wa_token);
401 if (w->wa_gen == *gen) {
403 TAILQ_INSERT_TAIL(&w->wa_waitq, td, td_threadq);
406 td->td_wmesg = wmesg;
409 /* token might be lost, doesn't matter for gen update */
411 lwkt_reltoken(&w->wa_token);
415 * Signal a wait queue. We gain ownership of the wait queue in order to
416 * signal it. Once a thread is removed from the wait queue we have to
417 * deal with the cpu owning the thread.
419 * Note: alternatively we could message the target cpu owning the wait
420 * queue. YYY implement as sysctl.
423 lwkt_signal(lwkt_wait_t w)
428 lwkt_gettoken(&w->wa_token);
431 while ((td = TAILQ_FIRST(&w->wa_waitq)) != NULL && count) {
434 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
437 if (td->td_cpu == mycpu->gd_cpu) {
441 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
442 initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
443 cpu_sendnormsg(&msg.mu_Msg);
445 panic("lwkt_signal: cpu mismatch");
447 lwkt_regettoken(&w->wa_token);
449 lwkt_reltoken(&w->wa_token);
453 * Aquire ownership of a token
455 * Aquire ownership of a token. The token may have spl and/or critical
456 * section side effects, depending on its purpose. These side effects
457 * guarentee that you will maintain ownership of the token as long as you
458 * do not block. If you block you may lose access to the token (but you
459 * must still release it even if you lose your access to it).
461 * Note that the spl and critical section characteristics of a token
462 * may not be changed once the token has been initialized.
465 lwkt_gettoken(lwkt_token_t tok)
468 * Prevent preemption so the token can't be taken away from us once
469 * we gain ownership of it. Use a synchronous request which might
470 * block. The request will be forwarded as necessary playing catchup
475 while (tok->t_cpu != mycpu->gd_cpu) {
476 lwkt_cpu_msg_union msg;
477 initTokenReqMsg(&msg.mu_TokenReq);
482 * leave us in a critical section on return. This will be undone
488 * Release your ownership of a token. Releases must occur in reverse
489 * order to aquisitions, eventually so priorities can be unwound properly
490 * like SPLs. At the moment the actual implemention doesn't care.
492 * We can safely hand a token that we own to another cpu without notifying
493 * it, but once we do we can't get it back without requesting it (unless
494 * the other cpu hands it back to us before we check).
496 * We might have lost the token, so check that.
499 lwkt_reltoken(lwkt_token_t tok)
501 if (tok->t_cpu == mycpu->gd_cpu) {
502 tok->t_cpu = tok->t_reqcpu;
508 * Reaquire a token that might have been lost. Returns 1 if we blocked
509 * while reaquiring the token (meaning that you might have lost other
510 * tokens you held when you made this call), return 0 if we did not block.
513 lwkt_regettoken(lwkt_token_t tok)
516 if (tok->t_cpu != mycpu->gd_cpu) {
517 while (tok->t_cpu != mycpu->gd_cpu) {
518 lwkt_cpu_msg_union msg;
519 initTokenReqMsg(&msg.mu_TokenReq);