Sunday, April 3, 2016

Introduction to Kthreads in Linux Kernel

Threads are programming abstractions used in concurrent processing. A kernel thread is a way to implement background tasks inside the kernel. A background task can be busy handling asynchronous events or can be asleep, waiting for an event to occur. Kernel threads are similar to user processes, except that they live in kernel space and have access to kernel functions and data structures. Like user processes, kernel threads appear to monopolize the processor because of preemptive scheduling.

To see these threads, run ps -ef from command line and note all of the processes in [square brackets] at the beginning of the listing are kernel threads. 





Examples of kthreads

(A). [ksoftirqd/n] is a kthread supporting implementation of softirqs in Kernel. where 'n' represents the core in SMP systems.Soft IRQs are raised by interrupt handlers to request “bottom half” processing of portions of the interrupt handler whose execution can be deferred. The idea is to minimize the code inside interrupt handlersm which results in reduced interrupt-off times in the system, thus resulting in lower latencies. ksoftirqd ensures that a high load of soft IRQs neither starves the soft IRQs nor overwhelms the system. On Symmetric Multi-Processing (SMP) machines, where multiple thread instances can run on different processors in parallel, one instance of ksoftirqd is created per processor to improve throughput.

(B). The [events/n] threads (where n is the processor number) help implement work queues, which are another way of deferring work in the kernel. If a part of the kernel wants to defer execution of work, it can either create its own work queue or make use of the default events/worker thread.

(C). The [pdflush] kernel thread flushes dirty pages from the page cache. 

(D). The [khubd] thread, part of the Linux USB core, monitors the machine’s USB hub and configures USB devices when they are hot-plugged into the system.


Example from Kernel Source

File :- kernel/time/clocksource.c

static int clocksource_watchdog_kthread(void *data)
{
mutex_lock(&clocksource_mutex);
if (__clocksource_watchdog_kthread())
clocksource_select();
mutex_unlock(&clocksource_mutex);
return 0;
}

static void __clocksource_watchdog_kthread(unsigned long data)
{
--- CODE -----
}

No comments:

Post a Comment