You are on page 1of 133

UNIT UNIT IV OSDependentfunctionalities Resourcemanagement RTOSvsGeneralpurposeOS.KernelArchitectureand Functionalities(Taskmanagement,ProcessScheduling,Resourcemanagement(SemaphoresandMutex),Task Synchronization).Interprocesscommunication IPCMethods(Signals,MessageQueues,Mailbox, SemaphoresandPipes) InterruptLatency(Servicebypolling,Servicebyinterrupt,).

Casestudyondevelopmentofatypicalembeddedsystems(DealtHere).SoftwarearchitectureforEmbeddedsystems(Dealtin unit2),CAN,I2C

ShriramKVasudevan shriram.kv@vit.ac.in shriram.kv@vit.ac.in

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

OS SERVICES Stepswhenustart! OS SERVICES Steps when u start!


When you turn on the power to a computer, the first program that runs is usually a set of instructions kept in the computer's readonly memory (ROM). This code examines the system hardware to make sure everything is functioning properly. This poweron self test (POST) checks the CPU, memory, and basic inputoutput systems (BIOS) for errors and stores the result in a special memory location. Once the POST has successfully completed, the software loaded in ROM (sometimes called the BIOS or firmware) ( ) will begin to activate the computer's disk drives. In most modern computers, when the computer activates the hard disk drive, it finds the first piece of the operating , p p g system: the bootstrap loader.
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 2

OS SERVICES Stepswhenustart! OS SERVICES Steps when u start!


Thebootstraploaderisasmallprogramthathasasingle function:Itloadstheoperatingsystemintomemoryand allowsittobeginoperation. Inthemostbasicform,thebootstraploadersetsupthe smalldriverprogramsthatinterfacewithandcontrolthe varioushardwaresubsystemsofthecomputer. Itsetsupthedivisionsofmemorythatholdtheoperating system,userinformationandapplications.Itestablishes thedatastructuresthatwillholdthemyriadsignals,flags andsemaphoresthatareusedtocommunicatewithinand betweenthesubsystemsandapplicationsofthecomputer. b t th b t d li ti f th t Thenitturnscontrolofthecomputerovertotheoperating system.
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 3

OSSERVICES OS SERVICES
Theoperatingsystem'stasks,inthemostgeneralsense,fallinto: 1)ProgramExecution: Loadingtheprogramintomemory,executing&terminatingtheprogram. 2)ErrorDeletion: Identifying&trafficoferrorsdetectedwhileprocessinguserrequesttohardwarelikekeyboarderror,shortageof memoryetc. 3)ResourceAllocation: Managementofavailableresources&allocationofresourcestodifferentusers. 4)Input/outputOperation: Executionofinput/outputrequestinvolvingdevices&files. 5)FileManagementorManipulation: Executingrequestforread,write,renameordeletethedatafileaswellasfilemanagementservices. 6)Accounting : Maintainingaccountsofusesoftheresourcesbydifferentusers&generatingusabletable. a ta g accou ts o uses o t e esou ces by d e e t use s & ge e at g usab e tab e 7)Security : Providingprotectiontoprogram&data&toensuredatasecurity.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

How?
In order to give the appearance of lots of things happening at the same time, the operating system has to switch between different processes thousands of ti th d f times a second. H ' d Here's how it happens:
A process occupies a certain amount of RAM. It also makes use of registers, stacks and queues within the CPU and operatingsystem memory space. When two processes are multitasking, the operating system allots a certain number of CPU execution cycles to one ProcessControlBlock program. Alloftheinformationneededtokeeptrackofaprocesswhenswitchingis All f h i f i d d k k f h i hi i After that number of cycles, the keptinadatapackagecalledaprocesscontrolblock.Theprocesscontrol operating system makes copies of all blocktypicallycontains: the registers, stacks and queues used by AnIDnumberthatidentifiestheprocess the processes, and notes the point at Pointerstothelocationsintheprogramanditsdatawhereprocessinglast which the process paused in its occurred execution. ti Registercontents Statesofvariousflagsandswitches It then loads all the registers, stacks and Pointerstotheupperandlowerboundsofthememoryrequiredforthe queues used by the second process and process allows it a certain number of CPU Alistoffilesopenedbytheprocess cycles. Thepriorityoftheprocess When those are complete, it makes ThestatusofallI/Odevicesneededbytheprocess copies of all the registers, stacks and queues used by the second program, EmbeddedSystems,ShriramKV,SENSE, and loads the first program. 3/18/2010 5
VIT

How?
Eachprocesshasastatusassociated Thisprocessswappinghappens withoutdirectuserinterference,and withit.Manyprocessesconsumeno eachprocessgetsenoughCPUcycles CPUtimeuntiltheygetsomesortof toaccomplishitstaskinareasonable amountoftime. t f ti input. i Troublecanbeginiftheusertriesto Forexample,aprocessmightbe havetoomanyprocessesfunctioning waitingforakeystrokefromtheuser. atthesametime. Theoperatingsystemitselfrequires ti t it lf i Whileitiswaitingforthekeystroke,it Th Whil i i ii f h k k i someCPUcyclestoperformthe usesnoCPUtime.Whileit'swaiting,it savingandswappingofallthe is"suspended".Whenthekeystroke registers,queuesandstacksofthe applicationprocesses. application processes arrives,theOSchangesitsstatus. arrives the OS changes its status Ifenoughprocessesarestarted,and Whenthestatusoftheprocess iftheoperatingsystemhasn'tbeen carefullydesigned,thesystemcan changes,frompendingtoactive,for begintousethevastmajorityofits g j y example,orfromsuspendedto example or from suspended to availableCPUcyclestoswapbetween running,theinformationintheprocess processesratherthanrunprocesses. Whenthishappens,it'scalled controlblockmustbeusedlikethedata thrashing,anditusuallyrequires inanyotherprogramtodirect in any other program to direct somesortofdirectuserintervention some sort of direct user intervention tostopprocessesandbringorder executionofthetaskswitchingportion backtothesystem. EmbeddedSystems,ShriramKV,SENSE, oftheoperatingsystem. 3/18/2010 6
VIT

SymmetricandAsymmetricOS Symmetric and Asymmetric OS


InasystemwithtwoormoreCPUs,the I t ith t CPU th operatingsystemmustdividetheworkload amongtheCPUs,tryingtobalancethe demandsoftherequiredprocesseswiththe q p availablecyclesonthedifferentCPUs. Asymmetricoperatingsystems useoneCPU fortheirownneedsanddivideapplication processesamongtheremainingCPUs. processes among the remaining CPUs Symmetricoperatingsystems divide themselvesamongthevariousCPUs, balancingdemandversusCPUavailability evenwhentheoperatingsystemitselfisall that'srunning.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

OSServices OS Services
ResourceManagement: ResourceManagementisbasically
Transforming Creatingnewresourcefromexistingresource. g g Thecreatedresourcecanbeansubstitutefortheexistingresourcebut wouldbemuchmoreeasiertouseit. Multiplexing Creatingtheillusionofseveralresourcesfromonceresource. Scheduling Decidingwhichprogramshouldgeteachresourceandwhentheyshould getit.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

OSServices
ResourceManagement:
Transformation
Operating systems transform physical resources into virtual resources to avoid Operatingsystemstransformphysicalresourcesintovirtualresourcestoavoid difficultiesassociatedwithPhysicalDevices. Avirtualresourceismuchmoreeasiertouseashardwareinterfaceishidden. Forexample,anoperatingsystemmayprovideavirtualprinterwhichiscapableof printingacharacter.Tousethisvirtualresource,anapplicationonlyneedsto i i h T hi i l li i l d specifythecharactertobeprinted.

Multiplexing
The sharing of physical resources is called multiplexing. Thesharingofphysicalresourcesiscalledmultiplexing. Letstakethesameprinterexample.Assumethatyoursystemhasgotonlyone printer.Ifyouarerunningtwoormoreapplications,operatingsystemshouldmake itappearasifeveryapplicationhasitsownprinter. OS OSmustmakesurethatthecharactersprintedbyonevirtualcomputerisnot t k th t th h t i t db it l t i t mixedwithothers. CanbeAchievedby TimeDivisionMultiplexing.(TimeSharing)

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

VirtualComputer

OSServices

An operating system creates software copies of Anoperatingsystemcreatessoftwarecopiesof processorandmemory. OScreatesmultipleprocesses(simulatedProcessors) outofsingleprocessorandallocatesthemtothe programs.Itisdonebytimesharing. programs. It is done by time sharing. OSCreatesmultipleaddressspace (memoryfora processtorun). ImplementsfilesystemandI/Osystemsothatthe processescaneasilyshareandusethedisks. processes can easily share and use the disks Letsjumpintovirtualcomputerinamuchdetailedway now! ThemostsignificantdifferencebetweentheVirtual Computersfromthephysicalcomputeristhat,there C f h h i l i h h aremanyVirtualComputersbutthereisonlyone physicalcomputer. Theoperatingsystemcreatestheillusionofmany virtualcomputersbytransformingsingle,physical i l b f i i l h i l computer.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

10

OSServices
Asthecomputerishaving2basicparts, ProcessorandPrimaryMemoryLetslook intothese,howtheyarehandledinVirtual computers. computers Inmostcomputers,it'spossibletoadd memorybeyondtheoriginalcapacity.For example,youmightexpandRAMfrom1to2 gigabytes. Thisworksfine,butcanberelatively Thi k fi b t b l ti l expensive.Italsoignoresafundamentalfact ofcomputing mostoftheinformationthat anapplicationstoresinmemoryisnotbeing usedatanygivenmoment. Aprocessorcanonlyaccessmemoryone A processor can only access memory one locationatatime,sothevastmajorityof RAMisunusedatanymoment.Sincedisk spaceischeapcomparedtoRAM,then movinginformationinRAMtoharddiskcan greatlyexpandRAMspaceatnocost.This greatly expand RAM space at no cost. This techniqueiscalledvirtualmemory management.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

11

Definition Definition RTOS


