M7350v1_en_gpl

This commit is contained in:
T
2024-09-09 08:52:07 +00:00
commit f9cc65cfda
65988 changed files with 26357421 additions and 0 deletions

View File

@ -0,0 +1,134 @@
/*
* Copyright (c) 2008-2009 Travis Geiselbrecht
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @defgroup debug Debug
* @{
*/
/**
* @file
* @brief Debug console functions.
*/
#include <debug.h>
#include <kernel/thread.h>
#include <kernel/timer.h>
#include <platform.h>
#if WITH_LIB_CONSOLE
#include <lib/console.h>
static int cmd_threads(int argc, const cmd_args *argv);
static int cmd_threadstats(int argc, const cmd_args *argv);
static int cmd_threadload(int argc, const cmd_args *argv);
STATIC_COMMAND_START
#if DEBUGLEVEL > 1
STATIC_COMMAND("threads", "list kernel threads", &cmd_threads)
#endif
#if THREAD_STATS
STATIC_COMMAND("threadstats", "thread level statistics", &cmd_threadstats)
STATIC_COMMAND("threadload", "toggle thread load display", &cmd_threadload)
#endif
STATIC_COMMAND_END(kernel);
#if DEBUGLEVEL > 1
static int cmd_threads(int argc, const cmd_args *argv)
{
printf("thread list:\n");
dump_all_threads();
return 0;
}
#endif
#if THREAD_STATS
static int cmd_threadstats(int argc, const cmd_args *argv)
{
printf("thread stats:\n");
printf("\ttotal idle time: %lld\n", thread_stats.idle_time);
printf("\ttotal busy time: %lld\n", current_time_hires() - thread_stats.idle_time);
printf("\treschedules: %d\n", thread_stats.reschedules);
printf("\tcontext_switches: %d\n", thread_stats.context_switches);
printf("\tpreempts: %d\n", thread_stats.preempts);
printf("\tyields: %d\n", thread_stats.yields);
printf("\tinterrupts: %d\n", thread_stats.interrupts);
printf("\ttimer interrupts: %d\n", thread_stats.timer_ints);
printf("\ttimers: %d\n", thread_stats.timers);
return 0;
}
static enum handler_return threadload(struct timer *t, time_t now, void *arg)
{
static struct thread_stats old_stats;
static bigtime_t last_idle_time;
bigtime_t idle_time = thread_stats.idle_time;
if (current_thread == idle_thread) {
idle_time += current_time_hires() - thread_stats.last_idle_timestamp;
}
bigtime_t busy_time = 1000000ULL - (idle_time - last_idle_time);
uint busypercent = (busy_time * 10000) / (1000000);
// printf("idle_time %lld, busytime %lld\n", idle_time - last_idle_time, busy_time);
printf("LOAD: %d.%02d%%, cs %d, ints %d, timer ints %d, timers %d\n", busypercent / 100, busypercent % 100,
thread_stats.context_switches - old_stats.context_switches,
thread_stats.interrupts - old_stats.interrupts,
thread_stats.timer_ints - old_stats.timer_ints,
thread_stats.timers - old_stats.timers);
old_stats = thread_stats;
last_idle_time = idle_time;
return INT_NO_RESCHEDULE;
}
static int cmd_threadload(int argc, const cmd_args *argv)
{
static bool showthreadload = false;
static timer_t tltimer;
enter_critical_section();
if (showthreadload == false) {
// start the display
timer_initialize(&tltimer);
timer_set_periodic(&tltimer, 1000, &threadload, NULL);
showthreadload = true;
} else {
timer_cancel(&tltimer);
showthreadload = false;
}
exit_critical_section();
return 0;
}
#endif
#endif

View File

