Вы находитесь на странице: 1из 52

Informatics for industrial applications

Lecture 10 - ChibiOS/RT
Martino Migliavacca
martino.migliavacca@gmail.com

November 17, 2011

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Outline
1

ChibiOS/RT Introduction Architecture Source organization Kernel services Base kernel services Synchronization Memory management I/O support Hardware Abstraction Layer Introduction ADC driver Serial driver

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Introduction

ChibiOS/RT is a complete, portable, open source, compact and extremely fast RTOS.

Complete: threads, synchronization, memory management, hardware drivers Portable: layered architecture enables easy porting Open source: GPL3, GPL3 with linking exception, commercial license Compact: 5.5 Kb kernel size, 400 bytes RAM (on ARM Cortex-M3) Extremely fast: best in class context switch performance

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

ChibiOS/RT history

ChibiOS/RT ancestor was an Operating System for Motorola 68000 In 1989 it supported GCC, ran EMACS, was preemptive and realtime ...but in 1991 Linus Torvalds began the development of Linux The original full-featured OS turned in a minimalistic, ecient, RTOS: ChibiOS/RT father In 2007, after 15 years, it turned to ChibiOS/RT: an open source RTOS project targeted to embedded systems The project is lead and mainly developed by Giovanni Di Sirio ChibiOS/RT started growing in features, ports and users Every part of the project has been deeply documented (Doxygen)

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

ChibiOS/RT ohloh.net code analysis

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

ChibiOS/RT Features
Not just a scheduler
Support for startup and board initialization HAL abstracting many common device drivers Integration with other open source projects

Static design
Everything in the kernel is static, nowhere memory is allocated or freed Allocator subsystems are optionally available, but they are not part of core OS Dynamic services are built as a layer on top of the fully static kernel

No error conditions
System APIs have no error conditions All the static core APIs always succeed if correct parameters are passed

Simple, fast and compact


Each API function should have the parameters you would expect Note: rst fast, then compact

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

ChibiOS/RT architecture
Kernel: the platform independent part of the OS kernel Port layer: the architecture/compiler dependent part of the OS kernel
System startup, interrupts abstraction, lock/unlock primitives, context switch related structures and code Very little code, but the quality of the implementation can aect heavily the performance of the ported OS Probably the most critical part of the whole OS

Hardware Abstraction Layer: abstract device drivers


Common I/O API to the application Totally portable across the various architectures and compilers

Platform layer: device drivers implementations Board Initialization: les used to initialize the target board and the HAL before launching the application

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Components dependancies

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

System states
Init In this state it is not possible to use any system API except chSysInit(), all the maskable interrupt are disabled Normal All the interrupt sources are enabled and the system APIs are accessible, threads are running Disabled In this state all interrupt sources are disabled, only chSysSuspend() or chSysEnable() APIs can be invoked Sleep Architecture-dependent low power mode, the idle thread goes in this state and waits for interrupts S-Locked Kernel locked and regular interrupt sources disabled, fast interrupt sources are enabled I-Locked Kernel locked and all interrupt sources disabled Serving Regular Interrupt No system APIs are accessible but it is possible to switch to the I-Locked state using chSysLockFromIsr() and then invoke any I-Class API Halted All interrupt sources are disabled and system stopped into an innite loop.

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

System states transitions

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

API Name Suxes

API name suxes indicate from which system states a function can be invoked. API sux can be one of the following: None APIs without any sux can be invoked only from the user code in the Normal state unless dierently specied I I-Class APIs are invokable only from the I-Locked or S-Locked states S S-Class APIs are invokable only from the S-Locked state

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Source organization: kernel le

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Source organization: port layer

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Source organization: HAL

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Source organization: platform layer

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Source organization: board initialization

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Outline
1

ChibiOS/RT Introduction Architecture Source organization Kernel services Base kernel services Synchronization Memory management I/O support Hardware Abstraction Layer Introduction ADC driver Serial driver

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Base kernel services


Initialization, low level locks, idle thread chSysInit() ChibiOS/RT initialization chSysHalt() Halts the system chSysLock() Enters the kernel lock mode chSysUnlock() Leaves the kernel lock mode chSysLockFromIsr() Enters the kernel lock mode from an ISR chSysUnlockFromIsr() Leaves the kernel lock mode from an ISR idle thread() Implements the idle thread innite loop ISRs abstraction macros CH IRQ PROLOGUE() IRQ handler enter code CH IRQ EPILOGUE() IRQ handler exit code CH IRQ HANDLER(id) Normal IRQ handler declaration CH FAST IRQ HANDLER(id) Fast IRQ handler declaration

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

IRQ declaration example

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Scheduler