What is an OS ??
An operating system is resource manager which helps the end user to use the system most effectively by having effective utilization of existing resources. E.g., OS manages Memory, Multitasking etc., g g, g y, g , Common OS in usage MS Windows Vista, XP etc.,

Wh t is RTOS ?? What i
Lets keep the first few lines of this slide in mind and shall now jump into sea of RTOS.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

12

Contd.,
A RTOS (Real-Time Operating System) ( p g y ) Is an Operating Systems with the necessary features to support a Real-Time System

What is a Real-Time System? A system where correctness depends not only on the correctness of the logical result of the computation, but a also on the result delivery time u d y A system that responds in a timely, predictable way to unpredictable external stimuli arrivals
EmbeddedSystems,ShriramKV,SENSE, VIT

3/18/2010

13

Comparison of RTOS and Desktop OS


Desktop OS
Example Memory Windows XP,2k etc., Very large memory requirements 300 to 400 MB is required for installation of OS

RTOS
Vx Works, Nucleus, Win CE etc., Very less memory requirement. RTOS typically include the just the services needed for the embedded systems. Most RTOS allow y the user to configure it before user links it to an application thereby enabling the user to leave the functions that he thinks are not required. Even 8 to 16 MB is considered to be q luxurious for Embedded systems. RTOS may not provide many features as Desktop OS, But they will at least provide Task C i M T k Creation / Management Scheduling Inter task communication Memory Management Timers etc.,
14

Support

Desktop OS normally has huge set of libraries that can provide the user many fancy and advanced features. E.g., plug and play feature

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

Comparison of RTOS and Desktop OS contd., d


Desktop OS
Control Desktop OS takes control of the machine as soon as it is turned on. It protects themselves carefully from application

RTOS
First the application will be started and then it starts the RTOS. RTOS do not protect themselves as carefully from your application as desktop does. For example Desktop OS will check if the pointer passed to a function is valid. But RTOS may skip it as they are more performance oriented. If an application is passing a bad pointer into the RTOS, probably the application may crash and will result in restarting the system Designers should take extra care about the response time as they are mostly employed in real time systems.

Protection

Response Time

Not as crucial as RTOS.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

15

Real Time Systems - Types


Hard Real-Time Missing a deadline has catastrophic (terrible) results for the system Firm Real-Time Missing a deadline causes an unacceptable quality reduction Soft Real-Time Reduction in system quality is acceptable Deadlines may be missed and can be recovered from Non Real-Time No deadlines have to be met
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 16

Kernel Architecture

Kernel has the following objects: Task Task Scheduler Task S T k Synchronization h i ti Semaphores Mutexes Timers Ti Mail box Message queue

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

17

TASK and TASK STATES


The basic building block of an RTOS is task. g Tasks are very simple to write and at most of the times tasks are simple routines. Task is an atomic unit of execution that can be scheduled by an RTOS to use the system resources. A task is considered to be atomic because, any other entity because smaller than task cannot compete for system resources. A task first needs to be created. A task is characterized by

3/18/2010

A Task Name. Priority Stack Size OS specific options. ifi ti


EmbeddedSystems,ShriramKV,SENSE, VIT 18

TASK and TASK STATES


At any point of time, a task can be in any one of the following states. Dormant Ready y Running Blocked Dormant: When the task is created, but not added to RTOS for scheduling. Running: The task is currently using the micro processor processor. Unless yours is a multiprocessor system, there can be only one microprocessor, and the task which is running will be using the microprocessor.
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 19

TASK and TASK STATES


Ready: The task is ready to run, But cannot do so because, a highest priority task is being executed. Blocked: This means that the task hasnt got anything to do right now, even if the micro now processor becomes available. Tasks get into this state because they are waiting for some external events. F example a task that h dl d For l k h handles data f from network will have nothing to do when there is no data.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

20

Task Transition
1.When a task is created it will be in Dormant state. 2. When it is added to the RTOS for scheduling it will come to ready state normally. If it is high priority task it will go to Running state. i.e., it could begin b i executing straight away. i i h 3. When a task is running and if another high priority task becomes ready, the task that is running currently will b k h i i l ill be pre empted and highest priority task will be scheduled for execution. 4. During h 4 D i the course of execution of a f i f task, it may require a resource or input. In this case if the input/resource is not readily available, the task gets blocked.
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 21

Other Transitions
1. ReadytoRunning: Foraparticulartask, ifallthehighprioritytasksareblocked, thenthetaskisscheduledforexecution. Itthenchangesthestatefromreadyto It then changes the state from ready to running. BlockedtoReady:Whenahigherpriority taskreleasesasourcerequiredforalow prioritytask,thenthelowerprioritytask cannotbeginitsexecution,thehigh prioritytaskwillcontinueexecution.But thestateoflowprioritytaskwillbe the state of low priority task will be changedfromblockedtoready. BlockedtoRunning:Sometimesahigh prioritytaskcanbeblocked.(waitingfor aresource/input).Whentheresource isavailablethetaskbeginsexecution,pre emptingthelowerprioritytaskthatwas executing. executing
22

2.

3.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

Task Scheduling
A part of RTOS called Scheduler keeps track of state of each task and decides which one should go to the running state. Unlike UNIX or Windows the scheduler in RTOS are 100% simpleminded about which task should get the processor. They simply look at the priorities you assign to the tasks, and among the tasks that are not in the blocked state, the one with highest priority runs, and rest of them will wait in Ready State. If a high priority task hogs the micro processor for a long time while lower priority tasks are waiting in ready state, the low priority task has to wait.. Scheduler assumes that you knew what you were doing when you set the priorities.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

23

Task Scheduling
A task will only block because it decides for itself that it has run out of things to do. Other tasks in the system or scheduler cannot decide that it needs to wait for something. So a task has to be in running just b f i before i i bl k d it is blocked. When the task is blocked, it never gets the micro processor. Therefore an i Th f interrupt routine or i some other task in the system must be able to signal whatever the task was waiting for has happened, else the task will be blocked for ever.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

24

Task Scheduling Contd Contd.,


Shuffling of tasks between the ready and running states is entirely the work of the scheduler. The scheduler has control over the running task. If a task is moved from blocked to the ready state and has a higher priority that the task that is currently running, the scheduler y g will move the high priority task to running state immediately.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

25

Task Scheduling Contd Contd.,

How does the scheduler know when a task has become blocked or unblocked??
The RTOS provides collection of functions that tasks can call to tell the scheduler what event they want to wait for and to signal that events have happened. h d

What will happen if all the tasks are blocked??


If all the tasks are blocked, then the scheduler will spin in some tight loop somewhere i id the RTOS waiting f something to h h inside h RTOS, i i for hi happen. If nothing hi happens ever.. Then it is your mistake

What will happen if there are two tasks with same priority??
It depends on the RTOS that you select.. d d th th t l t
Some RTOS will time slice between two such tasks. Some will run one of them and will block other until first task is completed.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

26

Task Scheduling Contd., Pre-Emptive Pre Emptive and Non-Pre-Emptive Non Pre Emptive RTOS
A Pre-Emptive RTOS will stop the lower priority task as soon as the higher priority task unblocks. A Non Pre-Emptive RTOS will only take the micro processor away from the lower-priority task when that task blocks.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

27

Task Scheduling Contd., - S h d li Policies A O Scheduling P li i An Overview. i


Strictly Pre-Emptive Scheduling
In this Scheme at any instance of time, only the highest priority task that is ready to run executes. The task other than currently executing task should have lower priority. This method makes sure that tasks that are important are handled first and less important task at later point of time.

Merits
Once priorities are set properly, we can be assured that only important things are handled first

De Merits Merits
X It is possible that one or h more of the lower priority p y tasks do not get to execute at all all.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

28

Strictly Pre-Emptive Scheduling Pre Emptive


Realtimekernelsgenerallysupport256 prioritylevels,inwhich0isthehighestand 255thelowest. Somekernelsappointtheprioritiesin reverseorder,where255isthehighestand0 thelowest. Regardless,theconceptsarebasicallythe same.Withapreemptiveprioritybased With ti i it b d scheduler,eachtaskhasapriority,andthe highestprioritytaskrunsfirst. Ifataskwithapriorityhigherthanthe currenttaskbecomesreadytorun,the y , kernelimmediatelysavesthecurrenttasks contextinitsTCBandswitchestothehigher prioritytask. Asshownheretask1ispreemptedby higherprioritytask2,whichisthen higher priority task 2 which is then preemptedbytask3.Whentask3 completes,task2resumes;likewise,when task2completes,task1resumes.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

29

Task Scheduling Contd., - S h d li Policies A O Scheduling P li i An Overview. i


Time Slicing l
In this Scheme the cpu time is shared between tasks. Each task gets a fraction of CPU time. There is no idea of Priority followed here. This method is called as round

Merits
No Need for Complex y analysis of the system. Easy to implement. i l

De Merits
X we cant prioritize .. This method is very rigid.

robin scheduling
This can be used in conjunction with Pre Emptive scheduling, When two tasks have same priority then time slicing can be used.
3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

30

RoundRobinScheduling/TimeSlicing Scheduling h d l
Roundrobinschedulingprovides eachtaskanequalshareoftheCPU executiontime. Pureroundrobinschedulingcannot satisfy real time system requirements satisfyrealtimesystemrequirements becauseinrealtimesystems,tasks performworkofvaryingdegreesof importance. Instead,preemptive,prioritybased schedulingcanbeaugmentedwith roundrobinschedulingwhichuses timeslicingtoachieveequal time slicing to achieve equal allocationoftheCPUfortasksofthe samepriority

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

31

Task Scheduling Contd., - S h d li Policies A O Scheduling P li i An Overview. i


Fairness Scheduling
Here in this scheme every task is given an opportunity to execute. t Unlike pre emptive scheduling, where a lower priority task may not get chance for execution, here every task will get chance to execute. i.e., very fair.

Merits

De Merits

every task is X Nony given an deterministic opportunity.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

32

