Lecture 10 Handout

March 27, 2018 | Author: Nguyễn Quốc Đạt | Category: Thread (Computing), Device Driver, Kernel (Operating System), Operating System, Input/Output


Comments



Description

Informatics for industrial applicationsLecture 10 - ChibiOS/RT Martino Migliavacca [email protected] 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 2 3 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, efficient, 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 fast and compact Each API function should have the parameters you would expect Note: first “fast”.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. then “compact” . 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. context switch related structures and code Very little code.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. but the quality of the implementation can affect 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: files used to initialize the target board and the HAL before launching the application . lock/unlock primitives. 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(). 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. 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 infinite loop. the idle thread goes in this state and waits for interrupts S-Locked Kernel locked and regular interrupt sources disabled. all the maskable interrupt are disabled Normal All the interrupt sources are enabled and the system APIs are accessible. . ChibiOS/RT Kernel services Hardware Abstraction Layer System states transitions . ChibiOS/RT Kernel services Hardware Abstraction Layer API Name Suffixes API name suffixes indicate from which system states a function can be invoked. API suffix can be one of the following: None APIs without any suffix can be invoked only from the user code in the Normal state unless differently specified 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 file . 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 2 3 . low level locks.ChibiOS/RT Kernel services Hardware Abstraction Layer Base kernel services Initialization. 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 infinite 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 . the round robin becomes cooperative .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 specified time quantum expired If CH TIME QUANTUM is equal to zero. 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. Threads are created with the chThdCreateStatic() API: Thread* chThdCreateStatic(void *wsp. size t size.ChibiOS/RT Kernel services Hardware Abstraction Layer Threads A thread is an abstraction of an independent instructions flow In ChibiOS/RT it is a C function owning a processor context. 128). it can be NULL . tprio t prio. tfunc t pf. state informations and a dedicated stack area The working area is declared with a macro: static WORKING AREA(waThread1. then the exit code is returned chThdResume() Resumes a suspended thread chThdTerminate() Requests a thread termination chThdSleep() Suspends the invoking thread for the specified time chThdYield() Yields the time slot .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 specified thread terminates. 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 . a wait operation would put in queue the invoking thread positive: no waiting threads.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 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 specified 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 flags Each thread has a mask of pending event flags inside its Thread structure Operations defined for event flags: Wait: the invoking thread goes to sleep until a certain combination of event flags becomes pending Clear: a mask of event flags 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 specified thread chMsgGet() Returns the message carried by the specified 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 simplified 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 first-fit 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 first-fit algorithm chHeapFree() Frees a previously allocated memory block chHeapStatus() Reports the heap status . size.ChibiOS/RT Kernel services Hardware Abstraction Layer Memory pools Memory pools allow to allocate/free fixed 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. 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 . g. 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 specified memory pool . e.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 final status.. with chThdWait(). bp. n)) #define chSequentialStreamRead(ip. sockets. bp. bp. n) ((ip)→vmt→read(ip. streams are just abstract interfaces The stream interface can be used as base class for high level object types such as files. serial ports. n) ((ip)→vmt→write(ip. pipes etc Methods are defined in BaseSequentialStreamVMT virtual methods table Methods are then called through macros: #define chSequentialStreamWrite(ip.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. n)) . bp. 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 defined 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 2 3 . g.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 definitions of the driver’s 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.. 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 defines a generic Analog to Digital Converter driver The driver supports several conversion modes: one shot: the driver performs a single group conversion linear buffer: the driver performs a series of group conversions then stops circular buffer: when the buffer is filled. it is automatically restarted from the buffer 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 ADCConfig is the platform dependent configuration structure . ChibiOS/RT Kernel services Hardware Abstraction Layer ADC driver operations adcStart() Configures 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 defines 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 flags 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 SerialConfig is the platform dependent configuration structure . ChibiOS/RT Kernel services Hardware Abstraction Layer Serial driver operations sdStart() Configures and starts the driver sdStop() Stops the driver sdWrite() Direct blocking write to a SerialDriver sdWriteTimeout() Direct blocking write to a SerialDriver with timeout specification sdAsynchronousWrite() Direct non-blocking write to a SerialDriver sdRead() Direct blocking read from a SerialDriver sdReadTimeout() Direct blocking read from a SerialDriver with timeout specification 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 . c .ChibiOS/RT Kernel services Hardware Abstraction Layer Serial driver example: main. ChibiOS/RT Kernel services Hardware Abstraction Layer Shell example: command implementation . ChibiOS/RT Kernel services Hardware Abstraction Layer Shell example: command definition .
Copyright © 2024 DOKUMEN.SITE Inc.