The strategy is very simple: the currently ready thread with the highest priority is executed The ready list is a double linked list of threads ordered by priority

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Priorities
Threads priority levels are integers from LOWPRIO to HIGHPRIO: IDLEPRIO Special priority level reserved for the Idle Thread LOWPRIO Lowest priority level usable by user threads NORMALPRIO The main() thread is started at this level HIGHPRIO Highest priority level usable by user threads ChibiOS/RT supports multiple threads at the same priority level and schedules them using an aggressive round-robin strategy A round-robin rotation can happen if the currently executed thread:
voluntarily invokes the chThdYield() API voluntarily goes into a sleep state is preempted by an higher priority thread if CH TIME QUANTUM constant is greater than zero and the specied time quantum expired

If CH TIME QUANTUM is equal to zero, the round robin becomes cooperative

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Threads
A thread is an abstraction of an independent instructions ow In ChibiOS/RT it is a C function owning a processor context, state informations and a dedicated stack area The working area is declared with a macro: static WORKING AREA(waThread1, 128); Threads are created with the chThdCreateStatic() API: Thread* chThdCreateStatic(void *wsp, size t size, tprio t prio, tfunc t pf, void *arg) wsp pointer to a working area dedicated to the thread stack size size of the working area prio the priority level for the new thread pf the thread function arg an argument passed to the thread function, it can be NULL

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Threads operations

chThdCreateStatic() Creates a new thread into a static memory area chThdExit() Terminates the current thread chThdWait() Blocks the execution of the invoking thread until the specied thread terminates, then the exit code is returned chThdResume() Resumes a suspended thread chThdTerminate() Requests a thread termination chThdSleep() Suspends the invoking thread for the specied time chThdYield() Yields the time slot

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Thread states

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Thread creation example

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Synchronization

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Counting and binary semaphores


ChibiOS/RT implements semaphores in their counting variant Counting semaphores are usually used as guards of resources available in a discrete quantity A semaphore counter can be:
negative: there are exactly -N threads queued on the semaphore zero: no waiting threads, a wait operation would put in queue the invoking thread positive: no waiting threads, a wait operation would not put in queue the invoking thread

Binary semaphores are implemented as a set of macros that use the existing counting semaphores primitives

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Mutexes
The mutexes in ChibiOS/RT implements the full priority inheritance mechanism When a thread is queued on a mutex, any thread holding the mutex gains the same priority of the waiting thread (if their priority was not already equal or higher) The algorithm complexity (worst case) is N with N equal to the number of nested mutexes Mutexes operations: chMtxLock() Locks the specied mutex chMtxTryLock() Tries to lock a mutex chMtxUnlock() Unlocks the next owned mutex in reverse lock order Enabling mutexes requires 5-12 extra bytes in the Thread structure

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Event ags

Each thread has a mask of pending event ags inside its Thread structure Operations dened for event ags:
Wait: the invoking thread goes to sleep until a certain combination of event ags becomes pending Clear: a mask of event ags is cleared from the pending events mask Signal: an event mask is directly ORed to the mask of the signaled thread Broadcast: each thread registered on an Event Source is signaled Dispatch: an events mask is scanned and for each bit set to one an associated handler function is invoked

Enabling events requires 1-4 extra bytes in the Thread structure

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Synchronous messages

Threads can both act as message servers and/or message clients Messages are not copied, a pointer passed Synchronous messages operations: chMsgSend() Sends a message to the specied thread chMsgGet() Returns the message carried by the specied thread chMsgWait() Suspends the thread and waits for an incoming message chMsgRelease() Releases a sender thread specifying a response message Enabling messages requires 6-12 extra bytes in the Thread structure

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Mailboxes
A mailbox is an asynchronous communication mechanism A message is a variable of type msg t that has the size of a data pointer To exchange large amount of data, memory can be allocated from the posting side and freed on the fetching side Mailboxes operations: chMBPost() Posts a message on the mailbox in FIFO order chMBPostAhead() Posts a message on the mailbox with urgent priority chMBFetch() A message is fetched from the mailbox and removed from the queue chMBReset() The mailbox is emptied and all the stored messages are lost

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Memory management

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Core memory manager

The core memory manager is a simplied allocator It only allows to allocate memory blocks without the possibility to free them This allocator is meant as a memory blocks provider for the other allocators By having a centralized memory provider the various allocators can coexist and share the main memory Core memory manager operations: chCoreAlloc() Allocates a memory block chCoreStatus() Reports the core memory status

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Heaps

