Kernel thread in linux

Are kernel threads processes and daemons?

From Mauerer’s Linux Kernel Architecture,

Kernel threads are processes started directly by the kernel itself. They delegate a kernel function to a separate process and execute it there in ‘‘parallel‘‘ to the other processes in the system (and, in fact, in parallel to execution of the kernel itself). Kernel threads are often referred to as (kernel) daemons. They are used to perform, for example, the following tasks:

  • To periodically synchronize modified memory pages with the block device from which the pages originate (e.g., files mapped using mmap ).
  • To write memory pages into the swap area if they are seldom used.
  • To manage deferred actions.
  • To implement transaction journals for filesystems.

Basically, there are two types of kernel thread:

  • Type 1 — The thread is started and waits until requested by the kernel to perform a specific action.
  • Type 2 — Once started, the thread runs at periodic intervals, checks the utilization of a specific resource, and takes action when utilization exceeds or falls below a set limit value. The kernel uses this type of thread for continuous monitoring tasks.

Since Mauerer’s book says kernel threads are processes, I think that they must be running in user mode, instead of kernel mode. (or am I wrong? Can a process run in either user mode or kernel mode at different times, or only one mode?)

But Bovet’s Understanding Linux Kernel says kernel threads are running only in kernel mode (see the quote below). Are the concepts of «kernel thread» in the two books the same concept?

Traditional Unix systems delegate some critical tasks to intermittently running processes, including flushing disk caches, swapping out unused pages, servicing network connections, and so on. Indeed, it is not efficient to perform these tasks in strict linear fashion; both their functions and the end user processes get better response if they are scheduled in the background. Because some of the system processes run only in Kernel Mode, modern operating systems delegate their functions to kernel threads, which are not encumbered with the unnecessary User Mode context. In Linux, kernel threads differ from regular processes in the following ways:

  • Kernel threads run only in Kernel Mode, while regular processes run alterna- tively in Kernel Mode and in User Mode.
  • Because kernel threads run only in Kernel Mode, they use only linear addresses greater than PAGE_OFFSET . Regular processes, on the other hand, use all four gigabytes of linear addresses, in either User Mode or Kernel Mode.

Mauerer’s book says kernel threads are started directly by the kernel, and it seems to also say that daemons are synonyms of kernel threads. So I think daemons must be started directly by the kernel.

But https://unix.stackexchange.com/a/193918/674 says that screen ‘s daemon is started by screen user interface (see the quote below). I think screen user interface is a process, instead of the kernel. Are the concepts of daemon in Mauerer’s book and in the linked reply the same concept?

When you first start screen , you are actually starting a user interface (ui), which by default will create a daemon (the session manager).

In general, How do you understand the concepts of «kernel threads», «process», and «daemon», their relations and their differences?

Источник

What is a Kernel thread?

i am just started coding of device driver and new to threading, went through many documents for getting an idea about threads. i still have some doubts.

  1. what is a kernel thread ?.
  2. how it differs from user thread ?.
  3. what is the relationship between the two threads ?.
  4. how can i implement kernel threads ?.
  5. where can i see the output of the implementation?.

Can anyone help me ?. thanks.

Читайте также:  Установка windows 10 по сети без сервера

4 Answers 4

  1. A kernel thread is a task_struct with no userspace components.
  2. Besides the lack of userspace, it has different ancestors ( kthreadd kernel thread instead of the init process) and is created by a kernel-only API instead of sequences of clone from fork/exec system calls.
  3. Two kernel threads have kthreadd as a parent. Apart from that, kernel threads enjoy the same «independence» one from another as userspace processes.
  4. Use the kthread_run function/macro from the kthread.h header You will most probably have to write a kernel module in order to call this function, so you should take a look a the Linux Device Drivers
  5. If you are referring to the text output of your implementation (via printk calls), you can see this output in the kernel log using the dmesg command.

A kernel thread is a kernel task running only in kernel mode; it usually has not been created by fork() or clone() system calls. An example is kworker or kswapd .

You probably should not implement kernel threads if you don’t know what they are.

Google gives many pages about kernel threads, e.g. Frey’s page.

user threads & stack:

Each thread has its own stack so that it can use its own local variables, thread’s share global variables which are part of .data or .bss sections of linux executable. Since threads share global variables i.e we use synchronization mechanisms like mutex when we want to access/modify global variables in multi threaded application. Local variables are part of thread individual stack, so no need of any synchronization.

Kernel threads Kernel threads have emerged from the need to run kernel code in process context. Kernel threads are the basis of the workqueue mechanism. Essentially, a thread kernel is a thread that only runs in kernel mode and has no user address space or other user attributes.

To create a thread kernel, use kthread_create():

kernel threads & stack: Kernel threads are used to do post processing tasks for kernel like pdf flush threads, workq threads etc. Kernel threads are basically new process only without address space(can be created using clone() call with required flags), means they can’t switch to user-space. kernel threads are schedulable and preempt-able as normal processes.

kernel threads have their own stacks, which they use to manage local info.

Since you’re comparing kernel threads with user[land] threads, I assume you mean something like the following.

The normal way of implementing threads nowadays is to do it in the kernel, so those can be considered «normal» threads. It’s however also possible to do it in userland, using signals such as SIGALRM, whose handler will save the current process state (registers, mostly) and change them to another one previously saved. Several OSes used this as a way to implement threads before they got proper kernel thread support. They can be faster, since you don’t have to go into kernel mode, but in practice they’ve faded away.

