LINUX DEVICE DRIVERS 3rd edition phần 4 - Pdf 21

This is the Title of the Book, eMatter Edition
Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved.
174
|
Chapter 6: Advanced Char Driver Operations
The scullsingle device maintains an atomic_t variable called scull_s_available; that
variable is initialized to a value of one, indicating that the device is indeed available.
The open call decrements and tests
scull_s_available and refuses access if some-
body else already has the device open:
static atomic_t scull_s_available = ATOMIC_INIT(1);
static int scull_s_open(struct inode *inode, struct file *filp)
{
struct scull_dev *dev = &scull_s_device; /* device information */
if (! atomic_dec_and_test (&scull_s_available)) {
atomic_inc(&scull_s_available);
return -EBUSY; /* already open */
}
/* then, everything else is copied from the bare scull device */
if ( (filp->f_flags & O_ACCMODE) = = O_WRONLY)
scull_trim(dev);
filp->private_data = dev;
return 0; /* success */
}
The release call, on the other hand, marks the device as no longer busy:
static int scull_s_release(struct inode *inode, struct file *filp)
{
atomic_inc(&scull_s_available); /* release the device */
return 0;
}
Normally, we recommend that you put the open flag scull_s_available within the

spin_lock(&scull_u_lock);
if (scull_u_count &&
(scull_u_owner != current->uid) && /* allow user */
(scull_u_owner != current->euid) && /* allow whoever did su */
!capable(CAP_DAC_OVERRIDE)) { /* still allow root */
spin_unlock(&scull_u_lock);
return -EBUSY; /* -EPERM would confuse the user */
}
if (scull_u_count = = 0)
scull_u_owner = current->uid; /* grab it */
scull_u_count++;
spin_unlock(&scull_u_lock);
Note that the sculluid code has two variables (scull_u_owner and scull_u_count)
that control access to the device and that could be accessed concurrently by multi-
ple processes. To make these variables safe, we control access to them with a spin-
lock (
scull_u_lock). Without that locking, two (or more) processes could test
scull_u_count at the same time, and both could conclude that they were entitled to
take ownership of the device. A spinlock is indicated here, because the lock is held
for a very short time, and the driver does nothing that could sleep while holding the
lock.
We chose to return
-EBUSY and not -EPERM, even though the code is performing a per-
mission check, in order to point a user who is denied access in the right direction.
The reaction to “Permission denied” is usually to check the mode and owner of the
/dev file, while “Device busy” correctly suggests that the user should look for a pro-
cess already using the device.
This code also checks to see if the process attempting the open has the ability to
override file access permissions; if so, the open is allowed even if the opening pro-
cess is not the owner of the device. The