The heap allocator implements a rst-t strategy Its APIs are functionally equivalent to the usual malloc() and free() functions Heap APIs are guaranteed to be thread safe Heap operations: chHeapInit() Initializes a memory heap from a static memory area chHeapAlloc() Allocates a block of memory from the heap by using the rst-t algorithm chHeapFree() Frees a previously allocated memory block chHeapStatus() Reports the heap status

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Memory pools

Memory pools allow to allocate/free xed size objects in constant time and reliably without memory fragmentation problems Memory pools can grow in size asking for memory to a memory provider Memory pools are initalized with the MEMORYPOOL DECL() macro: MEMORYPOOL DECL(name, size, provider) Memory pool operations: chPoolInit() : Initializes an empty memory pool chPoolAlloc() : Allocates an object from a memory pool chPoolFree() : Releases an object into a memory pool

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Dynamic threads
If one of the memory allocators is available, threads can be declared dynamically Thread working area can be allocated from both heaps and memory pools The memory is not freed when the thread terminates The spawning thread has to collect the thread nal status, e.g., with chThdWait(), to free the memory Dynamic threads operations: chThdCreateFromHeap() Creates a new thread allocating the memory from the heap chThdCreateFromMemoryPool() Creates a new thread allocating the memory from the specied memory pool

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Abstract Streams
Abstract streams are abstract interface for generic data streams They make the access to streams independent from the implementation logic No code is present, streams are just abstract interfaces The stream interface can be used as base class for high level object types such as les, sockets, serial ports, pipes etc Methods are dened in BaseSequentialStreamVMT virtual methods table Methods are then called through macros: #dene chSequentialStreamWrite(ip, bp, n) ((ip)vmtwrite(ip, bp, n)) #dene chSequentialStreamRead(ip, bp, n) ((ip)vmtread(ip, bp, n))

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

I/O queues

ChibiOS/RT queues are mostly used in serial-like device drivers Input queues and output queues are dened Bidirectional queue are implemented pairing an input and an output queue together I/O queues operations: chIQInit() Initializes an input queue chIQReset() Resets an input queue chIQPutI() Input queue write chIQGetTimeout() Input queue read with timeout chOQPutTimeout() Output queue write with timeout chOQGetI() Output queue read

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Outline
1

ChibiOS/RT Introduction Architecture Source organization Kernel services Base kernel services Synchronization Memory management I/O support Hardware Abstraction Layer Introduction ADC driver Serial driver

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Introduction

The HAL is the abstract interface between ChibiOS/RT application and hardware A device driver is usually split in two layers The high level device driver contains the denitions of the drivers APIs and the platform independent part of the driver The low level device driver (LLD) contains the platform dependent part of the driver The LLD may be not present in those drivers that do not access the hardware directly but through other device drivers (e.g., MMC SPI)

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

HAL architecture

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Supported platforms

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

ADC driver
This driver denes a generic Analog to Digital Converter driver The driver supports several conversion modes:
one shot: the driver performs a single group conversion linear buer: the driver performs a series of group conversions then stops circular buer: when the buer is lled, it is automatically restarted from the buer base

The driver is able to invoke callbacks during the conversion process It is not thread safe for performance reasons adcAcquireBus() and adcReleaseBus() to gain exclusive access Two main structures are used: ADCDriver is the generic driver structure ADCCong is the platform dependent conguration structure

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

ADC driver operations

adcStart() Congures and activates the ADC peripheral adcStop() Deactivates the ADC peripheral and enters low power mode adcStartConversion() Starts an ADC conversion adcStopConversion() Stops an ongoing conversion adcAcquireBus() Gains exclusive access to the ADC peripheral adcReleaseBus() Releases exclusive access to the ADC peripheral

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

ADC driver state machine

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Serial driver

This driver denes a generic full duplex serial driver The driver implements a implements a SerialDriver interface (VMT) It uses I/O Queues for communication between the upper and the lower driver Event ags are used to notify the application about incoming data, outgoing data and other I/O events Two main structures are used: SerialDriver is the generic driver structure SerialCong is the platform dependent conguration structure

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Serial driver operations

sdStart() Congures and starts the driver sdStop() Stops the driver sdWrite() Direct blocking write to a SerialDriver sdWriteTimeout() Direct blocking write to a SerialDriver with timeout specication sdAsynchronousWrite() Direct non-blocking write to a SerialDriver sdRead() Direct blocking read from a SerialDriver sdReadTimeout() Direct blocking read from a SerialDriver with timeout specication sdAsynchronousRead() Direct non-blocking read from a SerialDriver

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Serial driver state machine

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Serial driver example: halconf.h

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Serial driver example: main.c

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Shell example: command implementation

ChibiOS/RT

Kernel services

Hardware Abstraction Layer

Shell example: command denition

Вам также может понравиться