Robotics Real-Time Programming
Robotics Real-Time Programming
Ludovic Saint-Bauzel
Ludovic Saint-Bauzel
2013-14
Contents
1 Introduction 4
1.1 What is a robot ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1.2 Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1.3 Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.2 What is a controller ? . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.2.1 System Design . . . . . . . . . . . . . . . . . . . . . . . . 10
1.2.2 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . 11
1
3.3 Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.3.1 Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.3.2 Posix Thread . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.4 Time Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
3.4.1 Posix Time . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
3.4.2 Xenomai Time services . . . . . . . . . . . . . . . . . . . . 50
3.5 Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
3.5.1 Mutex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
3.5.2 Variable Conditionnal . . . . . . . . . . . . . . . . . . . . 51
3.5.3 Counting Semaphore . . . . . . . . . . . . . . . . . . . . . 52
3.5.4 Xenomai Native API Synchronisation tools . . . . . . . . 54
3.6 Messages and Communication . . . . . . . . . . . . . . . . . . . 54
3.6.1 Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.6.2 Mail Queue . . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.6.3 Xenomai Native API . . . . . . . . . . . . . . . . . . . . . 57
3.7 IO Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
3.7.1 Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
3.7.2 IO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4 OS Driver Programming 62
4.1 First Idea : From Scratch . . . . . . . . . . . . . . . . . . . . . . . 62
4.1.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
4.1.2 x86 example . . . . . . . . . . . . . . . . . . . . . . . . . . 63
4.1.3 From scratch approach . . . . . . . . . . . . . . . . . . . . 68
4.2 Second Idea : Operating System Approach . . . . . . . . . . . . 68
4.2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . 68
4.2.2 Linux Kernel Introduction . . . . . . . . . . . . . . . . . . 69
4.3 Linux Kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
4.3.1 Main Concepts . . . . . . . . . . . . . . . . . . . . . . . . 71
4.3.2 Components and mechanisms . . . . . . . . . . . . . . . 73
4.3.3 Developing environment . . . . . . . . . . . . . . . . . . 77
4.4 Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
4.4.1 Dev. tools . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
4.4.2 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.4.3 Practical . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
4.5 User Space Mechanisms . . . . . . . . . . . . . . . . . . . . . . . 81
4.5.1 Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
4.5.2 System Calls . . . . . . . . . . . . . . . . . . . . . . . . . . 81
4.5.3 Hardware access . . . . . . . . . . . . . . . . . . . . . . . 82
4.6 Kernel/Hardware Interface . . . . . . . . . . . . . . . . . . . . . 84
4.6.1 Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
4.6.2 Interruptions and events . . . . . . . . . . . . . . . . . . . 86
4.6.3 Waiting queues . . . . . . . . . . . . . . . . . . . . . . . . 88
4.7 Driver (Module) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
4.7.1 Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . 89
4.7.2 Basic Routines . . . . . . . . . . . . . . . . . . . . . . . . . 90
2
4.7.3 Char Devices . . . . . . . . . . . . . . . . . . . . . . . . . 92
4.7.4 Memory Management . . . . . . . . . . . . . . . . . . . . 94
4.7.5 Xenomai a RTOS example . . . . . . . . . . . . . . . . . . 94
4.7.6 Description . . . . . . . . . . . . . . . . . . . . . . . . . . 94
4.7.7 Main Mechanisms . . . . . . . . . . . . . . . . . . . . . . 98
4.7.8 RTDM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
5 Application 100
5.1 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
5.1.1 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
6 Documentations 106
6.1 Doc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
6.1.1 Interface with community . . . . . . . . . . . . . . . . . . 106
6.1.2 References . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
6.1.3 Licences . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
6.1.4 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
3
1 Introduction
1.1 What is a robot ?
1.1.1 Definition
Robot
1.1.2 Hardware
Structure Choice criteria
• Critical path?
4
Robot Environment
Sensors
Control
Effectors
Supervision / Decision
Sensors
Decision
Effectors
5
Figure 2: mc2e
• Parameters
– Computation
– Time constraints
– Memory needs
– Precision of measure
Monocomputer
• Properties
– Limited Computation Ability
– Delays are limited too
– Simple but efficient
• Recent Improvements
– GPU
– Multicore CPU
• Example
6
Robot
Sensors
Control
Effectors
Supervision / Decision
Monocomputer
• Properties
– Limited Computation Ability
– Delays are limited too
– Simple but efficient
• Recent Improvements
– GPU
– Multicore CPU
• Example
Multi computer
• Properties
– High scalability of computation
– High time lost : Bus communication
• Recent Improvement
– Distributed algorithms developpment
• Example
7
Figure 4: Staubli
Multi computer
• Properties
– High scalability of computation
– High time lost : Bus communication
• Recent Improvement
• Image
8
Robot
Sensors
Robot Models
Control - Kinematics UDP
- Velocities
Trajectory Control
Effectors
GUI To choose
trajectories
Supervision / Decision
Bus
• Definition
– Physical connection
– Multiple devices
• Common elements :
9
1.1.3 Software
How the robot can make environment interaction ?
• Categories
– Perception
– Decision
– Actions
• Computer Science Name : tasks
Real-Time Programming
DOS
# include < dos .h >
...
unsigned char inputb ( unsigned short port ) ;
void outputb ( unsigned short port , unsigned char byte ) ;
SADT : Structure
Petri Net
10
Figure 6: SADT: Structured Analysis and Design Technique
1.2.2 Methodology
Find the tasks!
• No Fuzzy properties
– Real-Time
– Good Refresh rate
• Nothing is perfect
– Properties
∗ Time (Loop (Freq?), Oneshot)
∗ Load (CPU)
– Boundaries
∗ Delays
∗ Memory
• Task repeated every miliseconds with acceptable delay of 0.01 ms
• Control Task
– Loop, Delay
– Variable Parameters
– Static parameters
• User Interface
– Supervision
– Send Orders (Asynchronous, Parameters)
11
Figure 7: SADT : Hierarchical Structure
12
Figure 9: RUPI
MVC+
• View
– Supervision
– GUI
• Controller
– Send Orders
– Control Task Information
– GUI
• Model
– Synchronization
– Communication System
– Database
• RT Task
13
2.2 OROCOS
2.2.1 Open RObotics COntrol Software
Introduction
The aim of this part is to present a framework that is a state of art of what
can be done by a system that manages the control of a robot. Of course this
framework is not perfect and some choices can be questionned but i decided
to choose this to give you the main rationales that one can imagine to use to
make a good controller. As a summary of the properties I appreciate:
• component programming that provides a good reusability of the code and
lets deploy differents things according to the needs
• Dataflow : The main system is based on a software dataflow approach.
That is very close to the control of systems.
• State-Machine of components lets work with hooks for every state. Gives
a supervision of the components.
• State-Machine of deployment, lets implement complex behaviour, change
the control kind
• Activity mechanism to update each component : gives a wide variety of
updating mechanism different to the data-flow
• logging Thanks to the component approach and the hook approach, it is
possible to subscribe to ports of component and see what happens
OROCOS Project
14
History
• European Funding
• European Labs
– K.U.Leuven in Belgium ( Orocos@KUL )
– LAAS Toulouse in France ( Orocos@LAAS )
– KTH Stockholm in Sweden ( Orocos@KTH )
• Real-Time Toolkit
• Orocos Component Library
Task Context
• 2 Solutions
– Custom Component
∗ + Complete control of the generated file
∗ - Some additional code that is not the heart of the controller
– Listen a component through logging tools
∗ In C++ code :
∗ In deployment :
∗
15
Figure 12: RTT Workflow
16
Figure 14: Component State Diagram
17
Task State Diagram
Activity vs Threads
Data Flow
Example : Definition
• Supervisor
– Initialisation
– Waiting
– Standing-Up
– Walking
– Alert
• Sensors
– Force Handles
– Orientation of the arm
– Orientations of the wheels(Beta_L,Theta_L, Beta_R,Theta_R)
• Controls
– Impedance Control
– Position Control
– Speed Control
18
– Models
∗ XZ MGD
∗ XYPhi MGD
∗ Trajectory Generator
19
Figure 18: State Machine of Walky Experiment
20
Figure 19: Dataflow of Walky Controller
21
Example : Component Skeleton(Excerpt)
class Supervisor : public TaskContext {
protected :
InputPort < std :: vector < char > > inButtons ;
InputPort < bool > STSDetected ; /*...*/
string s t a t e M a c h i n e N a m e ;
public :
Supervisor ( string const & name )
: TaskContext ( name ) ,
s t a t e M a c h i n e N a m e (" statemachine ")
{
this - > addEventPort (" STSDetected " , STSDetected );
this - > addProperty (" s t a t e M a c h i n e N a m e " , s t a t e M a c h i n e N a m e );
}
bool configureHook () {
return true ;
}
bool startHook () {
scripting :: S c r i p t i n g S e r v i c e :: shared_ptr sa
= boost :: dynamic_pointer_cast < scripting :: ScriptingService >(
provides () - > getService (" scripting "));
scripting :: St a te Ma c hi ne P tr sm = sa - > g e tS ta t eM ac h in e ( s t a t e M a c h i n e N a m e );
if (! sm ) {
log ( Error ) << " State Machine not loaded in Supervisor ." < < endlog ();
return false ;
}
return sm - > activate () && sm - > start ();
}
void updateHook () {
}
void errorHook () {
}
void stopHook () {
scripting :: S c r i p t i n g S e r v i c e :: shared_ptr sa
= boost :: dynamic_pointer_cast < scripting :: ScriptingService >(
provides () - > getService (" scripting "));
scripting :: St a te Ma c hi ne P tr sm = sa - > g e tS ta t eM ac h in e ( s t a t e M a c h i n e N a m e );
if (! sm ) {
log ( Error ) << " State Machine not loaded in Supervisor ." < < endlog ();
return ;
}
sm - > stop ();
sm - > deactivate ();
}
void cleanupHook () {
}
};
22
Example : Deployment File(Excerpt)
< properties >
< struct name =" Supervisor " type =" Supervisor " >
< struct name =" Activity " type =" Activity " >
< simple name =" Period " type =" double " > < value >0.1 </ value > </ simple >
< simple name =" Priority " type =" short " > < value >50 </ value > </ simple >
< simple name =" Scheduler " type =" string " > < value > ORO_SCHED_RT </ value > </ simple >
</ struct >
< struct name =" Peers " type =" PropertyBag " >
< simple type =" string " > < value > STSDetector </ value > </ simple >
<! - -... [ EVERY PEERS that will be touched by this component ] ... -->
</ struct >
< struct name =" Ports " type =" PropertyBag " >
< simple name =" STSDetected " type =" string " > < value > STSDetected </ value > </ simple >
</ struct >
< simple name =" RunScript " type =" string " > < value > deployment / smSTSandWALK . osd </ value > </ simple >
</ struct > <! - -...... - - > </ properties >
2.3 ROS
2.3.1 Robotics Operating System
Definition
• ROS (Robot Operating System) provides libraries and tools to help soft-
ware developers create robot applications. It provides hardware abstrac-
tion, device drivers, libraries, visualizers, message-passing, package man-
agement, and more.
• Willow Garage
– Created in 2006
– 2008 first stable release of ROS
– 2010 ROS 1.0
Connecting Middleware
• Nodes
– Server (roscore)
– Output (rosout)
• Topics
– Publishers
– Subscribers
• Parameterized Connections
– TCP
23
– SharedMemory
– Serial (Arduino RosSerial)
Meta-Operating System
• Meta-Operating-System
– rosdep
– rosmake
– roscd
– rosed
– rosrun
• Usefull tools
– rxgraph
– rxplot
24
Figure 21: rxplot of /Example node with its topics
25
excerpt Manifest
< package >
< description brief =" depth_reg " >
depth_reg
2.4 Frameworks
2.4.1 Conclusion
Connectivity Question
• Exercice :
• Description
– Kinect
– OpenCV
– SLAM
– Directions
• Aim
– When someone do hello then go to its direction
Example
• Exercice
– Description
∗ Kinect
∗ OpenCV
∗ SLAM
∗ Directions
– Aim
∗ When someone do hello then go to its direction
• Result
– Kinect -> OpenCV -> Position -> SLAM -> Directions
26
Connectivity Solutions
• In OROCOS :
– Omni ORB
– From Scratch Components Connection
∗ RPC
∗ CORBA
∗ Sockets -> Server/Client Approach
• ROS
Conclusion
• Overview Implementation
27
Resources
Computer Science :
• Processor : CPU, IRQ
• Communication : BUS
• Memory
• ...
Robotics :
• Motor
• Sensors
What is RealTime
Two examples :[3mm]
A navigation system computing the best path for a boat.
A navigation system computing a boat position during its sailing.
• First case: Computing time is not a constraint, the result is this only thing
that is interesting
• Second case, if computing time is too long, position is false.
An informal definition
3.1.2 Properties
Time scheduling
28
Predictability determinism reliability
Real time system : in worst case.[3mm]
Predictability : Ability to identify in advance if a system is able to respect
its time constraints Knowledge of parameters related to computation.
Determinism : remove any uncertainty in individual task behaviour and
when they are together
• Variation of task execution time
• IO duration, reaction time
• Interruption reaction
3.1.3 Multitasks
Services of a multitasks system
Conclusion : A single program rarely use all CPU load[2mm]
Used those idle times to compute some concurrent other tasks from other
software : a part of what an operating system must do
29
CPU Management - Task, process
Standard operating systems manage process that can be described as follow
:
30
Created Terminated
Main Memory
Running
Waiting Blocked
Virtual Memory
Scheduling
Scheduler must manage how the task are allocated to the CPU.
Schedule in the best way is very hard.
A scheduler called with request or pre-emptive if running process can be
unallocated by scheduler.
Non pre-emptive systems can do context switch only when a task is termi-
nated or when it is asking for context switch
Scheduler works most of the time on-line. That means that a policy must
exists and be applied[3mm]
Scheduling policy
Classical scheduling rules :
• First In First Out (FIFO)
• Each one its turn (tourniquet, Round Robin : RR)
• Priority based
Example
Task Length Priority Start time
T1 6 1 0
T2 3 2 0
T3 4 1 0
31
Created Terminated
Main Memory
Running
Waiting Blocked
Virtual Memory
Scheduling example 1
• FIFO
T1 T1 T1 T1 T1 T1 T2 T2 T2 T3 T3 T3 T3
• RR
T1 T2 T3 T1 T2 T3 T1 T2 T3 T1 T3 T1 T1
• Priority
T2 T2 T2 T1 T1 T1 T1 T1 T1 T3 T3 T3 T3
Scheduling example 1
Scheduler with task interactions
Task 1 (prio = 2) Task 2 (prio = 2) Task 3 (prio = 3)
(not started)
T[1.1] T[2.1] T[3.1]
wait (event) Signal wait (1 sec.)
T[1.2] (Task 1, event)
T[2.2] T[3.2]
Starting Task 3
Scheduling example 2
Pre-emption after OS signal
32
Task 1 (prio = 2) Task 2 (prio = 2) Task 3 (prio = 3)
T[1.1]
Wait (evt)
T[2.1] Signal T1
T[1.2]
T[2.2] Start T3
T[3.1] Wait 1 sec.
T[3.2]
Scheduling example 2
Without pre-emption
Task 1 (prio = 2) Task 2 (prio = 2) Task 3 (prio = 3)
T[1.1]
Wait (evt)
T[2.1] Signal T1
T[2.2] Start T3
T[3.1] Wait 1 sec.
T[1.2]
T[3.2]
Interruptions
• 2 kind
Interruption management
The way interruptions are processed have a large influence on efficiency of
the OS
33
Resources management
Those mechanisms are used to give one access to one resource in one time.
• Define some sections as atomic : critical sections
• Mask interruptions (hardware)
Synchronization
Force an order of processing instructions of a process
• Mutex
• Rendezvous
• Product/Consume
Uses the following mechanisms :
• Signal an event
• Semaphores use
• Mailboxes
• Rendezvous
Synchronization Limits
Maintain coherency of data : creation of waiting queues
Some solutions :
• Priority based waiting management : unlock view the priority level of
the task
34
Input/Output
Different policies for CPU scheduling and for Input/Output (IO)
• Access through a specialized layer
• Synchronous processing
• Asynchronous processing
• Difficult to manage priorities
• Bad time management
3.1.4 Real-Time
Services
Components
The main components of a RTOS are :
• scheduler, inside every kernel, it is the component that apply different
algorithms to manage access to the CPU
• kernel interfaces that give developers the ability to create software
– tasks
– semaphores
– message queue...
• services : actions that a kernel can do on a device or on the system like
time measurement, interruption, bus controller,...
35
3.2 Scheduling
3.2.1 Model
Scheduler
Aim : address any needs of a real-time software like emergency stop, high
level action or reactivity need
Taxonomy :
• Off-line/On-line algorithm : static/dynamic algorithm
• Static/Dynamic priorities
• pre-emptive/non pre-emptive algorithms :
– Ability to have mutual exclusion of a device
– Scheduler cost low
– Small efficient
Scheduler
Properties that we look for :
• Feasibility : ability to decide "a priori" that all the constraints will be ful-
filled
• Predictability : response time of tasks is predictable.
• Optimality : Optimal if able to find a schedule of every set of feasibility
tasks
• Complexity : feasibility test is long and difficult?
• Easiness to implement
Scheduler
Scheduler works only on active tasks :
• Schedule Table : off-line scheduling
• Off-line priorities definition, root of the scheduling
• On-line analysis and scheduling
Analysis recipe
Scheduling problem :
• To Model tasks of the system and their constraints
• To Choose a scheduling algorithm
• To Validate feasibility on a set of tasks
– Theoretical feasibility : scheduling ability and complexity
– Empirical feasibility : implement scheduler
36
Task model
Task families :
• Linked task or not (Precedence constraint).
• Important task or not
Task model
Parameters for task i
• Si : start time when task arrives in the scheduler
• Ci : Computation time needed by the task (Capacity).
• Pi : Period
Task model
Let’s consider a simplified model :
• Periodic task
• Independent (No precedence constraint)
• Starting time (worst case) : Si = 0
37
Scheduler Structure
Computation of scheduling information
• On-line or Off-line
• Period, Deadline...
Election phase
• Priority, deadline, ...
3.2.2 Algorithms
Rate Monotonic Algorithm
Off-line analysis, fixed priority, periodic tasks : Static software
Rationale
1
• Computation phase : priority = period
Properties
• Low Complexity
• Optimal Algorithm in fixed priority algorithm set
Can be scheduled if load rate of the CPU U agrees with the following suffi-
cient condition :
n
C 1
U= ∑ Tii ≤ n × (2 n − 1)
i
38
Critical time theorem
If every tasks both arrive at the same time in a system if they respect their
first deadline,
then
every other following deadlines will be respected whatever time they arrive
in the system
• it’s a necessary and sufficient condition if every tasks arrive at the same
time
• else, it is a sufficient condition
If Di = Ti , finishing test is :
& '
iCj t
∀i, 1 ≤ i ≤ n min0≤t≤ Di ∑ t Tj
≤1
j =1
TRi = Ci + ∑ Ij
j∈hp(i )
& '
TRi
TRi = Ci + ∑ Pj
Cj
j∈hp(i )
39
Aperiodic tasks with high priorities
Periodic task dedicated to these tasks.
Rationale :
• Computation phase : Deadline computation
With priorityi (t) current priority at t and i the task :
EDF Example
Let consider 2 tasks : [3mm]
T1 : C1 = 6, P1 = 10[3mm] T2 : C2 = 9, P2 = 30
• Pre-emptive case
• Non pre-emptive case
EDF Properties
Ability to schedule : Pre-emptive case, periodic and independent tasks
• Necessary and sufficient condition if ∀i, Di = Pi ; Only necessary if ∃i, Di ≤
Pi :
n C
j
U=∑ ≤1
P
j =1 j
40
PS
e1
e2
0 5 10 15 20
e1 e2
41
3.2.3 Thread Scheduling
Services
Properties :
• Threads and process capability
• Fixed priorities, pre-emptive ⇒ RM easy. A minimum of 32 levels is a
mandatory
• One waiting queue for each priority and scheduling policy (SCHED_F
IFO, SCHED_RR, SCHED_OTHERS).
• Available Services to specific users (like root)
Standard say that scheduling policies must be able to be applied each time
the choice threadprocess exists (ex. : choice of a threadprocess to release a
semaphore).
Policies
POSIX.4 policies :
# define SCHED_OTHER 0
# define SCHED_FIFO 1
# define SCHED_RR 2
42
• Parameters modification:
– Thread : creation of a thread from an attribute or modification of a
running thread.
– Inherit from a fork() or modify of a running process.
API
sched_get_priority_max Get max priority value.
sched_get_priority_min Get min priority value.
sched_rr_get_interval Get duration of one time unit.
sched_yield Free the CPU of this thread.
sched_setscheduler Choose the scheduler policy.
The
sched_getscheduler Get the scheduler policy value.
sched_setparam Set parameters of the scheduler.
sched_getparam Get parameters of the scheduler.
pthread_setschedparam Set parameters of the scheduler for thread.
pthread_getschedparam Get parameters of the scheduler for thread.
last 2 function are working only on threads, other functions can be applied on
process/thread.
Example
struct sched_param parm ;
int res = -1;
...
/* Task T1 ; P1 =10 */
parm . s ched_p riorit y =15;
res = s c h e d _ s e t s c h e d u l e r ( pid_T1 , SCHED_FIFO ,& parm )
if ( res <0)
perror (" s c h e d _ s e t s c h e d u l e r task T1 ");
/* Task T2 ; P2 =30 */
parm . s ched_p riorit y =10;
res = s c h e d _ s e t s c h e d u l e r ( pid_T2 , SCHED_FIFO ,& parm )
if ( res <0)
perror (" s c h e d _ s e t s c h e d u l e r task T2 ");
3.3 Management
3.3.1 Process
Fork
# include < unistd .h >
pid_t fork ( void );
43
Kill - Signal
# include < signal .h >
POSIX Threads
• Code must be re-entrant (or "thread safe") ⇒ code is able to be computed
in multiple instances in a safe way
• re-entrant code means :
– don’t manipulate shared variables.
– or it manipulate shared variables in a critical section (that mean no
other is able to access this variable when one is manipulating it) .
• Everything must be re-entrant user code but also system libraries (ex.
libc.so)
POSIX threads
pthread_create Creation of a thread.
Paramters : code, attributes, arg.
pthread_exit End of a thread.
Parameter : return error value.
pthread_self returns id of the running thread
pthread_cancel Destroy a thread.
Parameter : id of the thread.
pthread_join Suspend a thread until
another is not finished.
pthread_detach Suppress parent link
between threads.
44
POSIX Threads
pthread_kill Emit a signal to a thread.
pthread_sigmask Modify signal mask of a thread.
POSIX Threads
Creation and join example of a thread
# include < pthread .h >
void * th ( void * arg )
{
printf (" I am thread % d ;
process % d \ n " ,
pthread_self () , getpid ());
pthread_exit ( NULL );
}
POSIX Threads
Creation and join example of a thread
# include < pthread .h >
void * th ( void * arg )
{
printf (" I am thread % d ;
process % d \ n " ,
pthread_self () , getpid ());
pthread_exit ( NULL );
}
POSIX Threads
int main ( int argc , char * argv [])
{
pthread_t id1 , id2 ;
pthr ead_cr eate (& id1 , NULL , th , NULL );
pthr ead_cr eate (& id2 , NULL , th , NULL );
pthread_join ( id1 , NULL );
pthread_join ( id2 , NULL );
printf (" End of main thread % d ;
process % d \ n " ,
pthread_self () , getpid ());
pthread_exit ( NULL );
}
45
POSIX Threads
• With Solaris :
gcc - D_REENTRANT create . c - lpthread - lrt
>a . out
I am thread 4 ; process 5539
I am thread 5 ; process 5539
End of main thread 1 ; process 5539
• With Linux :
gcc - D_REENTRANT create . c - lpthread
>a . out
I am thread 1026 ; process 1253
I am thread 2051 ; process 1254
End of main thread 1024 ; process 1251
Thread Attributes
Thread Attributes : properties of a thread that are defined during its cre-
ation. No heritage between father and son threads.
Example of attributes :
Attribute Name Meaning
detachstate pthread_join possible or not
policy scheduler policy
priority level of priority of the thread (≥ 0)
stacksize Size of the allocated stack
Thread Attributes
During creation of a thread, an structure of type pthread_attr_t can be
filled and given if we want to specify none default attributes to the new thread
:
pthread_attr_init Creation of a default attribute structure.
pthread_attr_delete Destruction of attribute structure.
pthread_attr_setATT set the value of "ATT" attribute.
pthread_attr_getATT set the value of "ATT" attribute.
Thread Attributes
# include < pthread .h >
void * th ( void * arg )
{
printf (" I am thread % d \ n " ,
pthread_self ());
}
46
Thread Attributes
int main ( int argc , char * argv [])
{
int i ;
pthread_t id ;
pthr ead_at tr_t attr ;
struct sched_param param ;
p t h r e a d _ a t t r _ i n i t (& attr );
p t h r e a d _ a t t r _ s e t d e t a c h s t a t e (& attr ,
P T H R E A D _ C R E A T E _ D E T A C H E D );
p t h r e a d _ a t t r _ s e t s c h e d p o l i c y (& attr ,
SCHED_FIFO );
param . sch ed_pri ority =1;
p t h r e a d _ a t t r _ s e t s c h e d p a r a m (& attr ,& param );
for ( i =1; i <10; i ++)
pthr ead_cr eate (& id ,& attr , th , NULL );
}
Thread Attributes
The TSD (Thread Specific Data area) : is an area of memory where are stored
specific information of each thread.
Allow extension of regular attributes.
Thread Attributes
Creation of a new attribute :
pthread_key_t cd_key ;
int p th re a d_ c d_ in i t ( void )
{
return p t h r e a d _ k e y _ c r e a t e (& cd_key , NULL );
}
Thread Attributes
int pthrea d_set_ cd ( char * cd )
{
char * mycd = ( char *) malloc ( sizeof ( char )*100);
47
strcpy ( mycd , cd );
return p t h r e a d _ s e t s p e c i f i c ( cd_key , mycd );
}
int main ( int argc , char * argv [])
{
p th re a d_ c d_ in i t ();
pthr ead_se t_cd ("/ here / dir ");
printf (" My local directory is % s \ n " ,
pthr ead_ge t_cd ());
}
• Available services :
• Get and set clocks.
• Put a task in sleep mode.
• Link periodic timer to UNIX signals ; and maybe with real-time signals.
With or without automatic restart.
48
Time Manipulation
clock_gettime Get clock value.
clock_settime Set clock value.
clock_getres Get clock resolution.
timer_create Create a timer.
timer_delete Remove a timer.
timer_getoverrrun Give the number of unprocessed signals
timer_settime Activate a timer.
timer_gettime Get time to the end of the timer
nanosleep Block a process/thread during a
defined duration.
int go =1;
void too_late ( int sig ){
printf (" Signal % d received \ n " , sig );
go =0;
}
Execution :
49
3.4.2 Xenomai Time services
API Timer Management System
API :
• void rt_timer_spin (RTIME ns) : busy clock
• int rt_timer_set_mode (RTIME nstick) : TM_ONESHOT or period time
Hardware level :
• oneshot
• periodic
3.5 Synchronization
3.5.1 Mutex
Mutex
Rationale
Programming mechanism that can block a thread while a condition is not
true.[3mm]
50
Mutex
pthread_mutex_init Initialize a mutex.
pthread_mutex_lock Lock the mutex in blocking manner eventually.
pthread_mutex_trylock Non blocking try to lock the mutex
pthread_mutex_unlock Release the mutex lock.
pthread_mutex_destroy Destruct the mutex.
pthread_mutexattr_init Initialize an attribute structure
pthread_mutexattr_setATT Set attribute ATT.
pthread_mutexattr_getATT Get attribute ATT value.
o ATT is one of the attributes of the mutex.
API
pthread_cond_init Initialize a variable.
pthread_cond_destroy Destruct a variable.
pthread_cond_wait Wait a waking signal coming from a condition.
pthread_cond_signal Signal that a condition is true to one thread
pthread_cond_broadcast Signal that a condition is true to all threads
p t h r e a d _ m u t e x _ u n l o c k (& var_mutex );
Mechanism
Classical program that wait for a variable to be modified :
p t h r e a d _ m u t e x _ l o c k (& var_mutex );
while (! condition ( var ))
{
/* If the condition is not true ,
wait */
p t h r e a d _ c o n d _ w a i t (& var_cond , & var_mutex );
}
/* use the variable in critical section */
.....
p t h r e a d _ m u t e x _ u n l o c k (& var_mutex );
51
Attention pthread_cond_wait is making some implicit lock and unlock of the
mutex.
Example
int y =2 , x =0;
p th re a d_ m ut ex _ t mut ;
pthr ead_co nd_t cond ;
void * th ( void * arg )
{
int cont =1;
while ( cont ){
p t h r e a d _ m u t e x _ l o c k (& mut );
x ++;
printf (" x ++\ n ");
if ( x > y ){
p t h r e a d _ c o n d _ s i g n a l (& cond );
cont =0; }
p t h r e a d _ m u t e x _ u n l o c k (& mut );}
}
Example
int main ( int argc , char * argv ){
pthread_t id ;
p t h r e a d _ m u t e x _ i n i t (& mut , NULL );
p t h r e a d _ c o n d _ i n i t (& cond , NULL );
p t h r e a d _ m u t e x _ l o c k (& mut );
pthr ead_cr eate (& id , NULL , th , NULL );
while ( x <= y )
p t h r e a d _ c o n d _ w a i t (& cond , & mut );
printf (" x > y is true \ n ");
p t h r e a d _ m u t e x _ u n l o c k (& mut );}
Execution :
x ++ x ++
x ++ x > y is true
52
• Waiting queue management : depend on scheduling policy (SCHED_FIFO,
SCHED_OTHER, etc ...). Default behaviour : threads are waked in de-
creasing order of priority.
• Two kind of semaphore : named and unnamed semaphore.
Counting Semaphore
sem_open Connection to a named semaphore.
sem_close Disconnection to a named semaphore.
sem_unlink Destruction of a named semaphore.
sem_init Initialisation of a unnamed semaphore..
sem_destroy Destruction of a unnamed semaphore.
sem_post Freeing a semaphore.
sem_wait Acquiring a semaphore.
sem_trywait Non blocking acquiring of a semaphore.
Execution
thread 4 waiting
main thread 1 : free from
the other thread
thread 4 unblocked
53
3.5.4 Xenomai Native API Synchronisation tools
API Mutexes
int rt_mutex_create (RT_MUTEX *mutex, const char *name)
int rt_mutex_acquire (RT_MUTEX *mutex, RTIME timeout)
int rt_mutex_release (RT_MUTEX *mutex)
Real-Time Signals
Existing mechanism in POSIX.1 but with the following issues :
• Implementation pending signal register = unsafe delivery (possible loss).
54
Real-Time Signals : POSIX Interface
kill Emission of a signal.
sigaction Connection of a handler to a signal.
sigemptyset Initialize with all signals disabled.(mask all signals)
sigfillset Initialize with all signals enabled.(unmask all signals)
sigaddset Add a signal in the set(unmask this signal).
sigdelset Remove a signal from the set(mask this signal).
sigismember Check if the signal is enabled in the set.
sigsuspend Block a process until a signal is received.
sigprocmask Install a mask.
Execution :
$sig &
$kill - USR1 14090
Signal 10 received
55
Real-Time Signals : RT Example
int main ( int argc , char * argv []){
struct sigaction sig ;
union sigval val ;
int cpt ;
sig . sa_flags = SA_SIGINFO ;
sig . sa_sigaction = handler ;
sigemptyset (& sig . sa_mask );
if ( sigaction ( SIGRTMIN ,& sig , NULL ) <0)
perror (" sigaction ");
for ( cpt =0; cpt <5; cpt ++){
struct timespec delai ;
delai . tv_sec =1; delai . tv_nsec =0;
val . sival_int = cpt ;
sigqueue (0 , SIGRTMIN , val );
nanosleep (& delai , NULL );
}
}
Execution :
\ $rt - sig
Received signal 38 , val = 0
Received signal 38 , val = 1
Received signal 38 , val = 2
Received signal 38 , val = 3
Received signal 38 , val = 4
56
API
mq_open Creation or connection to a queue.
mq_unlink Destruction of a queue.
mq_receive Reception of the oldest and the most important
mail.
mq_send Emission of a mail with a given priority
mq_close Disconnection to a queue.
mq_notify Notification that there is a new mail.
mq_setattr Set attributes of the queue.
mq_getattr Get attributes of the queue.
Example
/* Emission with a priority 1 ( from 0 to
MQ_PRIO_MAX ) */
mq_send ( id , buff ,100 ,1);
pthr ead_cr eate (& tid , NULL , consumer , NULL );
pthread_exit ( NULL );
}
Example
# include < pthread .h >
# include < mqueue .h >
int main ( int argc , char * argv [])
{
pthread_t tid ;
mqd_t id ;
char buff [100];
struct mq_attr attr ;
attr . mq_maxmsg =100;
attr . mq_flags =0;
attr . mq_msgsize =100;
id = mq_open ("/ mafile " , O_CREAT | O_WRONLY ,
444 ,& attr );
strcpy ( buff ," Hi !!");
...
}
57
• Synchronizing object based on a long word structure.
• Any bit in the word can be used as a user flag
• Task oriented signal mechanism
• Conjunctive or Disjunctive
RT_TASK task_desc ;
58
RT_PIPE pipe_desc ;
3.7 IO Control
3.7.1 Memory
Memory Management
A shared time system leads to possible time indeterminism because :
59
• Dynamic memory allocation.
• Page swap : swapin=swapout.
Solution : limit dynamic memory allocation and lock pages in central mem-
ory (POSIX.4 Interface) :
• mlockall()=munlockall() : lock/unlock swap with all memory pages of
this process..
• mlock()=munlock() : lock/unlock a range of addresses.
! Warning : mlock() is not portable (because there is no memory model in
POSIX standard).
3.7.2 IO
Posix AIO
• aio_read
• aio_write
• aio_return, aio_error
• aio_cancel
• aio_fsync
• aio_suspend
Example :
sa . sa_sigaction = aioSigHandler ;
if ( sigaction ( IO_SIGNAL , & sa , NULL ) == -1) errExit (" sigaction ");
aiocb . aio_nbytes = BUF_SIZE ;
aiocb . aio_reqprio = 0;
aiocb . aio_offset = 0;
aiocb . aio_sigevent . sigev_notify = SIGEV_SIGNAL ;
aiocb . aio_sigevent . sigev_signo = IO_SIGNAL ;
aiocb . aio_sigevent . sigev_value . sival_ptr = & ioValue ;
aio_read (& aiocb );
err = aio_error (& aiocb ));
switch ( err ) {
case 0: printf (" I / O succeeded \ n "); break ;
case EINPROGRESS : printf (" In progress \ n "); break ;
case ECANCELED : printf (" Canceled \ n "); break ;
default : errMsg (" aio_error "); break ;
}
aio_return (& aiocb );
60
API Interrupt management
int rt_intr_create (RT_INTR *intr, const char *name, unsigned irq,
rt_isr_t isr, rt_iack_t iack, int mode)[Kernel]
int rt_intr_create (RT_INTR *intr, const char *name, unsigned irq, int mode)[User]
int rt_intr_enable (RT_INTR *intr)
int rt_intr_disable (RT_INTR *intr)
int rt_intr_wait (RT_INTR *intr, RTIME timeout)
RT_INTR intr_desc ;
RT_TASK server_desc ;
61
Figure 24: Autonomous Mobile Robot
4 OS Driver Programming
4.1 First Idea : From Scratch
4.1.1 Example
RobModex
• ISA Card
62
Figure 25: IRQ Process
error
PID Controller Robot
qdes
qmes
qcons =
olderror = error
• 0x20
– Command Register
– Status Register
• 0x21
– Int Mask Register
• Internal Registers
– Int. Req. Reg.
– In Service Register
• System Memory
– Interrupt Vector Table (4 bytes)
63
Figure 26: Interruption Recent Mechanism more complex
Piece of code :
turboC DOS example
# define IMR 0 x21
void _ i n s t a l l _ i n t _ f u n c t i o n ( int IRQn ,
void interrupt (* _ n e w _ i n t _ f u n c t i o n )())
{
int inter = IRQn + 8;
_disable (); // disable interrupts
// save the old interrupt vector
_ o l d _ i n t _ f u n c t i o n = _dos_getvect ( inter );
// install the new interrupt vector
_dos_setvect ( inter , _ n e w _ i n t _ f u n c t i o n );
// save the state of the 8259 A IMR register
_old_mask = inportb ( IMR );
// Set new value for IMR register
outportb ( IMR , _old_mask & _i n te r ru pt _ ma sk ( IRQn ));
_enable (); // enable interrupts
}
IRQ
64
Figure 27: Intel SMP Interrupt Systems
65
Bus : ISA
• Ax : Addresses
• Dx : Data
• IRQs : 3,4,5,6,7
• AEN : DMA
Bus : ISA
# define ISAADDR
short data ;
void interrupt _ n e w _ i n t _f u n c t i o n ()
{
Digital/Analog Converter
RobModex Application
# define ISAADDR .....
short data ;
void interrupt _ n e w _ i n t _f u n c t i o n ()
{
_disable (); // disable interrupts
data = inb ( );
outb ( , );
_end _inter rupt ();
_enable (); // enable interrupts again
}
66
Figure 28: ISA Port
67
Figure 29: Digital Analog Converter Schematic
• OS Hardware
• Native Robot SW
68
Figure 31: Robot Unified Platform Initiative
• MiddleWare
• Communication Framework
State of Art
• OS Hardware
– Linux WindowsCE VxWorks
• Native Robot SW
– Xenomai RTAI RTLinux OROCOSRT
• MiddleWare
– RoSta Robotics Standards : OROCOS, Microsoft Robotics Studio,
URBI, Robotic Operating System (ROS), ORCA. MARIE...
• Communication Framework
69
• funding no cheap OS present on the market place
• Minix had too many limits
Main initial choices taken by Linus
• using GNU licenses tools compiler and tools
Key dates
Features
• Monolithic Kernel
• UNIX type architecture all files concept
• MultiTasks
• MultiUsers
• MultiProcessors
• Multiplatform
70
Properties
• User space where possibilities are restricted with safety mechanisms (ex
: memory access)
Schema
User/Kernel Transitions
Three kind of transitions user/kernel :
• system calls ;
71
Espace Utilisateur
Application Utilisateur
Espace Noyau
Noyau
Driver
Matériel
Périphériques
Signaux Extérieurs
Rationale
Main rule
”Always try to bring complexity outside of the kernel ”
Consequences
• kernel must stay as small as possible
• system calls must be limited in their numbers
72
Motivations
Kernel device drivers or user mode software?
Kernel device drivers:
• Direct Access : Memory and devices ;
Kernel Structures
Many structures are commonly used in the kernel :
• Complex structures (ex : task_struct defined in <linux/sched.h>) ;
73
Memory Translation Virtual-Real
Virtual Address
Segmentation table
Addition
Real Address
Virtual Address
Page table
Real Address
Process
Elementary Execution Unit of the Operating System
Two kinds
74
• process based on a copy of resources coming from father process im-
proved with the use of copy on write mechanisms or vfork
• thread share the maximum part of the resources coming from the main
process ⇒ context switch accelerated
Scheduling
Pre-emptive Multi-task :
Kernel is pre-emptive itself (from 2.6 version);
UNIX Policy to share CPU time between each processes;
Real-Time API in POSIX.1b ;
Linux is nevertheless a real-time kernel :
• Execution time not predictive;
• non-determinist system. Priorities management (41 normal levels + 99
real-time levels).
Interruption management
Linked to a device (ex : bus, interface, timer...) ;
Material interruptions can pre-empt a process even if it work in kernel
mode;
Two phases computing :
• top-half : high-speed part and critical (ex : acknowledge an interruption
for a device), and
• bottom-half : slow part in a queue of tasks that is emptied by the sched-
uler (ex : processing associated to the interruption). Possibility to share
IRQ.
Mutual Exclusion
Linux Kernel is re-entrant and pre-emptive;
There is consequently many possible concurrencies :
• between each CPU (SMP architecture) ;
• between Interruption Controller and System Calls ;
• between different System Calls (because of explicit or implicit pre-emption)
;
⇒ Blocking mechanism (locking) for protection :
• global variables,
• non-re-entrant functions,
75
File Systems
Fundamental of every UNIX based systems ;
Two main kind :
File System
Abstraction layer to implement writing mechanism with file system (VFS) :
• can be based on every bloc device ;
Network
One of the big asset of Linux system ; Many devices and protocols are sup-
ported ; Divided in two set of sub-systems :
• driver of interfaces that fit with physical level (1) and Data level (2) of
OSI Model (ex : Ethernet, Token Ring, PPP...) ;
• Protocols corresponding to layers Net (3) and Transport (4) (ex : TCP, IP,
IPX, Appletalk...).
Network
Interface drivers use device drivers to have access to them ; Communication
between device drivers, interface drivers and protocols is done with packets
(ex : structure sk_buff defined in <linux/skbuff.h>) ;
IP layer integrate route tables and name resolution.
Modules
Dynamic Kernel Modules : object files (.o/.ko) implementing a functionality
of the kernel ;
Used to reduce the size of the Kernel and bring it more flexibility ;
We can load and unload in dynamic way (during run-time) a new function-
ality (ex : driver, protocol, file system ...)
Module Dependencies management with modprobe tool ;
Management of dynamic link edition with insmod.
76
Device drivers
Piece of software plugged in the kernel to bring an interface between kernel
and hardware devices;
There must be two different interfaces :
• one for users that is generic and stable ;
• one to communicate with the kernel .
With Linux, user interface is provided as a special file ;
So we are able to use classic system call like open(), read(), write() ;
Can be implemented as a module dynamically linked "on demand" or stat-
ically compiled in the kernel.
TreeView
Documentation/ : documentation related to the kernel and its sub-systems
(ex : sound/, DocBook/...) ;
arch/ : specific part for architectures (ex : alpha/, arm/, i386/...) ;
drivers/ : device drivers (ex : usb/, net/...) ;
fs/ : file systems (ex : xt2/, fat/...) et VFS ;
include/ : headers files (ex : asm-i386/, linux/, net/...) ;
init/ : initialisation process (boot) of the kernel ;
TreeView
ipc/ : inter-processes communication mechanisms (ex : shared memories,
semaphores...) ;
kernel/ : core of the system (ex : scheduler, signals...) ;
lib/ : mini C library to be used in the kernel (ex : strcmp(), sprintf()...) ;
mm/ : memory management ;
net/ : interfaces and network protocols (ex : ethernet/, ipv4/...) ;
scripts/ : useful scripts for configuration and compilation of the kernel.
77
TreeView
In 2.6 version, new directories : crypto : generic API cryptography and
their implementations ; security : security mechanisms running in the kernel
et implementations (SELinux) ; sound : sound sub-systems (in drivers before).
4.4 Tools
4.4.1 Dev. tools
Compilation
Only supported tools for compilation :
Ex Makefile
Ex : Makefile
CC = gcc
CCOPTS = - Wall - Wstrict - prototypes - O2
KSRC = / lib / modules /\ $ ( shell uname -r )/ build
MODVERSIONS = - DMODVERSIONS
MODVERSIONS += - include $ ( KSRC )/ include / linux / modversions . h
CFLAGS = - I$ ( KSRC )/ ... $ ( CCOPTS ) - DMODULE $ ( MODVERSIONS )
CFLAGS += - D__KERNEL__
%. o : %. c
$ ( CC ) $ ( CFLAGS ) -c $ < -o $@
78
Patches
Collecting modifications in one or more files ;
Must keep the original file or directories ;
Ex : creation of a patch
> diff - urN < orig > < dest > > patch_ < description >
4.4.2 Debugging
Console
Kernel function printk() to send information in standard output (console) ;
Multiple levels of debugging are defined in <linux/kernel.h> (ex : KERN_EMERG,
KERN_INFO...) ;
Messages are logged by syslogd deamon (entry kern.*) ;
dmesg software display and check the round buffer used by printk() ;
Prototype :
• int printk (const char *fmt, ...) ;
KGDB
kgdb patch for the kernel (http ://kgdb.sourceforge.net) ;
Need of a second machine :
KDB
Embedded in the kernel debugging tool ;
Developed by SGI (http ://oss.sgi.com/projects/kdb/) ;
It includes :
• A set of user commands that allow to debug the kernel and real-time
kernels ;
• a kernel debugger in assembly mode (not in source mode)
79
Profiling
It is possible to analyse time spent by each function of the kernel :
Allow to identify :
• structural misbehaviour ;
• to be optimised parts of the driver.
Other possibilities
On request Debugging :
4.4.3 Practical
Practical
• Reboot.
80
4.5 User Space Mechanisms
4.5.1 Review
• Threads
• Signals
• Systems Calls
• Hardware access
syscall
# include < syscall .h >
# include < unistd .h >
# include < stdio .h >
# include < sys / types .h >
int main ( void ) {
long ID1 , ID2 ;
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
/* direct system call */
/* SYS_getpid ( func no . is 20) */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
ID1 = syscall ( SYS_getpid );
printf (" syscall ( SYS_getpid )=% ld \ n " , ID1 );
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
/* " libc " wrapped system call */
/* SYS_getpid ( Func No . is 20) */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
ID2 = getpid ();
printf (" getpid ()=% ld \ n " , ID2 );
return (0);
}
81
...
# define SYS_chmod __NR_chmod
# define SYS_chown __NR_chown
# define SYS_chroot __NR_chroot
# define SYS_clock_getres __NR_clock_getres
# define SYS_clock_gettime __NR_clock_gettime
...
Prototypes
Prototypes x86 (<asm/io.h>) :
• unsigned char inb (unsigned short port) ;
• void outb (unsigned char byte, unsigned short port) ;
• unsigned char insb (unsigned short port, void *addr, unsigned long count)
;
• void outsb (unsigned short port, void *addr, unsigned long count) ;
82
Mapping addresses
Memory
• mmap
• mremap
• mprotect
IO In some cases, it is mandatory to map addresses range of IO in linear ad-
dress space of the kernel (ex : PCI ⇒ addresses > PAGE_OFFSET) :
• ioremap() : map physical addresses range to a linear address range (sim-
ilar to vmalloc()),
• iounmap() : free an address range already mapped .
Memory Mapping
# include < sys / mman .h >
# include < sys / stat .h >
# include < fcntl .h >
# include < stdio .h >
# include < stdlib .h >
# include < unistd .h >
int main ( int argc , char * argv []){
char * addr ;
int fd ;
struct stat sb ;
off_t offset , pa_offset ;
size_t length ;
ssize_t s ;
fd = open ( argv [1] , O_RDONLY );
if ( fstat ( fd , & sb ) == -1) /* To obtain file size */
offset = atoi ( argv [2]);
pa_offset = offset & ~( sysconf ( _SC_PAGE_SIZE ) - 1);
/* offset for mmap () must be page aligned */
Memory Mapping
if ( argc == 4) {
length = atoi ( argv [3]);
if ( offset + length > sb . st_size )
length = sb . st_size - offset ;
/* Can ’ t display bytes past end of file */
} else {
/* No length arg == > display to end of file */
length = sb . st_size - offset ;
}
addr = mmap ( NULL , length + offset - pa_offset ,
PROT_READ , MAP_PRIVATE , fd , pa_offset );
s = write ( STDOUT_FILENO ,
addr + offset - pa_offset , length );
exit ( EXIT_SUCCESS );
}
83
Kernel Services
/sys : system / driver status information
> cat / sys / bus / usb / devices / usb4 /4 -2/ product
USB - PS /2 Optical Mouse
Memory Reservation
To avoid conflicts, kernel can reserve IO memory region for some device
driver :
• request_mem_region() : reserve one memory range of adress,
• check_mem_region() : check if the region is already reserved (deprecated
in 2.6),
• release_mem_region() : free this region.
Listing of memory regions reserved appears in /proc/iomem ;
84
Prototypes
Prototypes (<asm/io.h> and <linux/ioport.h>) :
• void * ioremap (unsigned long offset, unsigned long size) ;
• void iounmap (void *addr) ;
Prototypes
x86 prototypes (<asm/io.h>) :
• char readb (void *addr) ;
• void writeb (char byte, void *addr) ;
• void * memcpy_{from,to}io (void *dest, const void *src, size_t count) ;
85
Kernel memory
Many methods exists in kernel to allocate memory :
• kmalloc()/kfree() : allocate/de-allocate a real continuous memory block
in the kernel (GFP_KERNEL ⇒ can sleep, GFP_ATOMIC ⇒ atomic),
• __get_free_pages()/free_pages() : allocate/de-allocate an integer num-
ber (2n ) of continuous real memory pages (idem previous but for biggest
needs - limit : 128 ko),
• vmalloc()/vfree() : allocate/de-allocate a virtual memory block composed
by many discontinuous memory blocks of real memory.
Prototypes
Prototypes (<linux/slab.h> et <linux/vmalloc.h>) :
• void * kmalloc (size_t size, int flags) ;
• void kfree (const void *addr) ;
• unsigned long __get_free_pages (int gfp_mask, unsigned long order) ;
• void free_pages (unsigned long addr, unsigned long order) ;
• void * vmalloc (unsigned long size) ;
• void vfree (void *addr) ;
Interruptions et events
Ex : polling
for ( ; ;)
{
if ( read_state ( carte ) & ETAT_END )
break ;
schedule () ;
}
86
In interruptible mode, calling process is asleep and put in a waiting queue ;
Interruption manager will have to wake the process (or processes according
to its policy)
Interruptions et events
Interruption manager is called interrupt handler.
Properties :
• must be fast ;
• can’t call sleeping function (ex : kmalloc() non atomic).
First part can exist without second part but inverse is not possible ;
Interruptions et events
Interrupt handler is declared with function request_irq() ;
It is freed by free_irq() ;
Prototypes (<linux/sched.h>, <linux/interrupt.h>) :
• int request_irq (unsigned int irq, irqreturn_t (*handler)(int, void *, struct
pt_regs *), unsigned long flags /* SA_SHIRQ */ , const char *device, void
*dev_id) ;
Interruptions et events
When irq arises, function handler() is called ;
dev_id field is used to identify devices when IRQ is shared (SA_SHIRQ) ;
It can be used to send specific structure to driver ; List of already declared
IRQ is available in /proc/interrupts ; Returning code of request_irq must be
IRQ_NONE or IRQ_HANDLED.
Interruptions et events
bottom-halves
Kernel functions used to manage asynchronous tasks ;
Executed after every return of system call, exception or interrupt handler ;
Two possible "implementations" :
• tasklets : can run on different CPU but one instance at one time
• softirqs : can run on different CPU and many instances can work in par-
allel
87
Interruptions et events
Ex :
void my_routine_bh ( unsigned long )
{
/* ... bottom - half code ... */
}
D EC LA R E_ T AS KL E T ( ma_tasklet , ma_routine_bh , 0) ;
Implementation
Manipulation methods on waiting queue are as follow :
• wait_event_interruptibletimeout() : put the running process in sleep mode,
in interruptible way or not and with/without time out limit, sleeping
process is put in waiting queue
Interruptible Implementation
’interruptible’ version check if a signal has been sent to a process and return
an error code in this case (-ERESTARTSYS).
This error code should be propagated as a return of the system call. Initial-
isation of a waiting queue (type wait_queue_head_t) :
• during declaration ⇒ DECLARE_WAIT_QUEUE_HEAD(), or
• during execution ( runtime ) ⇒ init_waitqueue_head().
Prototypes (<linux/wait.h>) :
• DECLARE_WAIT_QUEUE_HEAD (name) ;
• void init_waitqueue_head (wait_queue_head_t *wq) ;
88
Prototypes
Prototypes (<linux/sched.h>, <linux/wait.h>) :
• void wait_event (wait_queue_head_t *wq, condition) ;
• int wait_event_interruptible (wait_queue_head_t *wq, condition) ;
Example
Ex :
static D E C L A R E _ W A I T _ Q U E U E _ H E A D ( ma_file ) ;
89
Manipulation
MODULE is a constant that allow the compiler to make the difference between
module versus in kernel compilation (no use for you!).
Implementation
The initialisation function must contain all necessary information and com-
putation to initialise a module (ex : allocations, hardware initialisations, re-
sources reservation...) ;
In the opposite, exiting function must undo all the things done by initial-
isation one (ex : freeing reserved memory, hardware deactivation, freeing re-
sources...) ;
90
routines
Linux uses optimisations of GCC to free in memory some unused part of
the code after they have been instantiated (<linux/init.h>) :
• __init : initialisation functions (freed after finishing module_init()) ;
• __exit : exit functions (ignored if statically linked to the kernel) ;
• __initdata : used data in initialisation functions (freed after finishing
module_init()) ;
• __exitdata : used data in exit functions (ignored if statically linked to the
kernel) ;
Ex :
int __init m y _ f u n c t i o n _ i n i t ( void )
{
/* ... code ... */
}
module_init ( m y _ f u n c t i o n _ i n i t ) ;
Usage counter
Each module is associated to a usage counter ;
Avoid that a module is unloaded while being used ;
Counter modification is done when the module is called ;
The module can be manipulated with functions described in (<linux/module.h>)
:
• MOD_INC_USE_COUNT : increase the usage counter ;
• MOD_DEC_USE_COUNT : decrease the usage counter ;
• MOD_IN_USE : bring the value of the usage counter.
Kernel 2.6 provides instead (<linux/module.h>) :
• try_module_get(THIS_MODULE) : try to increase the usage counter.
• module_put(THIS_MODULE) : decrease the usage counter.
• module_refcount(THIS_MODULE) : bring the value of the usage counter.
Symbols
Exported symbols by the kernel are available in /proc/ksyms (/proc/kall-
syms in 2.6) ;
Used by insmod to do dynamical linking ;
Most of the symbols are exported in kernel/ksyms.c ;
Modules can declare new symbols according to macro EXPORT_SYMBOL()
(<linux/module.h>) ;
ksyms tool give a more precise and readable view of /proc/ksyms.
91
Integration to kernel sources
Choose an appropriate directory in kernel tree ;
Create a sub-tree if necessary (ex : many elements) ;
In 2.4, edit Config.in and Makefile files of upper directory ;
En 2.6, edit Kconfig et Makefile files of upper directory ;
Add an entry inspired by the other ;
Add a help entry in Documentation/Configure.help (2.6 only, in 2.6 content
is in Kconfig)
Syntax is defined in Documentation/kbuild/... ;
Practical
Creation of the simplest module (HelloWorld) ;
Add some parameters to this module ;
Link it to the kernel in a static point of view.
Structure Associated
Initialisation of structure variables is done with the new C syntax (.var =
value) (in old times a specificity of GCC)
Some not implemented methods are replaced by default functions (ex :
open(), close())
Others not implemented functions return -EINVAL ;
Ex :
static struct f il e _o pe r at i on s mond river_ fops = {
. owner = THIS_MODULE ,
. read = mondriver_read ,
. write = mondriver_write ,
. open = mondriver_open ,
. release = m o n d r i v e r _ r e l e a s e };
92
Majors et minors
Special files are created with command mknod ;
A inod file is described by a unique identifier (i_rdev, of type kdev_t, size 16
bits in 2.4, 32 bits in 2.6) separated in two numbers (8+8 / 12+20) :
• major : identifier of the driver kind (ex : IDE, /dev/hd* ⇒ Major=3),
Returning Value
Negative means error defined in <linux/errno.h> and <asm/errno.h> ;
Positive or zero means working ;
This standard is used in every functions in the kernel; Error values trans-
mitted between each functions ;
93
Returning Value
Ex : invalid argument
if ( arg $ > $ 3) return - EINVAL ;
Ex : error transmission
int ret ;
94
• Dynamic community (Forum and mailing list1 )
Main Structure
• nucleus
• Multi-skins
– RTAI,
– VXWorks,
– POSIX,
– RTDM,
– pSOS+,
– VRTX,
– uITRON ...
Architecture
1 Quality to be observed when we want to use a free tool in long term point of view
95
ADEOS - Virtual Domains
96
– Non-ambiguity
– More functions combination than more complex functions
• Context independent :
– Kernel Space
– User space : privileged
• Small Semantic for localisation : Same names
– Kernel (ex. xeno_native.ko),
– User (ex. libnative.so)
• Tasks Management
• Time Service
• Synchronisation tools
• Tasks Management
– Increasing Priorities 1-99
• Time Service
– Timers,
– Time,
– Alarm...
• Synchronisation tools
– Counting Semaphores,
– Mutex,
– Conditional Variables,
– Event Flags
97
NATIVE API - Services
– Interruptions
– Heap memory
– Memory Access of a device in user space
• Registers
myapp : myapp . c
$ ( CC ) -o $@ myapp . c $ ( CFLAGS ) $ ( LDFLAGS )
• Create / Delete
• Bind / Unbind ⇒ Registry and binding
• Inquire ⇒ Inquiries
• "/proc/xenomai/registry"
• int rt_object_bind (RT_OBJECT *obj, const char *name, RTIME timeout)
• static int rt_object_unbind (RT_OBJECT *obj)
Ex :
98
main1 . c :
RT_TASK t ;
rt_t ask_cr eate (& t ," myTask " ,0 ,0 ,0);
main2 . c :
RT_TASK * tt ;
rt_task_bind ( tt , " myTask " , ( RTIME )10000);
... Execution ...
rt_t ask_un bind ( tt );
Inquiries
State informations of any object.
RTDK
Introduces a collection of utilities aimed at forming a Real-Time Develop-
ment Kit for userland usage.
int rt_vfprintf ( FILE * stream , const char * format , va_list args );
int rt_vprintf ( const char * format , va_list args );
int rt_fprintf ( FILE * stream , const char * format , ...);
int rt_printf ( const char * format , ...);
4.7.8 RTDM
Real Time Driver Model RTDM
• User API
99
– Clock Services
– Task Services
– Timer Services
– Synchronisation Services
– Interrupt Management Services
– Non-Real-Time Signalling Services
– Utility Services
• User API
• Driver Development API
– Inter-Driver API
– Device Registration Services + Synchronisation Services
– Clock Services
– Task Services
– Timer Services
– Synchronisation Services
– Interrupt Management Services
– Non-Real-Time Signalling Services
– Utility Services
• Device Profiles
– CAN Devices
– Serial Devices
– Testing Devices
5 Application
5.1 Examples
5.1.1 Examples
MC2e
• Aim :
– Surgical Robotics
– 3rd Hand
100
– Minimal invasive operation
– Co-manipulation
• Technical notes :
– Spherical kinematics
– Force based robot
User Kernel
robotCmd
UI Asserv
robotState
101
MC2e : Synchro Solution
User Kernel
robotCmd
UI Asserv
robotState
Shared Memory
Mutex
Only one shared memory with all the state and command information. ⇒
leads to only one synchronization mechanism
Monimad : Description
• Aim :
– Sit-To-Stand
– Walking
– disbalance recover
– Old and Diseased people
– Assistance
102
Monimad : Tasks Architecture
Shared Time Constrained Time
User Kernel
robotPosCmd robotPosCmd
UI : Trajectory, Decision Com MPC555 : Pos Asserv
robotState robotState
Elements :
• CAN Bus
103
Shared Time Constrained Time
User Kernel
robotPosCmd robotPosCmd
UI : Trajectory, Decision Com MPC555 : Pos Asserv
robotState robotState
CAN Bus
Shared Memory Char Device
Shared Structure
Mutex
Cardioloc : Description
• Aim :
– Heart Surgery
– Compensation
– Visual Servoying
• technical information :
– 2000Hz
– PiezoElectric Actuator
– High frequency camera
User Kernel
Elements :
• GUI
• Camera Driver
• Threads
104
Cardioloc : Synchro Solutions
Shared Time Constrained Time
User Kernel
RobModex : Description
• Aim :
– Pedagogic Solution
– Polytechnique School of Engineering (Palaiseau)
• Technical
– Fixed Wheel Structure
– Usb Camera
RobModex : Tasks
105
Shared Time Constrained Time
User Kernel
UI robotStartStopCmd Asserv
WebCam
Elements :
• USB Driver
• Threads
User Kernel
UI robotStartStopCmd Asserv
WebCam
6 Documentations
6.1 Doc
6.1.1 Interface with community
Documentation
106
The Documentation/ directory in kernel sources ;
The documentation Linux project
Information
Specialised Mailing Lists ( newsgroups http://www.uwsg.indiana.edu/
search/) :
• linux-kernel,
• kernel-newbies,
• linux-net... ;
6.1.2 References
References
Use the source, Luke !
The answer of all your questions are inside the kernel sources...
References
Books - Linux Device Drivers 2nd edition (O’Reilly) http://www.xml.com/
ldd/chapter/book/index.html :
107
References
E-Books - Linux Kernel Internals (kernel 2.4) [http://www.tldp.org/LDP/
lki/] :
References
Articles and documents
• Articles on how import drivers from 2.4 to 2.6 [http://lwn.net/Articles/
driver-porting/]
References
• http://www.xenomai.org
• http://www.xenomai.org/index.php/Publications
– Native-API-Tour-rev-C.pdf
– Life-with-Adeos-rev-B.pdf
– RTDM-and-Applications.pdf
• http://www.xenomai.org/index.php/API_documentation
108
6.1.3 Licences
GPL
GNU General Public License (GPL) Maintained et defended by Free Soft-
ware Foundation (FSF) ;
Give the right (and it is also a duty !) to copy, modify et redistribute the
software only under the same licence terms (GPL).
This rule includes also software linked to codes licensed under GPL ;
No free of charge are described, only freedom in using ;
It is possible to sell a software under GPL but not to forbid them to modify
it and redistribute (free of charge or not).
LGPL
• Less restricted than GPL ; Possibility to call LGPL code from a non-free
program (ex : software under licence incompatible with GPL) ;
• Used mainly for libraries (ex : GNU libC).
Others
• A lot of work has been done to clarify the GPL/non GPL frontier : EX-
PORT_SYMBOL_GPL, MODULE_LICENSE...
Licences
Technically very difficult to provide compatible binary modules because of
all possible configurations of the kernel (ex : versions, external patches...) ;
Legal but not advised (no support from community).
6.1.4 Glossary
109
• BE , Big-Endian : bytes organization where most significant byte (MSB)
are stored before less significant bytes (LSB), :
• DMA , Direct Memory Access : Mechanism in Computer that bring the
ability to avoid the CPU to be used when we want data transfer between
central memory and devices;
110
• SMP , Symmetric Multi-Processing : use of multiple same CPU that share
the same resources (memory...) and devices in one operating system ⇒
transparent for users :
• TCP , Transmission Control Protocol : ( 4th level in OSI model) working
in connected mode :
• VFS , Virtual File System : abstraction layer in high level part of the kernel
to enable fast writing on file systems ;
111