purpose
this examples shows how to create and stop a kernel thread.
the driver is implemented as a loadable module. in the init_module() routine five kernel threads are created. this kernel threads sleep one second, wake up, print a message and fall asleep again. on unload of the module (cleanup_module), the kernel threads are killed.
the example has been tested with linux kernel 2.4.2 on intel (uni processor only) and alpha platform (compaq personal workstation 500au (uni processor), ds20 and es40 (smp).
a version for the 2.2 kernel can be found here. note: depending on the context of the creator of the threads the new threads may inherit properties from the parent you do not want to have. the new version avoids this by having keventd create the threads. the 2.2. kernel do not have a keventd, so this approach is not implementable there.
functions in example
* start_kthread: creates a new kernel thread. can be called from any process context but not from interrupt. the functions blocks until the thread started.
* stop_kthread: stop the thread. can be called from any process context but the thread to be terminated. cannot be called from interrupt context. the function blocks until the thread terminated.
* init_kthread: sets the environment of the new threads. is to be called out of the created thread.
* exit_kthread: needs to be called by the thread to be terminated on exit
creation of new thread
a new thread is created with kernel_thread(). the thread inherits properties from its parents. to make sure that we do not get any weired properties, we let keventd create the new thread.
the new thread is created with start_kthread(). it uses a semaphore to block until the new thread is running. a down() blocks the start_kthread() routine until the corresponding up() call in init_kthread() is executed.
the new thread must call init_kthread() in order to let the creator continue.
stop of new thread
stop_kthread() sets a flag that the thread uses to determine whether do die or not and sends a sigkill to the thread. this signal causes the thread to be woken up. on wakeup it will check for the flag and then terminate itself by calling exit_kthread and returning from the thread function. with a semaphore the stop_kthread() function blocks until the thread terminated.
initialization of new thread
within the new created thread, init_kthread() needs to be called. this function sets a signal mask, initialises a wait queue, the termination flag and sets a new name for the thread. with a up() call it notifies the creator that the setup is done.
exit of new thread
when the thread receives the notification to terminate itself, is calls the exit_kthread() function. it notifies the stop_kthread() function that it terminated with an up() call.
the new thread itself
the new thread is implemented in the example_thread() function. it runs an endless loop (for(;;)). in the loop it falls asleep with the interruptible_sleep_on_timeout() function. it comes out of this function either when the timeout expires or when a signal got caught.
the "work" in the thread is to print out a message with printk.
kernel versions
the example has been tested on 2.4.2.
example device driver code
the example consists of four files: kthread.h, kthread.c, thread_drv.c and a makefile
kthread.h
#ifndef _kthread_h
#define _kthread_h
#include
#include
#include
#include
#include
#include
#include
#include
/* a structure to store all information we need
for our thread */
typedef struct kthread_struct
{
/* private data */
/* linux task structure of thread */
struct task_struct *thread;
/* task queue need to launch thread */
struct tq_struct tq;
/* function to be started as thread */
void (*function) (struct kthread_struct *kthread);
/* semaphore needed on start and creation of thread. */
struct semaphore startstop_sem;
/* public data */
/* queue thread is waiting on. gets initialized by
init_kthread, can be used by thread itself.
*/
wait_queue_head_t queue;
/* flag to tell thread whether to die or not.
when the thread receives a signal, it must check
the value of terminate and call exit_kthread and terminate
if set.
*/
int terminate;
/* additional data to pass to kernel thread */
void *arg;
} kthread_t;
/* prototypes */
/* start new kthread (called by creator) */
void start_kthread(void (*func)(kthread_t *), kthread_t *kthread);
/* stop a running thread (called by "killer") */
void stop_kthread(kthread_t *kthread);
/* setup thread environment (called by new thread) */
void init_kthread(kthread_t *kthread, char *name);
/* cleanup thread environment (called by thread upon receiving termination signal) */
void exit_kthread(kthread_t *kthread);
#endif
kthread.c
#include
#include
#if defined(modversions)
#include
#endif
#include
#include
#include
#include
#include
#include
#include
#include "kthread.h"
/* private functions */
static void kthread_launcher(void *data)
{
kthread_t *kthread = data;
kernel_thread((int (*)(void *))kthread->function, (void *)kthread, 0);
}
/* public functions */
/* create a new kernel thread. called by the creator. */
void start_kthread(void (*func)(kthread_t *), kthread_t *kthread)
{
/* initialize the semaphore:
we start with the semaphore locked. the new kernel
thread will setup its stuff and unlock it. this
control flow (the one that creates the thread) blocks
in the down operation below until the thread has reached
the up() operation.
*/
init_mutex_locked(&kthread->startstop_sem);
/* store the function to be executed in the data passed to
the launcher */
kthread->function=func;
/* create the new thread my running a task through keventd */
/* initialize the task queue structure */
kthread->tq.sync = 0;
init_list_head(&kthread->tq.list);
kthread->tq.routine = kthread_launcher;
kthread->tq.data = kthread;
/* and schedule it for execution */
schedule_task(&kthread->tq);
/* wait till it has reached the setup_thread routine */
down(&kthread->startstop_sem);
}
/* stop a kernel thread. called by the removing instance */
void stop_kthread(kthread_t *kthread)
{
if (kthread->thread == null)
{
printk("stop_kthread: killing non existing thread!\n");
return;
}
/* this function needs to be protected with the big
kernel lock (lock_kernel()). the lock must be
grabbed before changing the terminate
flag and released after the down() call. */
lock_kernel();
/* initialize the semaphore. we lock it here, the
leave_thread call of the thread to be terminated
will unlock it. as soon as we see the semaphore
unlocked, we know that the thread has exited.
*/
init_mutex_locked(&kthread->startstop_sem);
/* we need to do a memory barrier here to be sure that
the flags are visible on all cpus.
*/
mb();
/* set flag to request thread termination */
kthread->terminate = 1;
/* we need to do a memory barrier here to be sure that
the flags are visible on all cpus.
*/
mb();
kill_proc(kthread->thread->pid, sigkill, 1);
/* block till thread terminated */
down(&kthread->startstop_sem);
/* release the big kernel lock */
unlock_kernel();
/* now we are sure the thread is in zombie state. we
notify keventd to clean the process up.
*/
kill_proc(2, sigchld, 1);
}
/* initialize new created thread. called by the new thread. */
void init_kthread(kthread_t *kthread, char *name)
{
/* lock the kernel. a new kernel thread starts without
the big kernel lock, regardless of the lock state
of the creator (the lock level is *not* inheritated)
*/
lock_kernel();
/* fill in thread structure */
kthread->thread = current;
/* set signal mask to what we want to respond */
siginitsetinv(¤t->blocked, sigmask(sigkill)|sigmask(sigint)|sigmask(sigterm));
/* initialise wait queue */
init_waitqueue_head(&kthread->queue);
/* initialise termination flag */
kthread->terminate = 0;
/* set name of this process (max 15 chars 0 !) */
sprintf(current->comm, name);
/* let others run */
unlock_kernel();
/* tell the creator that we are ready and let him continue */
up(&kthread->startstop_sem);
}
/* cleanup of thread. called by the exiting thread. */
void exit_kthread(kthread_t *kthread)
{
/* we are terminating */
/* lock the kernel, the exit will unlock it */
lock_kernel();
kthread->thread = null;
mb();
/* notify the stop_kthread() routine that we are terminating. */
up(&kthread->startstop_sem);
/* the kernel_thread that called clone() does a do_exit here. */
/* there is no race here between execution of the "killer" and real termination
of the thread (race window between up and do_exit), since both the
thread and the "killer" function are running with the kernel lock held.
the kernel lock will be freed after the thread exited, so the code
is really not executed anymore as soon as the unload functions gets
the kernel lock back.
the init process may not have made the cleanup of the process here,
but the cleanup can be done safely with the module unloaded.
*/
}
thread_drv.c
#include
#include
#include
#if defined(modversions)
#include
#endif
#include
#include
#include
#include
#include "kthread.h"
#define nthreads 5
/* the variable that contains the thread data */
kthread_t example[nthreads];
/* prototype for the example thread */
static void example_thread(kthread_t *kthread);
/* load the module */
int init_module(void)
{
int i;
/* create new kernel threads */
for (i=0; i start_kthread(example_thread, &example[i]);
return(0);
}
/* remove the module */
void cleanup_module(void)
{
int i;
/* terminate the kernel threads */
for (i=0; i stop_kthread(&example[i]);
return;
}
/* this is the thread function that we are executing */
static void example_thread(kthread_t *kthread)
{
/* setup the thread environment */
init_kthread(kthread, "example thread");
printk("hi, here is the kernel thread\n");
/* an endless loop in which we are doing our work */
for(;;)
{
/* fall asleep for one second */
interruptible_sleep_on_timeout(&kthread->queue, hz);
/* we need to do a memory barrier here to be sure that
the flags are visible on all cpus.
*/
mb();
/* here we are back from sleep, either due to the timeout
(one second), or because we caught a signal.
*/
if (kthread->terminate)
{
/* we received a request to terminate ourself */
break;
}
/* this is normal work to do */
printk("example thread: thread woke up\n");
}
/* here we go only in case of termination of the thread */
/* cleanup the thread, leave */
exit_kthread(kthread);
/* returning from the thread here calls the exit functions */
}
makefile
# set to your kernel tree
kernel = /usr/src/linux
# get the linux architecture. needed to find proper include file for cflags
arch=$(shell uname -m | sed -e s/i.86/i386/ -e s/sun4u/sparc64/ -e s/arm.*/arm/ -e s/sa110/arm/)
# set default flags to compile module
cflags = -d__kernel__ -dmodule -i$(kernel)/include
cflags = -wall -wstrict-prototypes -o2 -fomit-frame-pointer -fno-strict-aliasing
all: thread_mod.o
# get configuration of kernel
include $(kernel)/.config
# modify cflags with architecture specific flags
include $(kernel)/arch/${arch}/makefile
# enable the module versions, if configured in kernel source tree
ifdef config_modversions
cflags = -dmodversions -include $(kernel)/include/linux/modversions.h
endif
# enable smp, if configured in kernel source tree
ifdef config_smp
cflags = -d__smp__
endif
# note: we are compiling the driver object file and then linking
# we link it into the module. with just one object file as in
# this example this is not needed. we can just load the object
# file produced by gcc
# link the thread driver module
thread_mod.o: thread_drv.o kthread.o
ld -r -o thread_mod.o thread_drv.o kthread.o
# compile the kthread object file
kthread.o: kthread.c kthread.h
gcc $(cflags) -c kthread.c
# compile the thread driver
thread_drv.o: thread_drv.c kthread.h
gcc $(cflags) -c thread_drv.c
clean:
rm -f *.o
ref:
阅读(2597) | 评论(0) | 转发(0) |