Sunday, December 31, 2006

Timers:

A System needs to keep account of time for various purpose. For e.g. to carry out rescheduling, waiting for some specified amount of time or for knowing the wall time.

The support for managing time is provided by means of two hardware devices: the system timer (responsible for timer interrupts and updates jiffies) and the real-time clock.

RTC: RTC or Real time clock is generally used for providing the wall time. It is on (non-volatile) even when the system is off, through the CMOS battery prsent on the system board. Kernel reads the RTC at booting time to keep track of wall time.

Sytem Timer: System Timer is required to generate interrupts at periodically. Generally provided through via clocks osciallating at programmable frequency. In x86, it is provided through PIT (programmable interrupt timer). Kernel can program the PIT to define the system timer interrupt (0) frequency Hz.

Saturday, December 30, 2006

Kernel Synchronisation:
Key points:

- Kernel Synchronisation is required to prevent shared data structures and resources from inconsistent/incorrect state.
- This may happen due to multiple threads of execution inside kernel, manipulating and working on shared data structures and resources. For e.g. muliple threads working on request queues if allowed conncurrent access may leave the queue inconsistent.
- In SMP scenario also same code may get executed on different processors simultaneously leaving a shared resource prone to inconsistency.
- In a premptive kernel (2.6), a reschedule may happen at any time (almost any time :).
- For all the above reasons "critical regions of codes" needs protection and to avoid race condition. Code paths that access and manipulate shared data are called critical regions.
- Atomic Operations and locking (implemented through atomic operations) can help in kernel synchronisation. Generally Processors provide instructions to atomically perform operations like i++ (read, manipulate and write).
- Locks (busy wait or sleep) are only advisory not mandatory.

- pseudo-concurrency: interleaving of two operations rather than actually occuring togethe (true concurrency can occur on smp only)
- Causes of concurrency:- Interrupts, Preemption, Sleep (reschedule), SMP- Code needs to be interrupt-safe, SMP-safe, preempt-safe.
- Deadlocks- Occurs when every thread is waiting for some resource(generally locks) that is already held, so no possiblitliy of success. To avoid this, whenever more than one locks needs to be taken, take them in a single order.
NOTE: A code can be SMP safe but still not preempt safe, for e.g. consider code manipulating per-processor data structures. This code will be SMP safe but will need explicit handling
for making it preempt safe.
Some Synchronisation Methods:
- Atomic operations (e.g. test_and_set_bit)
- Barriers (preserve ordering of operations)
- Spin locks
- Semaphores