100% found this document useful (1 vote)
157 views27 pages

ESET Internet Security Crack Latest Version

The document provides an overview of the kernel's timekeeping mechanisms, including the concepts of jiffies, hardware clocks, and timer interrupts. It explains how the kernel tracks wall time and system uptime using a tick rate and discusses the advantages and disadvantages of higher tick rates. Additionally, it covers the implementation of timers in the kernel, including their setup and expiration handling.

Uploaded by

naeem55ddf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
157 views27 pages

ESET Internet Security Crack Latest Version

The document provides an overview of the kernel's timekeeping mechanisms, including the concepts of jiffies, hardware clocks, and timer interrupts. It explains how the kernel tracks wall time and system uptime using a tick rate and discusses the advantages and disadvantages of higher tick rates. Additionally, it covers the implementation of timers in the kernel, including their setup and expiration handling.

Uploaded by

naeem55ddf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

TIM

MODULE

ER

IT’S

TIMER
TIME
FOR
0
OVERVIEW OVER
VIEW
1 4
Kernel Notion of Time The Timer Interrupt Handler

2 Jiffies 5
Timers

3 6 Delaying Execution
Hardware Clocks and Timers
1
KERNAL NOTION OF TIME

 The kernel knows the preprogrammed tick rate, so it knows the time between any
two successive timer interrupts. This period is called a tick and is equal to 1/(tick
rate) seconds.

 This is how the kernel keeps track of both wall time and system uptime.

 Wall time—the actual time of day—is important to user-space applications.

 The system uptime—the relative time since the system booted—is useful to both
kernel-space and user-space.
1
KERNAL NOTION OF TIME

 Some Functions Of Timer Interrupt  The Tick Rate: HZ

 The frequency of the system timer (the tick


 Updating the system uptime. rate) is programmed on system boot based
on a static preprocessor define, HZ.The value
of HZ differs for each supported architecture.
 Updating the time of day.

 The tick rate has a frequency of HZ hertz and


 On an SMP system, ensuring that the a period of 1/HZ seconds. For example, by
scheduler runqueues are balanced and, if default the x86 architecture defines HZ to be
not, balancing them. 100.

 Running any dynamic timers that have  The frequency of the timer interrupt is
expired. important. So changing its frequency has a
reasonable impact on the system.
1
KERNAL NOTION OF TIME

 Advantages with a Larger HZ  Disadvantages with a Larger HZ

 Kernel timers execute with finer  A higher tick rate implies more frequent timer
resolution and increased accuracy. interrupts, which implies higher overhead.

 Measurements, such as resource  The higher the tick rate,the more time the
usage or the system uptime, are processor spends executing the timer
recorded with a finer resolution. interrupt.

 Process preemption occurs more  More frequent thrashing of the processor’s


accurately. cache and increase in power consumption.
1
KERNAL NOTION OF TIME

 A Tickless OS

 The Linux kernel supports an option known as a tickless operation. When a


kernel is built with the CONFIG_HZ configuration option set, the system
dynamically schedules the timer interrupt in accordance with pending timers.
Instead of firing the timer interrupt every, say, 1ms, the interrupt is dynamically
scheduled and rescheduled as needed.

 With a tickless system, moments of idleness are not interrupted by


unnecessary time interrupts, reducing system power consumption also
reduction in overhead.
21
JIFFIES
The global variable jiffies holds the number of ticks that have occurred since the
system1 The Etymology of
booted. On boot, the kernel initializes the variable to zero, and it is incremented by
one during each timer interrupt.
the Jiffy:
The origin of the term jiffy is
unknown. Phrases such as in a
 There are HZ timer interrupts in a second, jiffy are thought to originate from
 There are HZ jiffies in a second.
18th-century England. In lay
 The system uptime is therefore jiffies/HZ seconds. terms, jiffy refers to an
indeterminate but brief period of
The jiffies variable is declared in <linux/jiffies.h> as time.
extern unsigned long volatile jiffies;

 The following expression converts from seconds to a unit of jiffies: In computer engineering, a jiffy