Task Scheduling an example ( (underground tank monitoring g g system) Here we can show how a
difficult system is built with ease with the help of RTOS RTOS.. Here vLevelsTask task takes up lot of computing time figuring out how much gasoline is in the tank. t k But as soon as the user pushes a button, vButtonTask the task unblocks. RTOS will now stop the lower priority task h k vLevelsTask and will move it to ready state, which will enable vButtonTask execution and user will get a response. ll When vButtonTask has finished responding, RTOS will give chance to vLevelsTask for execution.
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 33

Performancemetricsinscheduling models. d l
AnRTOSshouldquicklyandpredictablyrespondtotheevent. Itshouldhaveminimuminterruptlatencyandmaximumcontextswitching speed. Thethreemajorperformancemetricsare
Ratioofsumofinterruptlatencieswithrespecttosumofexecutiontimes. CPUload Worstcaseexecutiontimewithrespecttomeanexecutiontime. Letthisbeanassignmentforyouguys!

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

34

Process detailedlook
Aprogramissetofmachineinstructionsanddatastoredinanexecutable image(a.out)onthegivenpath. image (a. out) on the given path. Aprocessisprograminexecutionwhichisusedtoperformtasksinasystem andstateiscontrolledbyOS. I.e.,itcanberunning,blockedetc., , g, , Eachprocesshasauniqueaddressspaceandoneprocesscannotaccess addressspaceofanotherprocessuntilitisshared. Communicationbetweenprocessesaredonebyinterprocesscommunication mechanisms. Aprocesswillneedmanyresourcelikememoryspace,CPUusage,filesetc., duringitslifetime. Kernelshouldkeeptrackoftheprocessesandusageofthesystemresources. Kernel(OS)shoulddistributeresourcesamongtheprocessesfairly

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

35

Process detailedlook
MostimportantresourceisCPUandinmultiprocessingenvironment,toattainanideal p p g , performanceofasystem,theCPUutilizationshouldbemaximum. LetstakeLINUXasanexampleandletstalk! InLinuxthetaskscanbeinfollowingstates: Task_Running TheprocessmayberunninginUSERmodeorKERNELmode(less/highprivileged modes)EveniftheprocessisinRUNqueue,waitingtoRUN,itwillbeinthisstate Task_Interruptable Theprocessisinsleepstate.Theprocessiswaitingforsomeeventtooccur.Thisprocess canbewokenupprematurelybyasignalsincetheprocessallowssignaltointerrupt. Task_Uninterruptable. Sameasbeforebutwillnotallowinterruption.Thesleepmodewillbeoveronlyifafter thewaitingeventhasoccurred. Task_Stopped Whenaprocessreceivesanyofthefollowingsignalsitwillenterthisstate,SIGSTOP, SIGTTINetc., Task_Zombie I ill b Itwillbeazombie,Completesitsexecutionandwaitforparenttogiveexitstatus. bi C l i i d i f i i (Thiswouldthrowsomelightonwhatallcouldbethestatesthataprocesscanresidein)
EmbeddedSystems,ShriramKV,SENSE, VIT

3/18/2010

36

Process DetailedLook
Thekernelkeepstrackofaprocessscreationtimeaswell astheCPUtimethatitconsumesduringthelifetime. E h l k ti k th k Eachclocktick,thekernelupdatestheamountoftime l d t th t f ti thatthecurrentprocesshasspentinsystem.
AclocktickunitiscalledJiffy!

InadditiontothisaccountingtimersLinuxsupports additionaltimersalso!Threesortoftimersareusedin Linux. Linux


Real Thistimerticksinrealtime,andwhenthetimerhasexpired,the processissentaSIGALRMsignal. Virtual This timer ticks when the process is running and when it expires Virtual Thistimertickswhentheprocessisrunningandwhenitexpires sendaSIGVTALRMsignal. Profile Thistimerticksbothwhentheprocessisrunningandwhenthe systemisexecutingonbehalfoftheprocessitself.Oncedonewillsend y g p SIGPROFsignal.
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 37

Process Process Scheduling


Policy FIFO,ROUNDROBIN,SHORTESTJOBFIRST,FILO etc., , Priority Higherpriorityjobwillbeallowedtorunfirst. Schedulingcanbeeitherpreemptiveornonpreemptive
PriorityRange 0to139forLinux.

AfteralltheseIcoulddefineprocessasacomputationalunit thatprocessesonaCPUandwhosestatechangesunderthe controlofkernelofanOS.Ithasastate,whichataninstance , definesbytheprocessstatus(Running/Blocked/Finishedetc.,)

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

38

ZombieandOrphan Zombie and Orphan


Whenachildexitsitshouldgiveexitstatustoparent. Iftheparentprocessisbusyorsuspendedthenthechild willnotbeabletoterminate. ill b bl i SuchstateiscalledZOMBIE. If the parent process exits before the child exits then the Iftheparentprocessexitsbeforethechildexits,thenthe childwillbecomeorphan.!!

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

39

ProcessControlBlock
PCBisadatastructurehavingtheinformationtheinformation usingwhichtheOScontrolstheprocessstates. g p PCBgetsstoredinprotectedmemoryaddressesatkernel. ThePCBwillhavefollowinginformation
Processid(pid) Processpriority ParentProcess ChildProcess AddresstothenextprocessPCB,whichwillrunnext. AllocatedprogrammemoryblockdetailsinPhysicalMemoryandVirtual Allocated program memory block details in Physical Memory and Virtual Memory Allocatedheapmemorydetails. Allocatedprocessstackaddressesforthefunctionscalledduringrunning ll d k dd f h f i ll d d i i oftheprocess.
EmbeddedSystems,ShriramKV,SENSE, VIT 40

3/18/2010

ProcessControlBlock
ThePCBwillhavefollowing information
AllocatedaddressesoftheCPU registersavememory(Context g y( Switch) Processstatesignalmask(when maskissetto0,theprocessis allowedtorun,andwhenmaskisset to1,theprocessissettorun) Signals Securityandaccesspermissions FileDescriptors
Eachprocesshasitsownfile descriptortable. descriptor table Validdescriptorrangesfrom0and maximumnumberisconfigurable. StandardInput 0,StandardOutput 1andStandardError2willbe presentinFDtable.

0 stdin 1 td t 1 stdout 2 stderr 3 file1 4 file2 FileDescriptorTable

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

41

ProcessControlBlock

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

42

Problemsofsharingdatabymultiple tasksandroutines tasks and routines


Theshareddataproblemcanbeexplainedasfollows.
Assume that there are several tasks/functions/ISR that share a Assumethatthereareseveraltasks/functions/ISRthatsharea variable. Letsassumethatataninstancethevalueofthatvariableoperates andduringitsoperations,onlyapartoftheoperationiscompleted andpartremainsincomplete. Atthatmomentletsassumethatthereisaninterrupt.Nowassume thatthereisanotherfunction.Italsosharesthesamevariable,the valueofthevariablemaydifferfromtheoneexpected.
Supposeavariableisof128bitsandtheprocessorisof32bits. Theoperationsonthevariablewillbeusingfour32bitALUoperationsinorderto usethe32bitALUofthisprocessor. p Atomicoperationisone,whichcannotbesubdividedintothesuboperationsor noneofthesuboperationscanbeleftincompleteandnootheroperationcanstart beforeallthesuboperationsarecomplete. Assume here the 128bit operation is non atomic This means that the operation Assumeherethe128 bitoperationisnonatomic.Thismeansthattheoperation canbeinterruptedbeforeallthefouroperationsarecompleted.
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 43

Problemsofsharingdatabymultiple tasksandroutines tasks and routines


Letsassumethataninterruptcanoccurattheendofeach32bit instruction,notnecessarilyattheendof128bitoperation. Therefore,thecalledISRoranotherfunctioncanusethe incompletelyoperatedvariableorcanchangethatvariablewhen itshareswithanotherfunction. Onreturn,newvaluesofthatvariablewillbefoundandthe incompleteoperationswillbeperformedonthatnew128bit variableintheplaceofoldone.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

44

Problemsofsharingdatabymultipletasksand routines Solution


Thefollowingarethesteps,thatifusedtogether,willalmosteliminate likelybugintheprogrambecauseofshareddataprogram
Usemodifiervolatile: Whenweusethekeywordvolatileforavariable,itwarnsthe compilerthatitmaymodify,Sothiswillbeanindicationthatthevariableisashared compiler that it may modify So this will be an indication that the variable is a shared variablewhichwouldchangeinduecourseoftime.Thiscouldhelpustoavoidbugsin theprogram. Putasharedvariableinacircularqueue: Afunctionthatrequiresvaluethevalueof thisvariablealwaystakesitfromqueuefrontandanotherfunctionwhichinsertsthe valueofthisvariablewillinsertattheback.Nowaproblemcanoccurincasethereare alargenumberoffunctions,thequeuesizewouldbecomparativelylarger! Disabletheinterruptsbeforeacriticalsectionstartsexecutingandenablethe interruptsoncompletion.Itisapowerfuloption.Aninterrupt,evenifofhigher prioritythanthepresentcriticalfunction,getsdisabled.Advantageisthatthe semaphoreishavinggreatercomputationaloverheadthandisablingtheinterrupt. Thisdifficultywiththisoptionisitincreasestheinterruptlatencyperiodforallthe tasks.Adeadlinemayalsobemissedforaninterruptservicebythattask. Analternativetodisablinginterruptistousesemaphorefortheshareddataproblem.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

45

Task Synchronization
In all trivial systems tasks need to interact with each others We can explain this with a simple road example.
When the tasks are independent they do not share any

resources between them, of course CPU is an exception. p This can be compared with two roads that run parallel and so they do not meet.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

46

Task Synchronization
Vehicles V hi l can move i this sort of in hi f road without collision. But the case becomes different when we h h have i intersecting roads. i d In this case we need to use a separate explicit mechanism like traffic signal to make sure that vehicles do not get into mess. The situation is different because there is a shared region between the roads. So traffic on both sides of the road needs explicit synchronization. Signal is required only at the point of intersection..

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

47

Task Synchronization
Task synchronization can be achieved in two ways y y
Task Synchronization using Mutexes. Task Synchronization using Semaphores.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

48

Semaphores
Asemaphoreislikeakeythatallowsatask tocarryoutsomeoperationortoaccessa to carry out some operation or to access a resource. Ifthetaskcanacquirethesemaphore,itcan carryouttheintendedoperationoraccess theresource. Asinglesemaphorecanbeacquiredafinite A single semaphore can be acquired a finite numberoftimes.Inthissense,acquiringa semaphoreislikeacquiringtheduplicateofa keyfromanapartmentmanagerwhenthe apartmentmanagerrunsoutofduplicates, themanagercangiveoutnomorekeys. g g y Likewise,whenasemaphoreslimitis reached,itcannolongerbeacquireduntil someonegivesakeybackorreleasesthe semaphore. Thekerneltracksthenumberoftimesa semaphorehasbeenacquiredorreleasedby maintainingatokencount,whichis initializedtoavaluewhenthesemaphoreis created. q p , Asataskacquiresthesemaphore,thetoken countisdecremented;asataskreleasesthe semaphore,thecountisincremented.
EmbeddedSystems,ShriramKV,SENSE, VIT 49

3/18/2010

Semaphores
Ifthetokencountreaches0,thesemaphore hasnotokensleft.Arequestingtask, has no tokens left. A requesting task, therefore,cannotacquirethesemaphore, andthetaskblocksifitchoosestowaitfor thesemaphoretobecomeavailable. Thetaskwaitinglisttracksalltasksblocked whilewaitingonanunavailablesemaphore. g p Theseblockedtasksarekeptinthetask waitinglistineitherfirstin/firstout(FIFO) orderorhighestpriorityfirstorder. Whenanunavailablesemaphorebecomes available,thekernelallowsthefirsttaskin thetaskwaitinglisttoacquireit. Thekernelmovesthisunblockedtaskeither totherunningstate,ifitisthehighest prioritytask,ortothereadystate,untilit becomesthehighestprioritytaskandisable torun.Notethattheexactimplementation ofataskwaitinglistcanvaryfromonekernel toanother. Akernelcansupportmanydifferenttypesof semaphores,includingbinary,counting,and mutualexclusion(Mutex)semaphores. l l i (M ) h
EmbeddedSystems,ShriramKV,SENSE, VIT 50

3/18/2010

Semaphores Resource Synchronization


When multiple tasks are running , two or more h l l k tasks will be in need of a resource. C id two tasks, b h of them want to use Consider k both f h display. Task 1 wants to display temperature is 40deg 40deg and Task2 wants to display humidity is humidity 50%. There should be proper synchronization otherwise it would be displayed as p y humitempdityerature is is 40deg 50%

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

51

Semaphores Task Synchronization


Consider that a task reads data from ADC and writes it to memory. Another task reads y that data and sends it to DAC. The read operation takes place only after the write operation and it should be done very fast with a very minimal delay. In this case there should be a mechanism for task1 to inform task2 that task1 has completed its job. So there needs synchronization. This is called task synchronization. h i ti Semaphore is a kernel object used to perform both Task and Resource Synchronization.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

52

Semaphores HOW IT WORKS


1. Consider 1 C id 2 tasks wants to access k the display. 2. Display is a shared resource 3. To control access, Semaphore is created. created 4. Semaphore is like a key for entering the house. 5. If task1 needs access, it will acquire semaphore, semaphore uses display and after usage it will release it. 6. If both the tasks need access, kernel can give the access to only one of the tasks. i.e., semaphore will b given t only one t k ill be i to l task. This allocation can be based on priority or first come first serve basis. 7. if many tasks need access, then they will be kept in queue. they will wait for their turn and they can gain access.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

53

BinarySemaphore Binary Semaphore


Abinarysemaphorecanhave avalueofeither0or1. l f ith 0 1 Whenabinarysemaphores valueis0,thesemaphoreis consideredunavailable(or considered unavailable (or empty); whenthevalueis1,thebinary semaphoreisconsidered available(orfull). Notethatwhenabinary semaphoreisfirstcreated,it canbeinitializedtoeither can be initialized to either availableorunavailable(1or 0,respectively).

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

54

Semaphores HOW IT WORKS


Consider another classical situation where pool of 10 memory buffers are available. il bl The buffers needs to be shared by all the n tasks as shown in figure. Any task can write to a buffer. Using Binary semaphore it will not be feasible. So counting semaphore is used. Initial value of semaphore is set as 10. Whenever a task acquires a h k semaphore the value will be decremented by 1.When the task releases it the value will be incremented by 1 When the value 1. becomes 0 it means the resource is no longer available. It can be taken as having multiple keys to enter a house.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

55

Semaphores HOW IT WORKS


Now a days we use the following terms: y g Semaphore_acquire (buffer, 3); Semaphore_release (buffer, 3); Earlier semaphore_p, semaphore_v were used. Where p proberen means try to acquire ( Dutch) h b (in h) Where v vrijgeven means release (Dutch)

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

56

Mutexes Task Synchronization


Mutex is mutual exclusion. We can conclude that problems occur when a resource is shared among tasks.. Also synchronization can be done only during resource acquisition and release. l d i i iti d l Consider a simple case, two tasks are there. Task1 and Task2. Task1 wants to print 1 2 3 and Task2 wants to print p p A B C . If the scheduling is based on round robin method, the output could be 1A2B3C which is messy.. S we need to use MUTEX a very simple way of avoiding So d i l f idi problems.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

57

Mutexes Task Synchronization


At any point of time if both the tasks want to use the printer, task whichever makes first attempt will get it!

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

58

Mutexes Task Synchronization


Lets assume that task B has high priority and it gets scheduled after print(1). Now task B will try to y acquire printer_mutex. But it would fail as already task A has it. So B will be blocked. Once A releases mutex B will acquire it and p proceeds. Once B is done with its work it will release the mutex and A can continue
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 59

Mutexes Task Synchronization


How to achieve Mutexes Some thought Mutexes..
Disable Scheduler: You know task switching is done by Scheduler. If at all the scheduler is Scheduler disabled.. The current task can complete its work freely with the resource available. This is an excellent Idea.. But Dangerous toooooo if something goes wrong the system may even crash. h

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

60

Mutexes Task Synchronization


How to achieve Mutexes Some thought Mutexes..
Disabling Interrupts A task in Waiting state will move from ready to run with the help of an ISR. Disabling Interrupts will enable running to use the resource freely. Decent idea it is. Mutex is a Special Binary Semaphore. It has only two states, Either locked or unlocked..

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

61

Interprocesscommunications
Introduction:
Inamultiprocessingenvironment,oftenmanyprocessesarein needtocommunicatewitheachotherandsharesomeresources. dt i t ith h th d h IPCmechanismshavemanydistinctpurposes,forexample
DataTransfer SharingData EventNotification ResourceSharing Resource Sharing Processcontrol.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

62

Interprocesscommunications p
Therearelotmanymechanismsusedforinterprocess communication! communication! Theyare
Signals Semaphores(Discussedearlier) Queues Mailboxes Pipes

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

63

Interprocesscommunications Signals
Signalsarethefundamentalmethodofinterprocess communicationandareusedineverythingfromnetwork communication and are used in everything from network serverstomediaplayers. Asignalisgeneratedwhen
Aneventoccurs(timerexpires,alarmetc.,) Auserquotaisexceeded(filesizeexceedinginstance) AnI/Odeviceisready Encounteringanillegalinstruction. AterminalinterruptlikeCTRL+CandCTRL+Z Someotherprocesssendsasignal Kill9PID EverysignalstartswithnameSIGandisdefinedasapositive integernumber.(SIGKILL 9,SIGINT 2) $killl inshellpromptwillgivethelistofavailablesignalsinUNIX orLINUX.
EmbeddedSystems,ShriramKV,SENSE, VIT 64

3/18/2010

Interprocesscommunications Signals
Whenaprocessreceivesasignalonlythreethingscouldhappen
First,theprocesscouldignorethesignal. Second,theprocesscouldcatchthesignalandexecuteaspecialfunction calledsignalhandler(similartoISR.Thehandlerrunsinasimilarwayto thehighestpriorityISR) the highest priority ISR) Thirditcouldexecutethedefaultactionforthesignal.Forexamplethe defaultactionforsignal15,SIGTERMistoterminatetheprocess. Some signals cannot be ignored SIGKILL and SIGSTOP are the two signals Somesignalscannotbeignored,SIGKILLandSIGSTOParethetwosignals whichcannotbecaughtorignored.
$kill9PID ThiswillkillprocesswithpidPID.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

65

Interprocesscommunications Signals
ASignalhandlerisnotdirectlycalledbyacode.Whenthe signalissentfromaprocess,OSinterruptstheprocess signal is sent from a process OS interrupts the process executionandcallsthefunctionforsignalhandling.Onreturn fromthesignalhandler,theprocesscontinuesasbefore. A signal is unlike semaphore The semaphore has to use a Asignalisunlikesemaphore.Thesemaphorehastousea token,tolockaresourcetoaparticulartaskforagiven sectionofcodes. Asignalisjustaninterruptthatissharedandusedby l h h d d db anotherinterruptservicingprocess. p Anotherimportantareatobeknownistoknowabout Exceptions. Asignalreportsanerrorduringrunningofataskandletsthe schedulerinitiateanerrorhandlingprocessorfunctionor scheduler initiate an error handling process or function or task.
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 66

It is something very similar to our postal mail box. Someone posts a message in your mail box and you can read it. Likewise a task can h k k have mailbox, in which other lb h h h tasks can post a mail.

Interprocesscommunications Mailbox lb

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

67

Interprocesscommunications Message Q Queue


It can be considered as array of Mail Boxes. y Message queues provide an asynchronous communications protocol, meaning that the sender and receiver of the message do t d not need to interact with the message queue at the same dt i t t ith th t th time. Typical applications include: yp pp Taking input from keyboard To display output Reading voltages from transducers or sensors

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

68

Interprocesscommunications Message Q Queue


In this mechanism a task can message in the queue and other tasks can take the message. Based on priority the highest priority can take the message first.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

69

IPC MessageQueues IPC Message Queues


A message queue is a buffer-like object through ag qu u bu bj ug which tasks and ISRs send and receive messages to communicate and synchronize with data. A message queue is like a pipeline. It temporarily holds messages from a sender until the intended receiver is ready to read them. h d d d d h This temporary buffering decouples a sending and receiving task; that i it frees the tasks from i i k h is, i f h k f having to send and receive messages simultaneously. simultaneously
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 70

IPC MessageQueues IPC Message Queues


Themessagequeueitselfconsistsofanumberof e essage queue tse co s sts o a u be o elements,eachofwhichcanholdasingle message. Theelementsholdingthefirstandlastmessages arecalledtheheadandtailrespectively. Someelementsofthequeuemaybeempty(not containingamessage).Thetotalnumberof elements(emptyornot)inthequeueisthetotal elements (empty or not) in the queue is the total lengthofthequeue.Thedeveloperspecifiedthe q queuelengthwhenthequeuewascreated. g q
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 71

IPCMessagequeues IPC Message queues

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

72

MessageQueueisFSMformat Message Queue is FSM format


Messagequeuesfollowthe logicofasimpleFSM,When l f l h amessagequeueisfirst created,theFSMisinthe emptystate. empty state Ifataskattemptstoreceive messagesfromthis messagequeuewhilethe message queue while the queueisempty,thetask blocksand,ifitchoosesto, isheldonthemessage g queue'staskwaitinglist,in eitheraFIFOorpriority basedorder.
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 73

QueueOperations Queue Operations


Creating and Deleting Message Queues CreatingandDeletingMessageQueues SendingandReceivingMessages Ob i i ObtainingMessageQueueInformation Q f i

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

74

Interprocesscommunications Message Queue


Eachqueueneedsinitialization. EachqueueneedsanId Each queue needs an Id Sizeofthekeyisuserdefined. Whenthequeuebecomesfull,thereshouldbeerror q handlingmechanisms.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

75

Interprocesscommunications Message Queue


LetsnowseehowQueuesarecreatedwith ets o see o Queues a e c eated t UNIXSystemProgramming!Iamgoanna presentthepseudocodeforthesame!
key=ftok(.,a); msqid=msgget(key,IPC_CREAT|0666); msgsnd (msqid, &struct, sizeof(struct), 0); msgsnd(msqid,&struct,sizeof(struct),0); msgrcv(msqid,&struct,sizeof(struct),mtype,0); msgctl(msqid,IPC_RMID,NULL); $ipcrmmsgmsqid
LetsnowCwhateachlinedoes!!!

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

76

InterprocesscommunicationsMessage Queue
key=ftok(.,a); IfwewishtocommunicatebetweendifferentprocessesusinganIPCresource, thefirststepiftocreateanuniqueidentifier.i.e.,akey! Ftok Filetokey! 2. msqid=msgget(key,IPC_CREAT|0666); Msqidisadatastructuredescribingoperationpermission,timeoflastmsgsnd command,timeoflastmsgrcv,currentnumberofbytesinqueueetc., d i fl b fb i Msgget firstargumentiskey.Tocreateanewmessagequeue,IPC_CREATis ORedwithaccesspermissions. 3.msgsnd(msqid,&struct,sizeof(struct),0); msgsnd(msqid,&struct,sizeof(struct),0); Th fi t ThefirstargumentisthemessageQIDandsecondargumentisaddressofthe t i th QID d d t i dd f th structure. Sob4callingthemsgsndfunction,weneedtofillthestructure.. Thirdargumentissizeofthemessage!(i.e.,sizeofthestructure) Finally the flag value i e 0 or IPC NOWAIT Finallytheflagvalue,i.e.,0orIPC_NOWAIT
Whenthereisnomorespaceavailableformessages,theprocesscanspecifythatitcanwait tillmorespaceisavailableforitsmessageorreturnswithanerrorwithoutwaiting!

1.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

77

InterprocesscommunicationsMessage Queue

4. msgrcv(msqid,&struct,sizeof(struct),mtype,0); msgrcv(msqid,&struct,sizeof(struct),mtype,0); Where 0 retrieveinFIFOorder +ve Retrievetheexactvalueofthemessagetype. ve firstmessage Onsuccessitwillreturnthenumberofbytescopiedintomessagetext. 5. msgctl(msqid,IPC_RMID,NULL); Ifwewanttoknowthestatusofthemessagequeueorifweliketo modifyanyparameters,wecanuse msgctl(msqid,IPC_RMID,NULL); msgctl (msqid IPC RMID NULL); Where IPC_STAT Willletyouknowthestatus IPC_SET Willhelpyoutosetormodify _ py y IPC_RMID willhelpyoutoremoveamessagequeue. 6.$ipcrm qmsqid 6.$ipcrm Fordeletingthequeuecreatedissue$ipcrm qmsgid
EmbeddedSystems,ShriramKV,SENSE, VIT

3/18/2010

78

QueueUsage Queue Usage


The following are typical ways to use message Thefollowingaretypicalwaystousemessage queueswithinanapplication:
non interlocked one way data communication noninterlocked,onewaydatacommunication, interlocked,onewaydatacommunication, interlocked two way data communication and interlocked,twowaydatacommunication,and broadcastcommunication.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

79

QueueUsage noninterlocked,onewaydatacommunication i t l k d d t i ti
Oneofthesimplestscenariosfor messagebasedcommunications message based communications requiresasendingtask(also calledthemessagesource),a messagequeue,andareceiving task(alsocalledamessagesink) task (also called a message sink) Thistypeofcommunicationis alsocallednoninterlocked(or looselycoupled),onewaydata communication. TheactivitiesoftSourceTaskand tSinkTaskarenotsynchronized. py TSourceTasksimplysendsa message;itdoesnotrequire acknowledgementfrom tSinkTask.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

80

QueueUsage interlocked,onewaydatacommunication i t l k d d t i ti
Insomedesigns,asendingtaskmight requireahandshake(acknowledgement) require a handshake (acknowledgement) thatthereceivingtaskhasbeensuccessfulin receivingthemessage. Thisprocessiscalledinterlocked communication,inwhichthesendingtask sendsamessageandwaitstoseeifthe g messageisreceived. Thisrequirementcanbeusefulforreliable communicationsortasksynchronization. Forexample,ifthemessageforsomereason isnotreceivedcorrectly,thesendingtaskcan is not received correctly, the sending task can resendit. Usinginterlockedcommunicationcanclose asynchronizationloop.Todoso,youcan constructacontinuousloopinwhichsending g p p andreceivingtasksoperateinlockstepwith eachother.

Inthiscase,tSourceTaskandtSinkTaskuse abinarysemaphoreinitiallysetto0anda bi h i i i ll 0 d messagequeuewithalengthof1(also calledamailbox).tSourceTasksendsthe messagetothemessagequeueandblocks onthebinarysemaphore.tSinkTask th bi h tSi kT k receivesthemessageandincrementsthe binarysemaphore.Thesemaphorethat hasjustbeenmadeavailablewakesup tSourceTask.tSourceTask,whichexecutes tS T k tS T k hi h t andpostsanothermessageintothe messagequeue,blockingagainafterward onthebinarysemaphore.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

81

QueueUsage Interlocked,TwoWayDataCommunication
Sometimesdatamustflowbi directionallybetweentasks, whichiscalledinterlocked, twowaydatacommunication t d t i ti (alsocalledfullduplexor tightlycoupled communication). ) Thisformofcommunication canbeusefulwhendesigning aclient/serverbasedsystem. Notethattwoseparate messagequeuesarerequired forfullduplexcommunication. Ifanykindofdataneedstobe If any kind of data needs to be exchanged,messagequeues arerequired;otherwise,a simplesemaphorecanbeused tosynchronize t h i acknowledgement.
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 82

QueueUsage BroadcastCommunication

Some messagequeue Somemessagequeue implementationsallow developerstobroadcast p acopyofthesame messagetomultiple tasks. Messagebroadcastingis aonetomanytask k relationship. tBroadcastTasksends tBroadcastTask sends themessageonwhich multipletSinkTaskare p waiting.
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 83

Interprocesscommunications Message Q Queue


Li it ti Limitations
Messagequeuesareeffectiveifsmallamountofdatais transferred. Veryexpensiveforlargetransfers Duringmessagesendingandreceiving,themessageiscopied fromuserbufferintokernelbufferandviceversa! from user buffer into kernel buffer and vice versa! Alsothemessagecantbereusedasoncemessageisretrieved, themessageisremovedfromthequeue

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

84

Interprocesscommunications Pipes
Theclientserverexamplecanverywellillustratetheapplicationof pipes. TheclientreadsafilenamefromtheSTDINandwritesintothepipe. TheserverreadsthisfilefromthePIPEandopensthefileforreading. Iftheopenissuccessful,theserverrespondsbyreadingthefileand writingintothepipe,otherwiseanerrormessagewouldbe writing into the pipe otherwise an error message would be generated. Theclientthenreadsfromthepipe,writingwhatitreceivestothe STDOUT. STDOUT.
STDIN PathName

Client
STDOUT Filecontent orerror message
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT

Server

FILE

85

Interprocesscommunications Pipes
Pipesarekernelobjectsthat provideunstructureddata provide unstructured data exchangeandfacilitate synchronizationamongtasks. Inatraditionalimplementation, apipeisaunidirectionaldata d ld exchangefacility. Twodescriptors,oneforeachend pp ( g ofthepipe(oneendforreading andoneforwriting),arereturned whenthepipeiscreated. Dataiswrittenviaonedescriptor andreadviatheother.Thedata and read via the other The data remainsinthepipeasan unstructuredbytestream.Datais readfromthepipeinFIFOorder.

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

86

Interprocesscommunications Pipes
Apipeprovidesasimple dataflowfacilitysothatthe d fl f l h h readerbecomesblocked whenthepipeisempty,and thewriterbecomesblocked the writer becomes blocked whenthepipeisfull. Typically,apipeisusedto exchangedatabetweena exchange data between a dataproducingtaskanda dataconsumingtask. It is also permissible to Itisalsopermissibleto haveseveralwritersforthe pipewithmultiplereaders onit.
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 87

Interprocesscommunications Pipes
Un namedPipeorPipe: p p
Oncommandlineformatpipeisrepresentedby| ItcanbeusedinShelltolinktwoormorecommands.
Ls lrt | grep file c Ls lrt|grepfile.c

Apipehasgottwoends.Theyarerepresentedbytwodescriptors. Apipeisusedtocommunicatebetweenrelatedprocesses. PipeisaHalfduplexmechanism Pi i H lf d l h i Dataispassedinorder theorderinwhichthedataissentis theorderinwhichyoureceiveatotherend!

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

88

Interprocesscommunications Pipes
LetstakeUnixsystemprogrammingasreference! ThePipefunctionisdeclaredinunistd.h p Whenaprocesscallsread()fromthepipe,theread()returnswith dataimmediately,ifthepipeisnotempty. Ifthepipeisemptythereadcallisblockeduntilsomeonewritestoit. If the pipe is empty the read call is blocked until someone writes to it Ifnoprocesshaspipeopenforwritingthentheread()returns0. Ontheotherhandifaprocesscallwritestoapipeandnoother processhasopeneditforreadingthenitwillreturnEPIPEERROR. process has opened it for reading then it will return EPIPE ERROR
Thisisfamousbrokenpipemessage! TheblockingnatureofRead()andWrite()effectivelysynchronizesthe processes.

Write

Read

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

89

Contextswitching. Context switching.


TheCPUhastoexecuteonetaskforsometimeandithasto executeanothertaskwhichisQueue. t th t k hi h i Q ConsiderasituationwhereCPUexecutinglowprioritytask, andtheCPUwillbecontainingthedatacorrespondingto thattask. that task CPUhastonowtakeoutthelowprioritytaskoutof executionandshouldexecutehighprioritytask(Should p preemptthelowprioritytaskinotherwords) p p y ) InthiscasecontentsoftheCPUregistersshouldbesaved beforeproceedingwiththeexecutionofhighprioritytask. ThestateoftheCPUregisterswhenataskistobe preemptediscalledContext. di ll d C SavingthecontentofCPUregisterandloadingthenewtask iscalledContextSwitching, L t Letsgetintoitinabitmoredetailedway!! t i t it i bit d t il d !!
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 90

Contextandperiodsforcontext switching g Gettinganaddressfromwherethe Getting an address from where the

newfunctionbegins,loadingthat addressintoPCandthenexecuting thecalledfunctionsinstructionwill CurrentProgramContext g changearunningfunctionatCPUto another.(newfunctionwillbe PC(ProgramCounter) executed,bykeepingapagemarkfor thefunctionfromwherethenew the function from where the new functioniscalled) SP(StackPointer) Beforeexecutingnewinstructionsof thenewfunctiontheprocessororOS alsosavesthecurrentprograms CPUregisters statusword,registersandprogram contexts. If not done by OS or Processor then IfnotdonebyOSorProcessor,then ProcessorStatusRegister thenewfunctions,instructionshould dothat. CurrentProgram (p g Thisisbecausethese(programs Context C statusword,registers)information mightbeneededbynewlycalled EmbeddedSystems,ShriramKV,SENSE, 3/18/2010 function. VIT

91

Thecontextmustsaveifafunction programorroutineleftearlierhastorun ti l ft li h t againfromthestatewhichwasleft. Whenthereisacalltoafunction(i.e. routineinassemblylanguage)the functionorISRorexceptionhandling function or ISR or exception handling functionexecutes3mainsteps:
SavingallCPUregistersincludingprocessor statusword,registersandfunctionscurrent addressfornextinstructioninPC.Saving q addressofthePContothestackisrequired ifthereisnolinkregistertopointtothePC ofleftinstructionoftheearlierfunction. Savingfacilitatesthereturnfromnew functiontothepreviousfunction. Loadnewcontexttoswitchtoanew function. function Executethenewfunction. Thesethreestepsaretogethercalledas contextswitching.

Context Switching

SavecurrentfunctionorISRcontext onastackandloadnewfunction

3/18/2010

Contextandperiodsforcontext Context and periods for context switching


EmbeddedSystems,ShriramKV,SENSE, VIT

92

Thelastactionofanyroutine y orfunctionisalwaysareturn. Thefollowingstepsoccur duringthereturnfromthe calledfunction: ll d f i


Beforereturnretrievethe previouslystoredstatusword, registersandothercontext parameters. parameters Retrieveaddressfromstackor linkregisterandadjustthe contentsofthestackifneeded. Executetheremainingpartof Execute the remaining part of theoldfunctionfromwherethe newfunctioniscalled. Letscheckitout diagrammatically!!!

Current routine

Stepsonswitchingfornewroutine
ContextSwitching

1.Savecurrentroutinecontextonstackandloadnew routinecontext.

2.Executethenewroutinecodes

3.Onreturnsavethenewroutinecontextandswitchfor thepreviousroutinebyretrievingthesavedcontext

ContextSwitching

3/18/2010

Contextandperiodsforcontext p switching
EmbeddedSystems,ShriramKV,SENSE, VIT

93

Whatisaninterrupt What is an interrupt


Everyembeddedsystemtypicallytakesinputfromitsuserorenvironment. Theinterruptmechanismisoneofthecommonwaystointeractwiththeuser. Considerasituationinwhichmicroprocessorhastoprocessinputsfromthree peripheraldevices. D1

P D2

Amicroprocessoris interactingwith3 devices!

D3
EmbeddedSystems,ShriramKV,SENSE, VIT

3/18/2010

94

Whatisaninterrupt What is an interrupt


Onewaytoaccomplishthisisthropolling!(i.e.askingeachdeviceforinput) Thealgorithmforthiscouldbe

Whiletheprogramisrunning{ 1. Poll Device D1 for input PollDeviceD1forinput 2. Iftheinputispresent,processinputfromD1 3. PollDeviceD2forinput 4. Iftheinputispresent,processinputfromD2 5. PollDeviceD3forinput 6. Iftheinputispresent,processinputfromD3 6 If th i ti t i tf D3 }

Algorithmforthreepolleddevices
Thiskeepsthemicroprocessoralwaysbusy.Itiseitherpollingfortheinput oritwillbe p p y y p g p processingtheinput.ThismethodhasmoreCONSthanPROSwithonedefinitedrawbackof makingthemicroprocessortoworkforever. Theothermechanismisinterrupting.Inthismechanismthedeviceinforms,i.e.,interruptsthe p p p microprocessorwheneverithassomeinputforthemicroprocessor. Theclearadvantageofthismethodoverthepollingmethodthattheprocessorisfreetodo otherwork.(Runningotherapplications )
3/18/2010 EmbeddedSystems,ShriramKV,SENSE, VIT 95

Interrupt Types
PeriodicInterrupts:ifthe interruptsoccuratfixedintervals interrupts occur at fixed intervals oftimeline,thentheyarecalled periodic

INTERRUPTS

AperiodicInterrupts:ifthe interruptsoccuratAnypointof timeitisaperiodic.(Anticipatinga keypressfromuser)

HARDWARE

SOFTWARE

1.Interruptscanberaised alsobyexecutingsoftware instructions.Itiscalled instructions It is called softwareinterrupts.

NormalInterrupt Normal Interrupt


1.IftheMicroprocessoris interruptedbyexternal interrupted by external device/hardware.,then wecanclassifyitas hardwareinterrupt 1.Iftheinterruptisplanned thenitiscalledNormal h i i ll d l Interrupt
3/18/2010

Exception

1.Ifaninterruptisunplanned p p thenitisclassifiedas Exceptions.


96

EmbeddedSystems,ShriramKV,SENSE, VIT

Interruptlatency Interrupt latency


Oneobviousquestionthateveryonewillgetinmindis
Howfastmyembeddedsystemwillrespondtoeachinterrupt??

Theanswerforthisquestiondependsonnumerousfactors: Theperiodoftimeittakestoexecuteanyinterruptroutinesforinterruptthat areofhigherprioritythanoneinquestion!! are of higher priority than one in question!! Howlongittakesforthemicroprocessortostopwhatitisdoing,donecessary bookkeeping,andstartexecutinginstructionswithintheinterruptroutine! How long it takes to store the context ??? Howlongittakestostorethecontext???

Theintervalbetweentheoccurrenceofaninterruptandstartofexecution oftheISRiscalledinterruptlatency. of the ISR is called interrupt latency

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

97

Interruptlatency Factorsthatgovern p y g interruptlatency


Makeyourinterruptroutinesshort! Make your interrupt routines short! Processingtimeusedbyaninterruptroutineslowsresponsefor everyotherinterruptofthesameorlowerpriority. Although lower priority interrupts are most probably lower priority Althoughlowerpriorityinterruptsaremostprobablylowerpriority becausetheirresponsetimerequirementsarelesscritical. Thisisnotnecessarilylicensetomaketheirresponsedreadfulby writingatimeconsuminginterruptroutineforhigherpriority writing a time consuming interrupt routine for higher priority interrupt. AnExamplewhichwouldbebetterdepictionforthiscase!Letstalk aboutitnow!!! about it now!!!

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

98

3/18/2010

Supposethatyouarewritingasystemthatcontrolsafactoryandthatevery secondyoursystemgetsmanyinterrupts(almostsayadozen)towhichit second your system gets many interrupts (almost say a dozen) to which it mustrespondpromptlytokeepthefactoryrunningsmoothly. Ifthatyoursystemmonitorsadetectorthatchecksforgasleaks,andyour systemmustcallfiredepartmentandshutdowntheaffectedpartofthe system must call fire department and shut down the affected part of the factoryifgasleakageisdetected. Nowitisverylikelythattheinterruptroutinethathandlesthegasleakage needstoberelativelyhighpriority,sinceitwouldbebadideaforother needs to be relatively high priority, since it would be bad idea for other interruptstogetmicroprocessorsattention. Howeverthesystemneedstocontinueoperatingtheunaffectedpartofthe factory,sothegasleakinterruptroutinemustnottakeuptoomuchtime.If acto y, so t e gas ea te upt out e ust ot ta e up too uc t e callingthefiredepartment aprocessthatwilltakeseveralseconds,at leastincludedinthegasleakinterruptroutine,thendozensofother interruptswillpileupwhilethisisgoingon,anrestofthefactorymaynot runproperly.Thereforethetelephonecallshouldnotbeapartofinterrupt routine. EmbeddedSystems,ShriramKV,SENSE,
VIT 99

Interruptlatency Example Make yourinterruptroutinesshort! h !

EmbeddedSystems,ShriramKV,SENSE,VIT

Interruptlatency Interrupt latency


WhenaninterruptoccurstheserviceoftheinterruptbyexecutingISR maynotstartimmediatelybycontextswitching. Theintervalbetweentheoccurrenceofaninterruptandstartof executionoftheISRiscalledinterruptlatency. CASE:1
ThetimetakenforcontextswitchisbeingreferredasTswitch T Whentheinterruptservicestartsimmediatelyoncontextswitching,theinterrupt latencyisequaltothecontextswitchingperiod. When instructions in a processor take variable clock cycles maximum clock cycles for Wheninstructionsinaprocessortakevariableclockcycles,maximumclockcyclesfor aninstructionaretakenintoaccountforcalculatingthelatency.

Interruptlatency t only where t is the context Interrupt latency =t onlywheret isthecontext switchingtimeforsavingtherunningprogramcontext andloadingthenewroutinecontext

3/18/2010

100

EmbeddedSystems,ShriramKV,SENSE,VIT

CASE:2 Wheninterruptservicedoesnotstartimmediatelybutcontext switchingstartsafteralltheISRscorrespondingtothehigherpriority interruptscompletetheexecution. interrupts complete the execution ifthesumoftimeintervalsforcompletinghigherpriorityISRsequals thentheinterruptlatencyequalsT Texec,thentheinterruptlatencyequalsTswitch+Texec.
Assumethatthisisa CurrentISRofhigher priority

Interruptlatency Interrupt latency

Processor ISR

High PriorityISR Priority ISR

AfterPresentISRofHigher priorityinterruptcompletes execution,thisISRwillbe giventheprocessortime. given the processor time

3/18/2010

101

CASE:3 Wedisabletheinterruptsystemwhenaroutineentersacriticalsection andenabletheinterruptswhenroutineexitsthecriticalsection. AroutineoffunctionorISRmayconsistsofcodesforcriticalregion instructionsandbeforethecriticalsectioncodesalltheinterruptsare disabledandenabledbytheendofcriticalsection. Letssay Tdisable istheperiodforwhicharoutineisdisabledinitscritical section. Theinterruptservicelatencyfromtheroutinewiththeinterrupt disablinginstructionwillbe
ISR Critical Section S i Codes

EmbeddedSystems,ShriramKV,SENSE,VIT

Tswitch+Texec+ Tdisable .
ISR
Interruptlatency=Tswitch+ Texec+Tdisable.Where Tswitchiscontextswitching time.Tdisableistimeforwhich time Tdisableistimeforwhich theinterruptsremaindisabled. Texecisthetimeforwhich otherhighpriorityroutinesare executed

Interruptlatency Interrupt latency


3/18/2010

102

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

103

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

104

I2C (I Square C)
I2C is a Serial bus used for interconnecting ICs. It is commonly used to link Mu-Cs to systems. Mu Cs systems I2C is an acronym for Inter-IC bus Developed in the early 1980's by Philips semiconductors to provide an easy way to connect a CPU to peripheral chips in a TV set TV-set.
Ex: being used in MPEG-2 video chip.

EmbeddedSystems,ShriramKV,SENSE, VIT

105

I2C (I Square C)
Designed to be: 1.low cost 2.easy to implement 3.moderate 3 moderate speed ( up to 400 kb/sec) . it uses only two lines: serial Data line ( SDL) F d t i l D t li For data serial clock line (SCL) indicates when valid data are on the line

EmbeddedSystems,ShriramKV,SENSE, VIT

106

I2C (I Square C)
2 wire protocol SDA, SCL. Master-Slave configuration. Multi master protocol

EmbeddedSystems,ShriramKV,SENSE, VIT

107

I2C (I Square C)

From the figure Every node in the network is connected to both SCL and SDL. Some nodes would be able to act as Masters and some as Slaves. There can be more than one master and I2C is a multi master bus. The slaves will be responding only to the queries from the master.

EmbeddedSystems,ShriramKV,SENSE, VIT

108

I2C (I Square C) Electrical Interface


The bus does not define particular voltages to be used , so that bipolar or MOS circuits can be connected to the bus. A pull up resistor is used to keep the default state of the signal as high. And transistors are used to pull down the signal when a zero is to be transmitted.

EmbeddedSystems,ShriramKV,SENSE, VIT

109

I2C (I Square C)
Open collector / drain signaling allows several devices to write p g g the bus without causing electrical damage. The I2C bus is a multi master bus. Any one of several devices may act as a master at various times. So, there is no global master to generate clock signal on SCL. Instead a master drives both SDL and SCL when it is sending data. When the bus is IDLE both SCL and SDL remains high

EmbeddedSystems,ShriramKV,SENSE, VIT

110

I2C (I Square C)

When two devices try to drive either SCL or SDL to different values, the open collector / drain circuitry prevents errors , but each master device must listen to the bus while transmitting to be sure that it is not interfering with another message if a device receives different value than it is trying to transmit, then is an interference.

EmbeddedSystems,ShriramKV,SENSE, VIT

111

I2C (I Square C) Data Link Layer


Every Inter IC bus has address. The addresses of the devices y are determined by system designer The address must be chosen such that no two devices should have same address I e no confliction should be there.. address..I.e. there A device address is seven bits in normal I2C definition( but extended bus allows 10 bit addresses).. The address 00000000 is used to signal a general call or a bus broadcast, which can be used to signal all devices simultaneously. The address 11110XX is reserved for extended 10 bit addressing scheme.. There are several other reserved addresses are there.
EmbeddedSystems,ShriramKV,SENSE, VIT 112

I2C (I Square C) - Bus Transaction


The bus transaction is comprised of series of 1 byte transaction and an address followed by one or more data types. The I2C bus allows data push programming style.. When Master wants to write the slave it transmits slaves address slave, slave s followed by data. A slave cannot initiate data transfer.. So master must send a read request with the slaves address and let the slave slave s transmit the data. Therefore, an address transmission includes seven bits for address and 1 bit for data direction : 0 for writing from master to slave and 1 for reading data from slave to master.

EmbeddedSystems,ShriramKV,SENSE, VIT

113

I2C (I Square C) Start and Stop


Prior to any transaction on the bus, a START condition needs to be issued on the bus. The start condition acts as a signal to all connected IC's that something is about to be transmitted on the bus. As a result, all connected chips will listen to the bus. After a message has been completed, a STOP condition is sent. This is the signal for all devices on the bus that the bus is available again (idle).

EmbeddedSystems,ShriramKV,SENSE, VIT

114

I2C (I Square C) - BYTEFORMAT


Transmission starts when SDL is pulled low while SCL remains high. After this clock line is pulled low to initiate data transfer. An ACK is sent at the end of each 8 bit transition.

EmbeddedSystems,ShriramKV,SENSE, VIT

115

I2C (I Square C)- BUS ARBITRATION:

The bus uses this feature to arbitrate on each message . When sending the devices listen to the bus as well.. If a device is trying to send a logic 1 , but hears a logic 0 it immediately stops transmissionand gives other sender priority. In many cases arbitration will be completed during address portion of data transfer.. But may continue into data portion in some cases. If two de ces try to t e identical data to sa e add ess, t e t o devices t y the de t ca same address, then of course they never interfere and they both will succeed.

EmbeddedSystems,ShriramKV,SENSE, VIT

116

Summary I2C
I2C is Inter IC Connectivity Protocol Synchronous 2 wire protocol Very useful for cost effective interconnect of slow peripheral ICs to the MCU Most cost effective for serial EEPROM for boot code onto the MCU RAM or for configuration Data Many MCUs and SOCs support I2C on Chip. y pp p Ex. MSP430 I2C SW Drivers are relatively simple to write for simple operations like EEPROM loads and LCD Displays. Displays But not so for generic data exchange

EmbeddedSystems,ShriramKV,SENSE, VIT

117

CAN Controllerareanetwork CAN Controller area network


CAN Controllerareanetwork.(MultiMasterBus) WasinventedbyGermanAutomotiveMajor,RobertBosch,forautomotive W i t db G A t ti M j R b tB h f t ti applicationsasamethodofenablingrobustserialcommunication. Thegoalwastomakeautomobilesmorereliable,safeandfuelefficient g g g whiledecreasingwiringharnessweightandcomplexity. Sinceitsinception,theCANprotocolhasgainedwidespreadpopularityin industrialautomationandautomotive/truckapplications. Othermarketswherenetworkedsolutionscanbringattractivebenefitslike medicalequipment,testequipmentandmobilemachinesarealsostarting medicalequipment testequipmentandmobilemachinesarealsostarting toutilizethebenefitsofCAN. CANcanrunatratesof1Mb/secoveratwistedpairofconnectionof40 meters. Insteadanopticallinkcanbeused. Thebusprotocolsupportsmultiplemastersonthebus.. I2CandCANaresimilarinsomeaspectsbuttheyaredifferentinsignificant factors. factors
EmbeddedSystems,ShriramKV,SENSE, VIT 118

CAN Controllerareanetwork Recessive anddominantstates


EachnodeinCANbushasitsown electricaldriversandreceiversthat connectthenodetothebusin wiredANDfashion. IncanTerminology,alogical1on I T i l g l gi l1 thebusiscalledrecessiveandlogic 0iscalledDominant. g Thedrivingcircuitsonthebus causesittobepulleddownto0. whenallnodesaretransmitting1s, thebusissaidtobeinrecessive state.Whenanodetransmits0itis saidtobeindominantstate. Dataaresentonthenetworkin packetsknownasdataframes.

EmbeddedSystems,ShriramKV,SENSE, VIT

119

CAN Controllerareanetwork CAN Controller area network


Overview
Mostnetworkapplicationsfollow alayeredapproachtosystem implementation.Thissystematic approachenablesinteroperability betweenproductsfromdifferent manufacturers.Astandardwas createdbytheInternational StandardsOrganization(ISO)asa templatetofollowforthislayered approach. ItiscalledtheISOOpenSystems Interconnection(OSI)Network LayeringReferenceModelandis g showninFigureforreference.
EmbeddedSystems,ShriramKV,SENSE, VIT 120

CAN Controllerareanetwork CAN Controller area network


Overview
TheCANprotocolitselfimplementsmostof thelowertwolayersofthisreferencemodel. TherestofthelayersoftheISO/OSIprotocol stackarelefttobeimplementedbythe systemsoftwaredeveloper. HigherLayerProtocols(HLPs)aregenerally usedtoimplementtheupperfivelayersofthe OSIReferenceModel.

HLPsareusedto: 1)Standardizestartupproceduresincludingbit ratesUsed, 2)Distributeaddressesamongparticipatingnodes ) gp p g ortypesofmessages, 3)Determinethestructureofthemessages,and 4)Providesystemlevelerrorhandlingroutines.

