本文转载自:Tasklets

1. Introduction

Tasklets are used in kernel to schedule a function some time in future. The major use of the tasklet is to schedule the bottom half of an interrupt service routine.

Bottom half is the part of the interrupt service routine which is not time critical and can be executed after a little delay from the time interrupt is generated. This helps is releasing the interrupt line quickly and processing more interrupts.

Let us look at how we can create a tasklet and schedule it in a kernel module.

The structure, tasklet_struct, declared in interrupt.h looks as follows

1
2
3
4
5
6
7
8
struct tasklet_struct
{
struct tasklet_struct *next;
unsigned long state;
atomic_t count;
void (*func)(unsigned long);
unsigned long data;
};

The members of the structure that has to be initialized in the module are :

  1. func : Pointer to the function that needs to scheduled for execution at a later time

  2. data : Data to be passed to the function func

The other members are initialized by the kernel as follows:

  • count : holds a nonzero value if the tasklet is disabled and 0 if it is enabled.
  • states : TASKLET_STATE_SCHED , which denotes it is scheduled to run. TASKLET_STATE_RUN , which denotes it is running.

There are two ways of creating a tasklet:
1. Creating Statically: (using Macros)

  1. DECLARE_TASKLET(name, func, data): Creates a tasklet in the enabled state
  2. DECLARE_TASKLET_DISABLED(name, func, data): Creates a tasklet in the disabled state

If the tasklets is created using the second macro, it needs to be enabled explicitly.

For details, just reference this Using Macros.
2. Creating in runtime

  • tasklet_init(name,func,data)

Where “name” is the name of the taskelet, “func” in the function which has to be executed as a part of the tasklet and “data” is the data that has to passed to func.

  • A tasklet is a softirq and hence runs in an interrupt context. Thus while executing the function you are not allowed to go to sleep and have to use proper locking for any data that is shared with other tasklets.

  • Scheduling a tasklet:

Once the tasklet has been created, it needs to be scheduled which is done by the function tasklet_schedule(&tasklet)

  • Enable and Disable :

The tasklets can be disabled, if they are not running already, using tasklet_disable(&taskelt)

and enabled using tasklet_enble(&tasklet)

When does the tasklet actually get scheduled can not be controlled and is decided by the scheduler depending on the load on the processor. If the processor is free, it might get scheduled immediately.

For details, just reference this using tasklet_init.