@ -0,0 +1,88 @@
/*
* Copyright (c) 2008 Travis Geiselbrecht
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <debug.h>
#include <list.h>
#include <malloc.h>
#include <err.h>
#include <kernel/dpc.h>
#include <kernel/thread.h>
#include <kernel/event.h>
struct dpc {
struct list_node node;
dpc_callback cb;
void *arg;
};
static struct list_node dpc_list = LIST_INITIAL_VALUE(dpc_list);
static event_t dpc_event;
static int dpc_thread_routine(void *arg);
void dpc_init(void)
{
event_init(&dpc_event, false, 0);
thread_resume(thread_create("dpc", &dpc_thread_routine, NULL, DPC_PRIORITY, DEFAULT_STACK_SIZE));
}
status_t dpc_queue(dpc_callback cb, void *arg, uint flags)
{
struct dpc *dpc;
dpc = malloc(sizeof(struct dpc));
dpc->cb = cb;
dpc->arg = arg;
enter_critical_section();
list_add_tail(&dpc_list, &dpc->node);
event_signal(&dpc_event, (flags & DPC_FLAG_NORESCHED) ? false : true);
exit_critical_section();
return NO_ERROR;
}
static int dpc_thread_routine(void *arg)
{
for (;;) {
event_wait(&dpc_event);
enter_critical_section();
struct dpc *dpc = list_remove_head_type(&dpc_list, struct dpc, node);
if (!dpc)
event_unsignal(&dpc_event);
exit_critical_section();
if (dpc) {
// dprintf("dpc calling %p, arg %p\n", dpc->cb, dpc->arg);
dpc->cb(dpc->arg);
free(dpc);
}
}
return 0;
}

View File

@ -0,0 +1,221 @@
/*
* Copyright (c) 2008-2009 Travis Geiselbrecht
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file
* @brief Event wait and signal functions for threads.
* @defgroup event Events
*
* An event is a subclass of a wait queue.
*
* Threads wait for events, with optional timeouts.
*
* Events are "signaled", releasing waiting threads to continue.
* Signals may be one-shot signals (EVENT_FLAG_AUTOUNSIGNAL), in which
* case one signal releases only one thread, at which point it is
* automatically cleared. Otherwise, signals release all waiting threads
* to continue immediately until the signal is manually cleared with
* event_unsignal().
*
* @{
*/
#include <debug.h>
#include <err.h>
#include <kernel/event.h>
#if DEBUGLEVEL > 1
#define EVENT_CHECK 1
#endif
/**
* @brief Initialize an event object
*
* @param e Event object to initialize
* @param initial Initial value for "signaled" state
* @param flags 0 or EVENT_FLAG_AUTOUNSIGNAL
*/
void event_init(event_t *e, bool initial, uint flags)
{
#if EVENT_CHECK
// ASSERT(e->magic != EVENT_MAGIC);
#endif
e->magic = EVENT_MAGIC;
e->signalled = initial;
e->flags = flags;
wait_queue_init(&e->wait);
}
/**
* @brief Destroy an event object.
*
* Event's resources are freed and it may no longer be
* used until event_init() is called again. Any threads
* still waiting on the event will be resumed.
*
* @param e Event object to initialize
*/
void event_destroy(event_t *e)
{
enter_critical_section();
#if EVENT_CHECK
ASSERT(e->magic == EVENT_MAGIC);
#endif
e->magic = 0;
e->signalled = false;
e->flags = 0;
wait_queue_destroy(&e->wait, true);
exit_critical_section();
}
/**
* @brief Wait for event to be signaled
*
* If the event has already been signaled, this function
* returns immediately. Otherwise, the current thread
* goes to sleep until the event object is signaled,
* the timeout is reached, or the event object is destroyed
* by another thread.
*
* @param e Event object
* @param timeout Timeout value, in ms
*
* @return 0 on success, ERR_TIMED_OUT on timeout,
* other values on other errors.
*/
status_t event_wait_timeout(event_t *e, time_t timeout)
{
status_t ret = NO_ERROR;
enter_critical_section();
#if EVENT_CHECK
ASSERT(e->magic == EVENT_MAGIC);
#endif
if (e->signalled) {
/* signalled, we're going to fall through */
if (e->flags & EVENT_FLAG_AUTOUNSIGNAL) {
/* autounsignal flag lets one thread fall through before unsignalling */
e->signalled = false;
}
} else {
/* unsignalled, block here */
ret = wait_queue_block(&e->wait, timeout);
if (ret < 0)
goto err;
}
err:
exit_critical_section();
return ret;
}
/**
* @brief Same as event_wait_timeout(), but without a timeout.
*/
status_t event_wait(event_t *e)
{
return event_wait_timeout(e, INFINITE_TIME);
}
/**
* @brief Signal an event
*
* Signals an event. If EVENT_FLAG_AUTOUNSIGNAL is set in the event
* object's flags, only one waiting thread is allowed to proceed. Otherwise,
* all waiting threads are allowed to proceed until such time as
* event_unsignal() is called.
*
* @param e Event object
* @param reschedule If true, waiting thread(s) are executed immediately,
* and the current thread resumes only after the
* waiting threads have been satisfied. If false,
* waiting threads are placed at the end of the run
* queue.
*
* @return Returns NO_ERROR on success.
*/
status_t event_signal(event_t *e, bool reschedule)
{
enter_critical_section();
#if EVENT_CHECK
ASSERT(e->magic == EVENT_MAGIC);
#endif
if (!e->signalled) {
if (e->flags & EVENT_FLAG_AUTOUNSIGNAL) {
/* try to release one thread and leave unsignalled if successful */
if (wait_queue_wake_one(&e->wait, reschedule, NO_ERROR) <= 0) {
/*
* if we didn't actually find a thread to wake up, go to
* signalled state and let the next call to event_wait
* unsignal the event.
*/
e->signalled = true;
}
} else {
/* release all threads and remain signalled */
e->signalled = true;
wait_queue_wake_all(&e->wait, reschedule, NO_ERROR);
}
}
exit_critical_section();
return NO_ERROR;
}
/**
* @brief Clear the "signaled" property of an event
*
* Used mainly for event objects without the EVENT_FLAG_AUTOUNSIGNAL
* flag. Once this function is called, threads that call event_wait()
* functions will once again need to wait until the event object
* is signaled.
*
* @param e Event object
*
* @return Returns NO_ERROR on success.
*/
status_t event_unsignal(event_t *e)
{
enter_critical_section();
#if EVENT_CHECK
ASSERT(e->magic == EVENT_MAGIC);
#endif
e->signalled = false;
exit_critical_section();
return NO_ERROR;
}

View File

@ -0,0 +1,168 @@
/*
* Copyright (c) 2008 Travis Geiselbrecht
*
* Copyright (c) 2009-2013, The Linux Foundation. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <compiler.h>
#include <debug.h>
#include <string.h>
#include <app.h>
#include <arch.h>
#include <platform.h>
#include <target.h>
#include <lib/heap.h>
#include <kernel/thread.h>
#include <kernel/timer.h>
#include <kernel/dpc.h>
#include <boot_stats.h>
extern void *__ctor_list;
extern void *__ctor_end;
extern int __bss_start;
extern int _end;
static int bootstrap2(void *arg);
#if (ENABLE_NANDWRITE)
void bootstrap_nandwrite(void);
#endif
static void call_constructors(void)
{
void **ctor;
ctor = &__ctor_list;
while(ctor != &__ctor_end) {
void (*func)(void);
func = (void (*)())*ctor;
func();
ctor++;
}
}
/* called from crt0.S */
void kmain(void) __NO_RETURN __EXTERNALLY_VISIBLE;
void kmain(void)
{
// get us into some sort of thread context
thread_init_early();
// early arch stuff
arch_early_init();
// do any super early platform initialization
platform_early_init();
// do any super early target initialization
target_early_init();
dprintf(INFO, "welcome to lk\n\n");
bs_set_timestamp(BS_BL_START);
// deal with any static constructors
dprintf(SPEW, "calling constructors\n");
call_constructors();
// bring up the kernel heap
dprintf(SPEW, "initializing heap\n");
heap_init();
// initialize the threading system
dprintf(SPEW, "initializing threads\n");
thread_init();
// initialize the dpc system
dprintf(SPEW, "initializing dpc\n");
dpc_init();
// initialize kernel timers
dprintf(SPEW, "initializing timers\n");
timer_init();
#if (!ENABLE_NANDWRITE)
// create a thread to complete system initialization
dprintf(SPEW, "creating bootstrap completion thread\n");
thread_resume(thread_create("bootstrap2", &bootstrap2, NULL, DEFAULT_PRIORITY, DEFAULT_STACK_SIZE));
// enable interrupts
exit_critical_section();
// become the idle thread
thread_become_idle();
#else
bootstrap_nandwrite();
#endif
}
int main(void);
static int bootstrap2(void *arg)
{
dprintf(SPEW, "top of bootstrap2()\n");
arch_init();
// XXX put this somewhere else
#if WITH_LIB_BIO
bio_init();
#endif
#if WITH_LIB_FS
fs_init();
#endif
// initialize the rest of the platform
dprintf(SPEW, "initializing platform\n");
platform_init();
// initialize the target
dprintf(SPEW, "initializing target\n");
target_init();
dprintf(SPEW, "calling apps_init()\n");
apps_init();
return 0;
}
#if (ENABLE_NANDWRITE)
void bootstrap_nandwrite(void)
{
dprintf(SPEW, "top of bootstrap2()\n");
arch_init();
// initialize the rest of the platform
dprintf(SPEW, "initializing platform\n");
platform_init();
// initialize the target
dprintf(SPEW, "initializing target\n");
target_init();
dprintf(SPEW, "calling nandwrite_init()\n");
nandwrite_init();
return 0;
}
#endif

