资源预览内容
第1页 / 共392页
第2页 / 共392页
第3页 / 共392页
第4页 / 共392页
第5页 / 共392页
第6页 / 共392页
第7页 / 共392页
第8页 / 共392页
第9页 / 共392页
第10页 / 共392页
亲,该文档总共392页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述
嵌入式培训专题微迪软件培训中心Tornado&VxWorks培训深圳市微迪软件技术有限公司培训中心嵌入式培训专题微迪软件培训中心实时系统概念实时系统是对外来事件在限定时间内能做出反应的系统。指标响应时间ResponseTime生存时间SurvivalTime吞吐量Throughput嵌入式培训专题微迪软件培训中心实时系统与普通系统在实时计算中,系统的正确性不仅仅依赖于计算的逻辑结果而且依赖于结果产生的时间对于实时系统来说最重要的要求就是实时操作系统必须有满足在一个事先定义好的时间限制中对外部或内部的事件进行响应和处理的能力此外作为实时操作系统还需要有效的中断处理能力来处理异步事件和高效的I/O能力来处理有严格时间限制的数据收发应用嵌入式培训专题微迪软件培训中心实时系统分类根据不同的分类方法可以分为几种。方法一是分为周期性的和非周期性的(periodic和aperiodic)方法二是分为硬实时和软实时(hard real_time和soft real_time)专用系统和开放系统集中式系统和分布式系统嵌入式培训专题微迪软件培训中心实时多任务操作系统与分时多任务操作系统实时多任务操作系统与分时多任务操作系统 分时操作系统,软件的执行在时间上的要求,并不严格,时间上的错误,一般不会造成灾难性的后果。实时操作系统,主要任务是对事件进行实时的处理,虽然事件可能在无法预知的时刻到达,但是软件上必须在事件发生时能够在严格的时限内作出响应(系统响应时间),即使是在尖峰负荷下,也应如此,系统时间响应的超时就意味着致命的失败。另外,实时操作系统的重要特点是具有系统的可确定性,即系统能对运行情况的最好和最坏等的情况能做出精确的估计。嵌入式培训专题微迪软件培训中心实时操作系统中的重要概念实时操作系统中的重要概念系统响应时间(System response time ) 系统发出处理要求到系统给出应答信号的时间。任务换道时间(Context-switching time) 是任务之间切换而使用的时间。中断延迟(Interrupt latency ) 是计算机接收到中断信号到操作系统作出响应,并完成换道转入中断服务程序的时间。嵌入式培训专题微迪软件培训中心实时操作系统应具有如下的功能任务管理(多任务和基于优先级的任务调度)任务间同步和通信(信号量和共享内存等)存储器优化管理(含ROM的管理)实时时钟服务中断管理服务嵌入式培训专题微迪软件培训中心硬实时、软实时(一)硬实时要求在规定的时间内必须完成操作,这是在操作系统设计时保证的软实时则没有那么严,只要按照任务的优先级,尽可能快地完成操作即可对于软实时系统基于优先级调度的调度算法可以满足要求,提供高速的响应和大的系统吞吐率;而对于硬实时系统则完成timely response是必须的。这两类系统的区别在于调度算法。实时操作系统是保证在一定时间限制内完成特定功能的操作系统。例如,可以为确保生产线上的机器人能获取某个物体而设计一个操作系统。在“硬”实时操作系统中,如果不能在允许时间内完成使物体可达的计算,操作系统将因错误结束。在“软”实时操作系统中,生产线仍然能继续工作,但产品的输出会因产品不能在允许时间内到达而减慢,这使机器人有短暂的不生产现象。嵌入式培训专题微迪软件培训中心硬实时、软实时(二)软实时的RTOS一般应用在消费类电子产品,如手持电脑、个人数字助理(PDA)和机顶盒等消费电子类。WinCE。硬实时的RTOS一般应用于通信、控制和航空航天等实时性强和可靠性高的领域。通信行业使用PSOS、VxWorks、VRTX,航天、航空使用VRTX、VxWorks,工业PC控制使用QNX。嵌入式培训专题微迪软件培训中心实时系统的体系结构设计实时系统的体系结构必须满足1.高运算速度2.高速的中断处理3.高的I/O吞吐率4.合理的处理器和I/O设备的拓扑连接5.高速可靠的和有时间约束的通信6.体系结构支持的出错处理7.体系结构支持的调度8.体系结构支持的操作系统9.体系结构支持的实时语言特性。10.系统的稳定性和容错也非常重要11.还要考虑到实时的分布式应用。嵌入式培训专题微迪软件培训中心实时进程调度算法(一)静态的周期性调度这种调度算法的基本思想是将处理器的时间分为帧。FIFO也就是将系统中所有的任务组织成一个队列。先到先服务优先级队列算法种算法从FIFO发展而来。给每个任务设定优先级,然后在FIFO中按照优先级排列。这种算法保证了高优先级的任务的完成,但是对于低优先级的任务很可能无法满足时间的正确性。而且对低优先级的任务来说等待的时间是无法预知的。以上的调度算法都是独占的即任务运行时,不允许别的任务抢先。完成一个任务后才能完成下一个嵌入式培训专题微迪软件培训中心实时进程调度算法(二)RateMonatomic/Pacing算法此算法是基于静态优先级调度协议的方法。此算法给系统中每个任务设置一个静态的优先级。这个优先级的设定是在计算任务的周期性和任务需要满足的deadline的时间的长短的基础上完成的。周期越短,deadline越紧迫,优先级越高。DeadlineDriven算法DeadlineDriven算法提供动态的优先级。因为此算法根据任务满足deadline的紧迫性来修改任务的优先级,以保证最紧迫的任务能够及时完成。Priority Ceiling算法这种算法用于抢先式多任务的实时操作系统。该算法的基本思想是在系统中使用优先级驱动的可抢先的调度算法。也就是系统首先调度高优先级的任务运行。低优先级的任务在高优先级的任务运行时不能抢先;CPU由高优先级进程独占。嵌入式培训专题微迪软件培训中心嵌入式系统概述嵌入式系统(EmbeddedSystems)是指以应用为中心、以计算机技术为基础、软件硬件可裁剪、适应应用系统对功能、可靠性、成本、体积、功耗严格要求的专用计算机系统。是将应用程序和操作系统与计算机硬件集成在一起的系统嵌入式培训专题微迪软件培训中心嵌入式硬件 嵌入式硬件包括处理器微处理器、存储器及外设器件和IO端口、图形控制器等 特点:1)对实时多任务有很强的支持能力,能完成多任务并且有较短的中断响应时间,从而使内部的代码和实时内核心的执行时间减少到最低限度。2)具有功能很强的存储区保护功能。这是由于嵌入式系统的软件结构已模块化,而为了避免在软件模块之间出现错误的交叉作用,需要设计强大的存储区保护功能,同时也有利于软件诊断。3)可扩展的处理器结构,以能最迅速地开展出满足应用的最高性能的嵌入式微处理器。4)嵌入式微处理器必须功耗很低,尤其是用于便携式的无线及移动的计算和通信设备中靠电池供电的嵌入式系统更是如此,如需要功耗只有mW甚至W级。嵌入式培训专题微迪软件培训中心嵌入式系统发展趋势嵌入式应用软件的开发需要强大的开发工具和操作系统的支持。联网成为必然趋势支持小型电子设备实现小尺寸、微功耗和低成本提供精巧的多媒体人机界面嵌入式培训专题微迪软件培训中心实时系统内存管理预先分配内存。在系统构造或编译时为每个任务指定其使用的内存空间。这种方法对于硬实时系统来说是很合适的。而且嵌入式实时操作系统很多都是在ROM中运行,仅仅只有需要变化的数据才放在RAM中。这种系统在组成上无疑是静态的。虚拟内存但必须给实时任务提供方法,以便将实时任务“锁”进内存,也就是系统在管理虚拟内存时,不将“锁”住的内存块换出物理内存。嵌入式培训专题微迪软件培训中心嵌入式系统和实时系统嵌入式系统经常被误解为就是实时性系统。其实,多数嵌入式系统并不需要实时性 Linux是嵌入式操作系统,并非实时操作系统。Vxwork、pSOS、Neculeus和Windowss CE 是嵌入式实时操作系统嵌入式培训专题微迪软件培训中心一、实时多任务嵌入式培训专题微迪软件培训中心任务状态实时系统的一个任务可有多种状态,其中最基本的状态有四种:就绪态:任务只等待系统分配CPU资源;悬置态:任务需等待某些不可利用的资源而被阻塞;休眠态:如果系统不需要某一个任务工作,则这个任务处于休眠状态;延迟态:任务被延迟时所处状态;嵌入式培训专题微迪软件培训中心任务状态迁移嵌入式培训专题微迪软件培训中心任务状态迁移函数(一)就绪态 - 悬置态 semTake()/msgQReceive()就绪态 - 延迟态 taskDelay()就绪态 - 休眠态 taskSuspend()悬置态 - 就绪态 semGive()/msgQSend()悬置态 - 休眠态 taskSuspend()嵌入式培训专题微迪软件培训中心任务状态迁移函数(二)延迟态 - 就绪态 expired delay延迟态 - 休眠态 taskSuspend()休眠态 - 就绪态 taskResume()/taskActivate()休眠态 - 悬置态 taskResume()休眠态 - 延迟态 taskResume()嵌入式培训专题微迪软件培训中心多任务内核进行任务管理任务是竞争系统资源的最小运行单元。任务可以使用或等待CPU、I/O设备及内存空间等系统资源,并独立于其它任务,与它们一起并发运行(宏观上如此)。VxWorks内核使任务能快速共享系统的绝大部分资源,同时有独立的上下文来控制个别线程的执行。 VxWorks实时内核Wind提供了基本的多任务环境,系统内核根据某一调度策略让它们交替运行。系统调度器使用任务控制块的数据结构(简记为TCB)来管理任务调度功能。嵌入式培训专题微迪软件培训中心任务控制快(TCB)任务控制块用来描述一个任务,每一任务都与一个TCB关联。 任务控制块里面包含了:当前状态、优先级、要等待的事件或资源、任务程序码的起始地址、初始堆栈指针 任务的“上下文”(context)。任务的上下文就是当一个执行中的任务被停止时,所要保存的所有信息。通常,上下文就是计算机当前的状态,也即各个寄存器的内容。 VxWorks中,内存地址空间不是任务上下文的一部分。所有的代码运行在同一地址空间。如每一任务需各自的内存空间,需可选产品VxVMI的支持。 嵌入式培训专题微迪软件培训中心内核管理示意图KernelTCBTCBTCBTCBTCBTCBSuspendedPendedTCBDelayedTCBReadyCPUExecuting嵌入式培训专题微迪软件培训中心任务上下文切换当前运行的任务的上下文被存入TCB将要被执行的任务的上下文从它的TCB中取出,放入各个寄存器中。上下文切换必须很快速的嵌入式培训专题微迪软件培训中心优先级调度基于优先级的抢占式调度法作为缺省策略这种调度方法为每个任务指定不同的优先级。没有处于悬置或休眠态的最高优先级任务将一直运行下去。当更高优先级的任务由就绪态进入运行时,系统内核立即保存当前任务的上下文,切换到更高优先级的任务。当有内核调用或有中断到来时,内核重新调度同时提供了时间片轮转调度嵌入式培训专题微迪软件培训中心基于优先级的抢占式调度嵌入式培训专题微迪软件培训中心时间片轮转调度ABCDABCDTime Slice Period(Constant - Programmable)嵌入式培训专题微迪软件培训中心混合调度策略嵌入式培训专题微迪软件培训中心内核时间片时间片的长度可由系统调用KernelTimeSlice(ticks) 通过输入参数值来指定。 当 ticks为0时,时间片调度被关闭基于优先级的抢占式调度可以发生在任何时候,时间片轮转调度只能在相同优先级的任务间每隔ticks发生一次。在VxWorks系统中,可以调用函数kernelTimeSlice来使用时间片轮转调度。嵌入式培训专题微迪软件培训中心VxWorks任务特性所有的代码运行在同一地址空间。任务能快速共享系统的绝大部分资源,同时有自己独立的上下文所有的任务都运行在特权模式下嵌入式培训专题微迪软件培训中心共享代码和重入(一)VxWorks提倡单个子程序或子程序库被多个不同的任务调用。例如printf。一个被多个任务调用的单个拷贝称为共享代码。VxWorks动态链接功能很容易实现代码共享。共享代码必须是可重入的。VxWorks的I/O和驱动程序是可重入的。但是要求应用小心设计。对于缓冲(buffer)I/O,VxWorks推荐使用文件指针。嵌入式培训专题微迪软件培训中心共享代码和重入(二)大部分VxWorks程序使用下面的重入机制动态堆栈变量如果程序仅仅是纯代码,除了自己的动态堆栈变量外没有自己的数据,除了调用者以参数传进的数据外,没有其他数据。任务只在自己的堆栈内进行操作。由信号量保护的全局或静态变量VxWorks的一些库封装对公共数据的访问。需要借用互斥机制任务变量一些程序可能会被多个任务同时调用,这些任务可能要求全局变量和静态变量有不同的值。这种情况下,VxWorks提供了所谓任务变量的机制,这种机制允许在任务上下文中增加4字节的变量,因此每次上下文交换时,改变量的值被保存。这种机制由taskVarLib库中的函数来提供。嵌入式培训专题微迪软件培训中心抢占禁止Wind内核可通过调用taskLock()和taskUnlock()来使调度器起作用和失效。当一个任务调用taskLock()使调度器失效,任务运行时没有基于优先级的抢占发生。然而,如果任务被阻塞或是悬置时,调度器从就绪队列中取出最高优先级的任务运行。当设置抢占禁止的任务解除阻塞,再次开始运行时,抢占又被禁止。这种抢占禁止防止任务的切换,但对中断处理不起作用。 嵌入式培训专题微迪软件培训中心POSIX调度schedPxLib库提供了POSIX1003.1b调度函数POSIX和Wind调度差异POSIX调度算法应用在进程到进程基础之上的,而Wind调度算法则用于整个系统基础之上的,所有任务即可以使用轮转调度,也可以使用基于优先级的抢占调度。POSIX的优先级编号方案与Wind的方案相反。POSIX中,优先数越高,优先级越高;Wind方案相反。为了解决这种冲突,用户需要通过将默认的全局变量posixPriorityNumbering的设置改委FALSE。使用POSIX调度程序,需要在配置VxWorks时,包含INCLUDE_POSIX_SCHED宏定义,系统将自动包含POSIX调度程序。嵌入式培训专题微迪软件培训中心VxWorks怎样满足实时性需求多任务特性基于抢占式多任务调度快速的任务上下文切换快速确定的系统响应高效的任务间通讯机制嵌入式培训专题微迪软件培训中心Real-Time MultitaskingIntroductionTask BasicsTask ControlError StatusSystem Tasks嵌入式培训专题微迪软件培训中心OverviewLow level routines to create and manipulate tasksare found in taskLib.Do not confuse executable code with the task(s) which execute it.A VxWorks task consists of:A stack (for local storage of automatic variables and parameters passed to routines).A TCB (for OS control)Code is downloaded before tasks are spawned.Several tasks can execute the same code (e.g., printf().嵌入式培训专题微迪软件培训中心Creating a TasktaskSpawnStackTCBPCfoo () .嵌入式培训专题微迪软件培训中心Creating a Taskint taskSpawn (name, priority, options,stackSize, entryPt, arg1, ., arg10)nameTask name, if NULL gives a default name.priorityTask priority, 0-255.optionsTask options e.g. VX_UNBREAKABLE.stackSizeSize of stack to be allocated in bytes.entryPtAddress of code to start executing (initial PC)arg1, ., arg10Up to 10 arguments to entry point routine.Returns a task id or ERROR if unsuccessful.嵌入式培训专题微迪软件培训中心Task IDsEfficient 32-bit handle for task.Assigned by kernel when task is created.May be reused after task exists.A task id of zero refers to task making call (self).Relevant taskLib routines:taskIdSelf()Get ID of calling task.taskIdListGet()Fill array with IDs of allexisting tasks.taskIdVerify()Verify a task ID is valid.Unique to each task.嵌入式培训专题微迪软件培训中心Task NamesProvided for human convenience.Typically used only from the shell (during development).Within programs, use task Ids.By convention, start with a t. Default is an ascending integer following a t.Promotes interpretation as a task name.Doesnt have to be unique (but usually is).Relevant taskLib routines.taskName()Get name from tid.taskNameToId()Get tid from task name.嵌入式培训专题微迪软件培训中心Task PrioritiesRange from 0 (highest) to 255 (lowest).No hard rules on how to set priorities. There are two (often contradictory) “rules of thumb”:Shorter deadline = higher priority.More important = higher priority.Can manipulate priorities dynamically with:taskPriorityGet (tid, &priority)taskPrioritySet (tid, priority)嵌入式培训专题微迪软件培训中心Task StacksAllocated from memory pool when task is created.Fixed size after creation.The kernel reserves some space from the stack, makingthe stack space actually available slightly less than the stack space requested.Exceeding stack size (“stack crash”) causes unpredictable system behavior.嵌入式培训专题微迪软件培训中心Stack OverflowsPress the check-stack button:To check for a stack overflow use the Browser.Examine the high-water mark indicator in thestack display window.High-water Mark Indicator (UNIX)Note: In the PC Browser Stack Check Window, the high water makr triangles are not present. Instead, the number displayed inside each stack bar is that stacks high water mark. The filled portion of the bar indicates the current stack usage graphically.嵌入式培训专题微迪软件培训中心Task OptionsCan be bitwise ored together when the task is created.VX_FP_TASKAdd floating point support.VX_NO_STACK_FILLDont fill stack with 0xees.VX_UNBREAKABEDisable breakpoints.VX_DEALLOC_STACKDeallocate stack and TCBwhen task exists (automaticallyset for you).Use taskOptionsGet() to inquire about a tasks options.Use taskOptionsSet() to unset VX_DEALLOC_STACK. 嵌入式培训专题微迪软件培训中心Task CreationDuring time critical code, task creation can beunacceptably time consuming.To reduce creation time, a task can be spawned with the VX_NO_STACK_FILL option bit set.Alternatively, spawn a task at system start-up, which blocksimmediately, and waits to be made ready when needed.嵌入式培训专题微迪软件培训中心Task DeletionDeletes the specified task.Deallocates the TCB and stack.Analogous to a taskDelete() of self.exit (code)code parameter gets stored in the TCB field exitCode.TCB may be examined for post-mortem debugging byUnsetting the VX_DEALLOC_STACK option or,Using a delete hook.taskDelete(tid)嵌入式培训专题微迪软件培训中心Resource ReclamationContrary to the philosophy of sharing system resources amongall tasks.Can be an expensive process, which must be the applicationsresponsibility.TCB and stack are the only resources automatically reclaimed.Tasks are responsible for cleaning up after themselves.Deallocating memory.Releasing locks to system resources.Closing files which are open.Deleting child / client tasks when parent / server exits.嵌入式培训专题微迪软件培训中心Real-Time MultitaskingIntroductionTask BasicsTask ControlError StatusSystem Tasks嵌入式培训专题微迪软件培训中心Task RestarttaskRestart (tid)Task is terminated and respawned with originalarguments and tid.Usually used for error recovery.嵌入式培训专题微迪软件培训中心Task Suspend / ResumetaskSuspend (tid)Makes task ineligible to execute.Can be added to pended or delayed state.taskResume (tid)Removes suspension.Usually used for debugging and development purposes.嵌入式培训专题微迪软件培训中心Task DelayTo delay a task for a specified number of systemclock ticks.To poll every 1/7 second:FOREVER taskDelay (sysClkRateGet() / 7);.STATUS taskDelay (ticks)Use sysClkRateSet() to change the clock rate.Accurate only if clock rate is a multiple ofseven ticks / seconds.Can suffer from “drift.”嵌入式培训专题微迪软件培训中心Reentrancy and Task VariablesIf tasks access the same global or static variables, theresource can become corrupted (called a race condition).Possible Solutions:Task Variables cause a 32-bit value to be saved andrestored on context switchs, like a register.Use only stack variables in applications.Protect the resource with a semaphore.Use task variables to make the variable privateto a taskCaveat: task variables increase context switch times.See the taskVarLib manual pages for details.嵌入式培训专题微迪软件培训中心Task HooksUser-defined code can be executed on every contextswitch, at task creation, or at task deletion:taskSwitchHookAdd ()taskCreateHookAdd ()taskDeleteHookAdd ()VxWorks uses a switch hook to implement task variables.See manual pages on taskHookLib for details.嵌入式培训专题微迪软件培训中心Task InformationLike i(), but also displays:Can also use show ():- show (tNetTask, 1)Stack informationTask optionsCPU registersFPU registers (if the VX_FP_TASK option bit is set)ti (taskNameOrId)嵌入式培训专题微迪软件培训中心Task BrowserTo obtain information about aspecific task, click on the taskssummary line in the main targetbrowser.嵌入式培训专题微迪软件培训中心What is POSIX ?Originally, an IEEE committee convened to createa standard interface to UNIX for:VxWors supports almost all of the 1003.1b POSIX Real-time Extensions.Increased portability.Convenience.Context switch times are very fast.Text, data, and bss are stored in a common, global address space.The POSIX real-time extensions are based on implicitassumptions about the UNIX process model which do not always hold in VxWorks. In VxWorks,嵌入式培训专题微迪软件培训中心What does VxWorks support ?LibraryDescriptionaioPxLibAsynchornous I/OsemPxLibPOSIX SemaphoresmqPxLibPOSIX Message QueuesmmanPxLibPOSIX Memory ManagementschedPxLibPOSIX Scheduler InterfacesigLibPOSIX SignalstimerLib, clockLibPOSIX Timer/Clock InterfacedirLib Information嵌入式培训专题微迪软件培训中心Real-Time MultitaskingIntroductionTask BasicsTask ControlError StatusSystem Tasks嵌入式培训专题微迪软件培训中心Error StatusVxWorks里使用一个全局整型变量errno来描述错误信息程序执行过程中我们可以设置并调用一些函数例程来检测错误信息,并针对错误信息设置相应的错误号然后调用一些函数例程检测错误号,当程序执行异常时可以根据错误号发现相应的错误嵌入式培训专题微迪软件培训中心Errno and Context SwitchesAt each contextswitch, the kernelsaves and restoresthe value of errno.TCBerrorStatuserrno嵌入式培训专题微迪软件培训中心Setting ErrnoLowest level routine to detect an error sets errno and returns ERROR:STATUS myRoutine ().if (myNumFlurbishes = MAX_FLURBISH) errno = s_myLib_TOO_MANY_FLURBISHES;return (ERROR);pMem=malloc(sizeof(myStruct);if ( pMem= NULL) /* malloc() sets errno - dont redefine it */return (ERROR);.嵌入式培训专题微迪软件培训中心Examining ErrnoExamine errno to find out why a routine failed.if (reactorOk() = ERROR) switch (errno) case S_rctorLib_TEMP_DANGER_ZONE:startShutDown ();break;case S_rctorLib_TEMP_CRITICAL_ZONE:logMsg (“Run!”);break;case S_rctorLib_LEAK_POSSIBLE:checkVessel ();break;default:startEmergProc ();errno is only valid after an error occurs.嵌入式培训专题微迪软件培训中心Interpreting ErrnoVxWorks uses the 32-bit value errno as follows:Module numbers are defined in vwModNum.h.Each module defines its own error numbers in itsheader file.Module number 0x11 (define in vwModNum.hto be memLib) andError number 0x01 (defined in memLib.h to be“not enough memory”).For example, an errno of 0x110001 would be:moduleerror number31150嵌入式培训专题微迪软件培训中心Error MessagesVxWorks uses an error symbol table (statSymTbl)to convert error numbers to error messages.To print the error message for the current taskserror status to STD_ERR:- perror (“darn”)darn: S_netDrv_NO_SUCH_To print the error message associated with anerror number to the WindSh console :- printErrno (0x110001)S_memLib_NOT_ENOUGH_MEMORY嵌入式培训专题微迪软件培训中心User-Defined Error CodesTo get perror() to print your error messages:1. Modify vwModNum.h to reserve a module number:#define M_myLib(501 =0时,s.queue为空; s.value0时,s.value的绝对值为s.queue中等待进程的个数;嵌入式培训专题微迪软件培训中心PV原语(一) 对一个信号量变量可以进行两种原语操作:p操作和v操作,定义如下:procedurep(vars:samephore);s.value=s.value-1;if(s.value0)asleep(s.queue);procedurev(vars:samephore);s.value=s.value+1;if(s.value repeat (1, semGive, semId);2.- repeat (2, semGive, semId);3.- repeat (3, semGive, semId);嵌入式培训专题微迪软件培训中心释放信号量图示信号量可用?有任务阻塞?任务继续信号量变为可用任务继续信号量保持不变等待该信号量的任务队列的任务就绪,信号量不可用YesNoNoYes嵌入式培训专题微迪软件培训中心Synchronizing Multiple TasksSTATUS semFlush (semId)Unblocks all tasks waiting for semaphore.Does not affect the state of a semaphore.Useful for synchronizing actions of multiple tasks.嵌入式培训专题微迪软件培训中心SemaphoresOverviewBinary Semaphores and SynchronizationMutual Exclusion嵌入式培训专题微迪软件培训中心Mutual Exclusion ProblemSome resources may be left inconsistently if accessed bymore than one task simultaneously.Must obtain exclusive access to such a resource beforeusing it.We say a race condition exists.Mutual exclusion cannot be compromised by priority.Shared data structures.Shared files.Shared hardware devices.Very difficult to detect during testing.If exclusive access is not obtained, then the order inwhich tasks execute affects correctness.嵌入式培训专题微迪软件培训中心Race Condition ExampletTask1tTask21char myBuf(BU_SIZE);/* store data here */2int myBufIndex = -1;/* Index of last data */34myBufPut (char ch)56myBufIndex+;7myBuf myBufIndex = ch;8myBufIndex+myBufIndex+myBuf myBufIndex = bmyBuf myBufIndex = a.嵌入式培训专题微迪软件培训中心Solution OverviewCreate a mutual exclusion semaphore to guard the resource.Call semTake() before accessing the resource; call semGive()when done.semTake() will block until the semaphore (and hence the resource) becomes available.semGive() releases the semaphore (and hence access to the resource).嵌入式培训专题微迪软件培训中心Creating Mutual Exclusion SemaphoresSEM_ID semMCreate (options)options can be :queue specificationSEM_Q_FIFO orSEM_Q_PRIORITYdeletion safetySEM_DELETE_SAFEpriority inheritanceSEM_INVERSION_SAFE Initial state of semaphore is available.嵌入式培训专题微迪软件培训中心Mutex OwnershipA task which takes a mutex semaphore “owns” it, so that no other task can give this semaphore.Mutex semaphores can be taken recursively.The task which owns the semaphore may take it more than once.Must be given same number of times as taken before it willbe released.Mutual exclusion semaphores cannot be used in an interruptservice routine.嵌入式培训专题微迪软件培训中心Taking a Mutex Semaphoreowner of Semaphore?task pends untilsem is given or timeoutanother tasktask continuessemTake()returns OKTask becomes ownerno onetask continues semTake() returns OKtask ownershipcount incrementedthis task嵌入式培训专题微迪软件培训中心Giving a Mutex Semaphoreownership count?semaphore madeavailableonesemGive()returns ERRORnot ownergreater than onetasks pended?nodecrement ownershipcounttask at head ofqueue is madeready, becomesowneryes嵌入式培训专题微迪软件培训中心Code Example - Solution1 #include ”vxWorks.h”2 #include ” semLib.h”34 LOCAL char myBufBUF_SIZE; /* Store data here */5 LOCAL int myBufIndex = -1; /* Index of last data */6 LOCAL SEM_ID mySemId;78 void myBufInit ( )9 10mySemID = semNCreate (SEM_Q_PRIORITY |11SEM_INVERSION_SAFE |12SEM_DELETE_SAFE );131415 void myBufPut (char ch)16 17semTake(mySemId, WAIT_OREVER);18myBufIndex+;19myBufmyBufIndex = ch;20semGIve (mySemId);21嵌入式培训专题微迪软件培训中心Deletion SafetyDeleting a task which owns a semaphore can be catastrophic.data structures left inconsistent.semaphore left permanently unavailable.The deletion safety option prevents a task from being deleted while it owns the semaphore.Enabled for mutex semaphores by specifying the SEM_DELETE_SAFE option during semMCreate( ).嵌入式培训专题微迪软件培训中心安全删除wind内核提供防止任务被意外删除的机制。通常,一个执行在临界区或访问临界资源的任务要被特别保护。我们设想下面的情况:一个任务获得一些数据结构的互斥访问权,当它正在临界区内执行时被另一个任务删除。由于任务无法完成对临界区的操作,该数据结构可能还处于被破坏或不一致的状态。而且,假想任务没有机会释放该资源,那麽现在其他任何任务现在就不能获得该资源,资源被冻结了。任何要删除或终止一个设定了删除保护的任务的任务将被阻塞。当被保护的任务完成临界区操作以后,它将取消删除保护以使自己可以被删除,从而解阻塞删除任务。嵌入式培训专题微迪软件培训中心Priority InversionHigh PriorityMedium PriorityLow PriorityPendedtHigh unblockstMediumunblocks semTake( )PendedPendedReadysemTake( )CriticalRegionReadytime嵌入式培训专题微迪软件培训中心优先级逆转/优先级继承优先级逆转发生在一个高优先级的任务被强制等待一段不确定的时间以便一个较低优先级的任务完成执行。T1,T2和T3分别是高、中、低优先级的任务。T3通过拥有信号量而获得相关的资源。当T1抢占T3,为竞争使用该资源而请求相同的信号量的时候,它被阻塞。如果我们假设T1仅被阻塞到T3使用完该资源为止,情况并不是很糟。毕竟资源是不可被抢占的。然而,低优先级的任务并不能避免被中优先级的任务抢占,一个抢占的任务如T2将阻止T3完成对资源的操作。这种情况可能会持续阻塞T1等待一段不可确定的时间。这种情况成为优先级逆转,因为尽管系统是基于优先级的调度,但却使一个高优先级的任务等待一个低优先级的任务完成执行。互斥信号量有一个选项允许实现优先级继承的算法。优先级继承通过在T1被阻塞期间提升T3的优先级到T1解决了优先级逆转引起的问题。这防止了T3,间接地防止T1,被T2抢占。通俗地说,优先级继承协议使一个拥有资源的任务以等待该资源的任务中优先级最高的任务的优先级执行。当执行完成,任务释放该资源并返回到它正常的或标准的优先级。因此,继承优先级的任务避免了被任何中间优先级的任务抢占。嵌入式培训专题微迪软件培训中心Priority InheritancePriority inheritance algorithm solves priority inversion problem.Task owning a mutex semaphore is elevated to priority of highest priority task waiting for that semaphore.Enabled on mutex semaphore by specifying the SEM_INVERSION_SAFE option during semMCreat( ).Must also specify SEM_Q_PRIORITY (SEM_Q_FIFO is incompatible with SEM_INVERSION_SAFE). 嵌入式培训专题微迪软件培训中心Priority Inversion SafetyHigh PriorityMedium PriorityLow PriorityPendedtHigh unblockstMediumunblocks semTake( )PendedPendReadysemTake( )CriticalRegionReadytimesemGive( )嵌入式培训专题微迪软件培训中心Avoiding MistakesIt is easy to miuse mutex semaphores, since you must protect all accesses to the resource.To prevent such a mistakeWrite a library of routines to access the resource.Initialization routine creates the semaphore.Routines in this library obtain exclusive access by callingsemGIve( ) and semTake( ).All uses of the resource are through this library.嵌入式培训专题微迪软件培训中心Caveat - DeadlocksA deadlock is a race condition associated with the taking of multiplemutex semaphores.Very difficult to detect during testing.INT 6INT 3tExcTasktLogTasktEvtTasktWdbTasktNetTasktTaskHitTaskLowtPortmapdtWvSvcu0idlesemTake(semId1,-1)semTake(semId1,-1)semTake(semId2,-1)semTake(semId2,-1)嵌入式培训专题微迪软件培训中心Other CaveatsMutual exclusion semaphores can not be used at interrupt time.This issue will be discussed later in the chapter.Keep the critical region (code between semTake( ) and semGive( ) short.嵌入式培训专题微迪软件培训中心Common RoutinesAdditional semaphore routines :semDelete( ) Destroy the semaphore.semTake( ) calls for all tasks pended on the semaphore return ERROR. show( ) Display semaphoreinformation.嵌入式培训专题微迪软件培训中心Semaphore BrowserTo inspect the properties of a specific semaphore insert the semaphore ID in the Browsers Show box, and click on Show. AttributesBlocked Tasks嵌入式培训专题微迪软件培训中心Locking out PreemptionWhen doing something quick frequently, it is preferable to lock the scheduler instead of using a Mutex semaphore.Call taskLock( ) to disable scheduler.Call taskUnLock( ) to reenable scheduler.Does not disable interrupts.If the task blocks, the scheduler is reenabled.Prevents all other tasks from running, not just the tasks contendingfor the resource.嵌入式培训专题微迪软件培训中心ISRs and Mutual Exclusion ISRs cant use Mutex semaphores.Task sharing a resource with an ISR may need to disable interrupts.To disable / re-enable interrupts :int intLock( )voidintUnLock(lockKey)lockKey is return value from intLock( ).Keep interrupt lock-out time short (e.g., long enough to set a flag) !Does not disable scheduler.嵌入式培训专题微迪软件培训中心计数器信号量计数器信号量是实现任务同步的和互斥的另一种方法。计数器信号量出了象二进制信号量那样工作外,他还保持了对信号量释放次数的跟踪。信号量每次释放,计数器加一,每次获取,计数器减一。当计数器减到0,试图获取该信号量的任务被阻塞。正如二进制信号量,当信号量释放时,如果有任务阻塞在该信号量阻塞队列上,那么任务解除阻塞。然而,不象二进制信号量,如果信号量释放时,没有任务阻塞在该信号量阻塞队列上,那么计数器加一。计数器信号量适用于保护拥有多个拷贝的资源。嵌入式培训专题微迪软件培训中心SummaryBinaryMutual ExclusionsemBCreatesemMCreatesemDeletesemTake, semGiveshow嵌入式培训专题微迪软件培训中心SummaryBinary semaphores allow tasks to pend until some event occurs.Create a binary semaphore for the given event.Tasks waiting for the event blocks on a semTake( ).Task or ISR detecting the event calls semGive( ) or semFlush( ).Caveat : if the event repeats too quickly, information may belost嵌入式培训专题微迪软件培训中心SummaryMutual Exclusion Semaphores are appropriate for obtaining access to a resource.Create a mutual exclusion semaphore to guard the resource.Mutex semaphores have owners.Caveats :Before accessing the resource, call semTake( ).To release the resource, call semGive( ).Keep critical regions short.Make all accesses to the resource through a library of routines.Cant be used at interrupt time. Deadlocks.嵌入式培训专题微迪软件培训中心SummarytaskLock( ) / taskUnLock( ) :Prevents other tasks from running.Use when doing something quick frequently.Caveat : keep critical region short.intLock( ) / intUnLock( ) :Disable interrupts.Use to protect resources used by tasks and interrupt service routines.Caveat : keep critical region short.嵌入式培训专题微迪软件培训中心NowHave a rest嵌入式培训专题微迪软件培训中心Chapter 7IntertaskCommunication嵌入式培训专题微迪软件培训中心Intertask CommunicationIntroductionShared MemoryMessage QueuesPipes嵌入式培训专题微迪软件培训中心OverviewMultitasking systems need communication between tasks. Data / information being shared.Mechanism to inform task that data is available to read or write.Mechanism to prevent tasks from interfering with eachother (e.g., if there are two writers).Two common methods :Intertask communication made up of three components :Shared memory.Message passing.嵌入式培训专题微迪软件培训中心Shared MemorytTaskAtTaskBfooLib.cLOCAL SEM_ID fooSem;LOCAL FOO_BUF fooBuffer;fooSet ( )fooGet ( ).嵌入式培训专题微迪软件培训中心Message Passing QueuesVxWorks pipes and message queues are used for passingmessages between tasks.FIFO buffer of messagesSynchronizationMore robust than shared data.Both pipes and message queues provide : taskAtaskBCan be used from task to task, or from ISR to task.Mutual Exclusion嵌入式培训专题微迪软件培训中心Intertask CommunicationMessage QueuesPipesShared MemoryIntroduction嵌入式培训专题微迪软件培训中心OverviewAll tasks reside in a common address space.Write a library of routines to access these global orstatic data-structures.All tasks which use these routines manipulate thesame physical memory.VxWorks provides libraries to manipulate common datastructures such as linked lists and ring buffers.User-defined data structures may be used for Intertaskcommunication :Semaphores may be used to provide mutual exlusion and synchronization.嵌入式培训专题微迪软件培训中心Linked ListslstLib contains routines to manipulate doubly linked lists.Mutual exclusion and synchronization are not built-in.NULLNULLList DescriptorUser node 1User node 2NODE NODE User specific dataUser specific dataheadtailcount = 2嵌入式培训专题微迪软件培训中心Ring BuffersrngLib contains routines to manipulate ring buffers (FIFO data streams)Mutual exclusion is not required if there is only one readerand one writer. Otherwise, user must provide.readerwriterSynchronization is not built-in.嵌入式培训专题微迪软件培训中心Intertask CommunicationShared MemoryPipesIntroductionMessage Queues嵌入式培训专题微迪软件培训中心Message QueuesUsed for intertask communication within one CPU.Synchronization.Task control is built-in :FIFO buffer of variable length messages.Mutual Exclusion.嵌入式培训专题微迪软件培训中心Creating a Message Queue Returns an id used to reference this message queue or NULL on error. MSG_Q_ID msgQCreate (maxMsgs, maxMsgLength, options)maxMsgs Maximum number of messages on the queue.maxMsgLength Maximum size in bytes of a message on the queue.options Queue type for pended tasks (MSG_Q_FIFO or MSG_Q_PRIORITY)嵌入式培训专题微迪软件培训中心Sending Messages STATUS msgQSend (msgQId, buffer, nBytes, timeout, priority)msgQId MSG_Q_ID returned by msgQCreate( ).buffer Address of data to put on queue.nBytes Number of bytes to put on queue.timeout Maximum time to wait (if queue is full). Values can be tick count, WAIT_FOREVER or NO_WAIT.priority “Priority“ of message to put on queue. If MSG_PRI_URGENT, message put at head of queue. If MSG_PRI_NORMAL message put at end of queue.嵌入式培训专题微迪软件培训中心Message Sending Exampleschar bufBUFSIZE;status = msgQSend (msgQId, buf, sizeof(buf), WAIT_FOREVER, MSG_PRI_NORMAL);status = msgQSend (msgQId, buf, sizeof(buf), NO_WAIT, MSG_PRI_URGENT);嵌入式培训专题微迪软件培训中心Receiving Messages int msgQReceive (msgQId, buffer, maxNBytes,timeout)msgQId Returned from msgQCreate( ). buffer Address to store message.MaxNBytes Maximum size of message to read from queue.timeout Maximum time to wait (if no message available). Values can be clock ticks, WAIT_FOREVER or NO_WAIT.Returns number of bytes read on success, ERROR on timeout orinvalid msgQId.Unread bytes in a message are lost.嵌入式培训专题微迪软件培训中心Deleting a Message Queue STATUS msgQDelete (msgQId)Deletes message queue.Tasks pended on queue will be unpended; their msgQSend( ) or msgQReceive( ) calls return ERROR. These tasks errno values will be set to S_objLib_OBJ_DELETED.嵌入式培训专题微迪软件培训中心Gathering Data with Message QueuesTo capture data quickly for future examination :poll taskor ISRconsumerHave a poll task or ISR place device data in a message queue.Input devicedevicdatadevicedatadevicdatadevicedataHave a lower priority task read data from this queue for processing.GO TO APPENDIX A3嵌入式培训专题微迪软件培训中心Client-Server model with Message QueuesServer Taskthis isa mesthis isa messthis isa mesthis is amessageClientClient嵌入式培训专题微迪软件培训中心Client-Server VariationsThe client needs a reply from the server ?How would the previous code example change if :We wish to simultaneously service several requests ?(we may wish to do this if there are multiple clients, and this service requires blocking while I / O completes).嵌入式培训专题微迪软件培训中心Message - Queue BrowserTo examine a message queue, enter the message queue ID in the Browsers Show box, and click on Show.mv152-externalmekong: Mempart Ox3ff988Attributes options =PRIORITY maxMsgs =10 maxLength=100 sendTimeouts=0 recvTimeouts=0Receivers BlockedSenders BlockedMessages Queued 0address=0x3ffdb4length=0x7value=68 65 66 6f 0a*hello. 1address=0x3ffd48length=0x4value=68 69 0a 0d*hi.嵌入式培训专题微迪软件培训中心POSIX消息队列POSIX消息对列由mqPxLib库提供,除了POSIX消息队列提供命名队列和消息具有一定范围的优先级之外,提供的这些函数与Wind消息队列类似。在使用POSIX消息队列前,系统初始化代码必须调用mqPxLibInit()进行初始化。也可以在配置VxWorks时进行配置。通知任务一个消息队列在等待任务可以调用mq_notify()函数要求系统当有一个消息进入一个空的消息队列时通知它。这样可以避免任务阻塞或轮询等待一个消息。mq_notify()以消息进入空队列时系统发给任务的信号(signal)作为参数。这种机制只对当前状态为空的消息队列有效,如果消息队列中已有可用消息,当有更多消息到达时,通知不会发生。嵌入式培训专题微迪软件培训中心POSIX和Wind消息队列比较特征Wind消息POSIX消息对列消息优先级132阻塞的任务队列FIFO或基于优先级基于优先级不带超时的接收可选不可用任务通知不可用可选关闭/解链语法无有嵌入式培训专题微迪软件培训中心Intertask CommunicationIntroductionShared MemoryMessage QueuesPipes嵌入式培训专题微迪软件培训中心Pipesthis isa mesthis isa messthis isa mesthis is amessageVirtual I/O device managed by pipeDrv.Built on top of message queues.Standard I/O system interface (read / write).Similar to named pipes in UNIX. (UNIX Host)嵌入式培训专题微迪软件培训中心Creating a PipeSTATUS pipeDevCreate (name, nMessages, nBytes)nameName of pipe device, by convention use“/pipe/yourName”.nMessagesMaximum number of messages in the pipe.nBytes Maximum size in bytes of each message.Returns OK on success, otherwise ERROR.嵌入式培训专题微迪软件培训中心Example Pipe Creation-pipeDevCreate (“/pipe/myPipe”,10,100)value = 0 = 0x0-devs drvname0/null1/tyCo/01/tyCo/14columbia:2/pipe/myPipe嵌入式培训专题微迪软件培训中心Reading and Writing to a Pipethis isa mesthis isa messthis isa mesthis is amessageTo access an existing pipe, first open it with open( ).To read from the pipe use read( ).To write to the pipe use write( ).fd = open (“/pipe/myPipe”, O_RDWR, 0);write (fd, msg, len);read (fd, msg, len);嵌入式培训专题微迪软件培训中心Message Queues vs. PipesMessage Queue advantages :Timeouts capability.Message prioritization.Faster.Pipe advantages :Use standard I / O interface i.e., open ( ), close ( ), read ( ), write( ), etc.Can perform redirection via ioTaskStdSet( ) (see I/O chapter)show( ).Can be deleted. can be used in select ( ).嵌入式培训专题微迪软件培训中心SummaryShared MemoryOften used in conjunction with semaphores.lstLib and rngLib can help.Message queues :msgQCreate( )msgQSend( )msgQReceive( )PipespipeDevCreate( )Access pipe via returned from open( ).Use write( ) / read( ) to send / receive messages from a pipe. 嵌入式培训专题微迪软件培训中心Chapter 8Memory嵌入式培训专题微迪软件培训中心Memory LayoutLOCAL_MEM_LOCAL_ADRSRAM_LOW-ADRSFREE_RAM_ADRSVxWorksSYSTEMMEMORYPOOLsysMemTop( )WDB_POOL_SIZEUSER_RESERVED_MEMsysPhysMemTop( )嵌入式培训专题微迪软件培训中心Target Server Memory PoolA pool of memory on the target reserved for use by the Tornado tools :Dynamic loading of object modules.Spawning task from WindSh or CrossWind.Creation of variables from WindSh.The initial size of the target server memory pool is configured by WDB_POOL_SIZE. The default is 1 / 16 of sysMemTop( ) - FREE_RAM_ADRS.The target server manages the pool, keeping overhead such as block lists on the host.Additional memory is silently allocated from the system memory pool,if needed. 嵌入式培训专题微迪软件培训中心System Memory PoolInitialized at system startup.Used for dynamic memory allocation in programs :malloc( ).Creating tasks (stack and TCB).Can modify USER_RESERVED_MEM to reserve memory for application-specific use.May need to modify sysPhysMemTop( ) (or just LOCAL_MEM_SIZE)when adding memory to your board.To add off board memory :void memAddToPool (pPool, poolSize)pPool must be the local address of the memory.VxWorks memory requests.嵌入式培训专题微迪软件培训中心Allocating / Releasing MemoryUses first-fit algorithm.To dynamically allocate memory :void *malloc (nBytes)Returns a pointer to the newly allocated memory or NULL on error.Free memory is stored in a linked list.Some (small) overhead for each malloc( ).To release allocated memory :void free (ptr)Adjacent blocks are coalesced.嵌入式培训专题微迪软件培训中心Debugging OptionsDefault free( ) debugging :Default malloc( ) debugging : If request too large, log an error message.Check block for consistency.If corrupted: suspend task, log error message.Can change default debugging options with :void memOptionsSet (options)Options can be :+ MEM_ALLOC_ERROR_LOG_FLAG- MEM_ALLOC_ERROR_SUSPEND_FLAG+ MEM_BLOCK_CHECK+ MEM_BLOCK_ERROR_LOG_FLAG+ MEM_BLOCK_ERROR_SUSPEND_FLAG嵌入式培训专题微迪软件培训中心Examining MemoryEnter the memory partition ID in the Show box.Use the browser.Free Listmv152-externalmekong: Mempart OxTotal bytes=3870840Allocated blocks=86 bytes=467224Free blocks=7 bytes=3403584Cummulative blocks=88 bytes=467832Free List 0addr=0x3fd8f8size=9604 1addr=0x4ef90size=3355432 嵌入式培训专题微迪软件培训中心Additional System Memory Management Routines void *calloc(nElems, size )Allocate zeroed memory for an array.void *realloc(ptr,newSize)Resize an allocated block. The block may be moved.int memFindMax( )Returns the size of the largest free blockin system memory.嵌入式培训专题微迪软件培训中心Fine TuningFor fast, deterministic allocation of fixed size buffers,use message queues instead of malloc( ).message queueptrptrptr. . . .bufGet( )bufReturn( ). . . .buffers嵌入式培训专题微迪软件培训中心Generic Partition ManagerVxWorks provides low level routines to create andmanipulate alternate memory pools.High level routines like malloc( ) and free( ) call theselower level routines, specifying the system memory pool.Application may use alternate memory partitions to reduce fragmentation.Applications may use alternate memory partitions to manage memory with different properties.嵌入式培训专题微迪软件培训中心Creating a memory PartitionReturns a partition id (PART_ID) or NULL or error.The memory for this partition (pPool) may be taken from :PART_ID memPartCreate (pPool, size)pPoolPointer to memory for this partitionsizeSize of memory partition in bytes.A separate memory board.A block allocated from the system memory partition.The top of the CPU boards RAM.嵌入式培训专题微迪软件培训中心Managing Memory PartitionsSystem partition management routines call routines listed below, specifying the PART_ID as memSysPartId. GenericSystem Memory Pool memPartAlloc( )malloc( ) memPartFree( )free( ) memPartShow( )memShow( ) memPartAddToPool( )memAddToPool( ) memPartOptionsSet( )memOptionsSet( ) memPartRealloc( )realloc( ) memPartFindMax( )memFindMax( )嵌入式培训专题微迪软件培训中心Example Creating a Memory Partition-partId=memPartCreate(pMemory, 100000)new symbol “partId” added to symbl table.partId = 0x23ff318 : value = 37745448 = 0x23ff328 = partId + 0x10-ptr=memPartAlloc(partId, 200)new symbol “ptr” added to symbl table.ptr = 0x23ff2ec : value = 37652632 = 0x23e8898-show partIdstatusbytesblocksaveblockmaxblockcurrent free9977619977699776 alloc2081208 -cumulative alloc2081208 -嵌入式培训专题微迪软件培训中心SummaryTo configure the system memory pool :Standard C routines used for dynamic memory allocation.Modify sysPhysMemTop( )Modify USER_RESERVED_RAMModify memAddToPool( )For fast, deterministic allocation of fixed size buffers, usemessage queues instead of malloc( ).Create separate memory partition for off-board memory, or to help reduce fragmentation.嵌入式培训专题微迪软件培训中心Chapter 9Exceptions,Interrupts andTimers嵌入式培训专题微迪软件培训中心Exceptions, Interrupts and TimersException Handling and SignalsInterrupt Service RoutinesTimers嵌入式培训专题微迪软件培训中心信号(Signals)(一)VxWorks支持软件信号功能。信号可以异步改变任务控制流。任何任务和ISR都可以向指定的任务发信号。获得信号的任务立即挂起当前的执行,在下次调度它运行时转而执行指定的信号处理程序。信号处理程序在信号接收任务的上下文中执行,使用该任务的堆栈。在任务阻塞时,信号处理程序仍可被唤醒信号机制适合于错误和异常处理。通常,信号处理程序可以作为中断处理程序看待。任何可能导致调用程序阻塞的函数均不能在信号处理程序中调用。Wind内核支持两种类型的信号接口UNIXBSD风格的信号POSIX兼容的信号嵌入式培训专题微迪软件培训中心信号(Signals)(二)信号在很多方面跟硬件中断相似。基本信号接口提供了31个不同的信号。调用sigvec()或sigaction()可为信号指定一个信号处理程序。这与调用intConnect()为中断指定一个中断处理程序(ISR)相似。可以调用kill()将信号发送给任务,这类似于于中断发生。函数sigsetmask()和sigblock或sigprocmask()可以用来象屏蔽中断那样屏蔽信号。使用sigInit()初始化信号函数库,使得基本信号函数可用嵌入式培训专题微迪软件培训中心基本信号接口函数POSIX1003.1b兼容调用UNIXBSD兼容调用说明signal()signal()指定信号的处理程序kill()kill()向任务发送一个信号raise()N/A发信号给自身sigaction()sigvec()检测或设置信号处理程序sigsuspend()pause()挂起任务直到信号提交sigpending()N/A取回一组提交阻塞的信号.设置信号屏蔽.嵌入式培训专题微迪软件培训中心几个函数原型intsigvec检测或设置信号处理程序(intsig,/*于处理程序相联系的信号*/conststructsigvec*pVec,/*新的处理程序信息*/structsigvec*pOvec/*旧的处理程序信息*/)intkill向任务发送一个信号(inttid,/*接收信号的任务号*/intsigno/*发送给任务的信号*/)sigqueue提供与kill()等价的功能(inttid,/*接收信号的任务*/intsigno,/*发送给任务的信号*/constunionsigvalvalue/*隋信号发送的值*/)嵌入式培训专题微迪软件培训中心SignalsnormalCode().mySignalHandler().mySignal嵌入式培训专题微迪软件培训中心UNIX: UNIX vs. VxWorks SIgnalsSignal is ignored if no handler is installed Automatic function restarting Can install a handler to catch SIGKILL.No SIGCHLD, SIGPIPE, or SIGURG.taskDelay() sets errno = EINTR and returns ERRORif interrupted by a signal.Pend QReady QSignalRun signal-handlersemTake(.OrgDelay)嵌入式培训专题微迪软件培训中心CaveatsSIgLib contains both POSIX and BSD UNIX interfaces. Do not mix them.Signals are not recommended for general intertask communication. A signal :May be handled at too high a priority if it arrives during a priority inheritence.Disrupts a tasks normal execution order.(It is better to create two tasks, than multiplex processing in one task via signals.)Can cause reentrancy problems between a task running its signal handler and the same task running its normal code.Can be used to tell a task to shut itself down.嵌入式培训专题微迪软件培训中心Registering a Signal Handlersignal ( signo.handler)signo Signal number.handler Routine to invoke when signal arrives (or SIG_IGN to ignore signal).Returns the previously installed signal handler,or SIG_ERR.To register a signal handlerThe signal handler should be declared as : void sigHandler (int sig) ; /* signal number */:嵌入式培训专题微迪软件培训中心Signals and ExceptionsHardware exceptions include bus error, address error,divide by zero, floating point overflow, etc.Some signals correspond to exceptions (e.g., SIGSEGVcorresponds to a bus error on a 68K; SIGFPE correpondsto various arithmetic exceptions).Task has SIGSEGVsignal handler installed ?raise signalSuspend taskLog error messagemyCode().bus error嵌入式培训专题微迪软件培训中心The Signal HandlerException signal handlers typically call :The offending task will be suspended.A message will be logged to the console.exit( ) to terminate the task, or taskRestart( ) to restart the task, orlongjmp( ) to resume execution at location saved by setjmp( )If an exception signal handler returns :嵌入式培训专题微迪软件培训中心Exceptions, Interrupts and TimersException Handling and SignalsInterrupt Service RoutinesTimers嵌入式培训专题微迪软件培训中心中断硬件中断处理是实时系统设计的最重要、最关键的问题。为了获得尽可能快的中断响应时间,VxWorks的中断处理程序运行在特定的上下文中(在所有任务上下文之外)。因此,中断处理不会涉及任何任务上下文的交换。VxWorks提供函数intConnect(),该函数允许将指定的C函数与任意中断相联系。STATUSintConnect(VOIDFUNCPTR*vector,/*要联系的中断向量*/VOIDFUNCPTR*routine,/*中断发生时要调用的函数*/intparameter/*传递给中断处理函数的参数*/)该函数将指定的C函数routine与指定的中断向量vector相联系,函数的地址存储在这个中断向量里。嵌入式培训专题微迪软件培训中心中断函数调用描述intConnect()设置中断处理程序intContext()如果是在中断级调用,返回真intCount()得到当前的中断嵌套深度intLevelSet()设置处理器中断屏蔽级intLock()禁止中断intUnlock()重新允许中断intVecBaseSet()设置向量基地址intVecBaseGet()得到向量基地址intVecSet()设置一个异常向量intVecGet()得到一个异常向量嵌入式培训专题微迪软件培训中心中断处理过程事件中断切换到中断堆栈、保存程序计数器和寄存器调用inConnect指定的中断处理程序处理该中断恢复寄存器、返回中断向量表执行顺序1255嵌入式培训专题微迪软件培训中心中断堆栈如果体系结构允许,所有的ISRs使用的中断堆栈。堆栈的定位和初始化由系统在启动时根据指定的配置参数完成。堆栈必须足够大,以保证能够处理系统最坏情形下的中断嵌套。体系结构不允许使用一个特定的堆栈。在这种结构中,ISRs使用中断任务的堆栈。对于这种结构的目标机,应用必须创建足够大的堆栈空间。开发过程中,可以调用checkStack()函数察看一个任务堆栈的使用或整个系统堆栈的使用情况。嵌入式培训专题微迪软件培训中心ISR的特殊限制基本约束:必须不能调用可能引起调用阻塞的函数。在中断服务程序中不能试图获取一个信号量,因为信号量可能不可用。中断服务程序里面不能使用malloc和free,因为他们都需要获取一个信号量。中断服务程序也不能通过VxWorks驱动执行I/O操作。多数设备驱动由于可能需要等待设备而引起调用者阻塞,因此需要任务上下文交换。VxWorks支持纪录功能,任务可以向系统输出平台打印文本信息。logMsg()嵌入式培训专题微迪软件培训中心InterruptsAn user-defined routine can be installed to execute when an interrupt arrives. Interrupts allow devices to notify the CPU that some eventhas occured.This routine runs at interrupt time. It is not a task.On-board timers are a common source of interrupts. Using them requires understanding interrupts.嵌入式培训专题微迪软件培训中心Device DriversAre beyond the scope of this courseUse interrupts for asynchronous I/OFor more information:intArchLib To install user defined ISRs.Board Support Package Board specific interrupt handling.Programmers Guide Architecture specific interrupt info.Tornado Users Guide System mode debugging info.BSP Porting Kit Optional product for writing BSPs.VxWorks Device Driver Workshop Write VMEbus and VxWorks standard device drivers. 嵌入式培训专题微迪软件培训中心Handling an interrupthander InterruptVector TableInterrupt Service Routine(ISR)User ISRhandler :save registerscall routinerestore registersRETVector numberhardwaremyISR().嵌入式培训专题微迪软件培训中心Interrupts and PrioritiesinterruptinterruptinterruptTaskTaskTaskAbsolute system -Wide PriorityInterrupt Level(Hard Wired)Execution Order Controlled by HardwareExecution Order Controlled by KernelTask Priority(Programmable).嵌入式培训专题微迪软件培训中心Interrupt StackInterrupt stack is allocated at system start-up.Most architectures use a single dedicated interrupt stackMust be large enough for worst-case nestingThe Interrupt stack size is contolled by the macro INT_STACK_SIZE in config All.hint level 2int level 3 int level 5Interrupt Stack嵌入式培训专题微迪软件培训中心ISR RestrictionsNo tasks can run until ISR has completedThe Programmers guide gives a list of routines which are callable at interrupt time ISRs are restricted from using some VxWorks facilities. In particular they cant block : Cant call semTake( ).Cant call malloc( ) (uses semaphores). Cant call I/O system routines (e.g.,printf( ) ).嵌入式培训专题微迪软件培训中心ISR GuidelinesKeep your ISRs short, because ISRs :Avoid using floating-point operations in an ISR. Try to off-load as much work as possible to some task:Delay lower and equal priority interrupts.Can be hard to debugDelay all tasksThey may be slow.User must call fppSave( ) and fppRestore( ).Work which is longer in duration.Work which is less critical.嵌入式培训专题微迪软件培训中心Typical ISR Read and writes memory-mapped I/O registers.Communicates information to a task by :Writing to memoryMaking non-blocking writes to a message queue.Giving a binary semaphore.嵌入式培训专题微迪软件培训中心Debugging ISRs To log diagnostic information to the console at interrupt time.Similar to printf( ), with the following caveats :Arguments must be 4 bytes.Format string plus 6 additional arguments.WDB agentEmulatorlogMsg(foo = %dn, foo, 0, 0, 0, 0, 0, 0);Sends a request to tLogTask to do a printf( ) for usUse a debugging strategy which provides system level debugging.嵌入式培训专题微迪软件培训中心Exceptions at Interrupts TimeLogged messages will not be printed.Causes a trap to the boot ROMs.Boot ROM program will display an exception description on reboot.An exception occuring in an ISR will generate a warm reboot.Can use sprintf( ) to print diagnostic information to memory notoverwritten on reboot, if necessary.嵌入式培训专题微迪软件培训中心Exceptions, Interrupts and TimersException Handling and SignalsInterrupt Service RoutinesTimers嵌入式培训专题微迪软件培训中心TimersAllows user-defined routines to be executed at periodic intervalswhich is useful for :Polling hardware.checking for system errors.Aborting an untimely operation.VxWorks supplies a generic interface to manipulate two timers : On board timers interrupts the CPU periodically.System clock.Auxiliary clock ( if available).嵌入式培训专题微迪软件培训中心System ClockIncrements the tick count (use tickGet() to examine thecount ).Updates the delatys and timeouts.Checks for round robin rescheduling.Default clock rate is 60Hz.System clock ISR performs book-keeping:sysClkRateSet (freq)Sets the clock rate .int sysClkRateGet()Returns the clock ratesysClkRateSet( ) should only be called at systems startup.These operations may cause a reschedule.嵌入式培训专题微迪软件培训中心Watchdog TimersAllows a C rioutine to be connected to a specified time delay.User interface to the system clock.Upon expiration of delay, connected routine runs.As part of system clock ISR Subject to ISR restriction.嵌入式培训专题微迪软件培训中心Creating watchdog TimersTo start (or restart) a watchdog timer :To ceate a watchdog timer : WDOG_ID wdCreate()Returns watchdog id, or NULL on error.Status wdSDtart (wdId,delay,pRoutine,parameter)wdIdWatchdog id, returned from wdCreate().delayNumber of ticks to delaypRoutineRoutine to call when delay has expired parameterArgument to pass to routine嵌入式培训专题微迪软件培训中心Using Watchdog To use watchdogs for periodic code execution :The doit( ) routine might :Poll some hardware device.Unblock some task.wdId = wdCreate();wdStart ( wdId, DELAY_PERIOD, myWdTsr, 0 )void myWdIsr ( int param) doit(param); wdStart ( wdId, DELAY_PERIOD, mywdIsr, 0); Check if system errors are present.嵌入式培训专题微迪软件培训中心Missed DeadlinesTo recover from a missed deadline :WDOG_ID wdId;void foo(void) wdId = wdCreate( ); /* Must finish each cycle in under 10 seconds */ FOREVER wdStart ( wdId, Delay_10_SEC, fooISR, 0); fooDoWork () ; void fooISR (int param) /* Handle missed deadline */ . 嵌入式培训专题微迪软件培训中心Stopping Watchdogs To cancel a previously started watchdog :To deallocate a watchdog timer ( and cancel any previous start) : STATUS wdCancel ( wdId)STATUS wdDelete ( wdId)嵌入式培训专题微迪软件培训中心Watchdog BrowserAfter creating, but prior to activating the watchdog, the Browser provides minimal information : After activating the watchdog, more useful information is provided : 嵌入式培训专题微迪软件培训中心Polling IssuesCan poll at task time or interrupt time.To poll at task time, two options :Interrupt time polling is more reliable .Task time polling has a smaller impact on the rst of the system.taskDelay( ) - fastest, but may drift.wdStart( ) + semGive( ) - more robust.嵌入式培训专题微迪软件培训中心Polling CaveatsThe following code is accurate only if the system clock rate is a multiple of 15hz : Do not set the system clock rate too hiogh because there is OS overhead in each clock tick.void myWdISR () pollMyDevice() ; wdStart (myWdId, sysClkRateGet )/15, 0) ;Use auxillary clock to poll at high speeds.嵌入式培训专题微迪软件培训中心Auxillary ClockFor high speed polling, use the auxillary clock.Precludes using spy, which also uses the auxillary clock.Some routines to manipulate auxillary clock :sysAuxClkConnect( )Connect ISR to Aux clocksysAuxClkRateSet( )Set Aux clock rate.sysAuxClkEnable( ) Start Aux clock .sysAuxClkDIsable( ) Stop Aux clock嵌入式培训专题微迪软件培训中心SummaryUsing signals for exception handling :Interrupt Service routines have a limited context : signal( )exit( )No blocking.No I/O system callstaskRestart( )longjmp()嵌入式培训专题微迪软件培训中心SummaryPolling with timers : aux clockwd timertaskDelay, orwd timer + semGiveInterrupt timetasktimelow speedhigh speed嵌入式培训专题微迪软件培训中心I/O SystemChapter10嵌入式培训专题微迪软件培训中心Chapter10I/O System嵌入式培训专题微迪软件培训中心I/O SystemIntroductionBasic I/OSelect( )Standard I/O嵌入式培训专题微迪软件培训中心I/O System InterfaceApplicationI/O SystemxxDriverDevicecreat( )open( )close( )read( )write( )ioctl( )xxCreat( )xxOpen( )xxClose( )xxread( )xxWrite( )xxIoctl( )嵌入式培训专题微迪软件培训中心I/O System BenefitsSimple interfaceStandard (portable) interfaceSelect( )I/O redirection嵌入式培训专题微迪软件培训中心Driver InstallationMust call driverss xxDrv( ) routine before using athird party driver.A device driver must be installed in the I/O system.Then VxWorks can call driver-specific routineswhen generic routines are called: e.g. callingxxRead( ) when read( ) is called on an XX device.Installation done automatically for VxWorks drivers included in VxWorks image.ttyDrv( ).pipeDrv( ).嵌入式培训专题微迪软件培训中心Device CreationEach device driver has a device creation routine: PipesCreated at your request withpipeDevCreate( ).Serial devicesCreated automatically at systemstart up (via ttyDevCreate( ).Remote See Network Basics ChapterLocal See Local chapter.Third-party devices xxDevCreate( ).These routines each initialize instances of a particulardevice type.嵌入式培训专题微迪软件培训中心Devices- devsdrvname0/null1/tyCo/01/tyCo/14columbia:2/pipe/dream2/pipe/cleaner5/vio嵌入式培训专题微迪软件培训中心I/O SystemIntroductionBasic I/OSelect( )Standard I/O嵌入式培训专题微迪软件培训中心Integer that identifies a file ( device).Assigned by open( ) or creat( ) .Used by read( ), write( ), ioctl( ) and close( ) tospeify file. table is globalTable size defined by the symbolic constantNUM_FILES (default of 50 is specified in configAll.h).嵌入式培训专题微迪软件培训中心Standard Input, Standard Output, andStandard ErrorThese three (0-2) are never returned by creat( )or open().The first three are predefined by the system and are never reassigned by the system.0STD_IN1STD_OUT2STD_ERR34n:.reservedTable嵌入式培训专题微迪软件培训中心Standard Input, Output, and ErrorBy default, these are directed to the console at system startup.Global assignments may be changed using:Redirect I / O on a per task basis with :Void ioGlobalStdSet(stdFd, newFd)Example:fd = open (“columbia:/vx/errLog”, O_RDWR, 0);ioGlobalStdSet ( STD_ERR, fd);void iotaskStdSet (taskId, stdFd, newFd)嵌入式培训专题微迪软件培训中心Accessing FilesReturns on success, otherwise ERRORcreat( ) routine similar to open( ), but for new files on a filesystem device.int open (name, flags, mode)nameflagsmodeName of open.Specifies type of access:O_RDONLYOpen reading only.O_WRONLYOpen writing only.O_RDWROpen for reading and writing.O_TRUNCTruncate open.O_CREATCreate it doesnt existPermissions used when creating a an NFS system.嵌入式培训专题微迪软件培训中心Examining the Table- iosFdShowfdnamedrv 3/tyCo/01 4(socket)310/pipe/dream212/pipe/cleaner2嵌入式培训专题微迪软件培训中心Closing FilesSTATUS close(fd)fd returned from open( ) or creat( )Flushes buffers.Frees up resources associated with .Tasks must explicitly close files when they are no longer needed.VxWorks does not close files on task deletion. table is fixed size.嵌入式培训专题微迪软件培训中心Read / Writeint read (fd, buffer, nBytes)int write (fd, buffer, nBytes)fdbuffernBytes returned by open( ) or creat( ).Address of buffer. Will be filled on a read,copied to device on write.Maximum number of bytes to read / write.Returns the number of bytes read / written or ERROR if unsuccessful.嵌入式培训专题微迪软件培训中心Ioctlint ioctl (fd, command, arg)fd returned from open( ) or creat( ).commandInteger identifying some driver specific command.Symbolic constants typically used.argType and value depends on command.Driver manual pages lists valid ioctl commands for that driver.嵌入式培训专题微迪软件培训中心ioctl() ExamplesTo get / set your current :status = ioctl ( fd, FIOSEEK, newOffset);position = ioctl ( fd, FIOWHERE, 0);To set the baud rate of a serial device:status = ioctl (fd, FIOBAUDRATE, baudRate);To find the number of messages in a pipe:status = ioctl (fd, FIONMSGS, &nMsgs);嵌入式培训专题微迪软件培训中心Setting Options for a Serial Devicestatus = ioctl (fd, FIOSETOPTIONS, option);Symbolic constants for options may be ORed:1OPT_ECHOEcho of input.2OPT_CRMODConvert n to CR-LF on output.4OPT_TANDEMImplement S / Q flow control.8OPT_7_BITStrip parity bit from 8 bit input.16OPT_MON_TRAPReboot on X.32OPT_ABORTRestart target shell on C.64OPT_LINEAllow line editing before n.-0OPT_RAWAll options off ( raw mode).127OPT_TERMINALAll options on.嵌入式培训专题微迪软件培训中心I/O SystemIntroductionBasic I/OSelect( )Standard I/O嵌入式培训专题微迪软件培训中心OverviewRequires driver support:VxWorks pipes, sockets and serial device drivers supportselect( ).Third party drivers may also support select( ).select( ) allows a task to wait for activity on set of .Also used to pend with a timeout.Serverpipe,socket,or serial portselect( )嵌入式培训专题微迪软件培训中心select()select调用及宏FD_CLR、FD_ISSET、FD_SET、FD_ZERO用于I/O多路复用。intselect(intwidth,/*numberofbitstoexaminefrom0*/fd_set*pReadFds,/*readfds*/fd_set*pWriteFds,/*writefds*/fd_set*pExceptFds,/*exceptionfdsunsupported*/structtimeval*pTimeout/*maxtimetowait,NULL=forever*/)pReadFds监测是否有字符可以从某个描述符读入pWriteFds监测是否某个描述符准备好了可以立即写入pExceptFds监测是否某个描述符有异常出现FD_SET(fd,&fdset)从一个集合中添加一个描述符FD_CLR(fd,&fdset)从一个集合中删除一个描述符FD_ZERO(&fdset)清空一个集合嵌入式培训专题微迪软件培训中心struct fd_setConceptually an array of bits, with bit N corresponding to N.used by select( ) to specify .Manipulated via a collection of macros:FD_SET(fd, &fdSet)Sets the bit which corresponds to fd.FD_CLR(fd, &fdSet)Clears the bit which corresponds to fd.FD_ISSET(fd, &fdSet)Returns TRUE if the fd bit is set, elseFALSE.FD_ZERO(&fdSet)Clears all bits.嵌入式培训专题微迪软件培训中心SelectReturns number of active devices, or ERROR.int select(width, pReadFds, pWriteFds, pExceptFds, pTimeOut)widthNumber of bits to examine in pReadFds and pWriteFds.pReadFdsstruct fd_set pointer for the we wish to read.pWriteFdsstruct fd_set pointer for the we wish to write.pExceptFdsNot implemented.pTimeOut.Pointer to a struct timeval, or NULL to wait forever.嵌入式培训专题微迪软件培训中心I/O SystemIntroductionBasic I/OSelect( )Standard I/O嵌入式培训专题微迪软件培训中心Standard I/OApplicationBasic I/O Routines(device independent) read( ), write( )Driver RoutinesxxRead( ) xxwrite( )Hardware Devices Network Disk Drive Serial DeviceBuffered I/O: ANSI stdio fread( ) fwrite( )fioLibfioRead( )printf( )sprintf( )嵌入式培训专题微迪软件培训中心Standard I/O FunctionsansiStdio functions include:fopen( )opens a stream to a device or file.fclose( )closes a stream.fread( )reads data into an array.fwrite( )writes data to a stream.getc( )gets next character from a stream.putc( )puts a character to a stream.ungetc( ) returns character to input stream.嵌入式培训专题微迪软件培训中心ansiStdio routines use (pointers to structure)instead of . The structure, typedefed in stdio.h, contains :stdin, stdout, and stderr are created using 0,1, and 2.The underlying .Pointers, etc., for managing the .(vxWorks.h)(stdio.h)STD_INSTD_OUTSTD_ERRstdinstdoutstderr嵌入式培训专题微迪软件培训中心Standard I/O BuffersPrivate buffers minimize driver access:myBufstdio bufferdevice driverbuffer size driver dependentfpdefault 1024 bytesfread(. . ., fp)嵌入式培训专题微迪软件培训中心Standard I/O Library CaveatsStdio buffers not protected with semaphores. Two tasks should not use the same fp at the same time.stdio library contains routines and macros.Routines useful for access from the shell.Macros override routines when including stdio.h.Symbolic constants in configAll.h (default):Breakpoints cannot be set on macros.INCLUDE_STDIOInitialize library.INCLUDE_ANSI_STDIOLink all ansiStdioroutines into VxWorks.嵌入式培训专题微迪软件培训中心Other ANSI LibrariesManual Page Header FileDescriptionExamplesansiCtypeansiStringansiStdargansiStdlibctype.hstring.hstdarg.hstdlib.hCharacter testingand conversion.isdigit( )isalpha( )toupper( )StringmanipulationVariable numberof argumentsStandard conversionroutinesstrlen( )strcat( )strcpy( )va_start( )var_arg( )va_end( )atoi( )atof( )rand( )嵌入式培训专题微迪软件培训中心Formatted I/OApplicationBasic I/O Routines(device independent) read( ), write( )Driver RoutinesxxRead( ) xxwrite( )Hardware Devices Network Disk Drive Serial DeviceBuffered I/O: ANSI stdio fread( ) fwrite( )fioLibfioRead( )printf( )sprintf( )嵌入式培训专题微迪软件培训中心Formatted I/OfioLib allows ansiStdio to be excluded without losing functionality.fioLib contains routines for non-bufferd formatted I/O.Includes printf() and sprintf() which are normally part of stdio.嵌入式培训专题微迪软件培训中心Buffered Vs. Non Buffered I/ODestinationBuffered I/O (ansiStdio)Unbuffered I/O (fioLib)stdoutstderrotherfprintf(stdout, )fprintf(stderr, )fprintf(fp, )printf()printErr()fdprintf(fd, )嵌入式培训专题微迪软件培训中心UNIX and VxWorks - I/O ComparisonSimilarities:Devices haave names like files.Concept of current directory.Source code compatible.Differences: in UNIX are local to a process; inVxWorks they are global.VxWorks uses only a subset of UNIX open( ) flags.Speed.Concept of stdin, stdout, stderr.printf( ) is not buffered.嵌入式培训专题微迪软件培训中心SummaryBuffered I/O (ansiStdio) built on top of basic I/O using :fopen( )fclose( )fread( )fwrite( )fprintf( )Basic I/O routines:open( )close( )read( )write( )ioctl( )creat( )Formatted Non-buffered I/O (fioLib):printf( )sprintf( )fdprintf( )嵌入式培训专题微迪软件培训中心NowHave a rest嵌入式培训专题微迪软件培训中心Chapter 11Local 嵌入式培训专题微迪软件培训中心Local OverviewDOS Raw SCSI Devices嵌入式培训专题微迪软件培训中心File SystemsApplicationBasic I/O Routines(devicen independent)read( )write( )Driver RoutinesxxRead( )xxWrite( )Hardware DevicesNetworkDisk DriveSerial Device RoutinesxxRead( )xxWrite( )Buffered I/O: stdiofread( )fwrite( )fioLibfioRead( )printf( )sprintf( )嵌入式培训专题微迪软件培训中心Local Available block device drivers :ramDrvMakes memory look like a diskscsiLibSupports SCSI random-access devices.xxDrvThird Party block drivers.Available libraries :dosFsLibMS-DOS compatible.rawFsLibSupports disk as a single file.rt11FsLibFor backward compatibility.嵌入式培训专题微迪软件培训中心Initialization and UseBlock device creation routinesramDevCreate( )scsiBlkDevCreate( ) xxDevCreate( ) BLK_DEVLocal initialization routines dosFsDevInit( ) rawFsDevInit( ) localioLib / dirLib / usrLib routinesopen / close read / write stat / fstat mkdir / rmdir creat / remove 嵌入式培训专题微迪软件培训中心Creating a RAM DiskReturns a pointer to a BLK_DEV structure describing the RAM disk,or NULL on error.BLK_DEV * ramDevCreate ( ramAddr , bytesPerBlk ,bytesPerTrack , nBlocks , blkOffset )ramAddrMemory location of ram disk ( 0 = malloc( ) ). bytesPerBlkNumber of bytes per block.blksPerTrackNumber of blocks per track.nBlocksSize of disk in blocks.blkOffsetNumber of blocks to skip. Typically zero.Define INCLUDE_RAMDRV to include ramDrv in your vxWorks image.嵌入式培训专题微迪软件培训中心A Simple Example- pBlkDev = ramDevCreate(0,512,400,400,0)- dosFsMkfs (“/RAM1” , pBlkDev)/* Create and write to a file. Flush to RAM disk */ - fd = creat(“/RAM1/myfile”,2)- writeBuf = “This is a string.n”- write(fd,writeBuf,strlen(writeBuf)+1)- close(fd)/* Open read contents. */- readBuf = (char *) malloc(100)- fd = open(“/RAM1/myfile”,2)- read(fd , readBuf , 100)- printf readBufThis is a string.嵌入式培训专题微迪软件培训中心Local OverviewDOS Raw SCSI Devices嵌入式培训专题微迪软件培训中心DOS Hierarchical Restrictive .Compatible with MS-DOS up to release 6.2.Disks are interchangeable with those created on PCs usingMS-DOS ( if configured properly). 嵌入式培训专题微迪软件培训中心Configuring dosFsSpecify Volume Configuration information in aDOS_VOL_CONFIG data structure :Define INCLUDE_DOSFS, in configAll.h , ( excluded bydefault ).VxWorks options.Disk layout.Maximum number of dosFs files that can be open at a time with NUM_DOSFS_FILES ( default of 20 defined in configAll.h ).嵌入式培训专题微迪软件培训中心Caveat : Data IntegrityAlternatively , set options in the dosvc_options field of a partitions DOS_VOL_CONFIG structure :To improve performance, FAT and directory changes are not flushed to disk immediately.DOS_OPT_AUTOSYNCFlush FAT and directorychanges.To flush FAT and directory changes (before removing media) , use dosFsVolUnmount( ).DOS_OPT_CHANGENOWARN Remount dosFs on open( ) or creat( ).Flush with, ioct(fd, FIOSYNC, 0).Setting these options will degrade performance.嵌入式培训专题微迪软件培训中心Caveat : DOS Enable UNIX - style by settingDOS_OPT_LONGNAMES option bit inDOS_VOL_CONFIG data structure.By default, standard 8 + 3 DOS are used.UNIX - style are not PC compatible.嵌入式培训专题微迪软件培训中心Caveat : PC CompatibilityA disk initialized on a PC will work with VxWorks.For PC compatibility, a disk initialized with VxWorksDo not enable UNIX - style enabled withDOS_OPT_LONGNAMES.Must use correct media byte.嵌入式培训专题微迪软件培训中心Configuration : New To create a new DOS with customconfiguration parameters :1. pBlkDev = xxDevCreate(.);2. Initialize DOS_VOL_CONFIG structure.3. dosFsDevInit( “/DOS”, pBlkDev , pConfig);4. fd = open( “/DOS” , O_WRONLY , 0 );5. ioctl ( fd , FIODISKFORMAT , 0); /* if necessary */ 6. ioctl ( fd , FIODISKINIT , 0); 7. close( fd );嵌入式培训专题微迪软件培训中心Configuration : New To create a new DOS with defaultconfiguration parameters :1. pBlkDev = xxDevCreate(.);2. dosFsMkfs( “/DOS”, pBlkDev); 嵌入式培训专题微迪软件培训中心Configuration : Using an Existing 1. pBlkDev = xxDevCreate(.);2. pDesc = dosFsDevInit( “/DOS”, pBlkDev , NULL );3. dosFsVolOptionsSet (pDesc , options); /* if needed */To remount an existing :Typically , are configured in startup code.嵌入式培训专题微迪软件培训中心Contiguous To pre-allocate contiguous disk space for a file :ioctl (fd , FIOCONTIG,numBytes )Must be called before anything is written to file.Pre-allocated space may be reclaimed with :ioctl (fd , FIOTRUNC , newLength)Example :fd = creat(“/dos1/myDir/myFile”, O_RDWR );ioctl ( fd , FIOCONTIG , 0x10000 );To obtain the largest contiguous block available , set numBytes to CONTIG_MAX. 嵌入式培训专题微迪软件培训中心Local OverviewDOS Raw SCSI Devices嵌入式培训专题微迪软件培训中心Introduction to the Raw Wind River Systems defined.Handles device (partition) as one file.No Directories or other structure on disk. Analogous to the UNIX raw interface to a block device.Fastest , least structured .嵌入式培训专题微迪软件培训中心Configuring the Raw Define INCLUDE_RAWFS in configAll.h (excluded by default ).Maximum number of rawFs files that can be open at a time controlled by NUM_RAWFS_FILES ( default of 5 is defined in configAll.h.)嵌入式培训专题微迪软件培训中心Raw FS InitializationTo initialize a raw device :raw FsDevInit ( devName , pBlkDev ) devName Name of raw device being created.pBlkDevPointer to the BLK_DEV returned from xxDevCreate( ).Returns NULL on error.With no structure on the disk to initialize, there is no diskInit( ) routine.To low-level format the disk : Open a on the rawFs device.Call the FIODISKFORMAT ioctl.嵌入式培训专题微迪软件培训中心Local OverviewDOS Raw SCSI Devices嵌入式培训专题微迪软件培训中心SCSI OverviewSCSI - Small Computer System Interface.Less driver writing is required. All devices “speak the same language.”ANSI standard providing device independence.Support for SCSI-1 and SCSI-2 devices.Support for general and block drives is supplied by scsiLib.Support for sequential devices is provided by scsiSeqLib.嵌入式培训专题微迪软件培训中心SCSI Bus VxWorksControllerTape DriveSCSI Bus InitiatorBus Id = 7Bus Id = 6Bus Id = 5LUN = 0Bus Id = 6LUN = 3Bus Id = 6LUN = 5嵌入式培训专题微迪软件培训中心SCSI -1 RestrictionsVxWorks must be the sole initiator.Disconnect / reconnect is not supported.scsiIoctl ( ) allows arbitrary SCSI commands to be put onthe bus.scsiLib provides routines to put commonly used SCSIcommands on the bus.Only SCSI I random-access block devices conforming to the Common Command Set is supported.Synchronous transfers are not supported.Drivers for non-random-access devices ( e.g., a tape drivse ) must be written by the user :嵌入式培训专题微迪软件培训中心SCSI -1 Support configurationTo configure VxWorks for SCSI-1 support , selectively define the appropriate macro(s) by moving them outside the # if FALSE block in wind/target/config/bspName/config.h : # if FALSE# define INCLUDE_SCSI# define INCLUDE_SCSI_BOOT# define INCLUDE_SCSI_DMA /* if supported by BSP */# define INCLUDE_DOSFS# define INCLUDE_TAPEFS /* SCSI -2 only */# define SYS_SCSI_CONFIG# endif. . . 嵌入式培训专题微迪软件培训中心SCSI -2 FeaturesSupports all mandatory features of the SCSI-2 protocol ,and many optional features.Disconnect / reconnect. Multiple Initiators.SCSI - 2 features not supported by SCSI-1 :Mandatory direct access commands. Mandatory sequential access commands. Identify message.Synchronous data transfer.Fast SCSIWide SCSITagged command queuing.嵌入式培训专题微迪软件培训中心SCSI -2 Support configurationAccess to SCSI-2 devices : To include SCSI-2 support , the macro INCLUDE_SCSI2 (as well asINCLUDE_SCSI) must be defined in wind/target/config/target/config.h INCLUDE_SCSI2 must be defined before the include control line for theBSP header file bspName.h# define INCLUDE_SCSI2# include “configAll.h” # include “bspName.h” DOS or RAW on direct-access devices.Tape on sequential-access devices.嵌入式培训专题微迪软件培训中心Initializing SCSI Block Devices #define INCLUDE_SCSI2pSysScsiCtrlscsiPhysDevcreate(pSysScsiCtrl,busId,LUN,.)Include SCSI-2 Support in VxWorksInitialization of SCSI PeripheralpScsiPhysDevInitialize Logical PartitionscsiBlkDevcreate( )pBlkDevdosFsDevInit( )Initialize File System嵌入式培训专题微迪软件培训中心Configuration of SCSI DevicesWhen support for SCSI is enabled, the system initialization code will :Initialize SCSI controller.Configure SCSI peripherals.Peripheral configuration call chain :usrRoot( ) = usrScsiConfig( ) = sysScsiConfig( )sysScsiConfig( ) is called only if SYS_SCSI_CONFIG isdefined.Configuring specific peripherals requires writing the sysScsiConfig( ) function.The sysScsiConfig( ) function should be placed in sysScsi.c(preferably) or sysLib.c in the BSP directory. Do not modifywind/target/src/config/usrScsi.c嵌入式培训专题微迪软件培训中心Configuration : Hard Disks0 /* configure Winchester at busId=2 , LUN=0 */1 if(pSpd20=2scsiPhysDevCreate(pSysScsiCtrl,2,0,0,NONE,0,0,0)3 = (SCSI_PHYS_DEV *) NULL)4 5 SCSI_DEBUG_MSG(“usrScsiConfig:” 6“scsiPhysDevCreate failed. n”);7 return ERROR;8 9 /* create block devices */10 if(pSbd0=scsiBlkDevcreate (pSpd20,0x10000,0)= 11NULL)|12 (pSbd1=scsiBlkDevcreate (pSpd20,0x10000,0x10000)13= NULL)14 return (ERROR);15 /* Configure on partitions */16 if(dosFsDevInit (“/sd0/”,pSbd0,NULL)= NULL)|17 (rawFsDevInit (“/sd1/”,pSbd1)=NULL) 18 return (ERROR);19 /* Continue with other devices */ SizeOffsetLUNBus Id嵌入式培训专题微迪软件培训中心Initializing SCSI Sequential Devices #define INCLUDE_SCSI2pSysScsiCtrlscsiPhysDevcreate(pSysScsiCtrl,busId,LUN,.)Include SCSI-2 Support in VxWorksInitialization of SCSI PeripheralpScsiPhysDevInitialize Logical PartitionscsiSeqDevcreate( )pSeqDevtapeFsDevInit( )Initialize File System嵌入式培训专题微迪软件培训中心Sequential DevicesReturns a pointer to a SEQ_DEV structure describing the sequential device , or NULL on error.Only need to define INCLUDE_SCSI and INCLUDE_SCSI2 in config.h.Sequential devices allow blocks of data to be read and written sequentially.SEQ_DEV * scsiSeqDevCreate (pScsiPhysDev) pScsiPhysDevpointer to a SCSI_PHYS_DEV structure returned by scsiPhysDevCreate( )嵌入式培训专题微迪软件培训中心The Tape To access a sequential device create a tape .No directory structure. No used.Can be configured for fixed block size transfers or variable size block transfers.The Sequential device is accessed through the standardI/O interface.Define INCLUDE_TAPEFS in config.h.嵌入式培训专题微迪软件培训中心Tape InitializationTAPE_VOL_DESC used to reference the .TAPE_VOL_DESC * tapeFsDevInit (devName, pSeqDev , pTapeConfig ) devNameVolume name of tape device being created.pSeqDevPointer to a SEQ_DEV returnedfrom sequential device creation routine.pTapeConfigPointer to a tape configurationstructure TAPE_CONFIG.嵌入式培训专题微迪软件培训中心Configuration : Sequential Devices1 /* configure Exabyte 8mm tape drive at busId=4 , LUN=0 */2 if(pSpd40=scsiPhysDevCreate3(pSysScsiCtrl,4,0,0,NONE,0,0,0)4 = (SCSI_PHYS_DEV *) NULL)5 6 SCSI_DEBUG_MSG(“usrScsiConfig:”7 ”scsiPhysDevCreate failed. n”);8 return (ERROR); 9 10 /* configure the sequential device for this physical device */11 if(pSd0=scsiSeqDevcreate (pSpd40)12= (SEQ_DEV *)NULL)13 14 SCSI_DEBUG_MSG(“usrScsiConfig:”15 ”scsiSeqDevCreate failed. n”);16 return (ERROR); 17 18 /* initialize a tapeFs device */ 19 .20 if(tapeFsDevInit (“/tape1/”,pSd0,pTapeConfig)= NULL)21 return (ERROR);嵌入式培训专题微迪软件培训中心Debugging ToolsCalls scsiShow( ) when done. Calls scsiPhysDevCreate( ) for each bus Id and LUN. When first starting out , define SCSI_AUTO_CONFIG in wind/target/config/target/config.h.If you dont see all your peripherals attached :- scsiShowID LUN VendorId ProductId Rev. Type Blocks BlkSize scsiPhysDev- - - - - - - - -5 0 ARCHIVE VIPER 150 21247-005 1R 0 0 0X003CF654 Check cable connections. Check SCSI bus terminations. Make sure your peripheral supports the SCSI protocol being used.In sysScsiConfig( ), set the global scsiDebug = TRUE.嵌入式培训专题微迪软件培训中心SummaryDOS and RAW for :RAM disk.SCSI devices.Custom block devices.Direct-access devices.SCSI-1 device support for :Direct-access devices.SCSI-2 device support for :Sequential-access devices.Tape .嵌入式培训专题微迪软件培训中心Chapter 12Network Basics嵌入式培训专题微迪软件培训中心Network BasicsIntroductionConfiguring The NetworkRemote LoginRemote Command ExecutionRemote 嵌入式培训专题微迪软件培训中心Network ProtocolsMachines on a network must agree to exchange data insome standard way.Internet protocol suite (also called TCP / IP) provides system independent protocols. VxWorks implementation of TCP / IP protocol suite is basedon 4.3BSD “Tahoe release”.嵌入式培训专题微迪软件培训中心Simple NetworkUNIX PC HostVxWorks Targetethernet(VMEbus and serial line are also supported)嵌入式培训专题微迪软件培训中心TerminologyEach node on the network is a “host”. Not to be confused with VxWorks host / target relationship.Internet is an ambiguous word : Internet Protocol Suite:A collection of protocols forsystem independent network communication.An Internet:A collection of connected networks.The Internet:The global internet.嵌入式培训专题微迪软件培训中心Complex Network (Internet)routers嵌入式培训专题微迪软件培训中心Shared Memory Network OverviewETHERNETUNIXVxWorksCPU0VxWorksCPU1VMEbus90.0.0.2Network 100.0.0.0100.0.0.2100.0.0.190.0.0.30Details in appendix and Programmers Guide.Network 90.0.0.0嵌入式培训专题微迪软件培训中心Network ServicesVxWorks network services include :Remote Remote loginRemote command executionUser can build other network services as needed. Writingnetwork applications will be discussed in the next chapter.嵌入式培训专题微迪软件培训中心Network Non-DeterminismEthernet collisionsVMEbus spin locksDropped packetsTimeouts and retransmissionsTCP / IP is non-deterministic because of :嵌入式培训专题微迪软件培训中心NetworkingIntroductionConfiguring The NetworkRemote LoginRemote Command ExecutionRemote 嵌入式培训专题微迪软件培训中心RoutingIf client and server are on different networks, data passingbetween them must be routed.Internet routing algorithm :if (destination on a directly attached network)send data to destinationelseuse routing table to find correct routerand send data to router.嵌入式培训专题微迪软件培训中心Internet AddressesInternet addresses written in “dot” notation90.0.0.70Analogous to a phone number having an area code and alocal portion.Two nodes are on the same network if they have the samenetwork number.This value encodes both a network number and a host number. Internally stored as 4 byte integer0x5a000046Makes routing easier.嵌入式培训专题微迪软件培训中心Internet Address ClassesClassABC010110network7 bitsnetwork14 bitsnetwork21 bitshost24 bitshost16 bitshost8 bits嵌入式培训专题微迪软件培训中心Internet Address Examples90.1.2.490.3.6.890.0.0.0 NetworkCLASS A128.11.3.21128.11.5.19128.11.0.0 NetworkCLASS B192.15.2.10192.15.2.45192.15.2.0 NetworkCLASS C嵌入式培训专题微迪软件培训中心Assigning Internet AddressesIn an isolated environment, there is no restriction on network prefix.If connected to the Internet, network prefix must be assigned by the InterNIC (Internet Network Information Center)Assigned by adminstrator of that internet.Must be unique for each network on an internet.Network PrefixesMust be unique for each host on a networkAssigned by administrator of that network.Host Numbers嵌入式培训专题微迪软件培训中心SubnetsTo improve network performanceTo make administration easier.At a large site, many physical networks are needed :Adding a new network normally requires obtaining a new network prefix.A new network number may not be available.Subnetting allows a site to add new networks transparently to the rest of the internet. 嵌入式培训专题微迪软件培训中心Subnet Example130.10.2.5130.10.2.6130.10.1.20130.10.1.37subnet mask : 0xffffff00130.10.2.0 subnetrouter to outside world130.10.0.0 network130.10.1.0 subnetVxWorks target on 130.10.1.0/24 subnet must specify: inet on ethernet (e) : 130.10.1.20:ffffff00嵌入式培训专题微迪软件培训中心inetLibRoutines for manipulating internet addresses :inet_addr( )Converts dot notation internet address to an integer.inet_lnaof( )Returns the host portion of an internet address.inet_netof( )Returns the network portion of an internet address.inet_netof_string( )Obtains network portion of address as a string. Knows about interface subnet masks.inet_ntoa_b( )Converts internet address to ASCII dot notation.嵌入式培训专题微迪软件培训中心Host NamesTo associate a name with an internet address : hostAdd (hostName, hostAddr)To display host name table use :hostShow ()嵌入式培训专题微迪软件培训中心Example-hostAdd “styx”, “147.11.1.80”value = 0 = 0x0-hostAdd “nelson”, “147.11.1.80”value = 0 = 0x0-hostShow hostnameinet addressaliaseslocalhost127.0.0.1ohio147.11.1.81styx147.11.1.80nelsonvalue = 0 = 0x0嵌入式培训专题微迪软件培训中心Routing Tablesepimetheusjanusmimas192.15.2.0 network192.15.2.22192.15.2.165.0.0.365.0.0.165.0.0.0 networkNetworkNetworkGatewayGatewayHost A Routing TableHost C Routing Table192.15.2.065.0.0.365.0.0.0192.15.2.1嵌入式培训专题微迪软件培训中心Adding Routes in VxWorksA specific host :routeAdd (“65.0.0.4”,”192.15.2.7”)To add a route use :route (destination, gateway)Can use a host name or an internet address.Destination can be :A network :routeAdd (“65.0.0.0”,”gateHost”)Anywhere else ( default route ):routeAdd (“0”,“192.15.2.1”)嵌入式培训专题微迪软件培训中心A Debugging Tool-routeAdd “150.39.0.0”, “147.11.54.254”value = 0 = 0x0-routeShowROUTE NET TABLEdestinationgatewayflagsRefcntUseInterface150.39.0.0147.11.54.254300enp0147.11.54.0147.11.54.1701152enp0ROUTE HOST TABLEdestinationgatewayflagsRefcntUseInterface127.0.0.1127.0.0.1500lo0value = 73 = 0x49 = I嵌入式培训专题微迪软件培训中心Testing RoutesSTATUS ping (host, nPackets, options)-ping “columbia”, 1columbia is alivevalue = 0 = 0x0-ping “90.0.0.70”, 1no answer from 90.0.0.70value = -1 = 0xffffffff = _end + 0xfff91c4fRouting information.If ping( ) fails, check :To check if a host is reachable :Hardware connections.嵌入式培训专题微迪软件培训中心Host ConfigurationTCP / IP Network Administration, OReilly & Associates.(UNIX Host)Associate host names with internet addresses in host table.Set up routing tables so that packets will be routed correctly.For more information, see :Networking personal Computers with TCP / IP, OReilly & Associates. (PC Host)Managing NFS and NIS, OReilly & Associates.(UNIX Host)Your network softwares documentation.Speak with your network administrator!嵌入式培训专题微迪软件培训中心Network ServicesIntroductionConfiguring The NetworkRemote LoginRemote Command ExecutionRemote 嵌入式培训专题微迪软件培训中心Remote Login and VxWorksTwo protocols :rlogin (UNIX Host)telnet (internet protocol)Gives access paths to VxWorks applications for sites withoutTornado interface.Security can be installed. Restricts access to VxWorks by user name and password:Define INCLUDE_SECURITYModify LOGIN_USER_NAME and LOGIN _PASSWORDAdd additional users with loginUserAdd( ) 嵌入式培训专题微迪软件培训中心Remote Login and Support FacilitiesSupport routines must be linked into VxWorks.Additional tools to be used in conjunction with remote login facilities can also be linked into VxWorks :Target resident symbol table.Target resident show routines.Target resident module loader / unloader.INCLUDE_RLOGINrlogin server and client.INCLUDE_TELNETtelnet server.Remote login also requires the target resident shell.INCLUDE_SHELL嵌入式培训专题微迪软件培训中心Network BasicsIntroductionConfiguring The NetworkRemote LoginRemote Command ExecutionRemote 嵌入式培训专题微迪软件培训中心Executing Remote CommandsVxWorks programs can invoke remote shell (RSH) commands on a UNIX hostA called a socket is created. Can read( ) from thissocket to get command output. UNIXVxWorksRSH serverRSH clientshellshell cmdsocket嵌入式培训专题微迪软件培训中心UNIX : Remote Command ExecutionReturns a socket or ERROR.int rcmd (host, remotePort, localUser, remoteUser, cmd, pFd2)hostHost name or inet number.remotePortRemote port number to connect to, typically 514(shell).localUserName of local user.remoteUserUser name on remote host.cmdShell command string to execute.pFd2If non-zero, a socket for STD_ERR is returned through this pointer.嵌入式培训专题微迪软件培训中心UNIX : rcmd Example-unixDate = calloc (300,1)unixDate = 0x23ff264 : value = 37744912 = 0x23ff110-aFd = rcmd(“ohio”,514,”debbie”,”debbie”,”date”,0)newsymbol “aFd” added to symbol table.aFd = 0x23fefa0 : value = 4 = 0x4-read (aFd, unixDate, 300)value = 29 = 0x1d-printf (“%s n”, unixDate)Mon Nov 18 12:25:45 PST 1991value = 30 = 0x1e-close (aFd)嵌入式培训专题微迪软件培训中心Network BasicsIntroductionConfiguring The NetworkRemote LoginRemote Command ExecutionRemote 嵌入式培训专题微迪软件培训中心Remote nfsDrvVxWorks comes with two drivers which allow access to files onremote machines.netDrv嵌入式培训专题微迪软件培训中心NFSNetwork (NFS) was developed by Sun MicrosystemsAllows efficient access to files. NFS transfers and buffers files in pieces (usually 8 Kbytes).Remote are mounted; then accessed as if they were local . VxWorks provides NFS client and server.NFS client excluded by default. To include, define INCLUDE_NFS in ConfigAll.h嵌入式培训专题微迪软件培训中心NFS OverviewTo access files on a remote machine using NFS :1.Export servers :2.Mount the on the client.3.Set the clients authentication parameters.Make a local available to remote host with appropriateaccess permissions.嵌入式培训专题微迪软件培训中心1. Exporting the NFS servers only export local %mount/dev/sd0a on / type 4.2/dev/sd0g on / dino type 4.2styx : /usr on /usr type nfsVxWorks Target styx/dino/usrWorkstation Columbia/嵌入式培训专题微迪软件培训中心2. Mounting NFS -nfsMount (“columbia”, “/dino”, “/dinoNfs”)-fd = open (“/dinoNfs/comics/myFile”, 2)STATUS nfsMount (host, , localName)hostName of remote host.Name of remote to mount (must be exported by remote host).localNameLocal device name for . If NULL, uses . Example :嵌入式培训专题微迪软件培训中心Examining NFS To display al mounted NFS :-nfsDevShowdevice name/usrNfsstyx : /usr/dinoNfscolumbia : / dinovalue = 0 = 0x0嵌入式培训专题微迪软件培训中心UNIX : 3. NFS AuthenticationFor UNIX NFS servers, once is mounted client can access files as if they were local after authentications are set.User id. depends on :Group id.Default ids specified in configAll.h :#define NFS_USER_ID2001#define NFS_GRUOP_ID100To find your user and group ids on UNIX host :%iduid = 219(marc) gid=700(training)嵌入式培训专题微迪软件培训中心UNIX : NFS AuthenticationSets authentication programmatically.void nfsAuthUnixSet (hostName, uid, gid, ngids, aup_gids)hostNameRemote host name.uidUser id on hostName.gidGroup id on hostName.ngidsNumber of gids listed in aup_gids.aup_gidsArray of additional group ids.To see current authentication parameters, use :void nfsAuthUnixShow( )嵌入式培训专题微迪软件培训中心netDrvnetDrv allows access to remote files :Entire into target memory on open( ).read( ) / write( ) act on copy of memory. Cant access large files (constrained by available memory).ioctl (fd, FIOSYNC, 0) is not supported written to remote host until close( ).dirLib routines opendir / readdir do not work on netDrv directories. stat / fstat only partially implemented.嵌入式培训专题微迪软件培训中心Creating network Devices-netDevCreate (“ohio:”, “ohio”, 1)-fd = open (“ohio:/u/teamN”, 2)STATUS netDevCreate (devName, host, protocol)devNameLocal name of device to create. By convention, ends with :.hostName of remote machine (from previous hostAdd( ). protocolProtocol to transfer files to / from VxWorks (0=RSH or 1=FTP).Example :嵌入式培训专题微迪软件培训中心Permissions- iam “team8” , “team8Password“ access requires a name and a password :RSH permission requires : (UNIX host)A user name to be sent on the target.- iam “team8”Target must be trusted to verify user name without a password.rcmd and rlogin to UNIX also use the RSH protocol. (UNIX host)team8/.rhostsvx8嵌入式培训专题微迪软件培训中心UNIX : netDrv Protocol ComparisonAdvantages of RSH : part of the TCP / IP protocol suite, so is available on allnetworked hosts.Advantages of RSH over FTP : faster on open / close; since there is no shell delay. supplied with VxWorks. text password goes over the network on each open( ) and close( ).嵌入式培训专题微迪软件培训中心netDrv vs. nfsDrvAdvantages of nfsDrv over netDrv :Reads and writes only needed parts of the file.Advantages of netDrv over nfsDrv :open( ) and close( ) much faster.Can access arbitrarily large files.All networked hosts have an . Can use dirLib routines.Can flush with FIOSYNC.read( ) / write( ) slightly faster.Easier to configure.嵌入式培训专题微迪软件培训中心Accessing Files on VxWorksVxWorks supplies NFS servers.Requires a : VxWorks does not supply RSH server.嵌入式培训专题微迪软件培训中心NFS Server OverviewAllows remote hosts to access a targets using NFS protocol.Only DOS is supported.Define INCLUDE_NFS_SERVER in configAll.hNFS server configuration :1.Initialize DOS with NFS server support.2.Inform NFS server that the is exportable.3.Mount on remote host.嵌入式培训专题微迪软件培训中心1. Creating A Mountable Enable the DOS_OPT_EXPORT configuration option, before initializinga DOS to support remote access.Example :/* Configure Block Device */pBlkDev = xxDevCreate(.);/* Configure with NFS Support */dosFsDevInitOptionsSet (DOS_OPT_EXPOT);dosFsDevInit (“/fsName, pBlkDev, NULL); 嵌入式培训专题微迪软件培训中心2. Exporting A To allow remote systems access to local : nfsExport (name, fsId, rdOnly, notUsed) name name. fsIdNFS export Id number - Use 0 for NFS to create an ID. rdOnlyTRUE = mountable read only. FALSE = mountable read write. notUsedSet to zero - reserved for future use.Example :nfsExport (“/fsName“, 0, FALSE, 0);嵌入式培训专题微迪软件培训中心3. Accessing From A Remote HostTo mount the VxWorks on a remote host, use :mount -F nfs node: directory Typically, superuser (root) privilege is required on UNIX systems to mount a . (UNIX host)Example :mount -F nfs vxtarget: /fsName /mountPointOnce mounted, files may be accessed as if they were on a local filesystem.嵌入式培训专题微迪软件培训中心CaveatsBy default, no authentication is performedOnly DOS supported. restrictions.No symbolic links.No directory renaming.Standard DOS limitations apply:嵌入式培训专题微迪软件培训中心VxWorks Define the macro INCLUDE_ in configAll.h or config.h.When target is rebooted, should see t (server daemon) running.嵌入式培训专题微迪软件培训中心 - VxWorks to VxWorksVxServerVxClient-pBlkDev = ramDevCreate (0, 512, 0, 400, 0)-dosFsMkfs = (“/RAM1”, pBlkDev)-fd = creat(“RAM1/dataFile”,2) -wirte (fd, dataPtr, nBytes)-close (fd)-netDevCreate (“VxServer :”, “VxServer”, 1) -fd = open(“VxServer:” “/RAM1/dataFile”,2) -getData (fd, dataBuf, maxSize)-close (fd)Can also use boot one VxWorks target from another.嵌入式培训专题微迪软件培训中心 - VxWorks to UNIXVxServerUNIX Client-pBlkDev = ramDevCreate (0, 512, 0, 400, 0)-dosFsMkfs = (“/RAM1”, pBlkDev)-fd = creat(“RAM1/aFile”,2) -wirte (fd, dataPtr, nBytes)-close (fd)% FTP VxServerconnected to VxServer.Name (VxServer : debbie) :Password :ftp cd /RAM1ftp get dataFilelocal : dataFile remote : dataFile 137 bytes received in 0.02 seconds (6.7Kbytes /s)ftp quit% lsdataFile嵌入式培训专题微迪软件培训中心NFS vs. NFS advantages :Efficient .Configurable number of servers pre-spawned. :Can access other than DOS.All network hosts have .嵌入式培训专题微迪软件培训中心SummaryInternet Protocol for node-to-node routing.VxWorks : routeAdd( ), hostAdd( ).Configure hosts host routing tables.Configuring the network :rlogin (UNIX host) and telnet support.rcmd ( ) (UNIX host)Reads and writes portion of remote file. must be exported by remote host.nfsDrv mounts remote with nfsMount( ) requires uid and gid.嵌入式培训专题微迪软件培训中心SummarynetDrv devices created with netDevCreate( ).Entire read into VxWorks on open( ), and not updated until close( ).Uses either RSH (UNIX host) or .RSH requires name and entry in .rhosts. (UNIX Host) name and password. NFS servers allows local VxWorks files to be accessed by a remote machine. 嵌入式培训专题微迪软件培训中心Chapter 13NetworkProgramming嵌入式培训专题微迪软件培训中心Network ProgrammingIntroductionSocketsUDP Sockets ProgrammingTCP Sockets ProgrammingRPC嵌入式培训专题微迪软件培训中心VxWorks NetworkingVxWorks network programming tools :Network programming allows users to :Build servicesCreate distributed applicationsBerkeley socketszbuf socket APISun RPC ( Remote Procedure Call )嵌入式培训专题微迪软件培训中心Network ComponentsSocketszbufAPIRPCNFSTornadotgtsvrTCPUDPIPrlogintelnetrshftpEthernetShared MemorySlip / PPPNetwork Driver嵌入式培训专题微迪软件培训中心Network ComponentsSocketszbufAPIRPCNFSTornadotgtsvrTCPUDPIPrlogintelnetrshftpEthernetShared MemorySlip / PPPNetwork DriverIP嵌入式培训专题微迪软件培训中心Network ComponentsSocketszbufAPIRPCNFSTornado tgtsvr TCPUDPIPrlogintelnetrshftpEthernetShared MemorySlip / PPPNetwork Driver嵌入式培训专题微迪软件培训中心PortsAbstract destination point within a node.TCP/ UDP intertask communication.Data is sent by writing to a remote port.Data is rceived by reading from a local port.UDPIP90.0.0.190.0.0.2嵌入式培训专题微迪软件培训中心Network ComponentsSocketszbufAPIRPCNFSTornadotgtsvrTCPUDPIPrlogintelnetrshftpEthernetShared MemorySlip / PPPNetwork DriverzbufAPI嵌入式培训专题微迪软件培训中心Network ComponentsSocketszbufAPIRPCNFSTornadotgtsvrTCPUDPIPrlogintelnetrshftpEthernetShared MemorySlip / PPPNetwork Driver嵌入式培训专题微迪软件培训中心Packet Encapsulationethernet headerIP headerUDP / TCP headerdataIP headerUDP / TCP headerdataUDP / TCP headerdatadataethernet headerIP headerUDP / TCP headerdataIP headerUDP / TCP headerdataUDP / TCP headerdatadataApplicationUDP / TCPIPEthernetEthernetIPUDP / TCPApplication嵌入式培训专题微迪软件培训中心Network ProgrammingIntroductionSocketsUDP Socket ProgrammingTCP Socket ProgrammingRPC嵌入式培训专题微迪软件培训中心Socket OverviewProgrammatic interface to internet protocols.Protocol specified when socket created ( e.g.,UDP or TCP ).Server binds its socket to a well known port.Clients port number dynamically assigned by the system.嵌入式培训专题微迪软件培训中心PortsPort identified by a short integer :Socket address consists of :An internet address ( node socket is on ).A port number ( destination within that node )0-1023Reserved for system services (e.g.,rlogin,telnet, etc).1024-5000Dynamically allocated5000User definedUnique to each machine and protocol嵌入式培训专题微迪软件培训中心Socket AddressGeneric socket address : struct sockaddr u_shortsa_family ; /* address family */charsa_data14 ; /*protocol specific address data */ ;Generic address structure used by Internet Protocol : struct sockaddr_in shortsin_family ; /* AF_INET */u_shortsin_port ; /* port number */struct in_addrsin_addr ; /*internet address */charsin_zero8 ; /* padding, must be zeroed out */ ;VxWorks supports only internet sockets.嵌入式培训专题微迪软件培训中心Network Byte OrderingFields in the struct sockaddr_in must be put in network byte order ( big - endian)Macros to convert long / short integers between the host and and the network byte ordering : hotnl( )host to network longhotns( )host to network shortntohl( )network to host longntohs( )network to host short嵌入式培训专题微迪软件培训中心Caveat - User DataThe standard format used must handle : To send data in a system independent way :Any standard data types used ( e.g.,int, short, float, etc.).Data structure alignement.One such facility, XDR, will be discussed in the RPC section of this chapter.1.Sender converts data from its system-dependent format to some standard format.2. Receiver converts data from the standard format to its system- dependent format.嵌入式培训专题微迪软件培训中心Creating a SocketOpens a socket ( analogous to open() for files)Returns a socket or ERRORint socket ( domain , type , protocol)domainMust be PF_INETtypeTypically SOCK_DGRAM (UDP) or SOCK_STREAM (TCP) protocolSocket protocol ( typically 0 ).嵌入式培训专题微迪软件培训中心Binding a SocketTo bind a socket to a well known address : Typically only called by server.STATUS bind ( sockFd , pAdrs , adsLen)sockFdSocket descriptor returned from socket( )pAdrsPointer to a struct sockaddr to which to bind this socketadrsLensizeof ( struct sockaddr ).嵌入式培训专题微迪软件培训中心Example Server Stub1 #define PORT_NUM ( USHORT ) 50012 struct sockaddr_in myAddr;3 int mySocket ;4 .5 mySocket = socket ( PF_INET, SOCK_DGRAM,0 );6 if ( mySocket = ERROR)7 return (ERROR) ;89 bzero (&myAddr, sizeof (struct sockaddr_in);10 myAddr.sin_family = AF_INET;11 myAddr.sin_port = htons (PORT_NUM) ;12 myAddr.sin_addr.s_addr = INADDR_ANY ;1314 if ( bind ( mySocket, (struct sockaddr *) &myAddr,15 sizeof (myAddr) = ERROR )16 17 close (mySocket) ;18 return (ERROR);19 嵌入式培训专题微迪软件培训中心Network ProgrammingIntroductionSocketsUDP Socket ProgrammingTCP Socket ProgrammingRPC嵌入式培训专题微迪软件培训中心UDP Socket Overviewfds = socket ( PF_INET, SOCK_DGRAM, 0 )bind ( fds , (struct sockaddr *)&saddr, sizeof(saddr)loop recvfrom(fds , .) /* wait for request */. /* perform service */sendto (.) /* Send reply */ ServerClientsocket fdcsocket fdsat saddrfds = socket ( PF_INET, SOCK_DGRAM, 0 )sendto (.) /* Send request to server */ select(.) /* wait for reply with timeout */嵌入式培训专题微迪软件培训中心Sending Data on UDP Socketsint sendto ( sockFd , pBuf , bufLen , flags ,pDestAdrs , destLen)sockFdSocket to send data from.pBufAddress of data to send.bufLenLength of data in bytes.flagsSpecial actions to be taken.pDestAdrsPointer to struct sockaddr containingdestination address.destLensizeof (struct sockaddr).Returns the number of bytes sent or ERROR.嵌入式培训专题微迪软件培训中心Receiving Data on UDP Socketsint recvfrom (sockFd, pBuf, buflen, flags, pFromAdrs, pFromLen) sockFdSocket to received data from. pBufBuffor to hold incoming data. buflenMaximum number of bytes to read. flagsFlags for special handling of data. pFromAdrsPointer to struct sockaddr. Routinesupplies internet address of sender. pFromLenPointer to integer. Must be initializedto sizeof (struct sockaddr).Blocks until data available to receive.Returns number of bytes received or ERROR.嵌入式培训专题微迪软件培训中心Network ProgrammingIntroductionSocketsUDP Socket ProgrammingTCP Socket ProgrammingRPC嵌入式培训专题微迪软件培训中心TCP Socket OverviewSERVERSlaveSlaveMaster Clients send connection requests to Masters socketNew socket created dynamically for each connection, serviced by work task.TCP is connection based (like making a phone call)Concurrent servers are often implemented.嵌入式培训专题微迪软件培训中心TCP Server Overview/ * master server * /masterFd = socket (PF_INET, SOCK_STREAM, 0)/ * fill in servers sockaddr struct * /bind (.) / * bind to well-known port * /listen (.) / * configure request queue * /FOREVERclientFd = accept (masterFd, .)taskSpawn (., slaveSrv, clientFd, .)/ * slave server * /slaveSrv (clientFd, .)read (clientFd, .) / * read request * /serviceClient ( )write (clientFd, .) / * send reply * /close (clientFd)1234567891012345678嵌入式培训专题微迪软件培训中心TCP Client Overview/ * TCP Client * /fd = socket (PF_INET, SOCK_STREAM, 0)/ * fill in sockaddr with servers address * /connect (fd, .) / * request service * /write (fd, .)/ * send request * /read (fd, .) / * read reply * /close (fd) / * terminate connection * /1234567891011嵌入式培训专题微迪软件培训中心Server Initialization STATUS listen (sockFd , queueLen)SockFdSocket descriptor returned from socket( ).queueLenNominal length of connection request queue.Before accepting connections, server must : Create a socket (socket( )Bind the socket to a well known address (bind( )Establish a connection request queue :嵌入式培训专题微迪软件培训中心Accepting Conncetionsint accept (sockFd , pAdrs , pAdrsLen)sockFdServers socket (returned from socket( ).pAdrsPointer to a struct sockaddr through whichthe clients address is returned.pAdrsLenPointer to length of address.Blocks until connection request occurs.Returns new socket (connected to the client)or ERROR.Original socket, sockFd, is unconnected and ready to accept other connection requests.嵌入式培训专题微迪软件培训中心Requesting Connections STATUS connect (sockFd, pAdrs, adsLen) sockFdClients socket descriptor. pAdrsPointer to servers socket address. adrsLensizeof (struct sockaddr)To connect to the server, the client calls: Blocks until connection is established or timeout. Returns ERROR on timeout or if no server is bound to pAdrs嵌入式培训专题微迪软件培训中心Exchanging Data ServerSlaveSlavewrite( )read( )Masterread( ) / write( ) may be used to exchange data:Caveat : TCP is stream oriented.write( ) may write only part of message if I / O is nonblocking.read( ) may read more or less than one message.嵌入式培训专题微迪软件培训中心Cleaning up a Stream Socket When done using a socket, close( ) it :Frees resources associated with socket.Attempts to deliver any remaining data.Next read( ) from peer socket will return 0.Can also use shutdown( ) to terminate output, while still reveiving data from peer socket.嵌入式培训专题微迪软件培训中心Setting Socket OptionsOptions can be enabled on a per socket basis, including :Dont delay write( )s to coalesce small TCP packets.Enable UDP broadcasts.Linger on close( ) until data is sent.bind( ) to an address already in use.Change the size of the send / receive buffers.Consult UNIX man pages on setsockopt( ) for details.To make a socket non-blocking : int val = 1; /* Set to 0 for blocking I / O */ ioctl (sock, FIONBIO, &val); 嵌入式培训专题微迪软件培训中心zbuf Socket APIImproves application performance by minimizing data copiesthrough buffer loaning.Application must manage buffers.zbuf application can communicate with a standard socket application.Supports TCP and UDP protocols.See zbufLib and zbufSockLib for details. Proprietary API.嵌入式培训专题微迪软件培训中心Network ProgrammingIntroductionSocketsUDP Socket ProgrammingTCP Socket ProgrammingRPC嵌入式培训专题微迪软件培训中心OverviewRPC (Remote Procedure Call) provides a standard way to invokeprocedures on a remote machine.AppendixTCP / IP Illustrated Volume I (Stevens).Power Programming with RPC (OReilly & Associates).Documentation and source code can be found in wind/target/unsupported/rpc4.0For more information about RPC :嵌入式培训专题微迪软件培训中心RPC Client - Server Modelclientserverclient routinesserver routinesclient stubserver stubnetwork routinesnetwork routines嵌入式培训专题微迪软件培训中心VxWorks and rpcgenSTATUS rpcTaskInit( )A client stub.rpcgen is a RPC protocol compiler.From a specification of the remote procedures, rpcgen creates :A server stub.The XDR routines for packing / unpacking data structures. Notcreated if all parameters / return_values are standard data types.A header inclusion by client and server.Each VxWorks task accessing RPC calls using code produced by rpcgen must first initialize access.嵌入式培训专题微迪软件培训中心SummaryUDP transport protocol.Transport layer network Protocols: TCPStream oriented, reliable port-to-port communication. UDPPacket oriented, non-reliable port-to-portcommunication.Sockets as the interface to network protocols: TCP transport protocol.Configurable socket options.zbuf socket API.Client / server programming strategies for distributed applications. 嵌入式培训专题微迪软件培训中心ReconfiguringVxWorksChapter14嵌入式培训专题微迪软件培训中心Chapter 14ReconfiguringVxWorks嵌入式培训专题微迪软件培训中心OverviewAfter development is completed, you may need to:Exclude unneeded VxWorks facilities.Final application may be:Linked with VxWorks and put into ROM.Link application code into VxWorks.Modify VxWorkss start-up code to spawn application tasks.Downloaded from host over a network.Loaded from a local disk.嵌入式培训专题微迪软件培训中心Typical Steps1. Exclude unneeded facilities from VxWorks.2. Modify system start up code to spawn a task to initialize your application.3. Modify the targets Makefile to link your application code with VxWorks.4. Run make to produce either a downloadable or a ROM- able application.嵌入式培训专题微迪软件培训中心1. Scaling VxWorksTo build a VxWorks image which includes a facility, the facilitys corresponding macro(s) must be defined in either:When the new VxWorks image is built and booted, it will initialize the facilities selected.Alternatively, WindConfig can be used to select or unselectVxWorks facilities.wind/target/config/bspName/config.h (target specific configuration).wind/target/config/all/configAll.h (generic base configuration - avoid modifying this possible).嵌入式培训专题微迪软件培训中心Configuration DependenciesSome optional facilities depend on others (e.g., the NFS facility requires RPC).wind/target/src/config/usrDepend.c checks thesedependencies and includes all required facilities.As a result of dependency checking, some facilitieswhich apparently were excluded may actually be included in the final system image.嵌入式培训专题微迪软件培训中心2. Modifying System Start-up CodeusrRoot( ) in usrConfig.c:Executed by first VxWorks task.Initializes system facilities.Start user application if macros defined appropriately :voidusrRoot(.).#ifdefINCLUDE_USER_APPL/*Starttheusersapplication.*/USER_APPL_INIT;/*mustbevalidCstatement*/*orblock.*/#endif嵌入式培训专题微迪软件培训中心Example USER_APPL_INITDefine INCLUDE_USER_APPL/*mv162/config.h-MotorolaMVME162header*/.#defineINCLUDE_USER_APPL#defineUSER_APPL_INITexternvoidmyApp(void);taskSpawn(“tMyApp”,60,0,30000,(FUNCPTR)myApp,0,0,0,0,0,0,0,0,0,0);.Define USER_APPL_INIT to be a statement or block whichstarts your application. You may make necessary declarationswithin the block :嵌入式培训专题微迪软件培训中心3. Linking An Application withVxWorksModify the Makefile in the target directory:MACH_EXTRA = myCode.o. . .myCode.o: . . .$(make) -f Makefile_myCode. . .Alternatively, specify your applications modules on thecommand line with ADDED_MODULES.% make -f Makefile_mycode% make ADDED_MODULES = muCode.o vxWorks_rom嵌入式培训专题微迪软件培训中心4. Building VxWorksUse makefile in target directory to rebuild VxWorks orboot ROMs:Common makefile objects:vxWorksVxWorks image (default).vxWorks_rom .hexROM-able VxWorks imagevxWorks_res_rom_nosymROM-resident standaloneversion of VxWorks without symbol table.Starts fast, uses little RAMbootrom .hexBoot ROM code.Go to the target directory.make object嵌入式培训专题微迪软件培训中心ROMable ObjectsIf using large capacity ROMs, may need to modify the constant ROM_SIZE in both:ROMable objects copy themselves into RAM before running.Most of the ROMable VxWorks objects are compressed. Anexception to this is vxWorks_romwind/target/config/target/config.h .wind/target/config/target/Makefile.Make will fail if the object is larger than the ROM_SIZE嵌入式培训专题微迪软件培训中心Downloadable ObjectsROM boot code copied into RAM at RAM_LOW_ADRS,bootstrap part decompresses rest to RAM_HIGH_ADDRS.VxWorks system image loaded at RAM_LOW_ADRS(typically 0x1000).BootStrap ProgramBoot ROMProgramVxWorksBoot ROMProgramROMRAMRAM_LOW_ADRSFREE_RAM_ADRSRAM_HIGH_ADRS嵌入式培训专题微迪软件培训中心Rebuilding Boot ROMsIf system image is large (570 Kbytes, typically), downloading will overwrite the booting code, failing while printing:Loading . . . 400316 + 28744 + 23852New ROMs are also required to boot off of a local diskMay need change RAM_HIGH_ADRS in:wind/target/config/target/config.h .wind/target/config/target/Makefile.嵌入式培训专题微迪软件培训中心Standard make TargetsNot all BSPs will support all of these images. Some BSPs support additionalimagesTYPES OF IMAGESVxWorks TornadoROMable compressedROMable uncompressedROM residentDownloadable uncompressedvxWorks_romvxWorks.res_rom_nosymvxWorksVxWorks StandaloneBoot ProgramvxWorks.st_rombootromvxWorks.res_romvxWorks.stbootrom_resbootrom_uncmpStandalone VxWorks has a target shell built-in symbol table.target/make/rules.bsp has the make rules for these images.嵌入式培训专题微迪软件培训中心Additional ConfigurationFor details, see the Configuration chapter in the Programmers Guide.Many other configuration changes are possible :Change the default boot line in config.hChange boot code in bootConfig.c.Modify I/O system parameters in ConfigAll.h嵌入式培训专题微迪软件培训中心ROM-based VxWorks Start-upMinimal initialization : mask interrupts, disable caches, set initial initial stack, initialize DRAM access.1. _romInit in config/bspName/romInit.sCopy text / data segment(s) to RAM, clear other RAM. Decompress if necessary.2. romStart( ) in config/all/bootnit.cDo pre-kernel hardware & software initialization; start kernelby calling kernelInit( ).3. usrInit( ) in bootconfig.c or usrConfig.cInitialize facilities configured into VxWorks; start boot program or user application4. usrRoot( ) in bootconfig.c or usrConfig.c5. Boot program or user application.嵌入式培训专题微迪软件培训中心Downloaded VxWorks Start-upMinimal initialization : mask interrupts, disable caches, set initial initial stack, initialize DRAM access.1. Boot program loads VxWorks over network, from local disk, etc. Call :Similar to _romInit: mask interrupts, disable caches, set initial stack pointer. Then call:2. _sysInit( ) in config/bspName/sysALib.s3. usrInit( ) in config/all/usrConfig.c4. usrRoot( ) in config/all/usrConfig.c5. User application.嵌入式培训专题微迪软件培训中心Summary1. Modify config.h to exclude unneeded facilities.2. Define INCLUDE_USER_APPL and USER_APPL_INIT to make usrRoot() spawn your tasks.3. Modify the Makefile to link your application into the VxWorks system image MACH_EXTRA = myCode.o . . .4. Remake the system image. New image can be booted or ROM-ed.% make vxWorks% make vxWorks_rom.hex% make bootrom.hex嵌入式培训专题微迪软件培训中心OVERThankyouverymuchGoodluck
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号