Realtime applications
with RTAI
[Link] Embedded Systems department
1
Outline
I.
Which RTOS to choose ?
II. Why not to choose Linux ?
III. Realtime Linux
IV. Using RTAI
V. RT TASK scheduling with RTAI
VI. Synchronisation, Communication
VII. RTAI: conclusion
[Link] other RTOS .
I. WHICH RTOS TO CHOOSE?
Specification of a RTOS
Minimum to manage realtime
-
Interrupt management,
Time base,
Tasks declaration, creation, execution, preemption,
destruction
Minimum cost (speed, memory,)
Additionnal Services
Memory Management
Communications with devices (driver)
Tools for communication an synchronisation
Human Machine Interface
Development Architecture
l
Cross Development
Development computer
Source writing
Cross compilation
Linking :
-code
-RT kernel and librairies
-loader
Simulation
Download
Debug
Target computer
Embedded system
I/O
Controlled system
Sometimes keyboard/Screen
Development Architecture II
Development & target computer
Source writing
Cross compilation
Linking :
-code
-RT kernel and librairies
-loader
Simulation
Debug
Execution
II. WHY NOT TO CHOOSE LINUX ?
LINUX
l
Linux is an open source OS
Manage I/O
Disk
IHM (keyboard, mouse, screen)
Network
Multitask
-
Load balancing
Resource management
Average response time
9
Linux kernel and Modules
User Space
Mozilla
Bash
Emacs
API
Kernel
space
COM
MODULE
DRIVER
KERNEL
Not Allowed
FILESYSTEM
Hardware
CPU
RAM
DISK
NETWORK
10
The Linux KERNEL
l
Functions
-
-
-
-
-
-
-
-
-
-
scheduling functions and priorities
processus management
Timers ans alarms, time functions
Hardware resources access
Interrupt handling
User and group management
Modules management
Debug functions (printk)
Exceptions handling
System information
The kernel is not multitask and cant be preempted
11
Linux Modules
l
l
l
Why modules ? Modularity !!!
_
Avoid kernel recompilation when drivers are added
Save memory : only needed functions or drivers can
be loaded
A module can use functions, variables and kernel
strucutres
Code is executed with administrator privileges
A module is allowed to acces I/O
!
Exceptions in a module are usually fatal for the system
12
Modules
l
Modules are referenced in a list updated by the
kernel (lsmod to vizualise this list)
A module can only use functions exported by
the kernel or other modules
A module can only be loaded and removed by
the user root
The kernel updated a list of linked between
modules (it allows to know when a module can
be removed)
13
Linux and Realtime
l
Process
wake up date cant be guaranted
-Round robin scheduler : load balancing
- Calls to kernel functions can not be preempted
-
Memory
- Swap
on Ram and process
Interrupt
- Regularly disabled by the kernel
_ LINUX IS NOT REAL TIME
14
III. REALTIME LINUX
15
KURT implementation
Linux
l
l
l
l
KURT
A realtime API is added in the kernel
kernel preemption is allowed
Interruption disable is reduced
response time 100s
! For soft realtime constraints applications
16
RT-Linux, RTAI
or RTAI
A micro kernel is added under linux kernel
Linux is executed in background
Linux and a RTOS in a same system
[Link]
Response time < 20s
l
l
Used in hard realtime constraints applications
17
Others realtime solutions around LINUX
l
l
l
l
l
RTLinux
RTAI (variante de RTLinux)
eCos
...
And commercial distributions
-
-
-
-
-
FSMLAbs (RTLinux)
MontaVista HardHat
Lineo Embedix Realtime
TimeSys Linux/RT
LynuxWorks BLueCat Linux (Lynx Real Time Systems)
18
RTAI
l
Real time small executive
New functions can be added
l
l
Multi schedulers
Communications
Open source
Split in sevral modules
Manage flotting point unit (FPU)
19
RTAI lives with LINUX
l
Linux is unchanged : all linux applications can still
be used
Clear separation between realtime (RTAI) and
non realtime (Linux) behaviour :
l
l
RT tasks : no linux system calls
RT tasks and linux application communications
Memory sharing
- Real time Fifo
-
20
IV. USING RTAI
21
How to build a realtime application ?
l
Modify the Linux kernel
-
RTAI installation, guidelines
l
l
l
Write the realtime application in module
-
-
-
Patch Linux
Compile the patched kernel
Install and run the new kernel
Executed in kernel space
Incorporates realtime tasks
1 or more module
Execute the application
-
-
-
Compile the application modules
Load all the needed RTAI modules
Load the application modules
22
Write a module (linux 2.4)
#define MODULE
#include<linux/init.h>
#include <linux/module.h>
#include<linux/version.h>
static int output=1;
int init_module(void) {
printk("Output= %d\n",output);
return 0;
}
void mon_code(void) {
output++;
}
void cleanup_module(void){
printk("Adis, Bye, Ciao, Ovuar, \n");
}
23
Write a module (linux 2.6)
#define MODULE
#include<linux/init.h>
#include <linux/module.h>
#include<linux/version.h>
no more needed
static int output=1;
int mon_init(void) {
printk("Output= %d\n",output);
return 0;
}
void mon_code(void) {
output++;
}
void mon_cleanup(void){
printk("Adis, Bye, Ciao, Ovuar, \n");
}
module_init(mon_init);
module_exit(mon_cleanup);
24
Compiling and executing
l
Compile a module :
Linux 2.4 : gcc -I /usr/src/linux/include/linux -O2 Wall
D__KERNEL__ -c exemple1.c
Linux 2.6 : kernel source and makefile needed
Load a module
> insmod [Link] (exemple1.o with kernel 2.4)
Printk output on console
> dmesg | tail -1
Output= 1
List modules
# lsmod
Module
exemple1
sb
Pages
1
6
Used by:
0
1
25
Load steps (resumed)
1) External referenced symbol verification
2) Kernel version verification
3) Code and data memory allocation and copy of
the module in the allocated space
4) Symbol table update with module symbols
(output and mon_code)
5) Call of module init_module function
26
Cleaning
l
Remove module
-
Will execute the cleanup_module()function
# rmmod exemple1
# dmesg | tail -2
Output= 1
Adis, Bye, Ciao, Orvua,
27
Pass data to a module ?
# insmod [Link] output=4
# dmesg | tail -3
Output= 1
Adis, Bye, Ciao, Orvua,
Output= 4
28
Makefile
l
l
l
Interpreted by the command make
Set of rules
Rule : define commands to build a target from
source files. Also define dependancies (source
files) needed by the commands
rule : dpendancies
command
[Link]/software/make/manual
29
RTAI modules
rtai_hal : base functions
rtai_sched : mono processor scheduler
rtai_sem : semaphore functions
rtai_fifos : RT modules and linux applications
communications functions
+ application modules
-
-
l
I/O handling
Tasks
To be loaded each time the application has to be
started
_ Script
30
Typical Realtime application
X Windows
User Process
RT
Fifo
Linux kernel
RT
Fifo
RT Task
RT Task
RTAI
Screen
Disk
Network
other peripheral
31
V. RT TASK SCHEDULING WITH
RTAI
32
RTAI : task handling
l
RTAI
-
Each Realtime task is a thread RT_TASK
Linux kernel = idle priority thread
Task scheduling
l
Preemptive
Fixed priority (default) or EDF
! Processor overload => Linux can not be executed
33
Task create
#include <rtai_sched.h>
MODULE_LICENSE("GPL");
static RT_TASK tache;
#define STACK_SIZE 2000
iret = rt_task_init(&tache, // task pointer
routine, // name of function to be execute
1,
// int passed to routine
STACK_SIZE,
// execution stack size
1,
// int priority, 0=highest priority
0,
// int 0 => fpu not used
//
1 => fpu is used
0
// signal (see rt_task_signal_handler)
);
iret = 0 if ok, <0 either
l task creation is done in init_module!
l
! rt_task_init doesnt execute the task
34
Periodic task
In init_module
iret = rt_task_make_periodic(&tache,
start_date, nano2count(PERIODE));
_
Periodic execution,first execution since start_date,
units is count
In the task
loop containing task + function rt_task_wait_period
();
_ suspend task execution until next period
35
Suspend and delete a task
l
Suspend
rt_task_suspend( rt_whoami() );
Re-execute
rt_task_resume( &tache);
_ Also
allows to execute a non-periodic task
Ending
rt_task_delete( &tache);
36
Time
l
Timer : 2 possible behaviour
-
rt_set_oneshot_mode()
l
Recent Pentium provides CPU TSC (Time Stamp Clock) =>
variable time base
386,486 and old pentium dont provide CPU TSC => need to
read an external timer 8254 => cost time, not efficient
rt_set_periodic_mode()
l
Default mode
Fixed period
The tasks whose period is not a multiple of timer period are
executed with the nearest multiple period
37
Time (2)
l
First, the timer must be started
tick_per = start_rt_timer(per);
- one shot mode : per irrelevant
- Periodic mode : per = period of the timer in count,
tick_per = alocated period
To read the timer
rt_get_time(); in count unit
rt_get_time_ns(); in nanosecond unit
Conversions
RTIME tn, tc;
tc = nano2count(tn);
tn = count2nano (tc);
Stop the timer (cleanup_module)
stop_rt_timer();
38
RTAI scheduling
l
Scheduling policy can be combined
-
-
EDF > fixed priority
Linux = task with the smallest priority
Priority
-
Fixed priority : de 0 RT_LOWEST_PRIORITY
ma_prio = rt_get_prio( rt_whoami());
old = rt_change_prio(rt_whoami(),
ma_prio+1);
Dynamic priority
rt_task_set_resume_end_times(wakeup_date, duedate_date);
rt_task_set_resume_end_times(-period,-deadline);
39
Multiprocessor scheduling
l
SMP : Symetric Multi Processor
2 solutions
-
1 scheduler handle n processors
l
Execute the n highest priority tasks among the t ready tasks
1 scheduler on each processor
l
Each task is allocated to a processor
40
VI. SYNCHRONISATION,
COMMUNICATION
41
Synchronisation / Communication: why?
l
Transmit an event
-
fugitive, memorised, incremented
With/without value
Ordering
-
before / after
Control the number of execution
Data exchange
-
With synchronisation
Without synchronisation
l
Ensure data integrity
42
RTAI : binary semaphore - mutex
l
Rendez-vous, mutual exclusion
Creation
SEM mon_sem;
rt_typed_sem_init(&mon_sem, // semaphore pointer
1, // initial value
BIN_SEM
// type
);
Take a semaphore
If the semaphore is prsent : on prend le smaphore et on continu
Si le smaphore est absent : on est bloqu jusqu ce que le smaphore
soit restitu
ierr = rt_sem_wait(&mon_sem);
Restituer le smaphore
ierr = rt_sem_signal(&mon_sem);
43
Smaphores (2)
l
Problmes : inversion de priorit, interblocage
Autres types
rt_typed_sem_init(&mon_sem,1,BIN_SEM);
A compte : CNT_SEM
l Ressource : RES_SEM
l
-
l
Destruction
-
met en place le protocole de priorit plafond
ierr = rt_sem_delete(&mon_sem);
Variantes asynchrones
-
rt_sem_wait_if : pas de blocage si smaphore absent
blocage au maximum
jusqu date
- rt_sem_wait_timed(&sem,dure) : blocage au maximum
pendant dure
- rt_sem_wait_until(&sem,date):
44
RTAI : Fifos
X Windows
Process utilisateur
RT
Fifo
Noyau Linux
RT
Fifo
Tche
RT
Tche
RT
RTAI
Ecran
Disques
Rseau
Priphriques
45
RTAI : RTFifos cot process utilisateur
l
ct process utilisateur
-
priphrique spciaux de type caractre :
l
/dev/rtf0, /dev/rtf1 v
accessibles travers les appels : open, ioctl, read, write
communication sans structure
l
file FIFO tampon d un nombre d octets fix
n existe (ne peut tre ouvert) que si dj cr par
tche RT ou par appel spcifique
46
RTAI : RTFifos cot RT
l
2 modes d utilisation
l
comme priphrique
API spcifique RT
rtf_create(unsigned int fifo, int taille);
cration,
priphrique /dev/rtffifo existe,
rtf_destroy(unsigned int fifo);
destruction,
mmoire ralloue
rtf_put(fifo, char *tampon, int compte);
rtf_get(fifo, char *tampon, int compte);
retour -1, si insuffisamment de donnes ou
de place
non bloquant
47
RTAI : RTFifos
l
ct tche RT (2)
l
API spcifique RT
int my_handler(unsigned int fifo);
rtf_create_handler(3,&my_handler);
routine my_handler excute en mode noyau quand des donnes
sont lues ou crites
l
l
l
permet de rveiller une tche RT, via [Link]. un task_resume
permet d viter la scrutation rgulire de la FIFO
permet de mettre en place un schma ASYN/SYN quelconque avec
smaphores
rtf_resize => redimensionner la fifo
l
plus d autres fonctions
48
Messages
l
Caractristiques
-
Communication point point (tche tche)
message : valeure entire
SYN/SYN
ierr = rt_send(&tache_but,valeur); //SYN
ierr = rt_receive
(&tache_orig,&entier); //SYN
Variantes
-
If : send ASYN, pas denvoi si recepteur non prt, pas de blocage de lemetteur
timed et until : blocage limit dans le temps
rt_receive(0 : n importe quel metteur
Pas d initialisation spcifique
49
Botes aux lettres (Bal)
l
Caractristiques
-
-
-
-
-
ierr = rt_mbx_send(&Bal,&msg,taille_msg); ASYN, mais
blocage tant que le message entier na pas t copi dans la Bal
ierr = rt_mbx_receive(&Bal,&msg,taille_msg); Blocage tant
que le message na pas t reu
Variantes send
-
-
-
Communication multi/multi point
message : taille variable
ASYN/SYN
if : envoi ssi le message entier peut tre copi dans la bal
Wp : envoi autant doctets que possible sans blocage
timed et until : blocage limit dans le temps
initialisation spcifique
-
-
ierr = rt_mbx_init(&Bal,taille)
ierr = rt_mbx_delete(&Bal);
50
Le problme de l allocation mmoire
l
l
l
Segmentation,
Mmoire pagine
pas new/delete ou malloc/free
-
kmalloc / kfree
non temps rel
solutions RT :
s allouer la mmoire de manire statique
- allocation dans une table de blocs limite
-
utilisation de kmalloc au niveau noyau
51
RTAI : Interruptions
l
l
l
l
permet ractions rapides
inhibe le noyau temps rel
niveau matriel et niveau logiciel
gestionnaire d IT simples avec temps de rponse fixe (ou
born)
-
-
prise en compte d un vnement
phase urgente, laisser une tche dans l espace utilisateur faire le
travail de fond
ITs/vnements peuvent tre mis par :
-
-
-
quipement informatique (clavier, cran, disque )
quipement industriel (capteur, actionneur, alarme )
horloge : donne le rythme (tick = priode d chantillonnage du
systme)
52
Interaction par Interruption
requt
e
masquage
encodeur
priorit
priorit
Acq
rt_global_cli() rt_global_sti()
rt_disable_irq(), rt_enable_irq()
IA
set
reset
Bus donnes
53
RTAI : Interruptions (2)
l
Installation
#define IT_CLAVIER 1
rt_request_global_irq(IT_CLAVIER,
mon_gestionnaire);
rt_free_global_irq(IT_CLAVIER);
void mon_gestionnaire(void) {
rt_pend_linux_irq(IT_CLAVIER);
Utilisation
traitement urgent
- rveiller tche endormie
-
54
RTAI : communication avec le matriel
l
par pilote de priphrique (posixio)
-
fichiers /dev/nom
l
open/ close/ read/ write
accs direct aux ports E/S
#include <asm/io.h>
outb(valeur, adresse)
valeur = inb(adresse)
l
taille du mot : b, w, l
pause : _p : outl_p
55
Schmas classiques
l
Chien de garde (Watchdog)
Comment grer un automate d tat (machine
caf, menu tlphone )
BD : lecteur rdacteur
Client Serveur
l
l
tableau noir
56
Exemple : machine caf
AN
N
U
L/
rendre_m
onnaie();
FR
AN
C
EN
CO
R
E
IN
IT
R
ETO
U
R
SER
VI
AN
N
U
L/
rendre_m
onnaie();
PR
EPAR
ATIO
N
SER
VIR
/
deplacer_tasse();
FR
AN
C
ACTIF
PU
SH
/
preparer_cafe();
57
Machine caf : spcfication fonctionelle
IHM
Process Linux
RTAI
Rt_fifo
Acqui
Appel
Genere_transition
Signal transition
Calcul Automate
Rendre monnaie
Dplacer tasse
Prparer caf
Afficher message
58
[Link] : CONCLUSION
59
RTAI : quelques remarques
l
volution permanente
possibilits en phase de mise au point non
dtailles ici
-
outils de trace : LTT
excution en mode user : LXRT
Xenoma
-
POSIX, VxWorks,VRTX,pSOS+,ITRON,RTAI
60
RTAI : quelques remarques
l
volution permanente
possibilits en phase de mise au point non
dtailles ici
-
debug
outils de trace : LTT
excution en mode user : LXRT
Xenomai
61
RTAI-LAB
Spcification schmas-blocs
SCILAB/SCICOS
MATLAB/SIMULINK
Gnration code
+
Librairie RTAI-LAB
RTAI
Excution
[Link]
[Link]
[Link]
62
VIII. AND OTHER RTOS
63
Some RTOS
RTOS
URL
([Link]
Processor
Licensing
Tornado, VxWorks
h"p://[Link]
x86, 68k, PPC, CPU 32, i960, SPARC,
SPARCLite, SH, ColdFire, R3000, R4000,
C16X, ARM, MIPS
$16,500 per user + target
Hard Hat Linux
h"p://[Link]
x86, PPC, MIPS and ARM
No
VRTX
h"p://[Link]
x86, 68k, PPC, i960, ARM
$2,000 par user + target
OS-9 V3.0
h"p://[Link]
x86, 68k, PPC, SH3, StrongARM
? + target
h"p://[Link]
AMD lanSC300/ 310/ 400/ 410, AM386
DE/SE Intel386 EX, Intel486, ULP Intel486, Pricing is based on OS modules
Pentium, Pentium Pro, and NatSemi
used on the target system and per
NS486SXF.
unit shipped.
pSOS
h"p://[Link]
86, 68k, PPC, 683xx, CPU32(+), MIPS
R3000/4000/5000, Coldfire 510x/520x,
i960, ARM 7 (TDMI), SH1/2/3, M32R
$17,000 per user + target
RTX
h"p://[Link]
x86, P5, P6
$150/RTX licence + target
QNX
US$10,000 per user
LynxOS
h"p://[Link]
x86, 68k, PPC, microSPARC, microSPARC
II, PA-RISC
Licence: US$7000 + target
. + many other
64
RTOS market survey(2005)
(source : [Link]
65
RTOS market survey
(source : [Link]
66
RTOS market survey
(source : [Link]
67
RTOS market survey
(source : [Link]
68
Choice of an RTOS
l
Performance = time to provide a service to the
application, it depends on:
-
-
-
Hardware architecture,
What measuring ? => benchmarks
Premption duration, Task switching, semaphore, memory allocation,
services
Price : licence + per unit shipped
Source Code, certification
Tools
69