The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The...

81
The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD Dipartimento di Elettronica, Informazione e Bioingegneria Politecnico di Milano [email protected]

Transcript of The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The...

Page 1: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

The FreeRTOS Projectintroduction and basic usage concepts

Patrick Bellasi, PhD

Dipartimento di Elettronica, Informazione e BioingegneriaPolitecnico di [email protected]

Page 2: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

2

RTOS ImplementationFundamentals

Introduction to real time and multitasking conceptsMultitaskingSchedulingContext SwitchingReal Time ApplicationsReal Time Scheduling

Page 3: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

3

RTOS ImplementationFundamentals - Multitasking

Each program is a task under control of the OSallow users access to resources seemingly simultaneouslymultiple tasks can execute apparently concurrently

Advantagesmultitasking and inter-task communications features

allow partitioning of complex application into a set of smaller and more manageable tasks

easier and more efficient developmenteasier software testing, work breakdown within teams, code reuse...

“disregard” complex timing and sequencing detailsthey become the responsibility of the operating system

Page 4: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

4

Example:t2: T1 preemption

t4: T2 lock a resource R

t7: try access resource R

t9: release lock on R

t10

: lock resource R

RTOS ImplementationFundamentals - Scheduling

Algorithm used to decide the task to executetasks can be suspend/resume many times during its lifetime"fair" proportions of CPU time are allocated to tasks

this is the aims of non real-time schedulers

a task can also suspend itselfin addition to being suspended involuntarily by the kernele.g. delay (sleep) for a fixed period, or wait (block) for a resource to become available (eg a serial port) or an event to occur

Page 5: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

5

RTOS ImplementationFundamentals – Context Switch (1/2)

Task execution requires exclusive usage of some computation resources

e.g. CPU registers and some RAM memory A task does not know when it is going to get

suspended or resumed by the kerneldoes not even know when this has happened

The task could be suspended when it is about to execute this

ADD instruction

Some registers are already set for the next

instruction. The task will not work if, when

resumed, these values has been changed

Page 6: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

6

RTOS ImplementationFundamentals – Context Switch (2/2)

While the task is suspended other tasks will execute and may modify the processor register values

Upon resumption the task will not know that the processor registers have been altered

e.g. if modified values are used the sum will be incorrect Upon resumption a task must have a context identical

to that immediately prior to its suspensionthe kernel is responsible for ensuring this

does so by saving the context of a task as it is suspended...… and restoring it when it is resumed, prior to its execution

Context switching is the process of saving the context of a task being suspended and restoring the context of a

task being resumed

Page 7: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

7

RTOS ImplementationFundamentals – RealTime Applications (1/2)

RTOS have specific objectives wrt other OSthese differences are reflected in the scheduling policy

RTOS are designed to provide timely responsesto real world events

Events occurring in the real world can have deadlinesbefore which the real time embedded system must respondthe RTOS scheduling policy must grant these deadlines

How to achieve such a behavior?software engineer must first assign a priority to each taskthe RTOS scheduler must ensure that the highest priority task, which is ready to execute, is the selected one

this may require sharing processing time "fairly" between tasks of equal priority if they are ready to run simultaneously

Page 8: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

8

RTOS ImplementationFundamentals – RealTime Applications (2/2)

Example: RT control system with keypad and LCDR1: users expect visual feedback within a reasonable periodR2: a control function relies on a digitally filtered input

Interface and Control Functionstwo user defined tasks

Stricter (critical) deadline

Deadline missing has less severe consequances

Page 9: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

9

RTOS ImplementationFundamentals – RealTime Scheduling

An additional idle task is created by the RTOSis always in a state where it is able to executewill execute only when there are no other tasks able to do so

Task scheduling is event-based, considering prioritiesthe higher priority task which is ready to run gets the CPU

Page 10: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

10

RTOS ImplementationBuilding Blocks

Overall view of mechanisms for task schedulingDevelopment ToolsThe RTOS TickWinAVR Signal AttributeWinAVR Naked AttributeExample: The AVR ContextSaving the ContextRestoring the Context

Page 11: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

11

RTOS ImplementationBuilding Blocks – The Tick Timer (1/2)

Provide support for real time kernel time measuresit is just a “counting variable”a timer interrupt increments the tick count

the RTOS tick interrupt, strict temporal accuracy

allowing the real time kernel to measure timewith a resolution of the chosen timer interrupt frequency