View File

@ -0,0 +1,208 @@
/*
* Copyright (c) 2008-2009 Travis Geiselbrecht
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file
* @brief Mutex functions
*
* @defgroup mutex Mutex
* @{
*/
#include <debug.h>
#include <err.h>
#include <kernel/mutex.h>
#include <kernel/thread.h>
#if DEBUGLEVEL > 1
#define MUTEX_CHECK 1
#endif
/**
* @brief Initialize a mutex_t
*/
void mutex_init(mutex_t *m)
{
#if MUTEX_CHECK
// ASSERT(m->magic != MUTEX_MAGIC);
#endif
m->magic = MUTEX_MAGIC;
m->count = 0;
m->holder = 0;
wait_queue_init(&m->wait);
}
/**
* @brief Destroy a mutex_t
*
* This function frees any resources that were allocated
* in mutex_init(). The mutex_t object itself is not freed.
*/
void mutex_destroy(mutex_t *m)
{
enter_critical_section();
#if MUTEX_CHECK
ASSERT(m->magic == MUTEX_MAGIC);
#endif
// if (m->holder != 0 && current_thread != m->holder)
// panic("mutex_destroy: thread %p (%s) tried to release mutex %p it doesn't own. owned by %p (%s)\n",
// current_thread, current_thread->name, m, m->holder, m->holder ? m->holder->name : "none");
m->magic = 0;
m->count = 0;
wait_queue_destroy(&m->wait, true);
exit_critical_section();
}
/**
* @brief Acquire a mutex; wait if needed.
*
* This function waits for a mutex to become available. It
* may wait forever if the mutex never becomes free.
*
* @return NO_ERROR on success, other values on error
*/
status_t mutex_acquire(mutex_t *m)
{
status_t ret = NO_ERROR;
if (current_thread == m->holder)
panic("mutex_acquire: thread %p (%s) tried to acquire mutex %p it already owns.\n",
current_thread, current_thread->name, m);
enter_critical_section();
#if MUTEX_CHECK
ASSERT(m->magic == MUTEX_MAGIC);
#endif
// dprintf("mutex_acquire: m %p, count %d, curr %p\n", m, m->count, current_thread);
m->count++;
if (unlikely(m->count > 1)) {
/*
* block on the wait queue. If it returns an error, it was likely destroyed
* out from underneath us, so make sure we dont scribble thread ownership
* on the mutex.
*/
ret = wait_queue_block(&m->wait, INFINITE_TIME);
if (ret < 0)
goto err;
}
m->holder = current_thread;
err:
exit_critical_section();
return ret;
}
/**
* @brief Mutex wait with timeout
*
* This function waits up to \a timeout ms for the mutex to become available.
* Timeout may be zero, in which case this function returns immediately if
* the mutex is not free.
*
* @return NO_ERROR on success, ERR_TIMED_OUT on timeout,
* other values on error
*/
status_t mutex_acquire_timeout(mutex_t *m, time_t timeout)
{
status_t ret = NO_ERROR;
if (current_thread == m->holder)
panic("mutex_acquire_timeout: thread %p (%s) tried to acquire mutex %p it already owns.\n",
current_thread, current_thread->name, m);
if (timeout == INFINITE_TIME)
return mutex_acquire(m);
enter_critical_section();
#if MUTEX_CHECK
ASSERT(m->magic == MUTEX_MAGIC);
#endif
// dprintf("mutex_acquire_timeout: m %p, count %d, curr %p, timeout %d\n", m, m->count, current_thread, timeout);
m->count++;
if (unlikely(m->count > 1)) {
ret = wait_queue_block(&m->wait, timeout);
if (ret < NO_ERROR) {
/* if the acquisition timed out, back out the acquire and exit */
if (ret == ERR_TIMED_OUT) {
/*
* XXX race: the mutex may have been destroyed after the timeout,
* but before we got scheduled again which makes messing with the
* count variable dangerous.
*/
m->count--;
goto err;
}
/* if there was a general error, it may have been destroyed out from
* underneath us, so just exit (which is really an invalid state anyway)
*/
}
}
m->holder = current_thread;
err:
exit_critical_section();
return ret;
}
/**
* @brief Release mutex
*/
status_t mutex_release(mutex_t *m)
{
if (current_thread != m->holder)
panic("mutex_release: thread %p (%s) tried to release mutex %p it doesn't own. owned by %p (%s)\n",
current_thread, current_thread->name, m, m->holder, m->holder ? m->holder->name : "none");
enter_critical_section();
#if MUTEX_CHECK
ASSERT(m->magic == MUTEX_MAGIC);
#endif
// dprintf("mutex_release: m %p, count %d, holder %p, curr %p\n", m, m->count, m->holder, current_thread);
m->holder = 0;
m->count--;
if (unlikely(m->count >= 1)) {
/* release a thread */
// dprintf("releasing thread\n");
wait_queue_wake_one(&m->wait, true, NO_ERROR);
}
exit_critical_section();
return NO_ERROR;
}

View File

@ -0,0 +1,16 @@
LOCAL_DIR := $(GET_LOCAL_DIR)
MODULES += \
lib/libc \
lib/debug \
lib/heap
OBJS += \
$(LOCAL_DIR)/debug.o \
$(LOCAL_DIR)/dpc.o \
$(LOCAL_DIR)/event.o \
$(LOCAL_DIR)/main.o \
$(LOCAL_DIR)/mutex.o \
$(LOCAL_DIR)/thread.o \
$(LOCAL_DIR)/timer.o

