Real-time performance in linux

Written by Ian on Friday 27/04/07


How to get realtime performance in Linux (especially embedded Linux)? Well one trick is to adjust the scheduler.


In Linux, there is a schedule() function in the kernel source code (kernel/sched.c)
which implements scheduling, and which you can look through/edit.
It handles interrupts, sorts through and chooses from the set of runnable
tasks by priority and other metrics, and switches to the chosen task.


schedule() is executed at task dispatch points (ret_from_sys_call) and
by explicit sleep instructions encountered in running code. In other words, this gets run quite frequently!


Every time it runs it decides which user code should get executed next, based on some metrics about priority, how long a piece of code has been waiting and so on.


You can use the Linux function sched_setscheduler() to set the scheduling policy
and parameters for the specified PIDs (process identifiers - a number which identifies each running program). You can call this function directly in your programs if you have root access.


There are three scheduling policies in standard Linux (some embedded flavours provide alternatives, and some provide none!).


Normally you don't touch the scheduling and don't touch the priorities,
on a general purpose desktop machine, but for efficient hard real-time embedded systems
it is often necessary to explicitly set priorities and scheduling algorithms. Otherwise you would need a grossly over-powered CPU to do even simple real-time tasks.



  • SCHED_OTHER: is the default time-sharing preemptive scheduler that uses a process nice level and a counter (how long has a process been waiting...)


  • SCHED_FIFO:is first-in, first-out preemptive non-timesliced scheduler that will run a high priority process to completion, and allows a newly-runnable process to preempt lower priority processes.


  • SCHED_RR:adds round-robin capabilities to SCHED_FIFO in that processes don't run to completion, but are time-sliced so that other processes get a chance to run/


  • You will need root access to select these or set a higher than default process priority level.


    WARNING!


    Note this piece of good advice from the sched_setscheduler() man page:



    As a non-blocking end-less loop in a process scheduled under SCHED_FIFO or
    SCHED_RR will block all processes with lower priority forever, a software
    developer should always keep available on the console a shell scheduled under
    a higher static priority than the tested application.

    This will allow an emergency kill of tested real-time applications that do
    not block or terminate as expected.