(seconds * HZ) is often the time between two
successive clock cycles. In
 Likewise, this expression converts from jiffies to seconds:
(jiffies / HZ) electrical engineering, a jiffy is
the time to complete one AC
(alternating current) cycle.
For example, code often needs to set a value for some time in the future, for example:

 unsigned long time_stamp = jiffies;


 unsigned long next_tick = jiffies + 1;
 unsigned long later = jiffies + 5*HZ;
 unsigned long fraction = jiffies + HZ / 10;
21
JIFFIES

 Internal Representation of Jiffies

 The jiffies variable has always been an unsigned long,


32 bits in size on 32-bit architectures and
64-bits on 64-bit architectures.

 With a tick rate of 100, a 32-bit jiffies variable would overflow in about 497 days. With HZ
increased to 1000, however, that overflow now occurs in just 49.7 days!

 If jiffies were stored in a 64-bit variable on all architectures, then for any reasonable HZ value the
jiffies variable would never overflow in anyone’s lifetime

A second variable is also defined in : extern u64 jiffies_64;

 Code that accesses jiffies simply reads the lower


32 bits of jiffies_64.

 The function get_jiffies_64() can be used to read


the full 64-bit value.
21
JIFFIES
 Jiffies Wraparound

Look at an example of a wraparound: define time_after(unknown, known)


((long)(known) - (long)(unknown) < 0)
unsigned long timeout = jiffies + HZ/2; /*
timeout in 0.5s */ #define time_before(unknown, known)
((long)(unknown) - (long)(known) < 0)
/* do some work ... */
#define time_after_eq(unknown, known)
/* then see whether we took too long */ ((long)(unknown) - (long)(known) >= 0)

if (timeout > jiffies) { /* we did not time out, #define time_before_eq(unknown, known)
good ... */ } ((long)(known) - (long)(unknown) >= 0)
else { /* we timed out, error ... */ }

Thankfully, the kernel provides four macros


for comparing tick counts that correctly
handle wraparound in the tick count. They
are in . Listed here are simplified versions of
the macros:
21
JIFFIES

 How It Actually Work  So this code can be written as


time_after(a,b) returns true if the time a is
after time b.

A special function is needed because 32-bit


architectures cannot atomically access both 32-bit
words in a 64-bit value. /* ... */
The special function locks the jiffies count if (time_before(jiffies, timeout)) { /*
via the xtime_lock lock before reading we did not time out, good ... */ }
Suppose b is 253, and five ticks later jiffies
has wrapped around to 2. We would therefore
expect else { /* we timed out, error ... */ }
time_after(2,253) to return true. And it does
(using int8_t to denote a signed 8-bit value):
(int8_t) 253 - (int8_t) 2 == -3 - 2 == -5 < 0
You can try other values, too. This one is
trickier, for time_after(128, 127), which should be
true as well:

(int8_t) 127 - (int8_t) 128 == 127 - (-128) ==