Task could be suspended for two main reasonssleeping => specify time after which it requires 'waking'

e.g. to introduce a certain delay between two actions

blocking => specify a maximum time it wishes to waite.g. to wait for an event or a resource being available

Page 12: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

12

RTOS ImplementationBuilding Blocks – The Tick Timer (2/2)

When the tick interrupt is triggered, the kernel:increment the tick countcheck to see if it is now time to unblock or wake a taskreturn to the newly woken/unblocked task

Iff newly ready task has higher priority than the interrupted one Preemptive context switch:

the interrupted task is preempted without suspending itself voluntarily

Page 13: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

13

RTOS ImplementationBuilding Blocks – GCC Signal Attribute

GCC allows interrupts to be written in Ce.g. a compare match event on the AVR Timer 1 peripheral can be written using the following syntax

exploiting the '__attribute__ ( ( signal ) )' directiveinforms the compiler that the function is an ISRresults in two important changes in the compiler output

ensures that every processor register that gets modified during the ISR is restored to its original value when the ISR exits

NOTE: only part of the execution context is automatically savedforces a 'return from interrupt' instruction (RETI) to be used

in place of the 'return' instruction (RET)

Page 14: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

14

RTOS ImplementationBuilding Blocks – GCC Naked Attribute

Prevents GCC to generate function entry or exit codecontext switch requires the entire context to be savedswitching code explicitly save all CPU registers at ISR entry

this would result in some CPU registers being saved twice...… unless the 'naked' attribute is used

in addition to the 'signal' attribute

Tow FreeRTSO macros save and restore the entire execution context

Page 15: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

15

RTOS ImplementationBuilding Blocks – The AVR Context (example)

On the AVR microcontroller the context consists of32 general purpose processor registers

the gcc development tools assume register R1 is set to zero

Status register, which value affects instruction executionthus it must be be preserved across context switches

Program counterupon resumption, a task must continueexecution from the instruction that wasabout to be executed immediately priorto its suspension

The two stack pointer registers

Page 16: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

16

RTOS ImplementationBuilding Blocks – Saving the Context

Each real time task has its own stack memory areathe context can be saved by pushing CPU registers there

Saving the context is one place where assembly code is usually unavoidable

the portSAVE_CONTEXT()is implemented as a macro

X AVR CPU register is loaded with the address to which the stack pointer is to be saved

The stack pointer is saved, first the low byte (10 and 11), then the high nibble (12 and 13)

Page 17: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

17

RTOS ImplementationBuilding Blocks – Restoring the Context

The context is restored by “reversing” the saving codethe portRESTORE_CONTEXT() macro is the reverse of portSAVE_CONTEXT()

the context of the task being resumed was stored in the tasks stack The kernel

retrieves the stack pointer forthe taskPOP's the context back intothe correct CPU registers

Page 18: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

18

RTOS ImplementationDetailed Example – Context Switch in AVR Microcontrollers

Demo building blocks and source code modules used to achieve a context switch on the AVR microcontroller

switching from lower priority TaskA to a higher priority TaskB

Page 19: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

19

RTOS ImplementationDetailed Example – Context Switch in AVR Microcontrollers

Step 1 - Prior to the RTOS tick interruptThis example starts with TaskA executingTaskB has previously been suspended so its context has already been stored on the TaskB stack

Page 20: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

20

RTOS ImplementationDetailed Example – Context Switch in AVR Microcontrollers

Step 2 - The RTOS tick interrupt occursTaskA is about to execute an LDI instructionInterrupt occurs: the AVR uC places the current PC onto the stack and it jumps to the start of the RTOS tick ISR

Page 21: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

21

RTOS ImplementationDetailed Example – Context Switch in AVR Microcontrollers

Step 3 - The RTOS tick interrupt executes

Page 22: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

22

RTOS ImplementationDetailed Example – Context Switch in AVR Microcontrollers

Step 4 - Incrementing the Tick CountvTaskIncrementTick() executes after the TaskA context has been savedlet assume that incrementing the tick count has caused TaskB to become ready to run, which has a higher priority than TaskA

vTaskSwitchContext() selects TaskB as the task to be given processing time when the ISR completes

Page 23: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

23

RTOS ImplementationDetailed Example – Context Switch in AVR Microcontrollers

Step 5 - The TaskB stack pointer is retrievedTaskB context must be restoredportRESTORE_CONTEXT:

