Cleanup lwkt threads a bit, change the exit/reap interlock.
[dragonfly.git] / sys / kern / lwkt_thread.c
CommitLineData
8ad65e08
MD
1/*
2 * Copyright (c) 2003 Matthew Dillon <dillon@backplane.com>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
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.
13 *
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
24 * SUCH DAMAGE.
25 *
f1d1c3fa
MD
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.
29 *
99df837e 30 * $DragonFly: src/sys/kern/lwkt_thread.c,v 1.6 2003/06/27 03:30:42 dillon Exp $
8ad65e08
MD
31 */
32
33#include <sys/param.h>
34#include <sys/systm.h>
35#include <sys/kernel.h>
36#include <sys/proc.h>
37#include <sys/rtprio.h>
38#include <sys/queue.h>
f1d1c3fa 39#include <sys/thread2.h>
7d0bac62 40#include <sys/sysctl.h>
99df837e 41#include <sys/kthread.h>
f1d1c3fa 42#include <machine/cpu.h>
99df837e 43#include <sys/lock.h>
f1d1c3fa 44
7d0bac62
MD
45#include <vm/vm.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>
54
99df837e
MD
55#include <machine/stdarg.h>
56
7d0bac62
MD
57static int untimely_switch = 0;
58SYSCTL_INT(_debug, OID_AUTO, untimely_switch, CTLFLAG_RW, &untimely_switch, 0, "");
59
60
f1d1c3fa
MD
61static __inline
62void
63_lwkt_dequeue(thread_t td)
64{
65 if (td->td_flags & TDF_RUNQ) {
66 td->td_flags &= ~TDF_RUNQ;
67 TAILQ_REMOVE(&mycpu->gd_tdrunq, td, td_threadq);
68 }
69}
70
71static __inline
72void
73_lwkt_enqueue(thread_t td)
74{
75 if ((td->td_flags & TDF_RUNQ) == 0) {
76 td->td_flags |= TDF_RUNQ;
77 TAILQ_INSERT_TAIL(&mycpu->gd_tdrunq, td, td_threadq);
78 }
79}
8ad65e08
MD
80
81/*
82 * LWKTs operate on a per-cpu basis
83 *
84 * YYY implement strict priorities & round-robin at the same priority
85 */
86void
87lwkt_gdinit(struct globaldata *gd)
88{
89 TAILQ_INIT(&gd->gd_tdrunq);
90}
91
7d0bac62
MD
92/*
93 * Initialize a thread wait structure prior to first use.
94 *
95 * NOTE! called from low level boot code, we cannot do anything fancy!
96 */
97void
98lwkt_init_wait(lwkt_wait_t w)
99{
100 TAILQ_INIT(&w->wa_waitq);
101}
102
103/*
104 * Create a new thread. The thread must be associated with a process context
105 * or LWKT start address before it can be scheduled.
0cfcada1
MD
106 *
107 * If you intend to create a thread without a process context this function
108 * does everything except load the startup and switcher function.
7d0bac62
MD
109 */
110thread_t
111lwkt_alloc_thread(void)
112{
99df837e
MD
113 struct thread *td;
114 void *stack;
7d0bac62 115
99df837e
MD
116 crit_enter();
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);
123 crit_exit();
124 stack = td->td_kstack;
125 } else {
126 crit_exit();
127 td = zalloc(thread_zone);
128 stack = (void *)kmem_alloc(kernel_map, UPAGES * PAGE_SIZE);
129 }
130 lwkt_init_thread(td, stack, TDF_ALLOCATED_STACK|TDF_ALLOCATED_THREAD);
131 return(td);
7d0bac62
MD
132}
133
134/*
135 * Initialize a preexisting thread structure. This function is used by
136 * lwkt_alloc_thread() and also used to initialize the per-cpu idlethread.
137 *
138 * NOTE! called from low level boot code, we cannot do anything fancy!
139 */
140void
99df837e 141lwkt_init_thread(thread_t td, void *stack, int flags)
7d0bac62 142{
99df837e
MD
143 bzero(td, sizeof(struct thread));
144 td->td_kstack = stack;
145 td->td_flags |= flags;
146 pmap_init_thread(td);
7d0bac62
MD
147}
148
99df837e
MD
149void
150lwkt_free_thread(struct thread *td)
151{
152 KASSERT(td->td_flags & TDF_EXITED,
153 ("lwkt_free_thread: did not exit! %p", td));
154
155 crit_enter();
156 if (mycpu->gd_tdfreecount < CACHE_NTHREADS &&
157 (td->td_flags & TDF_ALLOCATED_THREAD)
158 ) {
159 ++mycpu->gd_tdfreecount;
160 TAILQ_INSERT_HEAD(&mycpu->gd_tdfreeq, td, td_threadq);
161 crit_exit();
162 } else {
163 crit_exit();
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;
168 }
169 if (td->td_flags & TDF_ALLOCATED_THREAD)
170 zfree(thread_zone, td);
171 }
172}
173
174
8ad65e08
MD
175/*
176 * Switch to the next runnable lwkt. If no LWKTs are runnable then
f1d1c3fa
MD
177 * switch to the idlethread. Switching must occur within a critical
178 * section to avoid races with the scheduling queue.
179 *
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.
184 *
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.
188 *
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
191 * thread.
192 *
193 * (self contained on a per cpu basis)
8ad65e08
MD
194 */
195void
196lwkt_switch(void)
197{
f1d1c3fa 198 thread_t td = curthread;
8ad65e08
MD
199 thread_t ntd;
200
f1d1c3fa 201 crit_enter();
99df837e
MD
202 if ((ntd = td->td_preempted) != NULL) {
203 /*
204 * We had preempted another thread on this cpu, resume the preempted
205 * thread.
206 */
207 td->td_preempted = NULL;
208 ntd->td_flags &= ~TDF_PREEMPTED;
209 } else if ((ntd = TAILQ_FIRST(&mycpu->gd_tdrunq)) != NULL) {
8ad65e08
MD
210 TAILQ_REMOVE(&mycpu->gd_tdrunq, ntd, td_threadq);
211 TAILQ_INSERT_TAIL(&mycpu->gd_tdrunq, ntd, td_threadq);
8ad65e08 212 } else {
f1d1c3fa
MD
213 ntd = &mycpu->gd_idlethread;
214 }
99df837e 215 if (td != ntd)
f1d1c3fa 216 td->td_switch(ntd);
f1d1c3fa 217 crit_exit();
8ad65e08
MD
218}
219
f1d1c3fa
MD
220/*
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.
224 *
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().
229 *
230 * (self contained on a per cpu basis)
231 */
232void
233lwkt_yield_quick(void)
234{
235 thread_t td = curthread;
236 while ((td->td_pri & TDPRI_MASK) < mycpu->gd_reqpri) {
237#if 0
238 cpu_schedule_reqs(); /* resets gd_reqpri */
239#endif
240 splz();
241 }
242
243 /*
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
7d0bac62
MD
246 * preemption and MP without actually doing preemption or MP, because a
247 * lot of code assumes that wakeup() does not block.
f1d1c3fa 248 */
7d0bac62 249 if (untimely_switch && intr_nesting_level == 0) {
f1d1c3fa
MD
250 crit_enter();
251 /*
252 * YYY temporary hacks until we disassociate the userland scheduler
253 * from the LWKT scheduler.
254 */
255 if (td->td_flags & TDF_RUNQ) {
256 lwkt_switch(); /* will not reenter yield function */
257 } else {
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 */
261 }
262 crit_exit_noyield();
263 }
f1d1c3fa
MD
264}
265
8ad65e08 266/*
f1d1c3fa
MD
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().
270 *
271 * (self contained on a per cpu basis)
8ad65e08
MD
272 */
273void
f1d1c3fa 274lwkt_yield(void)
8ad65e08 275{
f1d1c3fa
MD
276 lwkt_schedule_self();
277 lwkt_switch();
278}
279
280/*
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
283 * function.
284 *
285 * (non-blocking, self contained on a per cpu basis)
286 */
287void
288lwkt_schedule_self(void)
289{
290 thread_t td = curthread;
291
292 crit_enter();
293 KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
f1d1c3fa
MD
294 _lwkt_enqueue(td);
295 crit_exit();
8ad65e08 296}
8ad65e08
MD
297
298/*
f1d1c3fa
MD
299 * Generic schedule. Possibly schedule threads belonging to other cpus and
300 * deal with threads that might be blocked on a wait queue.
301 *
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
305 * by the target cpu.
306 *
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.
8ad65e08
MD
310 */
311void
312lwkt_schedule(thread_t td)
313{
f1d1c3fa
MD
314 crit_enter();
315 if (td == curthread) {
316 _lwkt_enqueue(td);
317 } else {
318 lwkt_wait_t w;
319
320 /*
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
326 * acted upon).
327 *
328 * (remember, wait structures use stable storage)
329 */
330 if ((w = td->td_wait) != NULL) {
331 if (lwkt_havetoken(&w->wa_token)) {
332 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
333 --w->wa_count;
334 td->td_wait = NULL;
335 if (td->td_cpu == mycpu->gd_cpu) {
336 _lwkt_enqueue(td);
337 } else {
338 panic("lwkt_schedule: cpu mismatch1");
8ad65e08 339#if 0
f1d1c3fa
MD
340 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
341 initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
342 cpu_sendnormsg(&msg.mu_Msg);
8ad65e08 343#endif
f1d1c3fa
MD
344 }
345 } else {
346 panic("lwkt_schedule: cpu mismatch2");
347#if 0
348 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
349 initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
350 cpu_sendnormsg(&msg.mu_Msg);
351#endif
352 }
353 } else {
354 /*
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.
359 */
360 if (td->td_cpu == mycpu->gd_cpu) {
361 _lwkt_enqueue(td);
362 } else {
363 panic("lwkt_schedule: cpu mismatch3");
364#if 0
365 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
366 initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
367 cpu_sendnormsg(&msg.mu_Msg);
368#endif
369 }
370 }
8ad65e08 371 }
f1d1c3fa 372 crit_exit();
8ad65e08
MD
373}
374
375/*
f1d1c3fa
MD
376 * Deschedule a thread.
377 *
378 * (non-blocking, self contained on a per cpu basis)
379 */
380void
381lwkt_deschedule_self(void)
382{
383 thread_t td = curthread;
384
385 crit_enter();
386 KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
f1d1c3fa
MD
387 _lwkt_dequeue(td);
388 crit_exit();
389}
390
391/*
392 * Generic deschedule. Descheduling threads other then your own should be
393 * done only in carefully controlled circumstances. Descheduling is
394 * asynchronous.
395 *
396 * This function may block if the cpu has run out of messages.
8ad65e08
MD
397 */
398void
399lwkt_deschedule(thread_t td)
400{
f1d1c3fa
MD
401 crit_enter();
402 if (td == curthread) {
403 _lwkt_dequeue(td);
404 } else {
405 if (td->td_cpu == mycpu->gd_cpu) {
406 _lwkt_dequeue(td);
407 } else {
408 panic("lwkt_deschedule: cpu mismatch");
409#if 0
410 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
411 initDescheduleReqMsg_Thread(&msg.mu_DeschedReq, td);
412 cpu_sendnormsg(&msg.mu_Msg);
413#endif
414 }
415 }
416 crit_exit();
417}
418
419/*
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.
424 *
425 * Note: alternatively we could dequeue our thread and then message the
426 * target cpu owning the wait queue. YYY implement as sysctl.
427 *
428 * Note: wait queue signals normally ping-pong the cpu as an optimization.
429 */
430void
ae8050a4 431lwkt_block(lwkt_wait_t w, const char *wmesg, int *gen)
f1d1c3fa
MD
432{
433 thread_t td = curthread;
f1d1c3fa 434
f1d1c3fa 435 lwkt_gettoken(&w->wa_token);
ae8050a4 436 if (w->wa_gen == *gen) {
f1d1c3fa
MD
437 _lwkt_dequeue(td);
438 TAILQ_INSERT_TAIL(&w->wa_waitq, td, td_threadq);
439 ++w->wa_count;
440 td->td_wait = w;
ae8050a4 441 td->td_wmesg = wmesg;
f1d1c3fa 442 lwkt_switch();
8ad65e08 443 }
ae8050a4
MD
444 /* token might be lost, doesn't matter for gen update */
445 *gen = w->wa_gen;
f1d1c3fa
MD
446 lwkt_reltoken(&w->wa_token);
447}
448
449/*
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.
453 *
454 * Note: alternatively we could message the target cpu owning the wait
455 * queue. YYY implement as sysctl.
456 */
457void
458lwkt_signal(lwkt_wait_t w)
459{
460 thread_t td;
461 int count;
462
463 lwkt_gettoken(&w->wa_token);
464 ++w->wa_gen;
465 count = w->wa_count;
466 while ((td = TAILQ_FIRST(&w->wa_waitq)) != NULL && count) {
467 --count;
468 --w->wa_count;
469 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
470 td->td_wait = NULL;
ae8050a4 471 td->td_wmesg = NULL;
f1d1c3fa
MD
472 if (td->td_cpu == mycpu->gd_cpu) {
473 _lwkt_enqueue(td);
474 } else {
475#if 0
476 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
477 initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
478 cpu_sendnormsg(&msg.mu_Msg);
479#endif
480 panic("lwkt_signal: cpu mismatch");
481 }
482 lwkt_regettoken(&w->wa_token);
483 }
484 lwkt_reltoken(&w->wa_token);
485}
486
487/*
488 * Aquire ownership of a token
489 *
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).
495 *
496 * Note that the spl and critical section characteristics of a token
497 * may not be changed once the token has been initialized.
498 */
499void
500lwkt_gettoken(lwkt_token_t tok)
501{
502 /*
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
506 * to the token.
507 */
508 crit_enter();
509#if 0
510 while (tok->t_cpu != mycpu->gd_cpu) {
511 lwkt_cpu_msg_union msg;
512 initTokenReqMsg(&msg.mu_TokenReq);
513 cpu_domsg(&msg);
514 }
515#endif
516 /*
517 * leave us in a critical section on return. This will be undone
518 * by lwkt_reltoken()
519 */
520}
521
522/*
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.
526 *
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).
530 *
531 * We might have lost the token, so check that.
532 */
533void
534lwkt_reltoken(lwkt_token_t tok)
535{
536 if (tok->t_cpu == mycpu->gd_cpu) {
537 tok->t_cpu = tok->t_reqcpu;
538 }
539 crit_exit();
540}
541
542/*
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.
546 */
547int
548lwkt_regettoken(lwkt_token_t tok)
549{
550#if 0
551 if (tok->t_cpu != mycpu->gd_cpu) {
552 while (tok->t_cpu != mycpu->gd_cpu) {
553 lwkt_cpu_msg_union msg;
554 initTokenReqMsg(&msg.mu_TokenReq);
555 cpu_domsg(&msg);
556 }
557 return(1);
558 }
559#endif
560 return(0);
8ad65e08
MD
561}
562
99df837e
MD
563/*
564 * Create a kernel process/thread/whatever. It shares it's address space
565 * with proc0 - ie: kernel only.
566 *
567 * XXX should be renamed to lwkt_create()
568 */
569int
570lwkt_create(void (*func)(void *), void *arg,
571 struct thread **tdp, const char *fmt, ...)
572{
573 struct thread *td;
574 va_list ap;
575
576 td = *tdp = lwkt_alloc_thread();
577 cpu_set_thread_handler(td, kthread_exit, func, arg);
578 td->td_flags |= TDF_VERBOSE;
579
580 /*
581 * Set up arg0 for 'ps' etc
582 */
583 va_start(ap, fmt);
584 vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
585 va_end(ap);
586
587 /*
588 * Schedule the thread to run
589 */
590 lwkt_schedule(td);
591 return 0;
592}
593
594/*
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.
598 */
599void
600lwkt_exit(void)
601{
602 thread_t td = curthread;
603
604 if (td->td_flags & TDF_VERBOSE)
605 printf("kthread %p %s has exited\n", td, td->td_comm);
606 crit_enter();
607 lwkt_deschedule_self();
608 ++mycpu->gd_tdfreecount;
609 TAILQ_INSERT_TAIL(&mycpu->gd_tdfreeq, td, td_threadq);
610 cpu_thread_exit();
611}
612
613/*
614 * Create a kernel process/thread/whatever. It shares it's address space
615 * with proc0 - ie: kernel only.
616 *
617 * XXX exact duplicate of lwkt_create().
618 */
619int
620kthread_create(void (*func)(void *), void *arg,
621 struct thread **tdp, const char *fmt, ...)
622{
623 struct thread *td;
624 va_list ap;
625
626 td = *tdp = lwkt_alloc_thread();
627 cpu_set_thread_handler(td, kthread_exit, func, arg);
628 td->td_flags |= TDF_VERBOSE;
629
630 /*
631 * Set up arg0 for 'ps' etc
632 */
633 va_start(ap, fmt);
634 vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
635 va_end(ap);
636
637 /*
638 * Schedule the thread to run
639 */
640 lwkt_schedule(td);
641 return 0;
642}
643
644/*
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.
648 *
649 * XXX duplicates lwkt_exit()
650 */
651void
652kthread_exit(void)
653{
654 lwkt_exit();
655}
656