EmbeddedSystems,ShriramKV,SENSE, VIT

121

CarrierSenseMultipleAccesswith p CollisionDetection(CSMA/CD)
The CAN communication protocol is a CSMA/CD protocol The CSMA stands protocol. for Carrier Sense Multiple Access. What this means is that every node on the network must monitor the bus for a period of no activity before trying to send a message on the bus (Carrier Sense). Also, once this period of no activity occurs, every node on the bus has an equal opportunity to transmit a message (Multiple Access). The CD stands for Collision Detection. If two nodes on the network start transmitting at the same time, the nodes will detect the collision and take the appropriate action. In CAN protocol, a nondestructive bitwise arbitration method is utilized. This means that messages remain intact (unbroken) after arbitration is completed even if collisions are detected. All of this arbitration takes place without corruption or delay of the higher priority message. g g
EmbeddedSystems,ShriramKV,SENSE, VIT 122

CarrierSenseMultipleAccesswith p CollisionDetection(CSMA/CD)
Thereareacoupleofthingsthatarerequired tosupportnondestructivebitwisearbitration. First,logicstatesneedtobedefinedas First logicstatesneedtobedefinedas dominantorrecessive. Second thetransmittingnodemustmonitor Second,thetransmittingnodemustmonitor thestateofthebustoseeifthelogicstateitis tryingtosendactuallyappearsonthebus.CAN tryingtosendactuallyappearsonthebus CAN definesalogicbit0asadominantbitanda g logicbit1asarecessivebit.
EmbeddedSystems,ShriramKV,SENSE, VIT 123