There’s also cooperative userland threads, where one thread runs until it calls a special function (usually called yield), which then switches to another thread in a similar way as with SIGALRM above. The advantage here is that the program is in total control, which can be useful when you have timing concerns (a game for example). You also don’t have to care much about thread safety. The big disadvantage is that only one thread can run at a time, and therefore this method is also uncommon now that processors have multiple cores.

Читайте также:  Имя текущей директории linux

Kernel threads are implemented in the kernel. Perhaps you meant how to use them? The most common way is to call pthread_create .

Источник

How to join a thread in Linux kernel?

The main question is: How we can wait for a thread in Linux kernel to complete? I have seen a few post concerned about proper way of handling threads in Linux kernel but i’m not sure how we can wait for a single thread in the main thread to be completed (suppose we need the thread[3] be done then proceed):

2 Answers 2

AFAIK there is no equivalent of pthread_join() in kernel. Also, I feel like your pattern (of starting bunch of threads and waiting only for one of them) is not really common in kernel. That being said, there kernel does have few synchronization mechanism that may be used to accomplish your goal.

Note that those mechanisms will not guarantee that the thread finished, they will only let main thread know that they finished doing the work they were supposed to do. It may still take some time to really stop this tread and free all resources.

Semaphores

You can create a locked semaphore, then call down in your main thread. This will put it to sleep. Then you will up this semaphore inside of your thread just before exiting. Something like:

This should work but is not the most optimal solution. I mention this as it’s a known pattern that is also used in userspace. Semaphores in kernel are designed for cases where it’s mostly available and this case has high contention. So a similar mechanism optimized for this case was created.

Completions

You can declare completions using:

Then you can use wait_for_completion(&comp); instead of down() to wait in main thread and complete(&comp); instead of up() in your thread.

Here’s the full example:

Multiple threads

I don’t really see why you would start 5 identical threads and only want to wait for 3rd one but of course you could send different data to each thread, with a field describing it’s id, and then call up or complete only if this id equals 3. That’s shown in the completion example. There are other ways to do this, this is just one of them.

Word of caution

Go read some more about those mechanisms before using any of them. There are some important details I did not write about here. Also those examples are simplified and not tested, they are here just to show the overall idea.

Источник

Kernel Level Thread Library

I have to implement kernel level thread but while searching on the net I found that there are three ways to create kernel level thread in linux:

It was written somewhere that linuxThreads are now abandoned. But I am unable to find current support of NPTL & kthread. Also I am unable to find any source that can simply explain me how to use their functionality.

Which is the currently supported and good library to use kernel level thread?

Also pls share any resource for installing these library and also using them?

2 Answers 2

You are confusing two very different definitions of «kernel thread».

LinuxThreads and NPTL are implementations of POSIX pthreads for user-space processes. They use a 1-to-1 mapping of kernel scheduling entities to user-space threads. They are sometimes described as kernel threads implementations only because they create threads that are scheduled by the kernel.

LinuxThreads is unsupported and entirely obsolete. NPTL is now part of glibc, so you already have it. There’s nothing special to install. You use these the same way you use any POSIX threading library, with calls to functions like pthread_create .

Читайте также:  C004f074 ошибка активации windows 10 kms

Actual kernel threads run kernel code. None of those libraries are relevant since they’re all user-space libraries. Have a look at functions like kthread_run . There’s no magic, no secret. Write kernel code the way similar kernel code is written. (Knowledge and experience in writing kernel code is needed. It’s, unfortunately, not simple.)

Источник

Linux World

Pages

Kernel Thread Creation : 1

Kernel Thread Creation : 1

The Linux way of handling threads is unique when compared to the traditional approach. Generally a thread and a process are treated in different ways, but in case of linux thread is also just another process and is handled in the same fashion as any other process. Let us take write a small module to create a kernel thread and try to understand the various functions involved in the same.

To work with threads you would need the header file linux/kthread.h A thread is created by the call to the function

The function takes the following arguments

function: The function that the thread has to execute

data : The «data» to be passed to the function

name: The name by which the process will be recognised in the kernel.

A thread created using the above call does not run but only gets created. To run the thread we need to call the function «wake_up_process» passing the thread id that is returned by «kthread_create».

When the wake_up_process is called the function passed to kthread_create gets executed.

To stop a thread that is running we need to call the kthread_stop(struct task_struct *threadid) where threadid is the same that is returned by the kthread_create call.

To understand the working of these system calls better let us create a module and create a kernel thread in it.

We need the following header files

Let us spawn a kernel thread as soon as the module gets inserted into the kernel, so we will have to add the kernel creation part in the init function.

In the call to kthread_create we have passed the following arguments

thread_fn : Which is the function that will be run as the thread.

NULL: As we are not passing any data to the function we have kept this NULL.

name: The process will be named «thread1» in the list of processes .

Now we need to implement the function «thread_fn» . The following functions prints a statement and waits for one minute before exiting. (If the syntax of waiting and jiffies is not clear right now, we will cover that soon ) .

The wait is just to give us enough time to look at the thread running.

To stop thread we can use the system call kthread_stop(struct task_struct *threadid). Note that in case the thread does not exist this call would end up in segmentation fault. The function kthread_stop does not terminate the thread but waits for the thread to terminate itself.

In our clean up function we will call kthread_stop and let the thread exit itself.

Putting all the above code together the complete code is as follows

The makefile need to compile the code is, assuming the above code is saved as threads.c

Now run the following commands

If this happens with out any errors, run the following command to see the thread running.

The timer in previous to last column shows from how long the thread has been running.

To remove the module run the command. But make sure you wait for a whole minute before running the command, because te

If you try to remove thread before a minute it will keep waiting until the thread exits which happens only at the end of a minute.

Источник

Оцените статью