View File

@ -0,0 +1,894 @@
/*
* Copyright (c) 2008-2009 Travis Geiselbrecht
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file
* @brief Kernel threading
*
* This file is the core kernel threading interface.
*
* @defgroup thread Threads
* @{
*/
#include <debug.h>
#include <list.h>
#include <malloc.h>
#include <string.h>
#include <err.h>
#include <kernel/thread.h>
#include <kernel/timer.h>
#include <kernel/dpc.h>
#include <platform.h>
#if DEBUGLEVEL > 1
#define THREAD_CHECKS 1
#endif
#if THREAD_STATS
struct thread_stats thread_stats;
#endif
/* global thread list */
static struct list_node thread_list;
/* the current thread */
thread_t *current_thread;
/* the global critical section count */
int critical_section_count = 1;
/* the run queue */
static struct list_node run_queue[NUM_PRIORITIES];
static uint32_t run_queue_bitmap;
/* the bootstrap thread (statically allocated) */
static thread_t bootstrap_thread;
/* the idle thread */
thread_t *idle_thread;
/* local routines */
static void thread_resched(void);
static void idle_thread_routine(void) __NO_RETURN;
#if PLATFORM_HAS_DYNAMIC_TIMER
/* preemption timer */
static timer_t preempt_timer;
#endif
/* run queue manipulation */
static void insert_in_run_queue_head(thread_t *t)
{
#if THREAD_CHECKS
ASSERT(t->magic == THREAD_MAGIC);
ASSERT(t->state == THREAD_READY);
ASSERT(!list_in_list(&t->queue_node));
ASSERT(in_critical_section());
#endif
list_add_head(&run_queue[t->priority], &t->queue_node);
run_queue_bitmap |= (1<<t->priority);
}
static void insert_in_run_queue_tail(thread_t *t)
{
#if THREAD_CHECKS
ASSERT(t->magic == THREAD_MAGIC);
ASSERT(t->state == THREAD_READY);
ASSERT(!list_in_list(&t->queue_node));
ASSERT(in_critical_section());
#endif
list_add_tail(&run_queue[t->priority], &t->queue_node);
run_queue_bitmap |= (1<<t->priority);
}
static void init_thread_struct(thread_t *t, const char *name)
{
memset(t, 0, sizeof(thread_t));
t->magic = THREAD_MAGIC;
strlcpy(t->name, name, sizeof(t->name));
}
/**
* @brief Create a new thread
*
* This function creates a new thread. The thread is initially suspended, so you
* need to call thread_resume() to execute it.
*
* @param name Name of thread
* @param entry Entry point of thread
* @param arg Arbitrary argument passed to entry()
* @param priority Execution priority for the thread.
* @param stack_size Stack size for the thread.
*
* Thread priority is an integer from 0 (lowest) to 31 (highest). Some standard
* prioritys are defined in <kernel/thread.h>:
*
* HIGHEST_PRIORITY
* DPC_PRIORITY
* HIGH_PRIORITY
* DEFAULT_PRIORITY
* LOW_PRIORITY
* IDLE_PRIORITY
* LOWEST_PRIORITY
*
* Stack size is typically set to DEFAULT_STACK_SIZE
*
* @return Pointer to thread object, or NULL on failure.
*/
thread_t *thread_create(const char *name, thread_start_routine entry, void *arg, int priority, size_t stack_size)
{
thread_t *t;
t = malloc(sizeof(thread_t));
if (!t)
return NULL;
init_thread_struct(t, name);
t->entry = entry;
t->arg = arg;
t->priority = priority;
t->saved_critical_section_count = 1; /* we always start inside a critical section */
t->state = THREAD_SUSPENDED;
t->blocking_wait_queue = NULL;
t->wait_queue_block_ret = NO_ERROR;
/* create the stack */
t->stack = malloc(stack_size);
if (!t->stack) {
free(t);
return NULL;
}
t->stack_size = stack_size;
/* inheirit thread local storage from the parent */
int i;
for (i=0; i < MAX_TLS_ENTRY; i++)
t->tls[i] = current_thread->tls[i];
/* set up the initial stack frame */
arch_thread_initialize(t);
/* add it to the global thread list */
enter_critical_section();
list_add_head(&thread_list, &t->thread_list_node);
exit_critical_section();
return t;
}
/**
* @brief Make a suspended thread executable.
*
* This function is typically called to start a thread which has just been
* created with thread_create()
*
* @param t Thread to resume
*
* @return NO_ERROR on success, ERR_NOT_SUSPENDED if thread was not suspended.
*/
status_t thread_resume(thread_t *t)
{
#if THREAD_CHECKS
ASSERT(t->magic == THREAD_MAGIC);
ASSERT(t->state != THREAD_DEATH);
#endif
if (t->state == THREAD_READY || t->state == THREAD_RUNNING)
return ERR_NOT_SUSPENDED;
enter_critical_section();
t->state = THREAD_READY;
insert_in_run_queue_head(t);
thread_yield();
exit_critical_section();
return NO_ERROR;
}
static void thread_cleanup_dpc(void *thread)
{
thread_t *t = (thread_t *)thread;
// dprintf(SPEW, "thread_cleanup_dpc: thread %p (%s)\n", t, t->name);
#if THREAD_CHECKS
ASSERT(t->state == THREAD_DEATH);
ASSERT(t->blocking_wait_queue == NULL);
ASSERT(!list_in_list(&t->queue_node));
#endif
/* remove it from the master thread list */
enter_critical_section();
list_delete(&t->thread_list_node);
exit_critical_section();
/* free its stack and the thread structure itself */
if (t->stack)
free(t->stack);
free(t);
}
/**
* @brief Terminate the current thread
*
* Current thread exits with the specified return code.
*
* This function does not return.
*/
void thread_exit(int retcode)
{
#if THREAD_CHECKS
ASSERT(current_thread->magic == THREAD_MAGIC);
ASSERT(current_thread->state == THREAD_RUNNING);
#endif
// dprintf("thread_exit: current %p\n", current_thread);
enter_critical_section();
/* enter the dead state */
current_thread->state = THREAD_DEATH;
current_thread->retcode = retcode;
/* schedule a dpc to clean ourselves up */
dpc_queue(thread_cleanup_dpc, (void *)current_thread, DPC_FLAG_NORESCHED);
/* reschedule */
thread_resched();
panic("somehow fell through thread_exit()\n");
}
static void idle_thread_routine(void)
{
for(;;)
arch_idle();
}
/**
* @brief Cause another thread to be executed.
*
* Internal reschedule routine. The current thread needs to already be in whatever
* state and queues it needs to be in. This routine simply picks the next thread and
* switches to it.
*
* This is probably not the function you're looking for. See
* thread_yield() instead.
*/
void thread_resched(void)
{
thread_t *oldthread;
thread_t *newthread;
// dprintf("thread_resched: current %p: ", current_thread);
// dump_thread(current_thread);
#if THREAD_CHECKS
ASSERT(in_critical_section());
#endif
#if THREAD_STATS
thread_stats.reschedules++;
#endif
oldthread = current_thread;
// at the moment, can't deal with more than 32 priority levels
ASSERT(NUM_PRIORITIES <= 32);
// should at least find the idle thread
#if THREAD_CHECKS
ASSERT(run_queue_bitmap != 0);
#endif
int next_queue = HIGHEST_PRIORITY - __builtin_clz(run_queue_bitmap) - (32 - NUM_PRIORITIES);
//dprintf(SPEW, "bitmap 0x%x, next %d\n", run_queue_bitmap, next_queue);
newthread = list_remove_head_type(&run_queue[next_queue], thread_t, queue_node);
#if THREAD_CHECKS
ASSERT(newthread);
#endif
if (list_is_empty(&run_queue[next_queue]))
run_queue_bitmap &= ~(1<<next_queue);
#if 0
// XXX make this more efficient
newthread = NULL;
for (i=HIGHEST_PRIORITY; i >= LOWEST_PRIORITY; i--) {
newthread = list_remove_head_type(&run_queue[i], thread_t, queue_node);
if (newthread)
break;
}
#endif
// dprintf("newthread: ");
// dump_thread(newthread);
newthread->state = THREAD_RUNNING;
if (newthread == oldthread)
return;
/* set up quantum for the new thread if it was consumed */
if (newthread->remaining_quantum <= 0) {
newthread->remaining_quantum = 5; // XXX make this smarter
}
#if THREAD_STATS
thread_stats.context_switches++;
if (oldthread == idle_thread) {
bigtime_t now = current_time_hires();
thread_stats.idle_time += now - thread_stats.last_idle_timestamp;
}
if (newthread == idle_thread) {
thread_stats.last_idle_timestamp = current_time_hires();
}
#endif
#if THREAD_CHECKS
ASSERT(critical_section_count > 0);
ASSERT(newthread->saved_critical_section_count > 0);
#endif
#if PLATFORM_HAS_DYNAMIC_TIMER
/* if we're switching from idle to a real thread, set up a periodic
* timer to run our preemption tick.
*/
if (oldthread == idle_thread) {
timer_set_periodic(&preempt_timer, 10, (timer_callback)thread_timer_tick, NULL);
} else if (newthread == idle_thread) {
timer_cancel(&preempt_timer);
}
#endif
/* do the switch */
oldthread->saved_critical_section_count = critical_section_count;
current_thread = newthread;
critical_section_count = newthread->saved_critical_section_count;
arch_context_switch(oldthread, newthread);
}
/**
* @brief Yield the cpu to another thread
*
* This function places the current thread at the end of the run queue
* and yields the cpu to another waiting thread (if any.)
*
* This function will return at some later time. Possibly immediately if
* no other threads are waiting to execute.
*/
void thread_yield(void)
{
#if THREAD_CHECKS
ASSERT(current_thread->magic == THREAD_MAGIC);
ASSERT(current_thread->state == THREAD_RUNNING);
#endif
enter_critical_section();
#if THREAD_STATS
thread_stats.yields++;
#endif
/* we are yielding the cpu, so stick ourselves into the tail of the run queue and reschedule */
current_thread->state = THREAD_READY;
current_thread->remaining_quantum = 0;
insert_in_run_queue_tail(current_thread);
thread_resched();
exit_critical_section();
}
/**
* @brief Briefly yield cpu to another thread
*
* This function is similar to thread_yield(), except that it will
* restart more quickly.
*
* This function places the current thread at the head of the run
* queue and then yields the cpu to another thread.
*
* Exception: If the time slice for this thread has expired, then
* the thread goes to the end of the run queue.
*
* This function will return at some later time. Possibly immediately if
* no other threads are waiting to execute.
*/
void thread_preempt(void)
{
#if THREAD_CHECKS
ASSERT(current_thread->magic == THREAD_MAGIC);
ASSERT(current_thread->state == THREAD_RUNNING);
#endif
enter_critical_section();
#if THREAD_STATS
if (current_thread != idle_thread)
thread_stats.preempts++; /* only track when a meaningful preempt happens */
#endif
/* we are being preempted, so we get to go back into the front of the run queue if we have quantum left */
current_thread->state = THREAD_READY;
if (current_thread->remaining_quantum > 0)
insert_in_run_queue_head(current_thread);
else
insert_in_run_queue_tail(current_thread); /* if we're out of quantum, go to the tail of the queue */
thread_resched();
exit_critical_section();
}
/**
* @brief Suspend thread until woken.
*
* This function schedules another thread to execute. This function does not
* return until the thread is made runable again by some other module.
*
* You probably don't want to call this function directly; it's meant to be called
* from other modules, such as mutex, which will presumably set the thread's
* state to blocked and add it to some queue or another.
*/
void thread_block(void)
{
#if THREAD_CHECKS
ASSERT(current_thread->magic == THREAD_MAGIC);
ASSERT(current_thread->state == THREAD_BLOCKED);
#endif
enter_critical_section();
/* we are blocking on something. the blocking code should have already stuck us on a queue */
thread_resched();
exit_critical_section();
}
enum handler_return thread_timer_tick(void)
{
if (current_thread == idle_thread)
return INT_NO_RESCHEDULE;
current_thread->remaining_quantum--;
if (current_thread->remaining_quantum <= 0)
return INT_RESCHEDULE;
else
return INT_NO_RESCHEDULE;
}
/* timer callback to wake up a sleeping thread */
static enum handler_return thread_sleep_handler(timer_t *timer, time_t now, void *arg)
{
thread_t *t = (thread_t *)arg;
#if THREAD_CHECKS
ASSERT(t->magic == THREAD_MAGIC);
ASSERT(t->state == THREAD_SLEEPING);
#endif
t->state = THREAD_READY;
insert_in_run_queue_head(t);
return INT_RESCHEDULE;
}
/**
* @brief Put thread to sleep; delay specified in ms
*
* This function puts the current thread to sleep until the specified
* delay in ms has expired.
*
* Note that this function could sleep for longer than the specified delay if
* other threads are running. When the timer expires, this thread will
* be placed at the head of the run queue.
*/
void thread_sleep(time_t delay)
{
timer_t timer;
#if THREAD_CHECKS
ASSERT(current_thread->magic == THREAD_MAGIC);
ASSERT(current_thread->state == THREAD_RUNNING);
#endif
timer_initialize(&timer);
enter_critical_section();
timer_set_oneshot(&timer, delay, thread_sleep_handler, (void *)current_thread);
current_thread->state = THREAD_SLEEPING;
thread_resched();
exit_critical_section();
}
/**
* @brief Initialize threading system
*
* This function is called once, from kmain()
*/
void thread_init_early(void)
{
int i;
/* initialize the run queues */
for (i=0; i < NUM_PRIORITIES; i++)
list_initialize(&run_queue[i]);
/* initialize the thread list */
list_initialize(&thread_list);
/* create a thread to cover the current running state */
thread_t *t = &bootstrap_thread;
init_thread_struct(t, "bootstrap");
/* half construct this thread, since we're already running */
t->priority = HIGHEST_PRIORITY;
t->state = THREAD_RUNNING;
t->saved_critical_section_count = 1;
list_add_head(&thread_list, &t->thread_list_node);
current_thread = t;
}
/**
* @brief Complete thread initialization
*
* This function is called once at boot time
*/
void thread_init(void)
{
#if PLATFORM_HAS_DYNAMIC_TIMER
timer_initialize(&preempt_timer);
#endif
}
/**
* @brief Change name of current thread
*/
void thread_set_name(const char *name)
{
strlcpy(current_thread->name, name, sizeof(current_thread->name));
}
/**
* @brief Change priority of current thread
*
* See thread_create() for a discussion of priority values.
*/
void thread_set_priority(int priority)
{
if (priority < LOWEST_PRIORITY)
priority = LOWEST_PRIORITY;
if (priority > HIGHEST_PRIORITY)
priority = HIGHEST_PRIORITY;
current_thread->priority = priority;
}
/**
* @brief Become an idle thread
*
* This function marks the current thread as the idle thread -- the one which
* executes when there is nothing else to do. This function does not return.
* This function is called once at boot time.
*/
void thread_become_idle(void)
{
thread_set_name("idle");
thread_set_priority(IDLE_PRIORITY);
idle_thread = current_thread;
idle_thread_routine();
}
/**
* @brief Dump debugging info about the specified thread.
*/
void dump_thread(thread_t *t)
{
dprintf(INFO, "dump_thread: t %p (%s)\n", t, t->name);
dprintf(INFO, "\tstate %d, priority %d, remaining quantum %d, critical section %d\n", t->state, t->priority, t->remaining_quantum, t->saved_critical_section_count);
dprintf(INFO, "\tstack %p, stack_size %zd\n", t->stack, t->stack_size);
dprintf(INFO, "\tentry %p, arg %p\n", t->entry, t->arg);
dprintf(INFO, "\twait queue %p, wait queue ret %d\n", t->blocking_wait_queue, t->wait_queue_block_ret);
dprintf(INFO, "\ttls:");
int i;
for (i=0; i < MAX_TLS_ENTRY; i++) {
dprintf(INFO, " 0x%x", t->tls[i]);
}
dprintf(INFO, "\n");
}
/**
* @brief Dump debugging info about all threads
*/
void dump_all_threads(void)
{
thread_t *t;
enter_critical_section();
list_for_every_entry(&thread_list, t, thread_t, thread_list_node) {
dump_thread(t);
}
exit_critical_section();
}
/** @} */
/**
* @defgroup wait Wait Queue
* @{
*/
/**
* @brief Initialize a wait queue
*/
void wait_queue_init(wait_queue_t *wait)
{
wait->magic = WAIT_QUEUE_MAGIC;
list_initialize(&wait->list);
wait->count = 0;
}
static enum handler_return wait_queue_timeout_handler(timer_t *timer, time_t now, void *arg)
{
thread_t *thread = (thread_t *)arg;
#if THREAD_CHECKS
ASSERT(thread->magic == THREAD_MAGIC);
#endif
if (thread_unblock_from_wait_queue(thread, false, ERR_TIMED_OUT) >= NO_ERROR)
return INT_RESCHEDULE;
return INT_NO_RESCHEDULE;
}
/**
* @brief Block until a wait queue is notified.
*
* This function puts the current thread at the end of a wait
* queue and then blocks until some other thread wakes the queue
* up again.
*
* @param wait The wait queue to enter
* @param timeout The maximum time, in ms, to wait
*
* If the timeout is zero, this function returns immediately with
* ERR_TIMED_OUT. If the timeout is INFINITE_TIME, this function
* waits indefinitely. Otherwise, this function returns with
* ERR_TIMED_OUT at the end of the timeout period.
*
* @return ERR_TIMED_OUT on timeout, else returns the return
* value specified when the queue was woken by wait_queue_wake_one().
*/
status_t wait_queue_block(wait_queue_t *wait, time_t timeout)
{
timer_t timer;
#if THREAD_CHECKS
ASSERT(wait->magic == WAIT_QUEUE_MAGIC);
ASSERT(current_thread->state == THREAD_RUNNING);
ASSERT(in_critical_section());
#endif
if (timeout == 0)
return ERR_TIMED_OUT;
list_add_tail(&wait->list, &current_thread->queue_node);
wait->count++;
current_thread->state = THREAD_BLOCKED;
current_thread->blocking_wait_queue = wait;
current_thread->wait_queue_block_ret = NO_ERROR;
/* if the timeout is nonzero or noninfinite, set a callback to yank us out of the queue */
if (timeout != INFINITE_TIME) {
timer_initialize(&timer);
timer_set_oneshot(&timer, timeout, wait_queue_timeout_handler, (void *)current_thread);
}
thread_block();
/* we don't really know if the timer fired or not, so it's better safe to try to cancel it */
if (timeout != INFINITE_TIME) {
timer_cancel(&timer);
}
return current_thread->wait_queue_block_ret;
}
/**
* @brief Wake up one thread sleeping on a wait queue
*
* This function removes one thread (if any) from the head of the wait queue and
* makes it executable. The new thread will be placed at the head of the
* run queue.
*
* @param wait The wait queue to wake
* @param reschedule If true, the newly-woken thread will run immediately.
* @param wait_queue_error The return value which the new thread will receive
* from wait_queue_block().
*
* @return The number of threads woken (zero or one)
*/
int wait_queue_wake_one(wait_queue_t *wait, bool reschedule, status_t wait_queue_error)
{
thread_t *t;
int ret = 0;
#if THREAD_CHECKS
ASSERT(wait->magic == WAIT_QUEUE_MAGIC);
ASSERT(in_critical_section());
#endif
t = list_remove_head_type(&wait->list, thread_t, queue_node);
if (t) {
wait->count--;
#if THREAD_CHECKS
ASSERT(t->state == THREAD_BLOCKED);
#endif
t->state = THREAD_READY;
t->wait_queue_block_ret = wait_queue_error;
t->blocking_wait_queue = NULL;
/* if we're instructed to reschedule, stick the current thread on the head
* of the run queue first, so that the newly awakened thread gets a chance to run
* before the current one, but the current one doesn't get unnecessarilly punished.
*/
if (reschedule) {
current_thread->state = THREAD_READY;
insert_in_run_queue_head(current_thread);
}
insert_in_run_queue_head(t);
if (reschedule)
thread_resched();
ret = 1;
}
return ret;
}
/**
* @brief Wake all threads sleeping on a wait queue
*
* This function removes all threads (if any) from the wait queue and
* makes them executable. The new threads will be placed at the head of the
* run queue.
*
* @param wait The wait queue to wake
* @param reschedule If true, the newly-woken threads will run immediately.
* @param wait_queue_error The return value which the new thread will receive
* from wait_queue_block().
*
* @return The number of threads woken (zero or one)
*/
int wait_queue_wake_all(wait_queue_t *wait, bool reschedule, status_t wait_queue_error)
{
thread_t *t;
int ret = 0;
#if THREAD_CHECKS
ASSERT(wait->magic == WAIT_QUEUE_MAGIC);
ASSERT(in_critical_section());
#endif
if (reschedule && wait->count > 0) {
/* if we're instructed to reschedule, stick the current thread on the head
* of the run queue first, so that the newly awakened threads get a chance to run
* before the current one, but the current one doesn't get unnecessarilly punished.
*/
current_thread->state = THREAD_READY;
insert_in_run_queue_head(current_thread);
}
/* pop all the threads off the wait queue into the run queue */
while ((t = list_remove_head_type(&wait->list, thread_t, queue_node))) {
wait->count--;
#if THREAD_CHECKS
ASSERT(t->state == THREAD_BLOCKED);
#endif
t->state = THREAD_READY;
t->wait_queue_block_ret = wait_queue_error;
t->blocking_wait_queue = NULL;
insert_in_run_queue_head(t);
ret++;
}
#if THREAD_CHECKS
ASSERT(wait->count == 0);
#endif
if (reschedule && ret > 0)
thread_resched();
return ret;
}
/**
* @brief Free all resources allocated in wait_queue_init()
*
* If any threads were waiting on this queue, they are all woken.
*/
void wait_queue_destroy(wait_queue_t *wait, bool reschedule)
{
#if THREAD_CHECKS
ASSERT(wait->magic == WAIT_QUEUE_MAGIC);
ASSERT(in_critical_section());
#endif
wait_queue_wake_all(wait, reschedule, ERR_OBJECT_DESTROYED);
wait->magic = 0;
}
/**
* @brief Wake a specific thread in a wait queue
*
* This function extracts a specific thread from a wait queue, wakes it, and
* puts it at the head of the run queue.
*
* @param t The thread to wake
* @param reschedule If true, the newly-woken threads will run immediately.
* @param wait_queue_error The return value which the new thread will receive
* from wait_queue_block().
*
* @return ERR_NOT_BLOCKED if thread was not in any wait queue.
*/
status_t thread_unblock_from_wait_queue(thread_t *t, bool reschedule, status_t wait_queue_error)
{
enter_critical_section();
#if THREAD_CHECKS
ASSERT(t->magic == THREAD_MAGIC);
#endif
if (t->state != THREAD_BLOCKED)
return ERR_NOT_BLOCKED;
#if THREAD_CHECKS
ASSERT(t->blocking_wait_queue != NULL);
ASSERT(t->blocking_wait_queue->magic == WAIT_QUEUE_MAGIC);
ASSERT(list_in_list(&t->queue_node));
#endif
list_delete(&t->queue_node);
t->blocking_wait_queue->count--;
t->blocking_wait_queue = NULL;
t->state = THREAD_READY;
t->wait_queue_block_ret = wait_queue_error;
insert_in_run_queue_head(t);
if (reschedule)
thread_resched();
exit_critical_section();
return NO_ERROR;
}