CarrierSenseMultipleAccesswith p CollisionDetection(CSMA/CD)
Adominantbitstatewillalwayswinarbitrationoverarecessivebit state,thereforethelowerthevalueintheMessageIdentifier(the fieldusedinthemessagearbitrationprocess),thehigherthepriority ofthemessage.Asanexample,supposetwonodesaretryingto transmitamessageatthesametime. Eachnodewillmonitorthebustomakesurethebitthatitistryingto sendactuallyappearsonthebus.Thelowerprioritymessagewillat d ll h b Th l i i ill somepointtrytosendarecessivebitandthemonitoredstateonthe buswillbeadominant. Atthatpointthisnodelosesarbitrationandimmediatelystops transmitting. Thehigherprioritymessagewillcontinueuntilcompletionandthe nodethatlostarbitrationwillwaitforthenextperiodofnoactivity p y onthebusandtrytotransmititsmessageagain
EmbeddedSystems,ShriramKV,SENSE, VIT 124

CAN MessageBasedCommunication
CANprotocolisamessagebasedprotocol,notanaddress basedprotocol. Thismeansthatmessagesarenottransmittedfromone f nodetoanothernodebasedonaddresses.Embeddedinthe CANmessageitselfisthepriorityandthecontentsofthe databeingtransmitted. d t b i gt itt d Allnodesinthesystemreceiveeverymessagetransmitted onthebus(andwillacknowledgeifthemessagewas properlyreceived). l i d) Itisuptoeachnodeinthesystemtodecidewhetherthe messagereceivedshouldbeimmediatelydiscardedorkept tobeprocessed. t b d Asinglemessagecanbedestinedforoneparticularnodeto receive,ormanynodesbasedonthewaythenetworkand systemaredesigned. t d i d
EmbeddedSystems,ShriramKV,SENSE, VIT 125