retrieve the TaskB stack pointerfrom the copy taken whenTaskB was suspendedthe TaskB stack pointer isloaded into the processorstack pointer

now the AVR stack points to thetop of the TaskB context

Page 24: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

24

RTOS ImplementationDetailed Example – Context Switch in AVR Microcontrollers

Step 6 - Restore the TaskB contextportRESTORE_CONTEXT() completes by restoring the TaskB context from its stack into the appropriate processor registersonly the program counter remains on the stack

Page 25: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

25

RTOS ImplementationDetailed Example – Context Switch in AVR Microcontrollers

Step 7 - The RTOS tick exitsTaskA return address: placed onto the stack at ISR entry

i.e. address of the next instruction to execute in TaskA

The ISR altered the stack pointer to points the TaskB stackThe RETI instruction POPs from stack the return address

i.e. the address of the instruction TaskB was going to execute immediately before it was suspended

Page 26: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

26

FreeRTOSCoding Standard

Core FreeRTOS source files (common to all ports) conform to the MISRA guidelines

MISRA (Motor Industry Software Reliability Association)few deviation from conformance tests, mostly for critical efficiency

Naming Conventionsvariables name are “type-based prefixed”

v (void), c (chars), s (short), l (long), e (enum), x (structure), p (*), u (unsiged)e.g. struct beef *pxBeef; unsigned long ulBacon

functions name are “scope/API-type/file prefixed”prv (static), “return type” (API), start with file mame

e.g. vTaskDelete() => defined in Task.c, return a void

Macros nameprefixed by (lowercase) defining file, other words are UPPERCASE and “_” separated

e.g. configUSE_PREEMPTION => defined in FreeRTOSConifg.h

style guide

Page 27: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

27

FreeRTOSTasks States

1) Runningcurrently utilising the processor

2) Readyable to execute

i.e. they are not blocked or suspended

not currently executingi.e. different task of equal or higher priorityis already in the Running state

3) Blockednot available for schedulingcurrently waiting for temporal or external event

e.g. vTaskDelay(), waiting for queue and semaphore events

always have a 'timeout' periodafter which they will be unblocked

4) Suspendednot available for schedulingexplicitly enter/exit by vTaskSuspend() and xTaskResume()

a 'timeout' period cannot be specified

A task can exist in one of this four states

Page 28: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

28

FreeRTOSTasks Priorities

Each task has an assigned priorityfrom 0 to ( configMAX_PRIORITIES - 1 )

configMAX_PRIORITIES is defined within FreeRTOSConfig.hNOTE: the higher this value the more RAM the kernel will consume

low priority numbers denote low priority tasksdefault idle priority defined by tskIDLE_PRIORITY as being zero

The scheduler grant CPU to a ready or running taskin preference to ready tasks of a lower priority

the task given processing time will always be the highest priority task that is able to run

Page 29: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

29

FreeRTOSImplementing a Task (1/2)

A task shouldhave a function prototype of type pdTASK_CODE

i.e. returns void and takes a void pointer as its only parameterthe parameter can be used to pass info of any type into the task

never returntypically implemented as a continuous loop

Tasks are created by calling xTaskCreate() and deleted by calling vTaskDelete()