255 == -1 (for 8-bit 2's complement) < 0
31
HARDWARE CLOCKS &
TIMERS
Architectures provide two hardware 2 way to implement System Timer-
devices to help with time keeping

1.Real-Time Clock – 1. Electronic clock –

The real-time clock (RTC) provides a oscillates at a programmable frequency


nonvolatile device for storing the system
time 2. Counter –
On boot, the kernel reads the RTC and
uses it to initialize the wall time, which is Set to some initial value and decrements at a
stored in the xtime variable fixed rate until the counter reaches zero, an
interrupt is
2.System Timer – triggered.
On x86,
The idea behind the system time is—to
provide a mechanism for driving an the primary system timer is the
interrupt at a periodic rate programmable interrupt timer (PIT)
Other include the local APIC timer and the
processor’s time stamp
counter (TSC).
31
HARDWARE CLOCKS &
TIMERS
Real-Time Clock (RTC):  All PCs include a clock called Real Time Clock(RTC),
which is independent of the CPU and all other
chips.

 The RTC continues to keep track of time even


when the system is off by way of a small battery
typically included on the system board. On the PC
architecture, the RTC and the

 CMOS are integrated, and a single battery keeps


the RTC running and the BIOS settings preserved.

 On boot, the kernel reads the RTC and uses it to


initialize the wall time, which is stored in the
xtime variable.

 The kernel does not typically read the value again;


however, some supported architectures, such as
x86, periodically save the current wall time back
to the RTC
31
HARDWARE CLOCKS &
TIMERS
Real-Time Clock (RTC): The “xtime” variable
 Linux uses the RTC only to derive the time
The Original Representation-
and date; however, it allows processes to
The simplest data structure is time_t , defined in the
program the RTC by acting on the
header <time.h>
/dev/rtc device file
On most Unix systems—Linux included—the type is
a simple typedef to the C long type:
 The RTC is capable of issuing periodic
typedef long time_t;
interrupts on IRQ 8 at frequencies ranging
between 2 Hz and 8,192 Hz.
#include <sys/time.h>
struct timeval
 It can also be programmed to activate the
{
IRQ 8 line when the RTC reaches a specific
time_t tv_sec; /* seconds */
value, thus working as an alarm clock.
suseconds_t tv_usec; /* microseconds */
};
 The kernel accesses the RTC through the
The timespec data structure is defined in
0x70 and 0x71 I/O ports.
<linux/time.h> as:
struct timespec
 Nonetheless, the real time clock’s primary
{
importance is only during boot, when the
time_t tv_sec; /* seconds */
xtime variable is initialized.
long tv_nsec; /* nanoseconds */
};
31
HARDWARE CLOCKS &
TIMERS
The “xtime” variable The “xtime” variable

 The xtime variable stores the current time  user programs get the current time and date
and date; it is a structure of type from the xtime variable.
timespec having two fields:
 The kernel also often refers to it, for instance,
tv_sec- when updating i-node timestamps.
Stores the number of seconds that have
elapsed since midnight of January 1, 1970  The xtime variable is usually updated once in a
(UTC) tick, that is, roughly 1000 times per The
xtime_lock seqlock avoids the race conditions
 This date is called the epoch(reference that could occur due to concurrent
date). Most Unix systems base their
notion of the  accesses to the xtime variable. Remember that
xtime_lock also protects the jiffies_64
 current wall time as relative to this epoch.
 variable; in general, this seqlock is used to define
tv_nsec several critical regions of the timekeeping
 Stores the number of nanoseconds that architecture.
have elapsed within the last second (its
value ranges between 0 and 999,999,999)
second.
31
HARDWARE CLOCKS &
How We SeeTIMERS
Time?

Some of the functions that we will cover convert between Unix time and strings, or programmatically
build a string representing a given date. To facilitate this process, the C standard provides the tm
structure for representing “broken-down” time in a more human-readable format. This structure is
also defined in <time.h> :
31
HARDWARE CLOCKS &
TIMERS
System Timer

kernel uses system timer to gauge the passing of time.

This system timer works off of an electronic time source, such as a digital clock or the frequency
of the processor.

The system timer goes off (often called hitting or popping) at a pre programmed
frequency, called the tick rate.

When the system timer goes off, it issues an interrupt that the kernel handles via a special
interrupt handler.

Because the kernel knows the pre programmed tick rate, it knows the time between any two
successive timer interrupts . This period is called a tick and is equal to 1/(tick rate) seconds.
This is how the kernel keeps track of both wall time and system uptime.

On x86, the primary system timer is the programmable interrupt timer (PIT).
The kernel programs the PIT on boot to drive the system timer interrupt (interrupt zero) at
HZ frequency.
41
2
TIMER INTERRUPT HANDLER
The timer interrupt is broken into two pieces
 interrupt handler – Architecture Depedent
 tick_periodic() – Architecture independent routine

Task of Interrupt handler – Task of Tick Periodic()

1. Obtain the xtime_lock lock, which 1. Increment the jiffies_64 count by one.
protects access to jiffies_64 and the wall 2. Update resource usages, such as consumed
time value, xtime. system and user time, for the currently
2. Acknowledge or reset the system timer 3. running process.
as required.
4. Run any dynamic timers that have expired
3. Periodically save the updated wall time (discussed in the following section).
to the real time clock. 5. Execute scheduler_tick(), as discussed in
Chapter 4
4. Call the architecture-independent timer
routine, tick_periodic(). 6. Update the wall time, which is stored in
xtime.

7. Calculate the infamous load average.


41
2
TIMER INTERRUPT HANDLER
The routine is simple because other functions handle most of the work:
static void tick_periodic(int cpu)
{ void do_timer(unsigned long ticks)
if (tick_do_timer_cpu == cpu) { {
write_seqlock(&xtime_lock); jiffies_64 += ticks;
/* Keep track of the next tick event */ update_wall_time();
tick_next_period = ktime_add(tick_next_period, tick_period); calc_global_load();
do_timer(1); }
write_sequnlock(&xtime_lock);
}
update_process_times(user_mode(get_irq_regs())); update_wall_time() - updates the
profile_tick(CPU_PROFILING); wall time in accordance with the
}
elapsed ticks, whereas
Most of the important work is enabled in
calc_global_load() -updates the
do_timer() and system’s load average statistics.
update_process_times() .

The former is responsible for actually performing the


increment to jiffies_64 :
5
21
TIMER

Timers — Timers are not cyclic.The timer is


destroyed after it expires
sometimes called dynamic timers or Timers are represented by struct
kernel timers—are essential for timer_list, which is defined in
managing the flow of time in kernel <linux/timer.h>:
code. Kernel code often needs to delay
execution of some function struct timer_list {
until a later time. struct list_head entry; /* entry in linked list
of timers */
A timer is easy to use. unsigned long expires; /* expiration value,
You perform some initial setup, in jiffies */
specify an expiration time ,Specify a void (*function)(unsigned long); /* the
function to execute upon said timer handler function */
expiration, and activate the timer. unsigned long data; /* lone argument to
The given function runs after the timer the handler */
expires. struct tvec_t_base_s *base; /* internal
timer field, do not touch */
};
5
21
TIMER
 Using Timers

1. The first step in creating a timer is defining it: 4. Finally, you activate the timer:

 struct timer_list my_timer;  add_timer(&my_timer);

2. the timer’s internal values must be initialized  Sometimes you might need to modify the
expiration of an already active timer
 mod_timer(&my_timer, jiffies + new_delay); /*
 init_timer(&my_timer);
new expiration */

3. Now you fill out the remaining values as  If you need to deactivate a timer prior to its
required: expiration,use the del_timer() function:

 my_timer.expires = jiffies + delay; /* timer  del_timer(&my_timer);


expires in delay ticks */
 my_timer.data = 0; /* zero is passed to the  To deactivate the timer and wait until a potentially
timer handler */ executing handler for the timer exits, use
 my_timer.function = my_function; /* del_timer_sync():
function to run when timer expires */  del_timer_sync(&my_timer);
5
21
TIMER
 Timer Race Conditions Timer Implementation

 Because timers run asynchronously with respect to The kernel executes timers in bottom-half context, as
the currently executing code, several potential race softirqs, after the timer interrupt
conditions exist. completes.
First
 never do the following as a substitute for a mere
The timer interrupt handler runs update_process_times(),
mod_timer(), because this is unsafe on which calls
multiprocessing machines: run_local_timers():
 del_timer(my_timer)
void run_local_timers(void)
 my_timer->expires = jiffies + new_delay; {
 add_timer(my_timer); hrtimer_run_queues();
raise_softirq(TIMER_SOFTIRQ); /* raise the timer softirq */
Second softlockup_tick();
}
Second, in almost all cases, you should use
del_timer_sync() over del_timer().
6
21
DELAYING EXECUTION
 Busy Looping 3.When we wan't to solve critical section problem
through semaphores....
Need for busy looping

1. When we want a delay, while using hardware


like (NIC for the first time ). s=1;
P1 P2
Implementation in case of first point:
---- ----
unsigned long timeout = jiffies + 10; /* ten ticks */ ---- ----
while (time_before(jiffies, timeout)) ; Wait(s) Wait(s) // Busy Looping
Critial Section Critical Section
Problem in above solution : Signal(s) Signal(s)
spinning in a silly loop—because no useful work is ---- ----
accomplished!!!
---- ----
Second Solution (Better solution)
Code of Wait(s) Code of Signal(s)
while (time_before(jiffies, delay)) { {
cond_resched(); (New process is scheduled) while(s<=0); s=s+1;
s=s-1; }
}`
6
21
DELAYING EXECUTION

 Small Delays- BOGOMips

for Hz = 100 we can not provide time delay BOGOMips


less than 10 ms Its name is a contraction of bogus
even (that is, fake) and MIPS (million of instructions per second).
for Hz= 1000 we can not provide time
delay less than 1 ms Everyone is familiar with a boot
so for smaller delay ....
message similar to the following (this is on a 2.4GHz 7300-series
kernel provides three functions for Intel Xeon):
microsecond, nanosecond, and millisecond
delays, defined in <linux/delay.h> and Detected 2400.131 MHz processor.
<asm/delay.h>, which do not use Calibrating delay loop... 4799.56 BogoMIPS
jiffies:
This value is stored in the loops_per_jiffy variable and is readable
void udelay(unsigned long usecs)
void ndelay(unsigned long nsecs)
from
void mdelay(unsigned long msecs) /proc/cpuinfo
6
21
DELAYING EXECUTION

 schedule_timeout()-

This call puts your task to sleep until at least the specified time has elapsed.
When the specified time has elapsed, the kernel wakes the task up and
places it back on the runqueue.

/* set task’s state to interruptible sleep */


set_current_state(TASK_INTERRUPTIBLE);

/* take a nap and wake up in “s” seconds */


schedule_timeout(s * HZ);

Sleeping on a Wait Queue, with a Timeout -

Sometimes it is desirable to wait for a specific event or wait for a specified time to
elapse—whichever comes first.
6
21
DELAYING EXECUTION
Schedule_timeout
signed long schedule_timeout(signed long timeout) expire = timeout + jiffies;
{ init_timer(&timer);
timer_t timer; Delaying Execution 229
unsigned long expire; timer.expires = expire;
switch (timeout) timer.data = (unsigned long) current;
{ timer.function = process_timeout;
case MAX_SCHEDULE_TIMEOUT: add_timer(&timer);
schedule(); schedule();
goto out; del_timer_sync(&timer);
default: timeout = expire - jiffies;
if (timeout < 0) out:
{ return timeout < 0 ? 0 : timeout;
printk(KERN_ERR “schedule_timeout: wrong timeout }

“value %lx from %p\n”, timeout,
__builtin_return_address(0));
current->state = TASK_RUNNING;
goto out;
}

}
721
SYSTEM CALLS
 System Call  Current time of day

A System call is the programmatic way in  TIME(): get time in seconds


which a computer program requests a
service from the kernel of the operating  SETTIMEOFDAY(): set time as well as time zone
system it is executed on.
 GETTIMEOFDAY(): get time as well as time zone

System calls of timer has  SLEEP(): process can sleep for s seconds.
#include<sys/time.h> header file.

 POSIX clocks

 CLOCK_SETTIME(): set the time of the specified


clock

 CLOCK_GETTIME(): get the time of the specified


clock

 CLOCK_GETRES(): get resolution of specified


clock

 CLOCK_ADJTIME(): tune the specified clock


5
21
TIMER
 Clocks-based timers  Timers

 TIMER_CREATE(): create a POSIX pre-process timer


 ALARM(): set an alarm clock for delivery of a signal

 TIMER_DELETE(): delete a POSIX and pre-process  SETTIMER(): set value of an interval timer
timer
 GETTIMER(): get value of an interval timer
 TIMER_SETTIME(): arm/disarm POSIX and pre-
process timer

 TIMER_GETTIME(): fetch state of POSIX and pre-


process timer

You might also like