The scullwuid device is a version of sculluid that waits for the device on open instead
of returning
-EBUSY. It differs from sculluid only in the following part of the open
operation:
spin_lock(&scull_w_lock);
while (! scull_w_available( )) {
spin_unlock(&scull_w_lock);
if (filp->f_flags & O_NONBLOCK) return -EAGAIN;
if (wait_event_interruptible (scull_w_wait, scull_w_available( )))
return -ERESTARTSYS; /* tell the fs layer to handle it */
spin_lock(&scull_w_lock);
}
if (scull_w_count = = 0)
scull_w_owner = current->uid; /* grab it */
scull_w_count++;
spin_unlock(&scull_w_lock);
The implementation is based once again on a wait queue. If the device is not cur-
rently available, the process attempting to open it is placed on the wait queue until
the owning process closes the device.
The release method, then, is in charge of awakening any pending process:
static int scull_w_release(struct inode *inode, struct file *filp)
{
int temp;
spin_lock(&scull_w_lock);
scull_w_count ;
temp = scull_w_count;
spin_unlock(&scull_w_lock);
,ch06.8719 Page 176 Friday, January 21, 2005 10:44 AM
This is the Title of the Book, eMatter Edition
Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved.

resents. When copies of the device are created by the software driver, we call them
virtual devices—just as virtual consoles use a single physical tty device.
Although this kind of access control is rarely needed, the implementation can be
enlightening in showing how easily kernel code can change the application’s perspec-
tive of the surrounding world (i.e., the computer).
The /dev/scullpriv device node implements virtual devices within the scull package.
The scullpriv implementation uses the device number of the process’s controlling tty
as a key to access the virtual device. Nonetheless, you can easily modify the sources to
use any integer value for the key; each choice leads to a different policy. For example,
using the
uid leads to a different virtual device for each user, while using a pid key cre-
ates a new device for each process accessing it.
The decision to use the controlling terminal is meant to enable easy testing of the
device using I/O redirection: the device is shared by all commands run on the same
,ch06.8719 Page 177 Friday, January 21, 2005 10:44 AM
This is the Title of the Book, eMatter Edition
Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved.
178
|
Chapter 6: Advanced Char Driver Operations
virtual terminal and is kept separate from the one seen by commands run on another
terminal.
The open method looks like the following code. It must look for the right virtual
device and possibly create one. The final part of the function is not shown because it
is copied from the bare scull, which we’ve already seen.
/* The clone-specific data structure includes a key field */
struct scull_listitem {
struct scull_dev device;
dev_t key;
struct list_head list;

Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved.
Quick Reference
|
179
dev_t key;
if (!current->signal->tty) {
PDEBUG("Process \"%s\" has no ctl tty\n", current->comm);
return -EINVAL;
}
key = tty_devnum(current->signal->tty);
/* look for a scullc device in the list */
spin_lock(&scull_c_lock);
dev = scull_c_lookfor_device(key);
spin_unlock(&scull_c_lock);
if (!dev)
return -ENOMEM;
/* then, everything else is copied from the bare scull device */
The release method does nothing special. It would normally release the device on last
close, but we chose not to maintain an open count in order to simplify the testing of
the driver. If the device were released on last close, you wouldn’t be able to read the
same data after writing to the device, unless a background process were to keep it
open. The sample driver takes the easier approach of keeping the data, so that at the
next open, you’ll find it there. The devices are released when scull_cleanup is called.
This code uses the generic Linux linked list mechanism in preference to reimple-
menting the same capability from scratch. Linux lists are discussed in Chapter 11.
Here’s the release implementation for /dev/scullpriv, which closes the discussion of
device methods.
static int scull_c_release(struct inode *inode, struct file *filp)
{
/*

_IOC(dir,type,nr,size)
_IO(type,nr)
_IOR(type,nr,size)
_IOW(type,nr,size)
_IOWR(type,nr,size)
Macros used to create an ioctl command.
_IOC_DIR(nr)
_IOC_TYPE(nr)
_IOC_NR(nr)
_IOC_SIZE(nr)
Macros used to decode a command. In particular, _IOC_TYPE(nr) is an OR com-
bination of
_IOC_READ and _IOC_WRITE.
#include <asm/uaccess.h>
int access_ok(int type, const void *addr, unsigned long size);
Checks that a pointer to user space is actually usable. access_ok returns a non-
zero value if the access should be allowed.
VERIFY_READ
VERIFY_WRITE
The possible values for the type argument in access_ok. VERIFY_WRITE is a super-
set of
VERIFY_READ.
#include <asm/uaccess.h>
int put_user(datum,ptr);
int get_user(local,ptr);
int __put_user(datum,ptr);
int __get_user(local,ptr);
Macros used to store or retrieve a datum to or from user space. The number of
bytes being transferred depends on
sizeof(*ptr). The regular versions call

void wake_up_interruptible_nr(struct wait_queue **q, int nr);
void wake_up_all(struct wait_queue **q);
void wake_up_interruptible_all(struct wait_queue **q);
void wake_up_interruptible_sync(struct wait_queue **q);
Wake processes that are sleeping on the queue q. The _interruptible form wakes
only interruptible processes. Normally, only one exclusive waiter is awakened,
but that behavior can be changed with the _nr or _all forms. The _sync version
does not reschedule the CPU before returning.
#include <linux/sched.h>
set_current_state(int state);
Sets the execution state of the current process. TASK_RUNNING means it is ready to
run, while the sleep states are
TASK_INTERRUPTIBLE and TASK_UNINTERRUPTIBLE.
void schedule(void);
Selects a runnable process from the run queue. The chosen process can be
current or a different one.
,ch06.8719 Page 181 Friday, January 21, 2005 10:44 AM
This is the Title of the Book, eMatter Edition
Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved.
182
|
Chapter 6: Advanced Char Driver Operations
typedef struct { /* */ } wait_queue_t;
init_waitqueue_entry(wait_queue_t *entry, struct task_struct *task);
The wait_queue_t type is used to place a process onto a wait queue.
void prepare_to_wait(wait_queue_head_t *queue, wait_queue_t *wait, int state);
void prepare_to_wait_exclusive(wait_queue_head_t *queue, wait_queue_t *wait,
int state);
void finish_wait(wait_queue_head_t *queue, wait_queue_t *wait);
Helper functions that can be used to code a manual sleep.

Deferred Work
At this point, we know the basics of how to write a full-featured char module. Real-
world drivers, however, need to do more than implement the operations that control
a device; they have to deal with issues such as timing, memory management, hard-
ware access, and more. Fortunately, the kernel exports a number of facilities to ease
the task of the driver writer. In the next few chapters, we’ll describe some of the ker-
nel resources you can use. This chapter leads the way by describing how timing
issues are addressed. Dealing with time involves the following tasks, in order of
increasing complexity:
• Measuring time lapses and comparing times
• Knowing the current time
• Delaying operation for a specified amount of time
• Scheduling asynchronous functions to happen at a later time
Measuring Time Lapses
The kernel keeps track of the flow of time by means of timer interrupts. Interrupts
are covered in detail in Chapter 10.
Timer interrupts are generated by the system’s timing hardware at regular intervals;
this interval is programmed at boot time by the kernel according to the value of
HZ,
which is an architecture-dependent value defined in <linux/param.h> or a subplat-
form file included by it. Default values in the distributed kernel source range from 50
to 1200 ticks per second on real hardware, down to 24 for software simulators. Most
platforms run at 100 or 1000 interrupts per second; the popular x86 PC defaults to
1000, although it used to be 100 in previous versions (up to and including 2.4). As a
general rule, even if you know the value of
HZ, you should never count on that spe-
cific value when programming.
It is possible to change the value of
HZ for those who want systems with a different
clock interrupt frequency. If you change

forms feature a high-resolution counter that software can read. Although its actual
use varies somewhat across platforms, it’s sometimes a very powerful tool.
Using the jiffies Counter
The counter and the utility functions to read it live in <linux/jiffies.h>, although
you’ll usually just include <linux/sched.h>, that automatically pulls jiffies.h in. Need-
less to say, both
jiffies and jiffies_64 must be considered read-only.
Whenever your code needs to remember the current value of
jiffies, it can simply
access the
unsigned long variable, which is declared as volatile to tell the compiler
not to optimize memory reads. You need to read the current counter whenever your
code needs to calculate a future time stamp, as shown in the following example:
#include <linux/jiffies.h>
unsigned long j, stamp_1, stamp_half, stamp_n;
j = jiffies; /* read the current value */
stamp_1 = j + HZ; /* 1 second in the future */
stamp_half = j + HZ/2; /* half a second */
stamp_n = j + n * HZ / 1000; /* n milliseconds */
This code has no problem with jiffies wrapping around, as long as different values
are compared in the right way. Even though on 32-bit platforms the counter wraps
around only once every 50 days when
HZ is 1000, your code should be prepared to
face that event. To compare your cached value (like
stamp_1 above) and the current
value, you should use one of the following macros:
#include <linux/jiffies.h>
int time_after(unsigned long a, unsigned long b);
,ch07.9142 Page 184 Friday, January 21, 2005 10:47 AM
This is the Title of the Book, eMatter Edition

unsigned long timeval_to_jiffies(struct timeval *value);
void jiffies_to_timeval(unsigned long jiffies, struct timeval *value);
Accessing the 64-bit jiffy count is not as straightforward as accessing jiffies. While
on 64-bit computer architectures the two variables are actually one, access to the
value is not atomic for 32-bit processors. This means you might read the wrong value
if both halves of the variable get updated while you are reading them. It’s extremely
unlikely you’ll ever need to read the 64-bit counter, but in case you do, you’ll be glad
to know that the kernel exports a specific helper function that does the proper lock-
ing for you:
#include <linux/jiffies.h>
u64 get_jiffies_64(void);
In the above prototype, the u64 type is used. This is one of the types defined by
<linux/types.h>, discussed in Chapter 11, and represents an unsigned 64-bit type.
If you’re wondering how 32-bit platforms update both the 32-bit and 64-bit counters
at the same time, read the linker script for your platform (look for a file whose name
matches vmlinux*.lds*). There, the
jiffies symbol is defined to access the least sig-
nificant word of the 64-bit value, according to whether the platform is little-endian
or big-endian. Actually, the same trick is used for 64-bit platforms, so that the
unsigned long and u64 variables are accessed at the same address.
,ch07.9142 Page 185 Friday, January 21, 2005 10:47 AM
This is the Title of the Book, eMatter Edition
Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved.
186
|
Chapter 7: Time, Delays, and Deferred Work
Finally, note that the actual clock frequency is almost completely hidden from user
space. The macro
HZ always expands to 100 when user-space programs include
param.h, and every counter reported to user space is converted accordingly. This

The most renowned counter register is the TSC (timestamp counter), introduced in
x86 processors with the Pentium and present in all CPU designs ever since—includ-
ing the x86_64 platform. It is a 64-bit register that counts CPU clock cycles; it can be
read from both kernel space and user space.
After including <asm/msr.h> (an x86-specific header whose name stands for
“machine-specific registers”), you can use one of these macros:
rdtsc(low32,high32);
rdtscl(low32);
rdtscll(var64);
,ch07.9142 Page 186 Friday, January 21, 2005 10:47 AM
This is the Title of the Book, eMatter Edition
Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved.
Measuring Time Lapses
|
187
The first macro atomically reads the 64-bit value into two 32-bit variables; the next
one (“read low half”) reads the low half of the register into a 32-bit variable, discard-
ing the high half; the last reads the 64-bit value into a
long long variable, hence, the
name. All of these macros store values into their arguments.
Reading the low half of the counter is enough for most common uses of the TSC. A
1-GHz CPU overflows it only once every 4.2 seconds, so you won’t need to deal with
multiregister variables if the time lapse you are benchmarking reliably takes less time.
However, as CPU frequencies rise over time and as timing requirements increase,
you’ll most likely need to read the 64-bit counter more often in the future.
As an example using only the low half of the register, the following lines measure the
execution of the instruction itself:
unsigned long ini, end;
rdtscl(ini); rdtscl(end);
printk("time lapse: %li\n", end - ini);

|
Chapter 7: Time, Delays, and Deferred Work
With gcc inline assembly, the allocation of general-purpose registers is left to the
compiler. The macro just shown uses
%0 as a placeholder for “argument 0,” which is
later specified as “any register (
r) used as output (=).” The macro also states that the
output register must correspond to the C expression dest. The syntax for inline
assembly is very powerful but somewhat complex, especially for architectures that
have constraints on what each register can do (namely, the x86 family). The syntax is
described in the gcc documentation, usually available in the info documentation tree.
The short C-code fragment shown in this section has been run on a K7-class x86 pro-
cessor and a MIPS VR4181 (using the macro just described). The former reported a
time lapse of 11 clock ticks and the latter just 2 clock ticks. The small figure was
expected, since RISC processors usually execute one instruction per clock cycle.
There is one other thing worth knowing about timestamp counters: they are not nec-
essarily synchronized across processors in an SMP system. To be sure of getting a
coherent value, you should disable preemption for code that is querying the counter.
Knowing the Current Time
Kernel code can always retrieve a representation of the current time by looking at the
value of
jiffies. Usually, the fact that the value represents only the time since the
last boot is not relevant to the driver, because its life is limited to the system uptime.
As shown, drivers can use the current value of
jiffies to calculate time intervals
across events (for example, to tell double-clicks from single-clicks in input device
drivers or calculate timeouts). In short, looking at
jiffies is almost always sufficient
when you need to measure time intervals. If you need very precise measurements for
short time lapses, processor-specific registers come to the rescue (although they bring

actual hardware mechanisms in use. For example, some m68knommu processors,
Sun3 systems, and other m68k systems cannot offer more than jiffy resolution. Pen-
tium systems, on the other hand, offer very fast and precise subtick measures by
reading the timestamp counter described earlier in this chapter.
The current time is also available (though with jiffy granularity) from the
xtime vari-
able, a
struct timespec value. Direct use of this variable is discouraged because it is
difficult to atomically access both the fields. Therefore, the kernel offers the utility
function current_kernel_time:
#include <linux/time.h>
struct timespec current_kernel_time(void);
Code for retrieving the current time in the various ways it is available within the jit
(“just in time”) module in the source files provided on O’Reilly’s FTP site. jit creates
a file called /proc/currentime, which returns the following items in ASCII when read:
• The current
jiffies and jiffies_64 values as hex numbers
• The current time as returned by do_gettimeofday
• The
timespec returned by current_kernel_time
We chose to use a dynamic /proc file to keep the boilerplate code to a minimum—it’s
not worth creating a whole device just to return a little textual information.
The file returns text lines continuously as long as the module is loaded; each read
system call collects and returns one set of data, organized in two lines for better read-
ability. Whenever you read multiple data sets in less than a timer tick, you’ll see the
difference between do_gettimeofday, which queries the hardware, and the other val-
ues that are updated only when the timer ticks.
phon% head -8 /proc/currentime
0x00bdbc1f 0x0000000100bdbc1f 1062370899.630126
1062370899.629161488

One important thing to consider is how the delay you need compares with the clock
tick, considering the range of
HZ across the various platforms. Delays that are reliably
longer than the clock tick, and don’t suffer from its coarse granularity, can make use
of the system clock. Very short delays typically must be implemented with software
loops. In between these two cases lies a gray area. In this chapter, we use the phrase
“long” delay to refer to a multiple-jiffy delay, which can be as low as a few millisec-
onds on some platforms, but is still long as seen by the CPU and the kernel.
The following sections talk about the different delays by taking a somewhat long
path from various intuitive but inappropriate solutions to the right solution. We
chose this path because it allows a more in-depth discussion of kernel issues related
to timing. If you are eager to find the right code, just skim through the section.
Long Delays
Occasionally a driver needs to delay execution for relatively long periods—more than
one clock tick. There are a few ways of accomplishing this sort of delay; we start with
the simplest technique, then proceed to the more advanced techniques.
Busy waiting
If you want to delay execution by a multiple of the clock tick, allowing some slack in
the value, the easiest (though not recommended) implementation is a loop that mon-
itors the jiffy counter. The busy-waiting implementation usually looks like the follow-
ing code, where
j1 is the value of jiffies at the expiration of the delay:
while (time_before(jiffies, j1))
cpu_relax( );
,ch07.9142 Page 190 Friday, January 21, 2005 10:47 AM
This is the Title of the Book, eMatter Edition
Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved.
Delaying Execution
|
191

requested. Therefore, a command such as cat /proc/jitbusy, if it reads 4
KB at a time, freezes the computer for 205 seconds.
The suggested command to read /proc/jitbusy is dd bs=20 < /proc/jitbusy, optionally
specifying the number of blocks as well. Each 20-byte line returned by the file repre-
sents the value the jiffy counter had before and after the delay. This is a sample run
on an otherwise unloaded computer:
phon% dd bs=20 count=5 < /proc/jitbusy
1686518 1687518
1687519 1688519
1688520 1689520
1689520 1690520
1690521 1691521
,ch07.9142 Page 191 Friday, January 21, 2005 10:47 AM
This is the Title of the Book, eMatter Edition
Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved.
192
|
Chapter 7: Time, Delays, and Deferred Work
All looks good: delays are exactly one second (1000 jiffies), and the next read system
call starts immediately after the previous one is over. But let’s see what happens on a
system with a large number of CPU-intensive processes running (and nonpreemptive
kernel):
phon% dd bs=20 count=5 < /proc/jitbusy
1911226 1912226
1913323 1914323
1919529 1920529
1925632 1926632
1931835 1932835
Here, each read system call delays exactly one second, but the kernel can take more
than 5 seconds before scheduling the dd process so it can issue the next system call.

|
193
explicitly release the CPU when we’re not interested in it. This is accomplished by
calling the schedule function, declared in <linux/sched.h>:
while (time_before(jiffies, j1)) {
schedule( );
}
This loop can be tested by reading /proc/jitsched as we read /proc/jitbusy above. How-
ever, is still isn’t optimal. The current process does nothing but release the CPU, but
it remains in the run queue. If it is the only runnable process, it actually runs (it calls
the scheduler, which selects the same process, which calls the scheduler, which ).
In other words, the load of the machine (the average number of running processes) is
at least one, and the idle task (process number
0, also called swapper for historical
reasons) never runs. Though this issue may seem irrelevant, running the idle task
when the computer is idle relieves the processor’s workload, decreasing its tempera-
ture and increasing its lifetime, as well as the duration of the batteries if the com-
puter happens to be your laptop. Moreover, since the process is actually executing
during the delay, it is accountable for all the time it consumes.
The behavior of /proc/jitsched is actually similar to running /proc/jitbusy under a pre-
emptive kernel. This is a sample run, on an unloaded system:
phon% dd bs=20 count=5 < /proc/jitsched
1760205 1761207
1761209 1762211
1762212 1763212
1763213 1764213
1764214 1765217
It’s interesting to note that each read sometimes ends up waiting a few clock ticks
more than requested. This problem gets worse and worse as the system gets busy,
and the driver could end up waiting longer than expected. Once a process releases

tions return
0; if the process is awakened by another event, it returns the remaining
delay expressed in jiffies. The return value is never negative, even if the delay is
greater than expected because of system load.
The /proc/jitqueue file shows a delay based on wait_event_interruptible_timeout,
although the module has no event to wait for, and uses
0 as a condition:
wait_queue_head_t wait;
init_waitqueue_head (&wait);
wait_event_interruptible_timeout(wait, 0, delay);
The observed behaviour, when reading /proc/jitqueue, is nearly optimal, even under
load:
phon% dd bs=20 count=5 < /proc/jitqueue
2027024 2028024
2028025 2029025
2029026 2030026
2030027 2031027
2031028 2032028
Since the reading process (dd above) is not in the run queue while waiting for the
timeout, you see no difference in behavior whether the code is run in a preemptive
kernel or not.
wait_event_timeout and wait_event_interruptible_timeout were designed with a hard-
ware driver in mind, where execution could be resumed in either of two ways: either
somebody calls wake_up on the wait queue, or the timeout expires. This doesn’t
apply to jitqueue, as nobody ever calls wake_up on the wait queue (after all, no other
code even knows about it), so the process always wakes up when the timeout
expires. To accommodate for this very situation, where you want to delay execution
waiting for no specific event, the kernel offers the schedule_timeout function so you
can avoid declaring and using a superfluous wait queue head:
#include <linux/sched.h>

is definitely not the way to go.
The kernel functions ndelay, udelay, and mdelay serve well for short delays, delaying
execution for the specified number of nanoseconds, microseconds, or milliseconds
respectively.
*
Their prototypes are:
#include <linux/delay.h>
void ndelay(unsigned long nsecs);
void udelay(unsigned long usecs);
void mdelay(unsigned long msecs);
The actual implementations of the functions are in <asm/delay.h>, being architec-
ture-specific, and sometimes build on an external function. Every architecture imple-
ments udelay, but the other functions may or may not be defined; if they are not,
<linux/delay.h> offers a default version based on udelay. In all cases, the delay
achieved is at least the requested value but could be more; actually, no platform cur-
rently achieves nanosecond precision, although several ones offer submicrosecond
* The u in udelay represents the Greek letter mu and stands for micro.
,ch07.9142 Page 195 Friday, January 21, 2005 10:47 AM
This is the Title of the Book, eMatter Edition
Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved.
196
|
Chapter 7: Time, Delays, and Deferred Work
precision. Delaying more than the requested value is usually not a problem, as short
delays in a driver are usually needed to wait for the hardware, and the requirements
are to wait for at least a given time lapse.
The implementation of udelay (and possibly ndelay too) uses a software loop based on
the processor speed calculated at boot time, using the integer variable
loops_per_jiffy.
If you want to look at the actual code, however, be aware that the x86 implementation

Kernel Timers
Whenever you need to schedule an action to happen later, without blocking the cur-
rent process until that time arrives, kernel timers are the tool for you. These timers
,ch07.9142 Page 196 Friday, January 21, 2005 10:47 AM
This is the Title of the Book, eMatter Edition
Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved.
Kernel Timers
|
197
are used to schedule execution of a function at a particular time in the future, based
on the clock tick, and can be used for a variety of tasks; for example, polling a device
by checking its state at regular intervals when the hardware can’t fire interrupts.
Other typical uses of kernel timers are turning off the floppy motor or finishing
another lengthy shut down operation. In such cases, delaying the return from close
would impose an unnecessary (and surprising) cost on the application program.
Finally, the kernel itself uses the timers in several situations, including the implemen-
tation of schedule_timeout.
A kernel timer is a data structure that instructs the kernel to execute a user-defined
function with a user-defined argument at a user-defined time. The implementation
resides in <linux/timer.h> and kernel/timer.c and is described in detail in the section
“The Implementation of Kernel Timers.”
The functions scheduled to run almost certainly do not run while the process that
registered them is executing. They are, instead, run asynchronously. Until now,
everything we have done in our sample drivers has run in the context of a process
executing system calls. When a timer runs, however, the process that scheduled it
could be asleep, executing on a different processor, or quite possibly has exited
altogether.
This asynchronous execution resembles what happens when a hardware interrupt
happens (which is discussed in detail in Chapter 10). In fact, kernel timers are run as
the result of a “software interrupt.” When running in this sort of atomic context,

current may be valid, but
access to user space is forbidden, since it can cause scheduling to happen. Whenever
you are using in_interrupt( ), you should really consider whether in_atomic( ) is what
you actually mean. Both functions are declared in <asm/hardirq.h>
One other important feature of kernel timers is that a task can reregister itself to run
again at a later time. This is possible because each
timer_list structure is unlinked
from the list of active timers before being run and can, therefore, be immediately re-
linked elsewhere. Although rescheduling the same task over and over might appear
to be a pointless operation, it is sometimes useful. For example, it can be used to
implement the polling of devices.
It’s also worth knowing that in an SMP system, the timer function is executed by the
same CPU that registered it, to achieve better cache locality whenever possible.
Therefore, a timer that reregisters itself always runs on the same CPU.
An important feature of timers that should not be forgotten, though, is that they are
a potential source of race conditions, even on uniprocessor systems. This is a direct
result of their being asynchronous with other code. Therefore, any data structures
accessed by the timer function should be protected from concurrent access, either by
being atomic types (discussed in the section “Atomic Variables” in Chapter 1) or by
using spinlocks (discussed in Chapter 5).
The Timer API
The kernel provides drivers with a number of functions to declare, register, and
remove kernel timers. The following excerpt shows the basic building blocks:
#include <linux/timer.h>
struct timer_list {
/* */
unsigned long expires;
void (*function)(unsigned long);
unsigned long data;
};


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status