void vATaskFunction( void *pvParameters ) { For( ;; ) { // Task application code here } }

Page 30: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

30

FreeRTOSImplementing a Task (2/2)

Task functions can be defined using macrosallow compiler specific syntax to be added

prototype definition: portTASK_FUNCTION_PROTOfunction definition: portTASK_FUNCTION

portTASK_FUNCTION_PROTO( vATaskFunction, pvParameters );portTASK_FUNCTION( vATaskFunction, pvParameters ) { For( ;; ) { // Task application code here } }

Page 31: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

31

FreeRTOSThe Idle Task

Automatically created when the scheduler is started Responsible for freeing memory of deleted tasks

if using vTaskDelete() => ensure idle task is not starved of CPU time Application tasks could share the idle task priority Provides an “Idle Task Hook”

function called during each cycle of the idle taskthere must always be at least one task that is ready to run

allows to code a functionality to run at the idle priorityNOTE: must not call any blocking API functions, except co-routines

requires configUSE_IDLE_HOOK = 1within FreeRTOSConfig.h

the function must have a pre-defined prototypevoid vApplicationIdleHook( void );

common use: simply put the uP into a power saving mode

Page 32: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

Tasks Decomposition

Page 33: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

33

Real Time Application Design TutorialIntroduction

Use-Case applicationexecute on an embedded single board computermust control a plant while...… maintaining both local and remote user interfaces

Control Panel

Ethernet

Remote Monitor

PDA

RS232

KeybardLDEs

Motor

Sensors

Page 34: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

34

Real Time Application Design TutorialSoftware Requirements (1/2)

Plant Controlcontrol cycle sequence

request data from the networked sensorswait to receive data from both sensorsexecute the control algorithmtransmit a command to the plant

transmit a request every 10ms exactlyresultant command shall be transmitted within 5mscontrol algorithm is reliant on accurate timing

Keypad and LCDused by the operator to select, view and modify system datafunction while the plant is being controlled

keypad shall be scanned at least every 15msLCD shall update within 50ms of a key being pressed

Page 35: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

35

Real Time Application Design TutorialSoftware Requirements (2/2)

LEDsindicate the system status

running as expected => flashing greenfault condition => flashing red

flash on and off once ever second (within 50ms) RS232Interface

viewing/accessing same data as the local operator interfacesame timing constraints apply

Ethernetembedded web servershall service HTTP requests within one second

Page 36: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

36

Real Time Application Design TutorialTiming requirements analysis

Three main categoriesStrict timing => the plant control

must execute every 10ms

Flexible timing => the LEDhave both maximum and minimum time constraints, but.....there is a large timing band within which they can function

Deadline only timing => the human interfaceskeypad, LCD, RS232 and TCP/IP Ethernet communications

Some time requirements are bound definede.g., only a maximum limit is specified

keypad must be scanned at least every 10ms

=> any higher rate (e.g. up to 10ms) is acceptable

Page 37: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

37

Real Time Application Design TutorialSolution #1: without the use of an RTOS kernel (1/2)

Use a traditional infinite loop approacheach app component is a run-to-completion function

HW timer schedule time critical plant control functionwait for the arrival of data, complex calculation performed=> unsuitable for execution within an ISR

Frequency and order in which the components are called within the infinite loop can be modified to introduce some prioritization

Page 38: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

38

Real Time Application Design TutorialSolution #1: without the use of an RTOS kernel (2/2)

Advantagessmall code sizeno reliance on third party source codeno RTOS RAM, ROM or processing overhead

Disadvantagesdifficult to cater for complex timing requirementsdoes not scale well without a large increase in complexitytiming hard to evaluate or maintain

due to inter-dependencies between different functions

very good for small applications and applications with flexible timing requirements

can become complex, difficult to analyze and difficult to maintain if scaled to larger systems

Page 39: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

39

Real Time Application Design TutorialSolution #2: fully preemptive system (1/4)

Traditional preemptive multitasking solutionmakes full use of the RTOS servicesno regard to the resultant memory and processor overhead

simplistic partitioning of functionality to a set of autonomous tasks A separate task is created for each part of the system

being able to exist in isolation… or as having a particular timing requirement

Event driven approachtasks block until an event requires processing

events can either be external (e.g. a key being pressed)… or internal (e.g. a timer expiring)

no CPU time is wasted polling for events not occurred Task priorities allocated based on timing requirements

stricter the timing requirement the higher the priority

Page 40: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

40

Real Time Application Design TutorialSolution #2: fully preemptive system (2/4)

Highest priority task that is able to execute is scheduled by the RTOS kernel

kernel immediately suspend an executing task when a higher priority task become available

Scheduling occurs automaticallyno explicit knowledge, structuring or commands within the application source code

Application designers is in charge to allocated an appropriate priority to each task

Idle task is scheduledwhen no other tasks areready

to place the processor intopower save mode

Page 41: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

41

Real Time Application Design TutorialSolution #2: fully preemptive system (3/4)

Advantagessimple, segmented, flexible, maintainable designprocessor usage automatically managed

based on a most urgent needno explicit action required within the application source code

no CPU time wasted on pollingprocessing is only performed when there is work needing to be done

Benefitspower consumption can be reduced by idle task scheduling

… but the tick interrupt sometimes wake the uP unnecessarily :-(

Page 42: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

42

Real Time Application Design TutorialSolution #2: fully preemptive system (4/4)

Disadvantageslot of tasks required => uses a lot of RAM

each require own stack, perhaps an event queue

context switching between same priority taskswaste processor cycles

good solutionprovided the RAM and processing capacity is available

requires some careful considerationpartitioning of the application into taskspriority assignment to each task

Page 43: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

43

Real Time Application Design TutorialSolution #3: reducing RAM utilization (1/3)

By changing the partitioning of functionality into tasksLED functionality is too simple to warrant its own task

especially if RAM is a constrained resource Grouping of functionality into the medium priority task

use of a single event queuejump to the relevant function to handle the event

improve latency issues of the infinite loop proposed in solution #1

Page 44: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

44

Real Time Application Design TutorialSolution #3: reducing RAM utilization (2/3)

Advantagescreates only two application tasks

uses much less RAM than solution #2

processor usage automatically managedbased on a most urgent need

utilize the idle task effectivelycreates three application task priorities with the overhead of only two

Criticalitiesexecution time of medium priority tasks could introduce timing issues

even if the separation of the web server reduces this risk and in any case any such issues would not effect the plant control task

power consumption may be wasted as the tick interrupt will sometimes wake the CPU unnecessarily

even if the idle task places the CPU into power save (sleep) mode

Page 45: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

45

Real Time Application Design TutorialSolution #3: reducing RAM utilization (3/3)

Disadvantagesdesign might not scale if the application grows too large

Good solution for systems with limited RAMbut it is still processor intensive

Spare capacity within the system should be checkedto allow for future expansion

Page 46: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

Communication and Synchronization

Page 47: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

47

Inter-task CommunicationQueues (1/2)

Primary form of inter-task communicationsend messages between tasks, and between ISR and taskstakes care of all mutual exclusion issues for you

Mainly used as thread safe FIFO buffersdata being sent to the back of the queuedata can also be sent to the front

Can contain 'items' of fixes sizeitem size and max number of items defined at creation time

Items are placed into a queue by copysimplifies your application design

two tasks cannot access the data simultaneously

not by reference => keep item size to a minimumexchange large data by queuing pointersmust clearly defines which task/ISR is the 'owner' of the data

Page 48: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

48

Inter-task CommunicationQueues (2/2)

Allows a blocking time to be specifiedmaximum number of 'ticks' a task should be in Blocked state

reading => wait for data to become available on a queuewriting => wait for space to become available on a queue

task with the highest priority will be unblocked first

Queue Management API

Page 49: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

49

Inter-task CommunicationBinary Semaphores

Better choice for implementing synchronizationsince unlike mutex does not support priority inheritancelooks like a queue that can only hold a single itemsupport for blocking timeout

looks like a queue that can only hold a single item Example: use to synchronise a task with an interrupt

the interrupt only ever 'gives' the semaphore… while the task only ever 'takes' the semaphore

Page 50: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

50

Inter-task CommunicationCounting Semaphores

Looks like a queues of length greater than oneusers not interested in the data that is stored in the queuejust whether or not the queue is empty or not

Typically used for two thingsCounting events difference between occurred and processed events

event handler will 'give' a semaphore each time an event occursincrementing the semaphore count value

handler task will 'take' a semaphore each time it processes an event decrementing the semaphore count value

Resource management count of available resourcestasks must first obtain a semaphore before using a resource

Page 51: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

51

Inter-task CommunicationMutexe (1/2)

Binary semaphores with priority inheritance supportbetter for simple mutual exclusion

… while binary semaphores are better for synchronization Acts like a token that is used to guard a resource

task wishing to access a resource must first obtain ('take') itwhen it has finished it must 'give' the token back

Same semaphore access API functionssupport for block timeout

Page 52: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

52

Inter-task CommunicationMutexe (2/2)

Priority inheritanceif an high priority task blocks while getting a mutex

priority of holding task temporarily raised to that of the blocked task

ensure high priority task are blocked for the shortest timedoes not cure priority inversion

it just minimizes its effect in some situations

hard real time applications should be designed such that priority inversion does not happen in the first place

Page 53: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

53

Inter-task CommunicationRecursive Mutexe

Can be 'taken' repeatedly by the owner Doesn't become available again until the owner has

completely release itthe same number of time has been acquired

Page 54: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

Time Management

Page 55: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

55

Software TimersIntroduction

Allows a callback function to be executed at a future timer period

must be explicitly created before it can be usedoptional FreeRTOS functionality

not part of the core FreeRTOS kernelprovided by a timer service (or daemon) task

freeRTOS provides a set of timer related APIuse standard queue to send commands to the timer service

Easy to implement... difficult to implement efficientlynot execute callback functions from an INTR contextnot consume process time unless a timer actually expirednot add processing overhead to the tick interruptnot walk any link list structures while interrupts are disabled

Page 56: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

56

Software TimersIntroduction

A

Page 57: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

57

Software TimersUsage

Add Source/timers.c source file to your project Configure proper defines into FreeRTOSConfig.h

configUSE_TIMERSconfigTIMER_TASK_PRIORITYconfigTIMER_QUEUE_LENGTHconfigTIMER_TASK_STACK_DEPTH

Write a timer callback functionexecutes in the context of the timer service taskessential that timer callback functions never attempt to block

i.e. not call vTaskDelay(), vTaskDelayUntil() or use zero timeouts

Page 58: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

58

Software TimersOne-shot Timers vs Auto-reload Timers

One-shot timer execute its callback function only oncecan be manually re-started, will not automatically re-start

Auto-reload timer automatically re-start itself after each execution of its callback function

Page 59: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

59

Software TimersResetting a software timer

Recalculate its expiry timeexpiry time becomes relative to when the timer was reset

Example: LCD backlight control

Page 60: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

Additional Contents

Page 61: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

FreeRTOS Introduction

Page 62: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

62

The FreeRTOS ProjectFact-sheet

Includes official ports to 28 architectures More than 77,500 downloads a year Market leading

robust, supported, portableopen source, free to download, and free to deploy

Can be used in commercial applicationswithout any requirement to expose your proprietary code

Growing ecosystemcommonly integrated with both open source and commercial TCP/IP, file system, and USB components

Official ports includes a pre-configured exampleapplication that demonstrates the kernel featuresexpedites learning, enables 'out of the box' development...

Page 63: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

63

The FreeRTOS ProjectDid you know that...

Some FreeRTOS ports never completely disable interrupts

Official FreeRTOS code is separated from community contributions

for strict quality control purposesto remove all IP ownership ambiguity

Community has provided both tick-less low power, and multicore versions of FreeRTOS

The RL78 port can create 13 tasks, 2 queues and 4 software timers in under 4K bytes of RAM!

Website: http://www.freertos.org/

Page 64: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

64

The FreeRTOS ProjectWhy choose FreeRTOS...

One solution fits many different architectures Undergoing continuous active development Minimal ROM, RAM and processing overhead

typically kernel binary image in the range of 4 to 9 [KB] The core of the kernel is contained in only 3 C files

very simple to study, understand... hack... Well established with a large and growing user base Smaller and easier real time processing alternative

where eCOS, Linux and even uCLinux won't fit, are not appropriate, or are not available

No software restrictionon number of tasks and priorities that can be used

Free development tools for many supported arch

Page 65: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

65

The FreeRTOS ProjectFeatures Overview

RTOS kernelpreemptive, cooperative and hybrid configuration options

Supports Cortex M3 Memory Protection Unit (MPU) Supports both tasks and co-routines Efficient communication and synchronization

between tasks, or between tasks and interruptsqueues, binary semaphores, counting semaphores, recursive semaphores & mutexes (with priority inheritance)

Many other featuressoftware timers, execution trace, stack overflow detection

Page 66: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

66

Source Code OrganizationBasic Directory Structure

The FreeRTOS download includes source code for every processor port, and every demo application

greatly simplifies distribution, very simple directory structurethe RT kernel is contained in just few sources

Page 67: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

67

Source Code OrganizationPlatform Independent Code

Sources common to every processor architecture

Page 68: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

68

Source Code OrganizationPlatform Specific Code

Processor architecture requires a small amount of kernel code specific to that architecture

Page 69: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

69

Creating a New FreeRTOS PortIntroduction

To yet unsupported microcontroller is not trivialvery dependent on the processor and tools being used

Within same processor family more straight forward Use existings ports as a reference

Page 70: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

70

Creating a New FreeRTOS PortSetting up the Directory Structure

create directory containing 'port' files for the [architecture]i.e. FreeRTOS/Source/portable/[compiler name]/[processor name]copy stub port.c and portmacro.h into that directory

contain stubs of functions and macro's that require implementing

configure [architecture] stack growing directionportSTACK_GROWTH macro in portmacro.h

create a demo application directoryi.e. FreeRTOS/Demo/[architecture_compiler]copy stub FreeRTOSConfig.h and main.c into that directory

properly setup macros into FreeRTOSConfig.hcreate a porting test subdirectory

i.e. FreeRTOS/Demo/[architecture_compiler]/ParTestcopy stub ParTest.c into thay directory

implement required functions to setup a GPIO to drive a LED, set/clear a specified LED, toggle a specified LED

Page 71: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

71

Creating a New FreeRTOS PortSetting up the Directory Structure

Never underestimate a blinking LED!

Page 72: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

72

Creating a New FreeRTOS PortBringing up the port (1/2)

Create a project Makefileshould successfully build the newly added files just stubs => will not yet do anything

...but: stubs can incrementally be replaced with working functions!

needed files are:Source/{Task.c,Queue.c,List.c}Source/portable/[compiler name]/[processor name]/port.cSource/portable/MemMang/heap_1.c (or heap_2.c or heap_3.c)Demo/[processor name]/{main.c,ParTest/ParTest.c}

setup also (relative) include pathsDemo/Common (i.e. ../Common)Demo/[Processor Name]Source/includeSource/portable/[Compiler name]/[Processor name]

Page 73: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

73

Creating a New FreeRTOS PortBringing up the port (2/2)

Implementing the Stubsthe difficult bits!

Once the project is compiling Add a proper implementation for portable layer stubs

better to start with pxPortInitialiseStack()decide the task context stack frame structure

very architecture dependent

Page 74: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

74

FreeRTOS Advanced FeaturesIntroduction

More advanced featuresTrace Hook MacrosRun Time StatisticsCustomizationMemory ManagementMemory Protection SupportStack Overflow ProtectionHook FunctionsPosix/Linux Simulator

Page 75: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

75

Look at a real embedded platformLPC17xx – CortexM3 uC by NXP

Download the reference material

Page 76: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

Advanced Features

Page 77: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

77

FreeRTOSCo-Routines

Supported since FreeRTOS v4 Conceptually similar to tasks, fundamental differences:

Stack usageall co-routines of an application share a single stack=> greatly reduced amount of RAM required

Scheduling and prioritiesthey use prioritised cooperative scheduling between them

=> fully prioritised relative to other co-routines.. but still can be used in an application that uses preemptive tasks

=> can always be preempted by tasks if the two are mixed

Macro implementationprovided through a set of macros

Restrictions on usestringent restrictions in how co-routines can be structured

Intended for small uC with severe RAM constraints

Page 78: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

78

FreeRTOSCo-Routines States

1) Runningcurrently utilizing the processor

2) Readyable to execute

i.e. they are not blocked or suspended

not currently executingi.e. another co-routine of equal or higher priorityis already in the Running stateOR: a task is in running state

3) Blockednot available for schedulingcurrently waiting for temporal or external event

e.g. crDelay()

A co-routine can exist in one of this three states

Page 79: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

79

FreeRTOSCo-Routines Priorities

Each co-routine has an assigned priorityfrom 0 to ( configMAX_CO_ROUTINE_PRIORITIES - 1 )

defined within FreeRTOSConfig.hNOTE: the higher this value the more RAM the kernel will consume

low priority numbers denote low priority co-routines Are only with respect to other co-routines

tasks will always take priority over co-routines

A ready co-routine is executed only if there are not ready tasks (of any priority)

Page 80: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

80

FreeRTOSImplementing a Co-Routine

A co-routine shouldhave a function prototype of type crCOROUTINE_CODE

i.e. returns void and takes exactly two parameters: xCoRoutineHandle and an index

start with crSTART() and end with crEND()never return

typically implemented as a continuous loop

Co-routines are created by calling xCoRoutineCreate() many co-routines can be created from a single co-routine function

void vACoRoutineFunction(xCoRoutineHandle xHandle, unsigned portBASE_TYPE uxIndex) {

crSTART( xHandle ); For( ;; ) { // Co-routine application code here } crEND(); }

Page 81: The FreeRTOS Project - Intranet DEIBhome.deib.polimi.it/fornacia/lib/exe/fetch.php?... · The FreeRTOS Project introduction and basic usage concepts Patrick Bellasi, PhD ... multitasking

81

FreeRTOSCo-Routine Scheduling

By repeated calls to vCoRoutineSchedule() Best placed within the idle task hook

even if your application only uses co-routinesallows tasks and co-routines to be easily mixed

Will only execute when there are no higher prio tasks

Quick Example