Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
83 views
Module5 AMES
embedded system RTOS notes
Uploaded by
anandreddyr
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Module5_AMES For Later
Download
Save
Save Module5_AMES For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
83 views
Module5 AMES
embedded system RTOS notes
Uploaded by
anandreddyr
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Module5_AMES For Later
Carousel Previous
Carousel Next
Save
Save Module5_AMES For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 88
Search
Fullscreen
ARM MICROCONTROLLER & EMBEDDED SYSTEM B.E., VI Semester, Electronics & Communication Engineering/ Telecommunication Engineering IAs per Choice Based Credit System (CBCS) scheme] Subject Code 15EC62 1A Marks 20 Number of Lectureltours/Week04 Exam Marks 80 Total Number of Lecture Hours 50 (10 Hours / Module) Exam Hours 03 Prepared by PRADEEPA S C Asst.Professor EC Dept. JNNCE,Shimoga,KarnatakaModule-5 RTOS and IDE for Embedded System Design: 1.Operating System basics, Types of operating systems, Task, process and threads (Only POSIX Threads with an example program), Thread preemption, Preemptive Task scheduling techniques, Task Communication, Task synchronization issues — Racing and Deadlock, Concept of Binary and counting semaphores (Mutex example without any program),How to choose an RTOS, 2.Integration and testing of Embedded hardware and firmware, 3.Embedded system Development Environment — Block diagram (excluding Keil), Disassembler/decompiler, simulator, emulator and debugging techniques (Text 2; Ch-10 (Sections 10.1, 10.2, 10.3, 10.5.2 , 10.7, 10.8.1.1, 10.8.1.2, 10.8.2.2,10.10 only), Ch 12, Ch-13 (a block diagram before 13.1, 13.3, 13.4, 13.5, 13.6 only)Assignment What is the difference between an assembler and disassembler Explain decompiler. What is the difference between a simulator and a emulator? Expalin the different tools used for hardware debugging. Expalin the boundary scan based hardware debugging in detail HletaeN i Last date:14-05-2018RTOS based Embedded System Design Operating System Basics ¥ The Operating System acts as a bridge between the user applications/tasks and the underlying system resources through a set of system functionalities and services ¥ OS manages the system resources and makes them available to the user applications/tasks on a need basis ¥ The primary functions of an Operating system is ¥ Make the system convenienttouse ¥ Organize and manage the system resources efficiently and correctlyThe Operating System Architecture User Applications I if » Application Programming Interface (API} Memory Management nua . Time Management File System Management 1/0 System Management Kernel Services Device Driver Interface Underlying HardwareDesigning with RTOS The Kernel ¥ The kernel is the core of the operating system Vit is responsible for managing the system resources and the communication among the hardware and other system services ~Kemel acts as the abstraction layer between system resources and user applications ¥ Kernel contains a set of system libraries and services. For a general purpose OS, the kemel contains different services like ¥ Process Management. ¥ Primary Memory Management ¥ File System management ¥Y/O System (Device) Management ¥ Secondary Storage Management ¥ Protection ¥ Time management 7 interrupt HandlingDesigning with RTOS Kernel Space and User Space ¥ The program code corresponding to the kernel applications/services are kept in a contiguous area (OS dependent) of primary (working) memory and is protected from the un-authorized access by user programs/applications ¥ The memory space at which the kemel code is located is known as ‘Kernel Space’ Y Alluser applications are loaded to a specific area of primary memory and this memory area is referred as ‘User Space’ ¥ The partitioning of memory into kernel and user space is purely Operating System dependent ¥ An operating system with virtual memory support, loads the user applications into its corresponding virtual memory space with demand paging techniqueDesigning with RTOS Monolithic Kernel ¥ Allkemel services run in the kernel space YAIl keel modules run within the same Memory space under a single kemel thread ¥The tight internal integration of kemel modules in monolithic kernel architecture allows the effective utilization of the low-level features of the underlying system ¥ The major drawback of monolithic kernel is that any error or failure in any one of the kernel modules leads to the crashing of the entire kernel application ¥ LINUX, SOLARIS, MS-DOS kemels are examples of monolithic kemelDesigning with RTOS Microkernel ¥ The microkemel design incorporates only the essential set of Operating System services >> —<—_ into the kernel aan Applicaions Rest of the Operating System services are ae diel’ implemented in programs known as ‘Servers’ 4? +. which runs in user space | [ | [ ¥ The kemel design is highly modular provides Pye OS-neutral abstraction / eco cesar \ ( services like memory ) ¥ Memory management, process management, management process ) timer systems and interrupt handlers are a a ae examples of essential services, which forms the part of the microkemel YQNX, Minix 3 kemels are examples for microkermelDesigning with RTOS Types of Operating Systems Depending on the type of kernel and kernel services, purpose and type of computing systems where the OS is deployed and the responsiveness to applications, Operating Systems are classified into General Purpose Operating System (GPOS) ¥ Operating Systems, which are deployed in general computing systems ¥The kernel is more generalized and contains all the required services to execute generic applications ¥ Need not be deterministic in execution behavior ¥ May inject random delays into application software and thus cause slow responsiveness of an application at unexpected times ¥ Usually deployed in computing systems where deterministic behavior is not an important criterion ¥ Personal Computer/Desktop system is a typical example for a system where GPOSs are deployed. ¥ Windows XP/MS-DOS etc are examples of General Purpose Operating SystemDesigning with RTOS Real Time Purpose Operating System (RTOS) ¥ Operating Systems, which are deployed in embedded systems demanding real-time response ¥ Deterministic in execution behavior. Consumes only known amount of time for kernel applications ¥ Implements scheduling policies for executing the highest priority task/application always ¥ implements policies and rules concerning time-critical allocation of a system’s resources Y¥ Windows CE, QNX, VxWorks MicroC/OS-IIl etc are examples of Real Time Operating Systems (RTOSDesigning with RTOS The Real Time Kernel The kernel of a Real Time Operating System is referred as Real Time kerel. In complement to the conventional OS kemel, the Real Time kemel is highly Specialized and it contains only the minimal set of services required for running the user applications/tasks. The basic functions of a Real Time kernel are — Task/Process management — Task/Process scheduling — Task/Process synchronization — Error/Exception handling — Memory Management — Interrupt handling — Time managementReal Time Kernel— Task/P1 Designing with RTOS Management Deals with setting up the memory space for the tasks, loading the task’s code into the memory space, allocating system resources, setting up a Task Control Block (TCB} for the task and task/process termination/deletion. A Task Control Block (TCB) is used for holding the information corresponding to a task. TCB usually contains the following set of information Task iD: Task Identification Number Task State: The current state of the task. (Fg. State—‘Ready' fora taskwhich is ready to execute) Task Type: Task type. Indicates what is the type for this task. The taskcan he a hard real time or soft real time or background task. ‘Task Priority: Task priority (E.g. Task priority =1 for task with priority= 1) Task Context Pointer. Context pointer. Pointer for context saving Task Memory Pointers: Pointersto the code memory, data memory and stack memory for the task Task System Resource Pointers: Pointers to system resources (semaphores, mutexetc) used by the task Task Pointers: Pointers to other TCBs (CRs for preceding, next and waiting tasks) ‘Other Parameters Other relevant task parameters The parametersand implementation of the TCBis kernel dependent. The TCB parameters vary across different kernels, based on the task management implementationDesigning with RTOS » Task/Process Scheduling: Deals with sharing the CPU among various tasks/processes. A kernel application called ‘Scheduler’ handles the task scheduling. Scheduler is nothing but an algorithm implementation, which performs the efficient and optimal scheduling of tasks to provide a deterministic behavior. * Task/Process Synchronization: Deals with synchronizing the concurrent access of a resource, which is shared across multiple tasks and the communication between various tasks. * Error/Exception handling: Deals with registering and handling the errors occurred/exceptions raised during the execution of tasks. Insufficient memory, timeouts, deadlocks, deadline missing, bus error, divide by zero, unknown instruction execution etc, are examples of errors/exceptions. Errors/Exceptions can happen at the kernel level services or at task level. Deadlock is an example for keel level exception, whereas timeout is an example for a task level exception. The OS kernel gives the information about the error in the form of a system call (API).Designing with RTOS Memory Management ¥The memory management function of an RTOS kernel is slightly different compared to the General Purpose OperatingSystems Vin general, the memory allocation time increases depending on the size of the block of memory needs to be allacated and the state of the allocated memory block (initialized memory block consumes mare allocation time than un- initialized memory black) YSince predictable timing and deterministic behavior are the primary focus for an RTOS, RTOS achieves this by compromising the effectiveness of memory allocation ‘RTOS generally uses ‘black’ based memory allocation technique, instead of the usual dynamicmemory allocation techniques used by the GPOS. RTOS kernel uses blocks of fixed size of dynamic memory and the block is allocated fora task on a need basis. The blocks are stored in a ‘Free buffer Queue’. Most of the RTOS kemels allow tasks to access any of the memory blacks without any memory protection to achieve predictable timing and avoid the timing overheads YRTOS keels assume that the whole design is proven correct and protection is unnecessary. Some commercial RTOS kernels allow memory protection as optional and the kemel enters a fail-safe mode when an illegal memory access occursDesigning with RTOS Memory Management ¥The memory management function of an RTOS kernel is slightly different compared to the General Purpose OperatingSystems WA few RTOS kemels implement Virtual Memory concept for memory allocation if the system supports secondary memory storage (like HDD and FLASH memory). Yin the ‘block’ based memory allocation, a block of fixed memory is always allocated for tasks on need basis and it is taken as a unit. Hence, there will not be any memory fragmentationissues. The memory allocation can be implemented as constant functions and thereby it consumes fixed amount of time for memory allocation. This leaves the deterministic behavior of the RTOS kernel untouchedDesigning with RTOS InterruptHandling “interrupts inform the processor that an external device or an associated task requires immediate attention of the CPU. Interruptscan be either Synchronous or Asynchronous. ¥ Interrupts which occurs in sync with the currently executing task is known as Synchronous interrupts. Usually the software interrupts fall under the Synchronous Interrupt category. Divide by zero, memory segmentation error etc are examples of asynchronous interrupts. ¥ Forsynchronous interrupts, the interrupt handler runs in the same context of the interrupting task. ¥ Asynchronous interrupts are interrupts, which occurs at any point of execution of any task, and are not insyncwith the currently executing task. The interrupts generated by extemal devices (by asserting the Interrupt line of the processor/eontroller to which the interrupt line of the device is conneded) connected to the processor/controller, timer overflow interrupts, serial data reception/ transmission interrupts etc are examples for asynchronous interrupts. ~ For asynchronous interrupts, the interrupt handler is usually written as separate task (Depends on OS. Keme! implementation) and it runs in a different context. Hence, a context switch happens while handling the asynchronous interrupts. Priority levels can be assigned to the interrupts and each interrupts can be enabled or disabled individually. ¥ Most of the RTOS kernel implements ‘Nested interrupts’ architecture. Interrupt nesting allows the pre- emption (interruption) of an Interrupt Service Routine (ISR), servicing an interrupt, by a higher priority interrupt.Designing with RTOS Time Management ¥ interrupts inform the processor that an external device or an associated task requires immediate attention of the CPU. “Accurate time management is essential for providing precise time reference for all applications “The time reference to keel is provided by a high-resolution Real Time Clock (RTC) hardware chip (hardware timer) ¥ The hardware timer is programmed to interrupt the processor/controller at a fixed rate. This timer interruptis referred as ‘Timer tick’ The ‘Timer tick’ is taken as the timing reference by the kemel. The ‘Timer tick’ interval may vary depending on the hardware timer. Usually the ‘Timer tick’ varies in the microseconds range The time parameters for tasks are expressed as the multiples of the ‘Timer tick” The System time is updated based on the ‘Timer tick” 7if the System time register is 32 bits wide and the ‘Timer tick’ interval is 1 microsecond, the System time register will reset in 2? © 10-5/ (24 * 60 * G0) = 49700 Days =~ 0.0497 Days = 1.19 Hours Ifthe ‘Timer tick’ interval is 1 millisecond, the System time register will reset in 332 #4193 / [24 * 6D * 60) — 497 Davs— 49.7 Davs—” 50 Davs:Designing with RTOS Time Management ‘The ‘Timer tick’ interrupt is handled by the ‘Timer Interrupt’ handler of kemel. The ‘Timer tick’ interrupt can be utilized for implementing the following actions. ¥ Save the current context (Context of the currently executing task) Y Increment the System time register by one. Generate timing error and reset the System time register if the timer tick count is greater than the maximum range available for System time register Y Update the timers implemented in kemel {Increment or decrement the timer registers for each timer depending on the count direction setting for each register. Increment registers with count direction setting = ‘count up’ and decrement registers with count direction setting = ‘count down’) ¥ Activate the periodic tasks, which are in the idle state ¥ Invoke the scheduler and schedule the tasks again based on the scheduling algorithm ¥ Delete all the terminated tasks and their associated data structures (TCBs) ¥ Load the context for the first task in the ready queue. Due to the rescheduling, the ready task might be changed to a new one from the task, which was pre-empted by the ‘Timer Interrupt’ taskDesigning with RTOS Hard Real-time System ¥ A Real Time Operating Systems which strictly adheres to the timing constraints for a task Y AHard Real Time system must meet the deadlinesfor a task without any slippage ¥ Missing any deadline may produce catastrophic results for Hard Real Time Systems, including permanent data lose and irrecoverable damages to the system/users ¥ Emphasizeon the principle‘A late answer isa wrong answer’ ¥ Air bag control systems and Anti-lock Brake Systems (ABS) of vehicles are typical examples of Hard Real Time Systems ¥ Asa rule of thumb, Hard Real Time Systems does not implement the virtual memory model for handling the memory. This eliminates the delay in swapping in and out the code corresponding to the task to and from the primary memory ¥ The presence of Human in the loop (HITL) for tasks introduces un-expected delays in the task execution. Most of the Hard Real Time Systems are automatic and does not containa ‘humanin the loop’Designing with RTOS Soft Real-time System ¥ Real Time Operating Systems that does not guarantee meeting deadlines, but, offer the best effort to meet the deadline ¥ Missing deadlines for tasks are acceptable if the frequency of deadline missing is within the compliance limit of the Quality of Service (QoS) ~A Soft Real Time system emphasizes on the principle ‘A late answer is an acceptable answer, but it could have done bit faster’ ¥ Soft Real Time systems most often have a ‘human in the oop (HITLY ¥ Automatic Teller Machine (ATM) is a typical example of Soft Real Time System. If the ATM takes a few seconds more than the ideal operation time, nothing fatal happens. ¥ An audio video play back system is another example of Soft Real Time system. No potential damage arises if a sample comes late by fraction of a second, for play backDesigning with RTOS Tasks, Processes & Threads ¥ In the Operating System context, a task is defined as the program in execution and the related information maintained by the Operating system for the program ¥ Taskis also known as ‘Job’ in the operating system context ¥ Aprogram or part of it in execution is also called a ‘Process’ ¥ The terms ‘Task’, ‘job’ and ‘Process’ refer to the same entity in the Operating System context and most often they are used interchangeably ~A process requires various system resources like CPU for executing the process, memory for storing the code corresponding to the process and associated variables, |/O devices for information exchange etcDesigning with RTOS The structure of a Processes Y The concept of ‘Process’ leads to concurrent execution {pseudo parallelism) of tasks and thereby the efficient utilization of the CPU and other system resources ¥ Concurrent execution is achieved through the sharing of CPU among the processes ¥ A process mimics a processor in properties and / mae \ holds a set of registers, process status, a / Program Counter (PC) to point to the next | executable instruction of the process, a stack for | holding the local variables associated with the process and the code corresponding to the Progam Courter @C) process . 4 7 A process, which inherits all the properties of the CPU, can be considered as a virtual Ereumrrg he Processor, awaiting its turn to have its Process Properties switched into the physical processor ¥ When the process gets its tum, its registers and Program counter register becomes mapped to the physical registers of the CPU Wetkirg Revisions | Sots Ropar }Process Praoess Process 2 Process S Pracess4 Adrittoe—pf Process Job Queue xe Frost Pravess 2 Praoessn wore Cerptea Process ta Feaoy queue Ready Queue |< ovo rcomtosprocacsto Reayy’ quous of oF Pence oo Manager Faces Je Process? Process Device Queue 9 9 im Resnurse Requs|_| iy Procese le! fun Process. i Completion >Designing with RTOS Memory organization of a Processes ¥The memory occupied by the process is segregated into three regions namely; Stack memory, Data memory and Code memory ~The ‘Stack’ memory holds all temporary data such as variables local to the process ¥ Data memory holds all global data for the process ¥ The code memory contains the program code (instructions) corresponding to the process ¥ On loading a process into the main memory, a Specific area of memory is allocated for the process ¥ The stack memory usually starts at the highest memory address from the memory area allocated for the process (Depending on the OS kemel implementation)Designing with RTOS Process States & State Transition ¥ The cycle through which a process changes its state from ‘newly created’ to ‘execution completed’ is known as ‘Process Life Cycle’. Execution|CompletionDesigning with RTOS Process States & State Tran: * Created State: The state at which a process is being created is referred as ‘Created State’. The Operating System recognizes a process in the ‘Created State’ but no resources are allocated to the process * Ready State: The state, where a process is incepted into the memory and awaiting the processor time for execution, is known as ‘Ready State’. At this stage, the process is placed in the ‘Ready lis? queue maintained by the OS = Running State: The state where in the source code instructions corresponding to the process is being executed is called ‘Running State’. Running state is the state at which the process execution happens. * Blocked State/Wait State: Refers to a state where a running process is temporarily suspended from execution and does not have immediate access to resources. The blocked state might have invoked by various conditions like- the process enters a wait ‘state for an event to occur (E.g. Waiting for user inputs such as keyboard input) or waiting for getting access to a shared resource like semaphore, mutex etc * Completed State: A state where the process completes its execution ¥ The transition of a process from one state to another is known as ‘State transition’ ¥ When a process changes its state from Ready to running or from running to blocked or terminated or from blocked to running, the CPU allocation for the process may also changeDesigning with RTOS Threads Y Athread is the primitive that can execute code ¥ A thread is a single sequential flow of control within process ¥ ‘Thread’ is also known as lightweight process ~ Aprocess can have many threads of execution Y Different threads, which are part of a process, share the same address space; meaning they share the data memory, code memory and heap memory area ¥ Threads maintain their own thread status (CPU register values), Program Counter (PC) and stack Stack memory fer Thread 1 Stack Mem ory Stack memory fox Thread 2 | Sask Mono Data Memory for Process Code Memory for ProcessDesigning with RTOS The Concept of multithreading TaskiProcess Stack Registers, Throsa 3Designing with RTOS The Concept of multithreading Use of multiple threads to execute a process brings the following advantage. ¥ Better memory utilization. Multiple threads of the same process share the address space for data memory. This also reduces the complexity of inter thread communication since variables can be shared across the threads. ¥ Since the process is split into different threads, when one thread enters a wait state, the CPU be utilized by other threads of the process that do not require the event, which the other thread is waiting, for processing. This speeds up the execution of the process. Y Efficient CPU utilization. The CPU is engaged all time.Designing with RTOS Thread Standards Thread standards deal with the different standards available for thread creation and management. These standards are utilized by the Operating Systems for thread creation and thread management. It is a set of thread class libraries. The commonly available thread class libraries are * POSIX Threads: POSIX stands for Portable Operating System Interface. The POSIX.4 standard deals with the Real Time extensions and POSiX.4a standard deals with thread extensions. The POSIX standard library for thread creation and management is ‘Pthreads’. ‘Pthreads’ library defines the set of POSIX thread creation and management functions in ‘C’ language.Designing with RTOS POSIX Thread Creation int pthread_create(pthread_t *new_thread_ID, const pthread _attr_t *attribute, void * (*start_functionXvoid *), void arguments);Designing with RTOS User & Kernel level threads * User Level Thread: : User level threads do not have kernel/Operating System support and they exist solely in the running process. Even if a process contains multiple user level threads, the OS treats it as single thread and will not switch the execution among the different threads of it. It is the responsibility of the process to schedule each thread as and when required. In summary, user level threads of a process are non-preemptive at thread level from OS perspective. * Kernel Level/System Level Thread: Kernel level threads are individual units of execution, which the OS treats as separate threads. The OS interrupts the execution of the currently running kernel thread and switches the execution to another kernel thread based on the scheduling policies implemented by the OS.Designing with RTOS Thread binding Models * Many-to-One Model: Many user level threads are mapped to a single kernel thread. The kermel treats all user level threads as single thread and the execution switching among the user level threads happens when a currently executing user level thread voluntarily blocks itself or relinquishes the CPU. Solaris Green threads and GNU Portable Threads are examples for this. * One-to-One Model: Each user level thread is bonded to a kemel/system level thread. Windows XP/NT/2000 and Linux threads are examples of One-to-One thread models. * Many-to-Many Model: In this model many user level threads are allowed to be mapped to many kemel threads. Windows NT/2000 with ThreadFiber packageis an example for this.Designing with RTOS Thread V/s Process Bais ‘Thread is a single unit of execution and is part of process. A thread docs not have its own data memory and heap memory. It shares the data memory and heap memory with other threads of the same process. A thread cannot live independently; it lives within the process. There can be multiple threads in a The first thread (main thread) calls the main function and occupies the start of the stack memory of the process. ‘Threads are very inexpensive to create Context switching is inexpensive and fast If a thread expires, its stack is reclaimed by the process. ey Process is a program i execution and contains one ormore threads. Process has its own code memory, data memory and stack memory. ‘Approcess contains at least one thread. ‘Threads within a process stare the code, data and heap m thread holds separate memory area for stack (shares the total stack memory of the process). Processes are very expensive to create. Involves many OS overhead. Context switching is complex and involves lot of OS overhead and is comparatively slower. Ifa process dies, the resources allocated to it are reclaimed by the OS and all the associated threads of the process also dies.Designing with RTOS Preemptive scheduling ¥ Employed in systems, which implements preemptive multitasking model ¥ Every task in the ‘Ready’ queue gets a chance to execute. When and how often each process gets a chance to execute (gets the CPU time) is dependent on the type of preemptive scheduling algorithm used for scheduling the processes ¥ The scheduler can preempt (stop temporarily) the currently executing task/process and select another task from the ‘Ready’ queue for execution ¥ When to preempt a task and which task is to be picked up from the ‘Ready’ queue for execution after preempting the current task is purely dependent on the scheduling algorithm ¥ A task which is preempted by the scheduler is moved to the ‘Ready’ queue. The act of moving a ‘Running’ process/task into the ‘Ready’ queue by the scheduler, without the processes requesting for it is known as ‘Preemption’ ¥ Time-based preemption and priority-based preemption are the two important approaches adopted in preemptive schedulingDesigning with RTOS Preemptive scheduling — Preemptive SIF Scheduling/ Shortest RemainingTime (SRT) ¥ The non preemptive S/F scheduling algorithm sorts the ‘Ready’ queue only after the current process completes execution or enters wait state, whereas the preemptive SJF scheduling algorithm sorts the ‘Ready’ queue when a new process enters the ‘Ready’ queue and checks whether the execution time of the new process is shorter than the remaining of the total estimated execution time of the currently executing process Y If the execution time of the new process is less, the currently executing process is preempted and the new process is scheduled for execution ¥ Always compares the execution completion time (ie the remaining execution time for the new process) of a new process entered the ‘Ready’ queue with the remaining time for completion of the currently executing process and schedules the process with shortest remaining time for executionDesigning with RTOS Preemptive scheduling — Preemptive SIF Scheduling + Three processes with process IDs P1, P2, P3 with estimated completion time 10, 5, 7 milliseconds respectively enters the ready queue together. A new process P4 with estimated completion time 2ms enters the ‘Ready’ queue after 2ms. Assume all the processes contain only CPU operation and no I/O operations are involved. + At the beginning, there are only three processes (P1, P2 and P3) available in the ‘Ready queue and the SRT scheduler picks up the process with the Shortest remaining time for execution completion (In this example P2 with remaining time Sms) for scheduling. Now process P4 with estimated execution completion time 2ms enters the ‘Ready’ queue after 2ms of start of execution of P2. The processes are re-scheduled for execution in the following order p2|p4| pe Ps Pt q 2 Gee? 1“ 24 <2ratre toe.Designing with RTOS Preemptive SJF Scheduling “The waiting tine for all the processes are given as Waiting Time for P2 = O ms + {4-2} ms = 2ms (P2 starts executing firstand is interrupted by P4 and has to waittill the completion of PA» getthe next CPU slot} ‘Wating Time for P4 =O ms {P4 starts excouting by precmpting P2 since the execution time for completion of PA {2ms) isless than ‘thatof the Remaining time for execution completion of P2 (Hereitis 3ens)} ‘Woalting Time for P3=7 ms {PS starts executing after completing PA and P2) Waiting Time for P1.=14 ms (PA starts exeruling alter ecenpleting PS, P2 and P3) Average waiting time {Waiting time for all the processes} / No. of Processes, (ating time for (P41 P24PS1PI}} £4 247+ aya = 23/4 =5.75 milliseconds ‘Tum Around Time{TAT) for P2-7ms {Time spent in Ready Queve + Execution Time} Turn Around Time {TAT} for PA = 2 ms (Time sperit in Ready Queue + Execution Time= (Execution Start Time —Arvival Tiene} + Estimated Execution Time= (2-2) +2) ‘Tur Around Time {TAI} for P3=14 ms {Time spent in Ready Queue + Execution Time} ‘Tum Around Time{TAT} for PL=24ms {Time spent in Ready Queve + Execution Time} AwerageTum AroundTime =(Turn Around Time: for all the processes) / No. of Processes = {Turn Around Time for (F2:P4:P31PI)) 14 =D MDa = 7/8 = 1175 rnilisecondsDesigning with RTOS Preemptive scheduling — Round Robin (RR) Scheduling ¥ Fach process in the ‘Ready’ queue is executed for a pre-defined time slot. ¥ The execution starts with picking up the first process in the ‘Ready’ queue. It is executed for a pre-defined time ¥ When the pre-defined time clapses or the process completes (before the pre-defined time slice}, the next process in the ‘Ready’ queue is selected for ‘execution. ¥ This is repeated for all the processes in the ‘Ready’ queue Y Once each process in the ‘Ready’ queue is executed for the pre-defined time period, the scheduler comes back and picks the first process in the ‘Ready’ queue again for execution ~ Round Robin scheduling is similar to the FCFS scheduling and the only difference is that a time slice based preemption is added to switch the execution between the processes in the ‘Ready’ queue Execution Switch 3 Execution Sitch Execution Switch > Execution SwitchDesigning with RTOS Preemptive scheduling — Round Robin Scheduling * Three processes with process IDs P1, P2, P3 with estimated completion time 6, 4, 2 milliseconds respectively, enters the ready queue together in the order P1, P2, P3. Calculate the waiting time and Turn ‘Around Time (TAT] for each process and the Average waiting time and Turn Around Time (Assuming there isno I/O waiting for the processes} in RR algorithm with Time slice= 2ms. * The scheduler sorts the ‘Ready’ queue hased on the FCFS policy and picks up the first process P1 from the ‘Ready’ queue and executes it for the time slice 2ms. When the time slice is expired, P1 is preempted and P2is scheduled for execution. The Time slice expires after 2ms of execution of P2. Now P2 is preempted and P3 is picked up for execution. P3 completes its execution within the time slice and the scheduler picks PL agpin for execution for the next time slice. This procedure is repeated till all the processes are serviced. The order in which the processes are scheduled for execution is represented as pi | pz | ps | pr | pe | pr ° 2 4 6 8 102 4-24 2b 24 2 a 2 edDesigning with RTOS Preemptive scheduling— Round Robin Scheduling “The waiting time for all the processes are given as Waiting Time for P1- 0-+ (6-2) + {10-8) - 01442-6ms {P1 starts executing first and wats for two time slices to get execution back and again 1 time slice for getting CPU time) Waiting Time for P2= (2-0) + (8-4) = 24 = Gms (P2 starts executing after P1 executes for 1 time slice and waits for two time slices to get the CPU time) ‘Waiting Time for P3= {4-0) = 4ms (P3 starts executing after completing the first time slices for PI and P? and completes its ‘execution in a single time slice) ‘Average waiting time = (Waiting time for all the processes) / No. of Processes {Waiting time for (P1+P2+P3)} /3 (6+6+4)/3 = 16/3 = 5.33 milliseconds ‘Jum Around Time (IAT) for P1=12ms_ {Time spent in Ready Queue + Execution Time) Jum Around Time (IAI) for P2=10ms (Do) ‘Tum Around Time (IAT) for P3 = 6 ms {Do} Average Tum Around Time = {Tum Around Time for all the processes) /No. of Processes = {lum Around Time for (P11P2+P3))/3 = (12s10+6)3 = 28/3 =9.33 millisecondsModule-5 RTOS and IDE for Embedded System Design: 1.Operating System basics, Types of operating systems, Task, process and threads (Only POSIX Threads with an example program), Thread preemption, Preemptive Task scheduling techniques, Task Communication, Task synchronization issues — Racing and Deadlock, Concept of Binary and counting semaphores (Mutex example without any program),How to choose an RTOS, 2.Integration and testing of Embedded hardware and firmware, 3.Embedded system Development Environment — Block diagram (excluding Keil), Disassembler/decompiler, simulator, emulator and debugging techniques (Text 2; Ch-10 (Sections 10.1, 10.2, 10.3, 10.5.2 , 10.7, 10.8.1.1, 10.8.1.2, 10.8.2.2,10.10 only), Ch 12, Ch-13 (a block diagram before 13.1, 13.3, 13.4, 13.5, 13.6 only)Designing with RTOS Task Communication Ina multitasking system, multiple tasks/processes run concurrently (in pseudo parallelism) and each process may or may not interact between. Based on the degree of interaction, the processes /tasks running on an OS are classified as + Co-coperating Processes: In the co-operating interaction model one process requires the inputs from other processes to complete its execution. * Competing Processes: The competing processes do not share anything among themselves but they share the system resources. The competing processes compete forthe system resources such as file, displaydevice etc ‘The co-operating processes exchanges information and communicate through + Co-operation through sharing: Exchange data through some shared resources. + Cooperation through Communication: No data is shared between the processes. But they communicate for execution synchronization.Designing with RTOS Inter Process (Task) Communication (IPC) ¥ IPC refers to the mechanism through which tasks/proce ¥ IPCis essential for task /process execution co-ordination and synchronization ¥ Implementation of IPC mechanism is OS keel dependent ¥ Some important IPC mechanisms adopted by OS kemels are: Y SharedMemory ¥ Global Variables Y Pipes (Named & Un-named) ¥ Memory mapped Objects Y Message Passing ¥ Message Queues ¥ Mailbox ¥ Mail slot Y Signals ¥ Remote Procedure Calls (RPC) communicate each otherDesigning with RTOS IPC - Shared Memory ¥ Processes share some area of the memory to communicate among them ¥ Information to be communicated by the process is written to the shared memory area ¥ Processes which require this information can read the same from the shared memory area ¥ Same as the real world concept where a ‘Notice Board’ is used by the college to publish the information for students (The only exception is; only college has the right to modify the information published on the Notice board and students are given ‘Read’ only access. Meaning it is only a one way channel) Process 1 | Shared Memory Area | Process 2 Concept of Shared MemoryDesigning with RTOS IPC — Shared Memory: Pipes Q) ‘Pipe’ is a section of the shared memory used by processes for communicating. Q Pipes follow the client-server architecture. Q A process which creates a pipe is known as pipe server and a process which connects to a pipe is known as pipe client. The implementation of ‘Pipes’ is OS dependent. Microsoft® Windows Desktop Operating Systems support two types of ‘Pipes’ for Inter Process Communication. Namely; «Anonymous Pipes: The anonymous pipes are unnamed, unidirectional pipes used for data transfer between two processes. «Named Pipes: Named pipe is a named, unidirectional or bi- directional pipe for data exchange between processes. Concept of Shared MemoryDesigning with RTOS IPC — Shared Memory: Memory Mapped Objects ¥ A shared memory technique adopted by certain Real Time Operating Systems for allocating a shared block of memory which can be accessed by multiple process simultaneously (of curse certain synchronization techniquesshould be applied to prevent inconsistent results). ¥ Amappingobjectis created and physical storage for itis reserved and committed. Y Aprocesscan map the entire committed physical area ora block of it to its virtual address space ¥ All read and write operation to this virtual address space by a process is directed to its committed physical area ¥ Any process which wants to share data with other processes can map the physical memory area of the mapped object to its virtual memory space and use it for sharing the data. iris? weaiice= coats cna a, en ‘nen snennaets Sealine, mn estoy Tesaramaannae (em bean enviDesigning with RTOS IPC — Shared Memory: Memory Mapped Objects Windows CE 5.0 RTOS uses the memory mapped object based shared memory technique for Inter Process Communication {Create a Mapping from the system memory CreateFileMapping (HANDLE hile, LPSECURITY_ATTRIBUTES ipFiieMappingAnributes, DWORD flProtect, DWORD dwMaximumSizeHigh, DWORD dwMaximumSizel ow, 1PCTSTRipName) IpFileMappingAttributes: the security attributes and it must be NULL. fiProtect : Specify read write access for the shared memory area. PAGE_READONLY > Read only access PAGE_READWRITE > Read-Write access dwMaximumSizeHigh : Specifies the higher order 32 bits of the maximum size of the memory mapped ‘object dwMaximumSizetow : Specifies the lower order 3? bits of the maximum size of the memory mapped ‘object. IpName: Points to a null terminated string specifying the name of the memory mapped object. The memory mapped object is created as unnamed object if the parameter /pName is NULL.Designing with RTOS IPC- Shared Memory: Memory Mapped Objects {1 Maps a view of the memory mapped object to the address space of the calling process MapViewOfFile (HANDLE hFileMappingObject DWORD dwDesiredAccess, DWORD dwrileOffsetHigh, DWORD dwFieOffsetLow, DWORD dwNumberOfBytesToMap) hFileMappingObject : Specifies the handle to an existing memory mapped object dwDesiredAccess : Specify the read write access for the mapped view area. FILE_MAP_WRITE makes the view access read-write, provided the memory mapped object hFileMappingObject is created with read-write access, whereas the value FILE_MAP_READ gives read only access to the shared memory dwFileOffsettigh : Specifies the higher order 32 bits of the memory offset where mapping is to begin from the memory mapped object dwFileOffsetiow specifies the lower order 32 bits of the memory offset where mapping is to begin from the memory mapped object. A value of ‘0’ for both of these maps the view from the beginning memory area of the memory object dwNumberOfBytesToMap : Specifies the number of bytes of the memory object to map. If dwNumberOfBytesToMap is zero, the entire memory area owned by the memory mapped object is mapped.Designing with RTOS IPC— Message Passing YA _ synchronous/asynchronous information exchange mechanism for Inter Process/ thread Communication ¥ Through shared memory lot of data can be shared whereas only limited amount of info/data is passed through message passing ¥ Message passing is relatively fast and free from the synchronization overheads compared to shared memoryDesigning with RTOS IPC — Message Passing: Message Queues ~ Process which wants to talk to another process pasts the message ta a First-In-First-Out (FIFO) queue called ‘Message queue’, which stores the messages temporarily in a system defined memory object, to pass it to the desired process ~ Messages are sent and received through send (Name of the process to which the message is to be sent, message) and receive (Name of the process from which the message is to be received, message) methods v The messages are exchanged through a message queue Y The implementation of the message queue, send and receive methods are OS kemel dependent. veomane |Designing with RTOS IPC— Message Passing: Mailbox Y Aspecial implementation of message queue ¥ Usually used for one way communication vOnly a single message is exchanged through mailbox whereas ‘message queue’ can be used for exchanging multiple messages ¥ One task/process creates the mailbox and other tasks/process can subscribe to this mailbox for getting message notification ¥ The implementation of the mailbox is OS kemel dependent ¥ The MicroC/OS-I| RTOS implements mailbox as a mechanism for inter task communication ) vatoo Concept of Message QueueDesigning with RTOS IPC — Message Passing: Signal ¥ Anasynchronous notification mechanism ¥Mainly used for the execution synchronization of tasks process/tasks ¥ Signal do not carry any data and are not queued ¥The implementation of signals is OS kernel dependent ¥ VxWorks RTOS kernel implements ‘signals’ for inter process communication ¥ A task/process can create a set of signals and register for it A task or Interrupt Service Routine (ISR) can signal a ‘signal’ ¥Whenever a specified signal occurs it is handled in a signal handler associated with the signalDesigning with RTOS IPC — Remote Procedure Call (RPC) wv wv The IPC mechanism used by a process to call a procedure of another process running ‘onthe same CPU or on a different CPU which is interconnected in a network In the object oriented language terminology RPC is also known as Remote invocation or Remote Method invocation (RMI) RPC is mainly used for distributed applications like client-server applications With RPC it is possible to communicate over a heterogeneous network (i.e. Network where Client and server applicationsare running on different Operating systems) The CPU/Process containing the procedure which needs to be invoked remotely is knownas server The CPU/Process whi ‘iates an RPC request is known as client In order to make the RPC communication compatible across all platforms it should ‘stick on to certain standard formats Interface Definition Language (IDL) defines the interfaces for RPC Microsoft Interface Definition Language (MIDL) is the IDL implementation from Microsoft for all Microsoft platforms The RPC communication can be either Synchronous (Blocking) or Asynchronous (Non- blocking)Designing with RTOS IPC — Remote Procedure Call (RPC) cPU cpu Prowass Process Procedure TCP/IP of UDP Over Socket Processes running on different CPUs which are networked Process 1 eu Process 2 JLCPAP or UCP] | Procedure ‘Over Socket Processes running on same CPU Concept of Remote Procedure Call (RPC) for IPCDesigning with RTOS IPC — Remote Procedure Call (RPC) v v v RPC uses sockets for implementing communication Socket is a logical endpoint in a two-way communication link between two applications running on a network. A port number is associated with a socket so that the network layer of the communication channel can deliver the data to the designated application Sockets are of different types namely; Internet sockets (INET}, UNIX sockets etc. The INET Socket works on Internet Communication protocol. TCP/IP, UDP etc are the communication protocols used by INET sockets INET sockets are classified into: ¥ Stream Sockets ~ Datagram Sockets Stream sockets are connection oriented and they use TCP to establish a reliable connection Datagram Sockets rely on UDP for establishing a connectionModule-5 RTOS and IDE for Embedded System Design: 1.Operating System basics, Types of operating systems, Task, process and threads (Only POSIX Threads with an example program), Thread preemption, Preemptive Task scheduling techniques, Task Communication, Task synchronization issues — Racing and Deadlock, Concept of Binary and counting semaphores (Mutex example without any program),How to choose an RTOS, 2.Integration and testing of Embedded hardware and firmware, 3.Embedded system Development Environment — Block diagram (excluding Keil), Disassembler/decompiler, simulator, emulator and debugging techniques (Text 2; Ch-10 (Sections 10.1, 10.2, 10.3, 10.5.2 , 10.7, 10.8.1.1, 10.8.1.2, 10.8.2.2,10.10 only), Ch 12, Ch-13 (a block diagram before 13.1, 13.3, 13.4, 13.5, 13.6 only)Designing with RTOS Task Synchronization ¥ Multiple processes may try to access and modify shared resources in a multitasking environment. This may lead to conflicts and inconsistent results ¥ Processes should be made aware of the access of a shared resource by each Process and should not be allowed to access a shared resource when it is currently being accessed by another processes ¥ The act of making processes aware of the access of shared resources by each Process to avoid conflicts is known as ‘Task/Process Synchronization’ ¥ Task Synchronization is essential for avoiding conflicts in shared resource access and ensuring a specified sequence for task execution ¥ Various synchronization issues may arise in a multitasking environment if processes are not synchronized properly in shared resource accessDesigning with RTOS Task Synchronbation teapes RacingDesigning with RTOS Task Synchronization Issues — Racing From a programmer perspective, the value of counter will be 10 at the end of execution of processes A & B. But it need not be always. program statement countert+; looks like a single statement from a high level programming language (C Language) perspective. The low level implementation of this statement is dependent on the underlying Processor instruction set and the (cross) compiler in use. The low level implementation of the high level program statement counter#+; under Windows XP operating system running on an Intel Centrino Duo processor is given below. The code snippet is compiled with Microsoft Visual Studio 6.0 compiler. moveax dword ptr febp-4]L.0ad counter fa Accumulator oddeax 1 ; increment Accumulator by 1 mov dword pir jebp-4.eax :Store counter with Accumulator. ‘At the processor instruction level, the value of the variable counter is loaded to the Accumulator register (EAX Register). The memory variable counter is represented using a pointer. The base pointer register [EBP Register) is used for pointing to the memory variable counter. After loading the contents of the variable counter to the ‘Accumulator, the Accumulator content is incremented by one using the add instruction. Finally the content of ‘Accumulator is loaded to the memory location which represents the variable counter. Both the processes Process A and Process B contain the program statement counter; Translating this into the machine instruction. Process A Process B mov eax,dword ptr [ebp-4] mov eax,dword ptr [ebp-4] add eax.1 add eax.1 mov dword ptr [ebp-4],eax mov dword ptr [ebp-4]eaxDesigning with RTOS Task Synchronization Issues — Racing Imagine a situation where a process switching (context switching) happens from Process A to Process 6 when Process A is executing the counter; statement. Process A accomplishes the counter; statement through three different low level instructions. Now imagine that the process switching happened at the point where Process A executed the low level instruction mov eax.tword ptr [ebp-4] and is about to execute the next instruction add eax)1. The scenario és illustrated below. Process A Process B mov eax.¢word pir febp-4] mov eax dword ptr [obp-4] add 001 ‘mov dword pl [ebp-S}, eax add eaxt mov dword ptr febp-4). eax Process B increments the shared variable ‘counter’ in the middle of the operation where Process A tries to increment it. When Process A gets the CPU time for execution, it starts from the point where it got interrupted (If Process 3 is ako using the same registers eax and ep for executing counter++; instruction, the original content of these registers will be saved (PUSHed) by Process B before using it and the contents will be retrieved (POPed) after finishing the operation. Hence the content of eax and ebp remains intact irrespective of context switching). Though the variable counter is incremented by Process B, Process Ais unaware of it and it increments the variable with the old value. ‘This leads to the loss of one increment for the variable counter.Designing with RTOS Task Synchronization Issues — Deadlock Deadlock is the condition in which a process is waiting for a resource held by another process which is waiting for a resource held by the first process Process A Process B Hop 1 ts, we Yi, sy Resource yo Resource ‘y' Scenarios leading to DeadlockDesigning with RTOS Task Synchronization Issues — Deadlock: Conditions favoring deadlock (“Mutual Exclusion: The criteria that only one process can hold a resource at a time. Meaning processes should access shared resources with mutual exclusion. Typical exampleis the accessing of display device in an embedded device U Hold & Wait: The condition in which a process holds a shared resource by acquiring the lock controlling the shared access and waiting for additional resources held by other processes U No Resource Preemption: The criteria that Operating System cannot take back a resource from a process which is currently holding it and the resource can only be released voluntarily by the process holdingit O Circular Wait: A process is waiting for a resource which is currently held by another process which in turn is waiting for a resource held by the first process. In general there exists a set of waiting process PO, P1 .... Pn with PO is waiting for a resource held by P1 and P1 is waiting for a resource held by PO, ......, Pn is waiting for a resource held by PO and PO is waiting for a resource held by Pn and so on... This forms a circular wait queue. ‘Deadlock’ is a result of the combined occurrence of these four conditions listed above. These conditions are first described by E. G. Coffman in 1971 and it is popularly known as Coffman conditions.Designing with RTOS Task Synchronization Issues — Deadlock: Handling deadlock A smart OS may foresee the deadlock condition and will act proactively to avoid such a situation. Now if a deadlock occurred, how the OS responds to it? The reaction to deadlock condition by OS is non uniform. The OS may adopt any of the following techniques to detect and prevent deadlock conditions. Ollgnore Deadlocks: always assume that the system design is deadlock free. This is acceptable for the reason the cost of removing a deadlock is large compared to the chance of happening a deadlock. UNIX is an example for an OS following this principle. ODetect and Recover: This approach suggests the detection of a deadlock situation and recovery from it. Operating Systems keep a resource graph in their memory. The resource graph is updated on each resource request and release. A deadlock condition can be detected by analyzing the resource graph by graph analyzer algorithms. Once a deadlock condition is detected, the system can terminate a process or preempt the resource to break the deadlocking cycle.Designing with RTOS Task Synchronization Issues — Deadlock: Handling deadlock OU Avoid Deadlocks: peadiock is avoided by the careful resource allocation techniques by the Operating System. UO Prevent Deadlocks: prevent the deadlock condition by negating one of the four conditions favoring the deadlock situation. Y Ensure that a process does not hold any other resources when it requests a resource. This can be achieved by implementing the following set of rules/guidelines in allocating resources to processes 1. A process must request all its required resource and the resources should be allocated before the process begins its execution. 2. Grantresource allocation requests from processes only il the process does not hokl a resource currently ¥ Ensure that resource preemption (resource releasing} is possible at operating system level. This can be achieved by implementing the following set of rules/guidelines in resources allocation and releasing 1. Release all the resources currently held by a process fa request made by the process for a new resource is notable to fulfilimmediately. 2. Add the resources which are preempted (released) to a resource list describing the resources which the process requires to complete its execution. 3. Reschedule the process for execution only when the process gets its old resources and the new resource which is requested by the process.Designing with RTOS Task Synchronization Issues — Livelock & Starvation Q) Livelock The Livelock condition is similar to the deadlock condition except that a process in livelock condition changes its state with time The livelock condition is better explained with the real world example, two people attempting to cross each other in a narrow corridor. Both of the persons move towards each side of the corridor to allow the opposite person to cross. Since the corridor is narrow, none of them are able to cross each other. Here both of the persons perform some action but still they are unable to achieve their target- Cross each other QO) Starvation In the task synchronization issue context, starvation is the condition in which a process does not get the resources required to continue its execution for a long time. As time progresses the process starves on resource. Starvation may arise due to various conditions like byproduct of preventive measures of deadlock, scheduling policies favoring high priority tasks and tasks with shortest execution time etc.Designing with RTOS Task Synchronization Issues — Dining Philosophers Problem Five philosophers (It can be ‘n’. The number 5 is taken for illustration) are sitting around a round table, involved in eating and brainstorming. At any point of time each philosopher will be in any one of the three states: eating, hungry or brainstorming. (While eating the philosopher is not involved in brainstorming and while brainstorming the philosopher is not involved in eating). For eating, each philosopher requires 2 forks. There are only 5 forks available on the dining table (‘n’ for ‘n’ number of philosophers) and they are arranged in a fashion one fork in between two philosophers. The philosopher can only use the forks on his/her immediate left and right that too in the order pickup the left fork first and then the right fork. Analyze the situation and explain the possible outcomes of this scenario. ee Sey @;:®@ © ‘+:Designing with RTOS ‘Task Synchronization Issues — Dining Philosophers Problem Scenario 1: All philosophers involve in brainstorming together and try to eat together. Each philosopher picks up the left fork and unable to proceed since two forks are required for eating the spaghetti presentiin the plate. Philosopher-1 thinks that Philosopher-2 sitting to the right of him/her will put the fork down and waits for it. Philosopher-? thinks that Philosopher 3 sitting to the right of him/her will put the fork down and waits for it and so on. This forms a circular chain of un-granted requests. If the philosophers continue in this state waiting for the fork from the philosopher sitting to the right of each, they will not make any progress in eating and this \willresult in starvation of the philosophers and dendiock. 1 Scenario 2: All philosophers start brainstorming together. One of the philosophers is hungry and he/she picks up the left fork. When the philosopher is about to pick up the right fork, the philosopher sitting to his right also become hungry and he uies to grab the left fork which is the right fork for his neighboring philosopher who is, ‘trying to lft it, resulting in a ‘Race condition’ C1 Scenario 3: All philosophers involve in brainstorming together and try to eat together. Each philosopher picks up the left fork and unable to proceed, since two forks are required for eating the spaghetti present in the plate. Each of them anticipates that the adjacently sitting philosopher will put his/her fork down and waits for a fised duration and after this puts the fork down. Each of them again tries to lift the fork after a fixed duration of time. Since all philosophers are Uying to lift the fork together, none of them will be able to grab two forks. This condition leads to livelock and starvation of philosophers, where each philosopher tries to do something, but they are unable to make any progressin achieving the target.‘Task Synchronization Issues— Dining Philosophers Problem 7 2B 2 2S ot gy ~~ aed \ ee ‘The Real Problerns in the ‘Din prern’ {eo} Starvation & Deadlock {b) Racing {c} Livelock & Starvation oyDesigning with RTOS Task Synchronization— Mutual Exclusion through Sleep & Wakeup v¥The ‘Busy waiting’ mutual exclusion enforcement mechanism used by processes makes the CPU always busy by checking the lock to see whether they can proceed. vIn the ‘Sleep & Wakeup’ mechanism, when a process is not allowed to access the critical section, which is currently being locked by another process, the process undergoes ‘Sleep’ and enters the ‘blocked’ state ¥The process which is blocked on waiting for access to the critical section is awakened by the process which currently owns the critical section ¥ The process which owns the critical section sends a wakeup message to the process, which is sleeping as a result of waiting for the access to the critical section, when the process leaves the critical section ¥The ‘Sleep & Wakeup’ policy for mutual exclusion can be implemented in different ways. Implementation of this policy is OS kernel dependentDesigning with RTOS ‘Task Synchronization— Mutual Exclusion - Sleep & Wakeup: Semaphore A sleep and wakeup based mutual exclusion implementation for shared resource access ¥ Semaphore is a system resource and a process which wants to access the Shared resource can first acquire this system object to indicate the other processes which wants the shared resource that the shared resource is currently in use by it ¥ The resources which are shared among a process can be either for exclusive use bya process or for using by a number of processes at atime ¥The display device of an embedded system is a typical example of a shared resource which needs exclusive access by a process ¥ The Hard disk (secondary storage) of a system is a typical example for sharing the resource among a limited number of multiple processes ¥ Based on the implementation Semaphores can be classified into ¥ BinarySemaphore ¥ Counting Semaphore ¥ Mutual exclusion SemaphoreDesigning with RTOS Task Synchronization— Mutual Exclusion - Sleep & Wakeup: Counting Semaphore limits the use of resources by a fixed number of processes/threads ¥ ‘Counting Semaphore’ maintains a count between zero and a maximum value ¥‘Counting Semaphore’ limits the usage of the resource to the maximum value of the count supported by it ~The count associated with a ‘Semaphore object’ is decremented by one when a process/thread acquires it and the count is incremented by one when a process/thread releases the ‘Semaphore object’ ~The state of the counting semaphore object is set to ‘signaled’ when the count of the object is greater than zero. ¥ The state of the ‘Semaphore object’ is set to non-signaled when the semaphore is acquired by the maximum number of processes/threads that the semaphore can support (i.e. when the count associated with the ‘Semaphore object’ becomes zero) ¥ The creation and usage of ‘counting semaphore object’ is OS kernel dependent‘Task Synchronization— jutual Exclusion - Sleep & Wakeup: Counting Semaphore Semaphore object unavailable. Sleep til Process A Semaphore object is available Room (Key) Unavailable. +—— Wait tit is avaiable Ts Semaphore object Cony available? - dl, Iskey SA 6 @ nie Shared Memory (Critical Section) Vacating the Room. Return the Key. Notity the availabilty to other users booked the Room’ Leaving crtical section. Release the Semaphore object. Wakeup the Sleeping ProcessesDesigning with RTOS Task Synchronization— Mutual Exclusion - Sleep & Wakeup: Binary Semaphore ¥ implements exclusive access to shared resource by allocating the resource to a Single process at a time and not allowing the other processes to access it when itis being used by a process. ¥ ‘Only one process/thread can own the ‘binary semaphore’ at a time ¥ The state of a ‘binary semaphore’ object is set to signaled when it is not owned by any process/thread, and set to non-signaled when it is owned by any process/thread. ¥The implementation of binary semaphore is OS keel dependent. Under certain OS kemel it is referred as mutex. ¥ The creation and usage of ‘counting semaphore object’ is OS kemel dependentDesigning with RTOS ‘Task Synchronization— Mutual Exclusion - Sleep & Wakeup: Binary Semaphore Tatex otjed unavailable. Steep Ui Mutex object is avalable Roam (Key) Uravadstle Process A [Book & Watt isavalale ts Mutex chject available? =i 1s Room (Key) mam Shared Memory (Critical Section) Leaving critoal sediion, Release the Mutex object ‘Wakeup the Sleeping Processes ‘Vacating the Room. Retum the Key. Notify the availabilty to other users who bookedthe Room’ The Concept of Binary SemaphoreDesigning with RTOS Task Synchronization— Mutual Exclusion - Sleep & Wakeup: Mutual Exclusion Semaphore YA special implementation of the binary semaphore by certain Realtime operating systems like VxWorks and uC/QS-II to prevent priority inversion problems in shared resource access ¥The mutual exclusion semaphore has an option to set a tasks priority to the highest priority of the task which is being pended while attempting to acquire the semaphore which is currently held by a low priority task ¥This ensures that the low priority task which is currently holding the semaphore, when a high priority task is waiting for it, is not pre-empted by a medium priority taskDesigning with RTOS Task Synchronization— Mutual Exclusion - Sleep & Wakeup: Events v v v v v A synchronization technique which uses notification mechanism for synchronization. In concurrent execution we may come across situations which demand the processes to wait for a particular sequence for its operations. A typical example for this is the producer consumer threads, where the consumer thread should wait for the consumer thread to produce the data and producer thread should wait for the consumer thread to consume the data before producing fresh data. A thread/process can wait for an event and another thread/process can set this event for processing by the waiting thread/process The creation and handling of event objects for notification is OS kemel dependent The uC/OS-|I kernel uses ‘events’ for task synchronization.Module-5 RTOS and IDE for Embedded System Design: 1.Operating System basics, Types of operating systems, Task, process and threads (Only POSIX Threads with an example program), Thread preemption, Preemptive Task scheduling techniques, Task Communication, Task synchronization issues — Racing and Deadlock, Concept of Binary and counting semaphores (Mutex example without any program),How to choose an RTOS, 2.Integration and testing of Embedded hardware and firmware, 3.Embedded system Development Environment — Block diagram (excluding Keil), Disassembler/decompiler, simulator, emulator and debugging techniques (Text 2; Ch-10 (Sections 10.1, 10.2, 10.3, 10.5.2 , 10.7, 10.8.1.1, 10.8.1.2, 10.8.2.2,10.10 only), Ch 12, Ch-13 (a block diagram before 13.1, 13.3, 13.4, 13.5, 13.6 only)How to choose an RTOS 10:10 “HOW TO GHOOSEAN RTOS The decision of choosing an RTOS for an embedded design is very crucial. A lot of factors needs to be analysed carefully before making a decision on the selection of an RTOS. These factors can be either functional or non-functional. The following section gives a brief introduction to the important func- tional and non-functional requirements that needs to be analysed in the selection of an RTOS for an embedded design Fundamental requirements: * Processor support ¢ Memory Requirements ¢ Real time capabilities ¢ Kernal and interrupt latency ¢ Inter process communication and task synchronisation ¢ Modularisation support ¢ Support for networking and communication ¢ Development language supportNon-fundamental requirements: * Custom development or off the shelf * Cost. * Development and debugging tools available ¢ Ease of use. ¢ After sales.2.Integration and testing of Embedded hardware and firmware Integration of hardware and firmware deals with the embedded firmware into the target hardware board. L) Out of circuit programming () In System Programming(ISP) QO In Application Programming(IAP) L) Firmware Loading for OS based devices.Out of circuit programming >» Outside the target board DB-9 COM/USB connector RS-232/USB cableThe sequence of operations for embedding the firmware with a programmer is listed below. 1. Connect the programming device to the specified port of PC (USB/COM port/parallel port) 2. Power up the device (Most of the programmers incorporate LED to indicate Device power up. Ensure that the power indication LED is ON) 3. Execute the programming utility on the PC and ensure proper connectivity is established between PC and programmer. In case of error, turn off device power and try connecting it again 4, Unlock the ZIF socket by turning the lock pin “oe : . Insert the device to be programmed into the open si as per the insert diagram shown on the programmer nw 6. Lock the ZIF socket 7. Select the device name from the list of mad devices 8. Load the hex file which is to be embediehip ito the device 9. Program the device by ‘Program’ opti utility program 10. Wait till the completion of prog operation (Till busy LED of programmer is off) IL. Ensure that programming is suc | by checking the status LED on the programmer (Usually ‘Green’ for success and ‘Red? for error condition) or by noticing the feedback from the utility program 12. Unlock the ZIF socket'and take the device out of programmerIn System Programming(ISP) With ISP, programming is done ‘within the system’, meaning the firmware is embedded into the target device without removing it from the target board, It is the most flexible and easy way of firmware em- bedding, The only pre-requisite is thatthe target device must have an ISP support. Apart from the target board, PC, ISP cable and ISP utility, no other additional hardware is required for ISP. Chips supporting 12.1.2.1 In System Programming with SPI Protocol Devices with SPI In System Programming support contains a built-in SPI interface and the on-chip EEPROM or FLASH memory is programmed) through this interface. The primary I/O lines involved in SPI ~ In System Programming are listed be- low. MOST — Master Out Slave In MISO — Master In Slave Out SCK — System Clock RST — Reset of Target Device GND - Ground of Target DeviceIn System Programming(ISP) The power up sequence for In System Programming for Atmel’s AT89S series microcontroller family is listed below. 1. Apply supply voltage between VCC and GND pins of target chip. 2. Set RST pin to “HIGH” state. 3. Ifacrystal is not connected across pins XTAL1 and XTAL2, apply a 3 MHz to 24 MHz clock to XTAL] pin and wait for at least 10 milliseconds. 4. Enable serial programming by sending the Programming Enable serial instruction to pin MOSI/ PLS. The frequency of the shift clock supplied at pin SCK/P1.7 needs to be less than the CPU clock at XTALI divided by 40. 5. The Code or Data array is programmed one byte at a time by supplying the address and data to- gether with the appropriate Write instruction. The selected memory location is first erased before the new data is written. The write cycle is self-timed and typically takes less than 2.5 ms at 5V. 6. Any memory location can be verified by using the Read instruction, which retums the content at the selected address at serial output MISO/P 1.6. 7. After successfully programming the device, set RST pin low or tum off the chip power supply and turn it ON to commence the normal operation.In Application Programming(IAP) InApplication Programming (IAP) is a technique used by the firmware running on the target deyice for modifying a selected portion of the code memory. It is not a technique for first time embedding of user 12.1.4 Use of Factory Programmed Chip It is possible to embed the firmware into the target processor/controller memory at the time of chip fabrication itself. Such chips are known as ‘Factory programmed chips’. Once the firmware design is over and the firmware achieved operational stability, the firmware files can be sent to the chip fabrica- tor to embed it into the code memory. Factory programmed chips are convenient for mass production. applications and it greatly reduces the product development time. It is not recommended to use factory programmed chips for development purpose where the firmware undergoes frequent changes. Factory programmed ICs are bit expensive.12.2 BOARD POWER UP Now the firmware is embedded into the target board using one of the programming techniques described above, ‘What Next?’ The answer is power up the board, You may be expecting the device functioning exactly in a way as you designed, But in real scenario it need not be and ifthe board functions well in the first attempt itself you are very lucky. Sometimes the frst power up may end up ina messy explosion leaving the smell of bumed components behind. It may happen due to various reasons, like Proper care was not taken in applying the power and power applied in reverse polarity (+ve of supply connected to
You might also like
RTOS Based Embedded System Design
PDF
No ratings yet
RTOS Based Embedded System Design
16 pages
Embedded Systems RTOS
PDF
No ratings yet
Embedded Systems RTOS
47 pages
RTOS - Threads & Process
PDF
100% (1)
RTOS - Threads & Process
20 pages
RTOS
PDF
No ratings yet
RTOS
16 pages
Esd Unit-4
PDF
No ratings yet
Esd Unit-4
38 pages
PE-EC 703 Embedded system
PDF
No ratings yet
PE-EC 703 Embedded system
51 pages
Real-Time Operating System (RTOS) Based Embedded System Design
PDF
No ratings yet
Real-Time Operating System (RTOS) Based Embedded System Design
39 pages
ES notes
PDF
No ratings yet
ES notes
44 pages
CHP4 Notes
PDF
No ratings yet
CHP4 Notes
5 pages
Esd 4
PDF
No ratings yet
Esd 4
40 pages
Embedded Esd 5 Unit
PDF
No ratings yet
Embedded Esd 5 Unit
18 pages
ERTOS 2025
PDF
No ratings yet
ERTOS 2025
63 pages
Embedded System
PDF
No ratings yet
Embedded System
61 pages
Rtos PDF
PDF
No ratings yet
Rtos PDF
12 pages
18CS44 MES Module5 NOTES PMR
PDF
No ratings yet
18CS44 MES Module5 NOTES PMR
146 pages
21CS43 MES Module5
PDF
No ratings yet
21CS43 MES Module5
146 pages
Rtos and Ide For Embedded System Design: Roopesh Kumar B N, Assistant Professor, Cse, Ksit
PDF
No ratings yet
Rtos and Ide For Embedded System Design: Roopesh Kumar B N, Assistant Professor, Cse, Ksit
72 pages
ES 2023 L6 Embedded System Interfacing RTOS
PDF
No ratings yet
ES 2023 L6 Embedded System Interfacing RTOS
13 pages
Module 5
PDF
No ratings yet
Module 5
22 pages
RTOS Class Notes
PDF
100% (1)
RTOS Class Notes
15 pages
Mes Mod5
PDF
No ratings yet
Mes Mod5
72 pages
Embedded RTOS -2
PDF
No ratings yet
Embedded RTOS -2
114 pages
Module 5 Class1
PDF
No ratings yet
Module 5 Class1
13 pages
21CS43 Module 5 Microcontroller and Embedded Systems Prof VANARASAN
PDF
No ratings yet
21CS43 Module 5 Microcontroller and Embedded Systems Prof VANARASAN
41 pages
RTOS Based Embedded System Design
PDF
No ratings yet
RTOS Based Embedded System Design
192 pages
Real Time Operating System
PDF
No ratings yet
Real Time Operating System
51 pages
RTOS
PDF
No ratings yet
RTOS
61 pages
Embedded systems unit 4.0
PDF
No ratings yet
Embedded systems unit 4.0
44 pages
Module 05
PDF
No ratings yet
Module 05
51 pages
Unit 5
PDF
100% (1)
Unit 5
70 pages
IES U-4 Final1
PDF
No ratings yet
IES U-4 Final1
25 pages
Need for Rtos (New)
PDF
No ratings yet
Need for Rtos (New)
17 pages
18ES62 Module 5 Notes
PDF
No ratings yet
18ES62 Module 5 Notes
27 pages
WINSEM2023-24 BCSE305L TH VL2023240501060 2024-03-22 Reference-Material-I
PDF
No ratings yet
WINSEM2023-24 BCSE305L TH VL2023240501060 2024-03-22 Reference-Material-I
50 pages
UNIT4 - Embedded System RTOS 1 - JP PDF
PDF
No ratings yet
UNIT4 - Embedded System RTOS 1 - JP PDF
41 pages
Module 05
PDF
No ratings yet
Module 05
50 pages
5
PDF
No ratings yet
5
14 pages
Unii III-BCS 3030 Final
PDF
No ratings yet
Unii III-BCS 3030 Final
66 pages
Arm Rtos
PDF
100% (1)
Arm Rtos
24 pages
unit 2 ertos ppt (1)
PDF
No ratings yet
unit 2 ertos ppt (1)
51 pages
Mes p2 Module5
PDF
No ratings yet
Mes p2 Module5
13 pages
RTOS For Embedded System Design: Mr. Anand H. D
PDF
No ratings yet
RTOS For Embedded System Design: Mr. Anand H. D
128 pages
WINSEM2023-24 BCSE305L TH VL2023240501060 2024-03-20 Reference-Material-I
PDF
No ratings yet
WINSEM2023-24 BCSE305L TH VL2023240501060 2024-03-20 Reference-Material-I
28 pages
Real Time Opearting System
PDF
No ratings yet
Real Time Opearting System
32 pages
Real Time Operating Systems
PDF
No ratings yet
Real Time Operating Systems
23 pages
4_Real-time_Operating_System[1]
PDF
No ratings yet
4_Real-time_Operating_System[1]
36 pages
Embedded Systems Ch-4
PDF
No ratings yet
Embedded Systems Ch-4
35 pages
UNIT-2-RTOS
PDF
No ratings yet
UNIT-2-RTOS
55 pages
Es Module 4
PDF
No ratings yet
Es Module 4
29 pages
Unit Ii
PDF
No ratings yet
Unit Ii
90 pages
Rtos PDF
PDF
No ratings yet
Rtos PDF
33 pages
Embedded System and Design (Theory Notes) Autonomous Course: Department OF Electronics & Communication Engineering
PDF
No ratings yet
Embedded System and Design (Theory Notes) Autonomous Course: Department OF Electronics & Communication Engineering
24 pages
Embedded System: Real-Time Operating Systems
PDF
100% (1)
Embedded System: Real-Time Operating Systems
44 pages
RTOS scheduling policy
PDF
No ratings yet
RTOS scheduling policy
79 pages
Unit2 Classnotes
PDF
No ratings yet
Unit2 Classnotes
77 pages
ERTOS Chapter 4
PDF
No ratings yet
ERTOS Chapter 4
51 pages
Introduction To Real-Time Operating Systems
PDF
No ratings yet
Introduction To Real-Time Operating Systems
36 pages
RTOS1-Introduction To RTOS
PDF
No ratings yet
RTOS1-Introduction To RTOS
16 pages
DBMS Question Bank and Solutions
PDF
No ratings yet
DBMS Question Bank and Solutions
45 pages
Employee Payment Management System
PDF
100% (1)
Employee Payment Management System
22 pages
An Improved Load Balancing Adaptive Qos Buffer Scheduler (I-Labs) For Streaming Services Over Manet
PDF
No ratings yet
An Improved Load Balancing Adaptive Qos Buffer Scheduler (I-Labs) For Streaming Services Over Manet
9 pages
Nodia and Company: Gate Solved Paper Computer Science Engineering 2007
PDF
No ratings yet
Nodia and Company: Gate Solved Paper Computer Science Engineering 2007
18 pages
Computer Peripheral Assembly Attendance: Date
PDF
No ratings yet
Computer Peripheral Assembly Attendance: Date
1 page
Banking Management System
PDF
No ratings yet
Banking Management System
14 pages
Oops Final
PDF
No ratings yet
Oops Final
44 pages
Java Notes (SJBIT) PDF
PDF
No ratings yet
Java Notes (SJBIT) PDF
78 pages
DS Lab
PDF
No ratings yet
DS Lab
94 pages
29 Slide Multi Threading
PDF
No ratings yet
29 Slide Multi Threading
57 pages