CAN Message BasedCommunication CAN MessageBased Communication


Forexample,anautomotiveairbagsensorcanbe connectedviaCANtoasafetysystemrouternode t d i CAN t f t t t d only. Thi Thisrouternodetakesinothersafetysystem d k i h f informationandroutesittoallothernodesonthe safetysystemnetwork.Thenalltheothernodeson safety system network Then all the other nodes on thesafetysystemnetworkcanreceivethelatest airbagsensorinformationfromtherouteratthe airbag sensor information from the router at the sametime,acknowledgeifthemessagewas receivedproperly,anddecidewhethertoutilizethis received properly, and decide whether to utilize this informationordiscardit.
EmbeddedSystems,ShriramKV,SENSE, VIT 126

CAN Message BasedCommunication CAN MessageBased Communication


One additional benefit of this messagebased message based protocol is that additional nodes can be added to the system without the necessity to reprogram all other nodes to recognize this addition. Thisnewnodewillstartreceivingmessagesfrom thenetworkand,basedonthemessageID,decide whethertoprocessordiscardthereceived information. information

EmbeddedSystems,ShriramKV,SENSE, VIT

127

CAN RTR(Remotetransferrequest) CAN RTR (Remote transfer request)


Another useful feature built into the CAN protocol is the ability for a node to request information from other nodes. This is called a Remote Transmit Request (RTR). This is different from the example in the previous case because instead of waiting for information to be sent by a particular node, this node specifically requests data to be sent to it. For example, a safety system in a car gets frequent updates from critical sensors like the airbags, but it may not receive frequent updates from other sensors like the oil pressure sensor or the low battery sensor to make sure they are functioning properly. Periodically, Periodically the safety system can request data from these other sensors and perform a thorough safety system check. The system designer can utilize this feature to minimize network traffic while still maintaining the integrity of the network network.
EmbeddedSystems,ShriramKV,SENSE, VIT 128