View File

@ -0,0 +1,278 @@
/*
* Copyright (c) 2008-2009 Travis Geiselbrecht
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file
* @brief Kernel timer subsystem
* @defgroup timer Timers
*
* The timer subsystem allows functions to be scheduled for later
* execution. Each timer object is used to cause one function to
* be executed at a later time.
*
* Timer callback functions are called in interrupt context.
*
* @{
*/
#include <debug.h>
#include <list.h>
#include <kernel/thread.h>
#include <kernel/timer.h>
#include <platform/timer.h>
#include <platform.h>
static struct list_node timer_queue;
static enum handler_return timer_tick(void *arg, time_t now);
/**
* @brief Initialize a timer object
*/
void timer_initialize(timer_t *timer)
{
timer->magic = TIMER_MAGIC;
list_clear_node(&timer->node);
timer->scheduled_time = 0;
timer->periodic_time = 0;
timer->callback = 0;
timer->arg = 0;
}
static void insert_timer_in_queue(timer_t *timer)
{
timer_t *entry;
// TRACEF("timer %p, scheduled %d, periodic %d\n", timer, timer->scheduled_time, timer->periodic_time);
list_for_every_entry(&timer_queue, entry, timer_t, node) {
if (TIME_GT(entry->scheduled_time, timer->scheduled_time)) {
list_add_before(&entry->node, &timer->node);
return;
}
}
/* walked off the end of the list */
list_add_tail(&timer_queue, &timer->node);
}
static void timer_set(timer_t *timer, time_t delay, time_t period, timer_callback callback, void *arg)
{
time_t now;
// TRACEF("timer %p, delay %d, period %d, callback %p, arg %p, now %d\n", timer, delay, period, callback, arg);
DEBUG_ASSERT(timer->magic == TIMER_MAGIC);
if (list_in_list(&timer->node)) {
panic("timer %p already in list\n", timer);
}
now = current_time();
timer->scheduled_time = now + delay;
timer->periodic_time = period;
timer->callback = callback;
timer->arg = arg;
// TRACEF("scheduled time %u\n", timer->scheduled_time);
enter_critical_section();
insert_timer_in_queue(timer);
#if PLATFORM_HAS_DYNAMIC_TIMER
if (list_peek_head_type(&timer_queue, timer_t, node) == timer) {
/* we just modified the head of the timer queue */
// TRACEF("setting new timer for %u msecs\n", (uint)delay);
platform_set_oneshot_timer(timer_tick, NULL, delay);
}
#endif
exit_critical_section();
}
/**
* @brief Set up a timer that executes once
*
* This function specifies a callback function to be called after a specified
* delay. The function will be called one time.
*
* @param timer The timer to use
* @param delay The delay, in ms, before the timer is executed
* @param callback The function to call when the timer expires
* @param arg The argument to pass to the callback
*
* The timer function is declared as:
* enum handler_return callback(struct timer *, time_t now, void *arg) { ... }
*/
void timer_set_oneshot(timer_t *timer, time_t delay, timer_callback callback, void *arg)
{
if (delay == 0)
delay = 1;
timer_set(timer, delay, 0, callback, arg);
}
/**
* @brief Set up a timer that executes repeatedly
*
* This function specifies a callback function to be called after a specified
* delay. The function will be called repeatedly.
*
* @param timer The timer to use
* @param delay The delay, in ms, before the timer is executed
* @param callback The function to call when the timer expires
* @param arg The argument to pass to the callback
*
* The timer function is declared as:
* enum handler_return callback(struct timer *, time_t now, void *arg) { ... }
*/
void timer_set_periodic(timer_t *timer, time_t period, timer_callback callback, void *arg)
{
if (period == 0)
period = 1;
timer_set(timer, period, period, callback, arg);
}
/**
* @brief Cancel a pending timer
*/
void timer_cancel(timer_t *timer)
{
DEBUG_ASSERT(timer->magic == TIMER_MAGIC);
enter_critical_section();
#if PLATFORM_HAS_DYNAMIC_TIMER
timer_t *oldhead = list_peek_head_type(&timer_queue, timer_t, node);
#endif
if (list_in_list(&timer->node))
list_delete(&timer->node);
/* to keep it from being reinserted into the queue if called from
* periodic timer callback.
*/
timer->periodic_time = 0;
timer->callback = NULL;
timer->arg = NULL;
#if PLATFORM_HAS_DYNAMIC_TIMER
/* see if we've just modified the head of the timer queue */
timer_t *newhead = list_peek_head_type(&timer_queue, timer_t, node);
if (newhead == NULL) {
// TRACEF("clearing old hw timer, nothing in the queue\n");
platform_stop_timer();
} else if (newhead != oldhead) {
time_t delay;
time_t now = current_time();
if (TIME_LT(newhead->scheduled_time, now))
delay = 0;
else
delay = newhead->scheduled_time - now;
// TRACEF("setting new timer to %d\n", delay);
platform_set_oneshot_timer(timer_tick, NULL, delay);
}
#endif
exit_critical_section();
}
/* called at interrupt time to process any pending timers */
static enum handler_return timer_tick(void *arg, time_t now)
{
timer_t *timer;
enum handler_return ret = INT_NO_RESCHEDULE;
#if THREAD_STATS
thread_stats.timer_ints++;
#endif
// TRACEF("now %d\n", now);
for (;;) {
/* see if there's an event to process */
timer = list_peek_head_type(&timer_queue, timer_t, node);
if (likely(!timer || TIME_LT(now, timer->scheduled_time)))
break;
/* process it */
DEBUG_ASSERT(timer->magic == TIMER_MAGIC);
list_delete(&timer->node);
// timer = list_remove_head_type(&timer_queue, timer_t, node);
// ASSERT(timer);
// TRACEF("dequeued timer %p, scheduled %d periodic %d\n", timer, timer->scheduled_time, timer->periodic_time);
#if THREAD_STATS
thread_stats.timers++;
#endif
bool periodic = timer->periodic_time > 0;
// TRACEF("timer %p firing callback %p, arg %p\n", timer, timer->callback, timer->arg);
if (timer->callback(timer, now, timer->arg) == INT_RESCHEDULE)
ret = INT_RESCHEDULE;
/* if it was a periodic timer and it hasn't been requeued
* by the callback put it back in the list
*/
if (periodic && !list_in_list(&timer->node) && timer->periodic_time > 0) {
// TRACEF("periodic timer, period %u\n", (uint)timer->periodic_time);
timer->scheduled_time = now + timer->periodic_time;
insert_timer_in_queue(timer);
}
}
#if PLATFORM_HAS_DYNAMIC_TIMER
/* reset the timer to the next event */
timer = list_peek_head_type(&timer_queue, timer_t, node);
if (timer) {
/* has to be the case or it would have fired already */
ASSERT(TIME_GT(timer->scheduled_time, now));
time_t delay = timer->scheduled_time - now;
// TRACEF("setting new timer for %u msecs for event %p\n", (uint)delay, timer);
platform_set_oneshot_timer(timer_tick, NULL, delay);
}
#else
/* let the scheduler have a shot to do quantum expiration, etc */
/* in case of dynamic timer, the scheduler will set up a periodic timer */
if (thread_timer_tick() == INT_RESCHEDULE)
ret = INT_RESCHEDULE;
#endif
// XXX fix this, should return ret
return INT_RESCHEDULE;
}
void timer_init(void)
{
list_initialize(&timer_queue);
/* register for a periodic timer tick */
platform_set_periodic_timer(timer_tick, NULL, 10); /* 10ms */
}