CAN data frame


First Field: (12 bits) The first field in the packet consists of packets destination address and RTR, known as arbitration field. RTR is Remote Transmission Request. It , ow a b t at o e d. s e ote a s ss o equest. t is defined on the basis of whether data byte sent is data for the device or request from the device. The trailing remote transfer request bit is set to 0 when the data frame is used t request d t f d to t data from d i specified b id tifi device ifi d by identifier. If RTR is 1 it can perform write operation into the address specified by identifier.

EmbeddedSystems,ShriramKV,SENSE, VIT

129

CAN data frame


11 bit address identifies the device to which the data is being sent or from which the data is going to be read. Second Field (6 bits) (DLC) It is control field. First bit is identifier extension The second bit is always 1 the field extension. 1. last 4 bits are code for data length. length of the data to be transmitted is dictated by DLC field Third Field (0 to 64 bits) Length depends on data length code in control field field. Fourth Field (16 bits) It is CRC field. Used to detect errors during transmission if any. Fifth Field (2 bit Ack field) First bit is ACK Slot. Sender sends it as 1 and the receiver which will send 0 in Slot this slot if there is an error detected. The sender on sensing 0 in ACK field will initiate retransmission. Second bit is Delimiter which signals end of ACK field. Sixth field. (7 bits) This is EOF and has 7 0s.

EmbeddedSystems,ShriramKV,SENSE, VIT

130

Can errortypes Can error types


BecauseCANwasinitiallydesignedforuseinautomobiles,aprotocolthat efficientlyhandlederrorswascriticalifitwastogainmarketacceptance. There are 2 basic error types!
CRC Error A 15-bit Cyclic Redundancy Check (CRC) value is calculated by the transmitting node and this 15-bit value is transmitted in the CRC field. All nodes on the network receive this message, calculate a CRC and verify that the CRC values match. If the values do not match, a CRC error occurs and an Error Frame is generated. Since at least one node did not properly receive the message, it is then resent after a proper intermission time. Bit Error A Bit Error occurs if a transmitter sends a dominant f bit and detects a recessive bit,, or if it sends a recessive bit and detects a dominant bit when monitoring the actual bus level and comparing it to the bit that it has just sent. If a Bit Error is detected, an Error Frame is generated and the original message is resent after a proper intermission time.

EmbeddedSystems,ShriramKV,SENSE, VIT

131

CANCAN Characteristics A Summary


Uses a single terminated twisted pair cable Is multi master Maximum Signal frequency used is 1 Mbit/sec Length is typically 40M at 1Mbit/sec up to 10KM at 5Kbits/sec Has high reliability with extensive error checking Typical maximum data rate achievable is 40KBytes/sec Maximum latency of high priority message <120 sec at y g p y g 1Mbit/sec 2.0A sometimes known as Basic or Standard CAN with 11 bit message identifiers which was originally specified to operated at a maximum frequency of 250Kbit/sec - ISO11519 ISO11519. 2.0B known as Full CAN or extended frame CAN with 29 bit message identifier which can be used at up to 1Mbit/sec - ISO 11898.
EmbeddedSystems,ShriramKV,SENSE, VIT 132

THANKSANDGOODLUCK THANKS AND GOOD LUCK


SHRIRAMKVASUDEVAN

3/18/2010

EmbeddedSystems,ShriramKV,SENSE, VIT

133

You might also like