Microcomputer Interfacing EE 352
Popular in Course
Popular in Electrical Engineering
This 42 page Class Notes was uploaded by Ms. Isobel Rau on Thursday October 15, 2015. The Class Notes belongs to EE 352 at New Mexico Institute of Mining and Technology taught by William Rison in Fall. Since its upload, it has received 17 views. For similar materials see /class/223647/ee-352-new-mexico-institute-of-mining-and-technology in Electrical Engineering at New Mexico Institute of Mining and Technology.
Reviews for Microcomputer Interfacing
Report this Material
What is Karma?
Karma is the currency of StudySoup.
Date Created: 10/15/15
Getting Started with RTLinux FSM Labs 1110 April 20 2001 Contents H Introduction 11 Sources of Help 12 Before You Begin A Warning 13 RTLinuX Overview The Basic API 21 Understanding an RTLinuX Program 22 The Basic APl 221 Creating RTLinuX POSlX Threads 222 Time Facilities 223 Conversion Routines 224 Scheduling Threads A Simpl Hello World RTLinuX program 231 Code Listing 232 Dissecting Hello World 233 Compiling and Executing Hello World 23 The Advanced API 31 Using Floating Point Operations in RTLinuX POSlX Threads 32 RTLinuX lPC 321 Using Real Time FlFOs 322 Using Shared Memory 323 Waking and Suspending RTLinuX Threads 324 Mutual Exclusion Accessing Memory lnterrupts 341 Hard lnterrupts 342 Soft interrupts 33 34 3 27 27 28 a CONTENTS Special Topics 29 41 Symmetric Multi Processing Considerations 29 42 RTLinuX Serial Driver rtcom 30 43 Interfacing RTLinuX Components to Linux 31 44 Writing RTLinux Schedulers 32 Running RTLinux Programs 33 A1 General 33 A2 Examples 34 A21 Using rtlinux 34 A22 Using modprobe 34 A23 Using insmod and rmmod 34 RTLinux API Reference 35 B1 Getting Around 36 B2 Scripts and Utilities 36 B3 Core RTLinuX API 36 B4 Version 1x API Not for New Projects 42 Chapter 1 Introduction Welcome to the RTLinux Getting Started Guide RTLinux is a hard realtime operating system that coexists with the Linux OS With RTLinux it is pos sible to create realtime POSlX1b threads that will run at precisely speci ed moments of time We have designed the Getting Started Guide with the assumption that the reader has had some programming experience but has never used RTLinux The document is organized as follows First we present basic information needed to get started sources of help common programming errors and an overview of the RTLinux design Chapter 1 Next we present the basic RTLinux API and will step you through your rst Hello World77 program Chapter 2 Third we offer some of the more advanced APl Chapter 3 after which you7ll nd some special considerations and concepts Chapter 4 Finally in the appendices you nd some different ways of running RTLinux programs Appendix A and most importantly a complete listing of the RTLinux APl utilities and important paths Appendix B 11 Sources of Help The RTLinux white paper in docdesignpdf explains the basic architecture in more detail and a summary of the design is presented in Section 13 As you progress in your use of RTLinux you7ll nd yourself wanting more information Fortunately there are many sources of help For the most up to date information see the httpwwwfsmlabscom httpwww rtlinuxcom and httpwwwrtlinuxorg websites 5 CHAPTER 1 INTRODUCTION If you are primarily interested in hard realtime control and not particularly interested in learning how to use RTLinuco itself take a look at FSM Labs RTiC Lab at wwwrtie laborg RTiC Lab is a front end to RTLinup that greatly simpli es hard realtime eontrol implementation monitoring and tuning I f you are interested in running RTLinuco on an industry stan dard P0404 board or other type of minimal or embedded sys tem see FSMLabs MiniRTL project found at wwwrtlinum orgminirtlhtml MiniRTL ts on a signle oppy disk and provides full RTLinup capabilities Some other documents you may nd useful are Note All references to directories and les assume that RTLinuX has been installed in its default location usrrtlinux The RTLinuX Manual Project available at wwwrtlinuxorgdocu mentsdocumentationRTLManualRTLManualhtml The Single UNIX speci cation available at wwwopengrouporgonlinepubs 7908799indexhtml The Single UNIX spec is also installed in HTML format with the RTLinuX distribution susv2indexhtml The LinuXThreads library documentation at httppauillacinriafr Xleroylinuxthreads included with glibc2 You can try running man 3 pthreadcreate to see if it is installed on your system Getting Started With POSlX Threads77 by Thomas Wagner and Don Towsley available at centauruscsumasseduquotwagnerthreads htmltutorialhtml Pthreads Programming available at WWWoreillycomcatalogpthread by Bradford Nichols Dick Buttlar and Jacqueline Proulx Farrell 12 BEFORE YOU BEGIN A WARNING 7 o Other documents or books describing POSlX threads The RTLinux distribution itself contains documentation to help you along in your RTLinux projects 0 The man directory contains UNIX manual pages describing features and commands speci c to RTLinux You can modify the MANPATH environment variable so that these manual pages can be found with the man command Type man man for instructions on how to change the MANPATH variable globally The htmlMAN directory contains the same manual pages converted to HTML 0 The RTLinux Frequently Asked Questions FAQ le can be found under the top level directory of the RTLinux source tree 0 The examples directory contains programs which will give you rst hand experience with the RTLinux APl If after attempting all of the above you still have questions there is another rich source of information via the RTLinux mailing lists You can subscribeunsubscribe to these lists at wwwrtlinuxorgmailinglistshtml Of course you may not be the rst person with your question To ease your search for answers the lists are both browseable and searchable 12 Before You Begin A Warning Realtime programs in RTLinux are executed in kernel space and have little or no protection against bugs in the users code Special care must be taken when programming realtime tasks because programming errors may bring the system down RTLinux supplies a debugger within its source tree under the directory debugger Use of the debugger is strongly recommended to reduce the risk of system crashes Note also that by default RTLinux tasks do not have access to the com puter7s Floating Point Unit FPU You must explicitly set permissions for each of your RTLinux tasks that require the use of the FPU 8 CHAPTER 1 INTRODUCTION 13 RTLinux Overview This section is intended to give users a top level understanding of RTLinux It is not designed as an in depth technical discussion of the systems ar chitecture Readers interested in the topic can start with Michael Bara banov7s Master7s Thesis A postscript version is available for download at WWWrtlinuxorgdocumentspapersthesisps The basic premise underlying the design of RTLinux is that it is not fea sible to identify and eliminate all aspects of kernel operation that lead to un predictability These sources of unpredictability include the Linux scheduling algorithm which is optimized to maximize throughput device drivers un interrruptible system calls the use of interrupt disabling and virtual memory operations The best way to avoid these problems is to construct a small predictable kernel separate from the Linux kernel and to make it simple enough that operations can be measured and shown to have predictable exe cution This has been the course taken by the developers of RTLinux This approach has the added bene t of maintainability prior to the development of RTLinux every time new device drivers or other enhancements to Linux were needed a study would have to be performed to determine that the change would not introduce unpredictability Figure 11 shows the basic Linux kernel without hard realtime support You will see that the Linux kernel separates the hardware from user level tasks The kernel has the ability to suspend any user level task once that task has outrun the slice of time allotted to it by the CPU Assume for example that a user task controls a robotic arm The standard Linux kernel could potentially preempt the task and give the CPU to one which is less critical eg one that boots up Netscape Consequently the arm will not meet strict timing requirements Thus in trying to be fair to all tasks the kernel can prevent critical events from occurring Figure 12 shows a Linux kernel modi ed to support hard realtime An additional layer of abstraction termed a virtual machine in the litera ture has been added between the standard Linux kernel and the computer hardware As far as the standard Linux kernel is concedrned this new layer appears to be actual hardware More importantly this new layer introduces its own xed priority scheduler This scheduler assigns the lowest priority to the standard Linux kernel which then runs as an independent task Then it allows the user to both introduce and set priorities for any number of realtime tasks 1339 RTLINUX OVERVIEW User Procesws 5mm Libmdcs Drvicc UnixLinux Kernel Lro T I T Hardwm 1mme Hardw are Figure 11 Detail of the bare Linux kernel a m mums le Racesses RTrLinux Plugin w I mmmwmw Figure 12 Detail of the RTLinux kernel 10 CHAPTER 1 INTRODUCTION The abstraction layer introduced by RTLinux works by intercepting all hardware interrupts Hardware interrupts not related to realtime activities are held and then passed to the Linux kernel as software interrupts when the RTLinux kernel is idle and the standard Linux kernel runs Otherwise the appropriate realtime interrupt service routine lSR is run The RTLinux executive is itself nonpreemptible Unpredictable delays within the RTLinux executive are eliminated by its small size and limited operations Realtime tasks have two special attributes they are privileged that is they have direct access to hardware and they do not use virtual memory Realtime tasks are written as special Linux modules that can be dynamically loaded into memory They are are not expected to execute Linux system calls The initialization code for a realtime tasks initializes the realtime task structure and informs RTLinux of its deadline period and release time constraints Non periodic tasks are supported through the use of interrupts In contrast with some other approaches to realtime RTLinux leaves the Linux kernel essentially untouched Via a set of relatively simple modi ca tions it manages to convert the existing Linux kernel into a hard realtime environment without hindering future Linux development Chapter 2 The Basic API Writing RTLinuX Modules This chapter Introduces critical concepts that must be grasped in order to successfully write RTLinux modules It also presents the basic Application Programming Interface API used in all RTLinux programs Then it steps the user through the creation of a basic Hello World77 programming example7 which is intended to help the user in developing their very rst RTLinux program 21 Understanding an RTLinuX Program In the latest versions of RTLinux7 programs are not created as standalone applications Rather7 they are modelled as modules which are loaded into the Linux kernel space A Linux module is nothing but an object le7 usually created with the C ag argument to gcc The module itself is created by compiling an ordinary C language le in which the main function is replaced by a pair of initCleanup functions int initmodule void Cleanupmodule As its name implies7 the initmodule function is called when the module is rst loaded into the kernel It should return 0 on success and a negative value on failure Similarly7 the Cleanupmodule is called when the module is unloaded 12 CHAPTER 2 THE BASIC API For example if we assume that a user has created a C le named mano dule C the code can be converted into a module by typing the following gcc C SOME FLAGS mymodulec This command creates a module le named mymoduleo which can now be inserted into the kernel To insert the module into the kernel we use the insmod command To remove it the rmmod command is used Documentation for both of these commands can be accessed by typing man 8 insmod and man 8 rmmod Here the quot8 forces the man command to look for the man ual pages associated with system administration From now on we will refer to commands by their name and manual category Using this format these two commands would be referred to as insmod 8 and rmmod 8 For further information on running RTLinux programs refer to Appendix A 22 The Basic API Now that we understand the general structure of modules and how to load and unload them we are ready to look at the RTLinux API 221 Creating RTLinuX POSIX Threads A realtime application is usually composed of several threads of execution Threads are light weight processes which share a common address space Conceptually Linux kernel control threads are also RTLinux threads with one for each CPU in the system In RTLinux all threads share the Linux kernel address space 22 THE BASIC API 13 To create a new realtirne thread7 we use the pthreadcreate3 func tion This function must only be called from the Linux kernel thread ie7 using initJnodule 0 include ltpthreadhgt int pthreadcreate pthreadt thread pthreadattrt attr void startroutine void void arg The thread is created using the attributes speci ed in the attr77 thread attributes object If attr is NULL7 default attributes are used For more detailed inforrnation7 refer to the POSlX functions 0 pthreadattrinit 3 7 o pthreadattrsetsChedparam37 and o pthreadattrgetsChedparam3 as well as these RTL speci c functions 0 pthreadattrgetcpu41p3 and o pthreadattrsetcpu41p3 which are used to get and set general attributes for the scheduling parameters and the CPUs in which the thread is intended to run The ID of the newly created thread is stored in the location pointed to by thread The function pointed to by startloutine is taken to be the thread code It is passed the arg77 argurnent To cancel a thread7 use the POSlX function pthreadcancelpthread thread You should join the thread in Cleanupmodule with pthreadjoin for its resources to be dealloeated 14 CHAPTER 2 THE BASIC API You must make sure the thread is cancelled before eall ing pthreadjoin from Cleanupmodule Other wise Linucs will hang waiting for the thread to n ish If unsure use pthreaddelete41p3 instead of pthreadjancel pthreadj oin 222 Time Facilities RTLinuX provides several clocks that can be used for timing functionality such as as referencing for thread scheduling and obtaining timestamps Here is the general timing APl inc lude ltrtltime hgt int Clockgettimeclockidt Clockid struct timespec ts hrtimet ClockgethrtimeClockidt Clock struct timespec timet tvsec seconds long tvnsec nanoseconds To obtain the current clock reading use the Clockgettime 3 function where Clockid is the clock to be read and ts is a structure which stores the value obtained The hrtimej value is expressed as a single 64 bit number of nanoseconds Thus Clocngethrtime 3 is the same as Clocngettime but returns the time as an hrtimei rather than as a timespec structure 223 Conversion Routines Several routines exist for converting from one form of time reporting to the other inc lude ltrtltime hgt hrtimet timespectonsconst struct timespec ts struct timespec timespecfromnshrtimet t const struct timespec hrt2ts hrtimetvalue 22 THE BASIC API 15 These are especially useful macros for passing time values into nanosleep7 pthreadmondiimedwait and the like Currently supported clocks are 0 CLOClLMONOTONlC This POSlX clock runs at a steady rate and is never adjusted or reset CLOClLREALTlME This is the standard POSlX realtime clock Cur rently7 it is the same as CLOClLMONOTONlC It is planned that in future versions of RTLinuX this clock will give the world time CLOClLRTLSCHED The clock that the scheduler uses for task schedul ing The following clocks are architecture dependent They are not normally found in user programs 0 CLOCK8254 Used on non SMP X86 machines for scheduling o CLOClLAPlC Used on SMP X86 machines 0 CLOClLAPlC corresponds to the local APlC clock of the processor that executes Clockgettime You cannot read or set the APlC clock of other processors 224 Scheduling Threads RTLinuX provides scheduling which allows thread code to run at speci c times RTLinuX uses a pure priority driven scheduler7 in which the highest priority ready thread is always chosen to run If two threads have the same priority7 which one is chosen is unde ned RTLinuX uses the following scheduling APl int pthreadsetschedparampthreadt thread int policy const struct schedparam param int pthreadmakeperiodicnppthreadt thread const struct itimerspec its int pthreadwaitnpvoid int schedgetprioritymaxint policy 16 CHAPTER 2 THE BASIC API int schedgetpriorityminint policy struct itimerspec struct timespec itinterval timer period struct timespec itvalue timer expiration Thread priority can be modi ed at thread creation time by using pthreadattrsetschedparam3 or afterwards by using pthreadisetschedparam3 The policy argument is currently not used in RTLinux7 but should be speci ed as SCHEDEIFD for compatibility with future versions The struc ture schediparam contains the schedipriority member Higher values cor respond to higher priorities Use 0 schedigetipriorityunax 7and o schedigetipriorityunin3 to determine possible values of schedipriority To make a realtime thread execute periodically7 users may use the non portablel function pthreademakeiperiodicmp 3 which marks the thread as periodic Timing is speci ed by the itimer struc ture its The itivalue member of the passed struct itimerspec speci es the time of the rst invocation the itiinterval is the thread period Note that when setting up the period for task T7 the period speci ed in the it imer structure can be 0 This means that task T will execute only once The actual execution timing is performed by use of the function 1It is possible to have threads execute periodically Within RTLinux by using the pure POSlX APli However7 this scheme is quite lengthy This particular function has been added7 therefore7 to reduce user development time 23 A SIMPL HELLO WORLD RTLINUX PROGRAM 17 pthreadJJaitJip 3 This function suspends the execution of the calling thread until the time speci ed by pthreadJnakeperiodi Cle 3 In the next section well put the API to practical use 23 A Simpl Hello World RTLinuX program well now write a small program that uses all of the API that we7ve learned thus far This program will execute two times per second7 and during each iteration it will print the message I m here my arg is 0 231 Code Listing Save the following code under the lename hello C include ltrtlhgt include lttimehgt include ltpthreadhgt pthreadt thread void startroutinevoid arg struct schedparam p p schedpriority 1 pthreadsetschedparam pthreadself SCHEDFIFU ampp pthreadmakeperiodicnp pthreadself gethrtime 500000000 while 1 pthreadwaitnp rtlprintfquotI m here my arg is ooxnquot unsigned arg return 0 18 CHAPTER 2 THE BASIC API int initmodulevoid return pthreadcreate ampthread NULL startroutine O void Cleanupmodule void pthreadcancel thread pthreadjoin thread NULL This program can be found in exampleshello Now lets analyze the code 232 Dissecting Hello World In our program the initmodule function begins the entire process by creating our execution thread 7 ern bodied in the function startroutine 7 with an argument of 0 passed to startloutine startloutine has three components initialization run tirne and terrni nation 7 best understood as the blocks before during and after the while loop respectively Upon the rst call to the newly created thread startroutine the initialization section tells the scheduler to assign this thread a scheduling priority of 1 one with the call to pschedpriority Next the thread sets the scheduler7s behavior to be SCHEDEIFO for all subsequent executions with the call to pthreadsetschedparam Finally by calling the function pthreadunakeperiodicmp 23 A SIMPL HELLO WORLD RTLINUX PROGRAM 19 the thread tells the scheduler to periodically execute this thread at a fre quency of 2H2 500 microseconds This marks the end of the initialization section for the thread The while loop begins with a call to the function pthreadlwaitmpo which blocks all further execution of the thread until the scheduler calls it again Once the thread is called again it executes the rest of the contents inside the while loop until it encounters another call to pthreadlwaitmpo Because we havent included any way to exit the loop this thread will con tinue to execute forever at a rate of 2H2 The only way to stop the program is by removing it from the kernel with the rmmod8 command 233 Compiling and Executing Hello World In order to execute our program we must rst do the following 1 Compile the source code and create a module We can normally accom plish this by using the Linux GCC compiler directly from the command line To simplify things however well create a Make le Then well only need to type make to compile our code E0 Locate and copy the rtl mk le The rtl mk le is an include le which contains all the ags needed to compile our code For simplicity we7ll copy it from the RTLinux source tree and place it alongside of our hello C le 9 Insert the module into the running RTLmucc kernel The resulting ob ject binary must be plugged in77 to the kernel where it will be executed by RTLinux Let7s look at these steps in some detail We begin by creating the Make le that will be used to compile our hello C program Type the following into a le called Makefile and put it in the same directory as your hello C program 20 CHLAPTYH2 THEIBASICiAPU helloo helloc gcc CFLAGS helloc If you havent already done so locate the le rtlmk and copy it into the same directory as your hello C and Makefile les The rtl mk le can usually be found at usrincludertlinuXrtl mk Cp usrincludertlinuXrtlmk Note the trailing dot Now type the following make f rtlmk helloo This compiles the helloc program and produces an object le named helloo We now need to load the RTLinuX modules There are several ways to do this The easiest is to use the rtlinux1 command as root rtlinux start hello You can check the status of your modules by typing the command rtlinux status hello For more information about the usage of the rtlinux1 command refer to its man page or type rt 1 inux he lp You should now be able to see your hello 0 program printing its message twice per second Depending on the con guration of your machine you should either be able to see it directly in your console or by typing dmesg To stop the program we need to remove it from the kernel To do so type rtlinux stop hello For other ways on running RTLinuX programs refer to Appendix A Congratulations you have now successfully created and run your very rst RTLinuX programl Chapter 3 The Advanced API Getting More Out of Your RTLinuX Modules RTLinuX has a rich assortment of functions which can be used to solve most realtime application problems This chapter describes some of the more advanced concepts 31 Using Floating Point Operations in RT LinuX POSIX Threads The use of oating point operations in RTL POSIX threads is prohibited by default The RTL speci c function pthreadsetfp41p3 is used to change the status of oating point operations int pthreadsetfpnp pthreadtthread int flag To enable FP operations in the thread7 set the ag to 1 To disable FP operations7 pass 0 The examplesfp directory contains several examples of tasks which use oating point and the math library 22 CHAPTER 3 THE ADVANCED AP 32 RTLinuX InterProcess Communication IPC The general philosophy of RTLinux requires the realtime component of an application to be lightweight small and simple Applications should be split in such a way that as long as timing restrictions are met most of the work is done in user space This approach makes for easier debugging and better understanding of the realtime part of the system Consequently communi cation mechanisms are necessary to interface RTLinux tasks and Linux RTLinux provides several mechanisms which allow communication be tween realtime threads and user space Linux processes The most important are realtime FlFOs and shared memory 321 Using RealTime FIFOS Realtime FlFOs are First ln First Out queues that can be read from and written to by Linux processes and RTLinux threads FlFOs are uni directional 7 you can use a pair of FlFOs for bi directional data exchange To use the FlFOs the systemrtlposixioo and fifosrtlfifoo Linux modules must be loaded in the kernel RT FlFOs are Linux character devices with the major number of 150 Device entries in dev are created during system installation The device le names are devrtf0 devrtf1 etc through devrtf63 the maximum number of RT FlFOs in the system is con gurable during system compila tion Before a realtime FIFO can be used it must be initialized include ltrtlfifohgt int rtfcreateunsigned int fifo int size int rtfdestroyunsigned int fifo rtfcreate allocates the buffer of the speci ed size for the fo buffer The fifo argument corresponds to the minor number of the device rtfdestroy deallocates the FIFO These functions must only be called from the Llnum kernel thread le from initmoduleO 32 RTLINUX IPC 23 After the FIFO is created the following calls can be used to access it from RTLinux threads open2 read2 write2 and close2 Support for other STDIU functions is planned for future releases Current implementation requires the FIFOs to be opened in non blocking mode OJVONBLOCK by RTL threads You can also use the RTLinux specific functions rtflput 3 and rtflget 3 Linux processes can use UNIX file 10 functions without restriction See the examplesmeasurementrtprocessc example program for a practical application of RT FIFUs 322 Using Shared Memory For shared memory you can use the excellent mbuff driver by To masz Motylewski motylchemieunibasch It is included with the RTLinux distribution and is installed in the driversmbuff directory A manual is included with the package Here we ll just briefly describe the basic mode of operation First the mbuffo module must be loaded in the kernel Two functions are used to allocate blocks of shared memory connect to them and eventually deallocate them include ltmbuffhgt void mbuffallocconst char name int size void mbufffreeconst char name void mbuf The first time mbufflalloc is called with a given name a shared memory block of the specified size is allocated The reference count for this block is set to 1 Un success the pointer to the newly allocated block is returned NULL is returned on failure If the block with the specified name already exists this function returns a pointer that can be used to access this block and increases the reference count 24 CHAPTER 3 THE ADVANCED API mbufflfree deassociates mbuff from the specified buffer The reference count is decreased by 1 When it reaches 0 the buffer is deallocated These functions are available for use in both Linux processes and the Linux kernel threads mbufflalloc dud mbufflfree cannot be used front 7edL time threads You should call them from initJnodule dud cleanumeodule O h 323 Waking and Suspending RTLinuX Threads Interrupt driven RTLinux threads can be created using the thread wakeup and suspend functions int pthreadwakeupnppthreadt thread int pthreadsuspendnpvoid The general idea is that a threaded task can be either awakened or suspended from within an interrupt service routine An interrupt driven thread calls pthreadlsuspendnppthreadlself and blocks Later the interrupt handler calls pthreadlwakeuplnp3 for this thread The thread will run until the next call to pthreadlsuspendj An example can be found in examplessoundirqthreadc Another way to implement interrupt driven threads is to use semaphores See examplesmeasurementsirqsemac for examples of this method 324 Mutual Exclusion Mutual exclusion refers to the concept of allowing only one task at a time out of many to read from or write to a shared resource Without mutual exclusion the integrity of the data found in that shared resource could become compromised Refer to the appendix for further information on mutual exclusion RTLinux supports the PDSIX pthreadJmutex family of functions includertlJmutexh Currently the following functions are available 33 ACCESSING MEMORY 25 o pthreadJnutexattrgetpshared3 pthreadJnutexattrlsetpshared3 o pthreadJnutexattrlinit 3 pthreadJnutexattrldestroy 3 o pthreadJnutexattrlsettype 3 pthreadJnutexattrgettype 3 o pthreadJnutexlinit3 o pthreadJnutexldestroy 3 pthreadJnutexllock 3 o pthreadJnutexltrylock 3 pthreadJnutexlunlock 3 The supported mutex types include o PTHREADMUTEXJIURMAL default PDSIX mutexes and o PTHREADMUTELSPINLUCK spinlocks See examplesmutex for a test program PDSIX semaphores are also supported An example using PDSIX semaphores can be found in examples mutexsemaltest c 33 Accessing Physical Memory and IO Ports from RTLinuX Threads These capabilities are essential for programming hardware devices in the computer RTLinux just like ordinary Linux supports the devmem device man4mem for accessing physical memory from RTLinux threads The rtllposixioo module must be loaded The program opens devmem mmaps it and then proceeds to read and write the mapped area See examplesmmap for an example 26 C L4P11H3 TYiEAADVQUVCEIAIU In a module you can call map from Linucc mode only lo from initmodule Calling map from RT threads will ja Another way to access physical memory is via Linux s iorenlap call char ptr ioremapPHYSAREAADDRESS PHYSAREALENGTH ptri X 10 port access functions specifically for X86 architecture are as follows 0 Output a byte to a port include ltasmiohgt void outbunsigned int value unsigned short port void outbpunsigned int value unsigned short port 0 Output a word to a port include ltasmiohgt void outwunsigned int value unsigned short port void outwpunsigned int value unsigned short port 0 Read a byte from a port include ltasmiohgt char inbunsigned short port char inbpunsigned short port 0 Read a word from a port include ltasmiohgt short inwunsigned short port short inwpunsigned short port 341NTERRUPTS 27 Functions with the p suffix eg outblp provide a small delay after reading or writing to the port This delay is needed for some slow ISA devices on fast machines See also the Linux lD port programming mini HUWTD Check out examplessound to see how some of these functions are used to program the PC realtime clock and the speaker 34 Soft and Hard Interrupts There are two types of interrupts in RTLinux hard and soft Soft interrupts are normal Linux kernel interrupts They have the advantage that some Linux kernel functions can be called from them safely However for many tasks they do not provide hard realtime performance they may be delayed for considerable periods of time Hard interrupts or realtime interrupts on the other hand have much lower latency However just as with realtime threads only a very limited set of kernel functions may be called from the hard interrupt handlers 341 Hard Interrupts The two functions 0 rtllrequestlirq3 and o rtllfreelirq3 are used for installing and uninstalling hard interrupt handlers for specific interrupts The manual pages describe their operation in detail include ltrtlcorehgt int rtlrequestirqunsigned int irq unsigned int handler unsigned int struct ptregs int rtlfreeirqunsigned int irq 28 C3L4PTYH3 TYiEiADVQUVCEIAIU 342 Soft interrupts int rtlgetsoftirq void handlerint void struct ptregs const char devname void rtlglobalpendirqint ix void rtlfreesoftirqunsigned int irq The rtllgetlsoftlirq3 function allocates a virtual irq number and installs the handler function for it This virtual interrupt can later be triggered using rtllgloballpendlirq3 rtllgloballpendlirq is safe to use from realtime threads and realtime interrupts frees the allocated virtual interrupt Note that soft interrupts are used in the RTLinuX FIFO implementation fifosrtllfifoc rtllfreelsoft Chapter 4 Special Topics You may never find yourself needing to know any of the following Then again you might 41 Symmetric MultiProcessing Considera tions From the point of View of thread scheduling RTLinuX implements a separate UNIX process for each active CPU in the system In general thread control functions can only be used for threads running on the local CPU Notable exceptions are 0 int pthreadlwakeuplnppthreadlt thread wake up suspended thread 0 int pthreadlcancel pthreadlt thread cancel thread 0 int pthreadljoinpthreadt thread wait for thread to finish 0 int pthreadldeletelnp pthreadlt thread kill the thread By default a thread is created to run on the current CPU To assign a thread to a particular CPU use the pthreadlattrlsetcpquKS function to set the CPU pthread attribute See examplesmuteX muteXc 30 CHLAPTYH4 SPECHAL TOIUCS 42 RTLinux Serial Driver rtlcom rtlcom3 is a driver for 8250 and 16550 families of UARTs commonly used in PCs CUMl CDM2 etc include ltrtcomhgt include ltrtcomPhgt The available API is as follows void rtcomwriteunsigned int com char pointer int cnt int rtcomreadunsigned int com char pointer int cnt int rtcomsetupunsigned int com unsigned int baud unsigned int parity unsigned int stopbits unsigned int wordlength define RTCDMCNT n struct rtcomstruct int magic int baud base int port int irq int flag void isrvoid int type int ier struct rtbufstruct ibuf struct rtbufstruct obuf rtcomtable RTCDMCNT where o rtlcouLwrite3 writes cnt realtime serial port com unused base rate 11520 BASEBAUD in rtcomPh for standard ports port number interrupt number IRQ for the port flags set for this port address of the interrupt service routine a copy of the IER register address of the port input buffer address of the port output buffer characters from buffer ptr to the 43 IN TERFA CIN G RTLINUX COMPONENTS TO LINUX 31 o rtlcomlread3 attempts to read cnt characters to buffer ptr from the realtime serial port com o rtlcomlsetup3 is used to dynamically change the parameters of each realtime serial port rtlcom is a Linux module The user must specify relevant serial port information via entries in rtlcouLsetup In addition the user must specify via entries in the rtlcouLtable located in rtlcomh the following 0 Number of serial ports available n 0 Serial ports and relevant parameters for each and 0 An ISR to be executed when the port irq fires When rtlcom 3 is installed with either insmod8 modprobe8 or rtlinux1 its initJmodule function in rtlcomc requests the port device memory registers the ISR and sets various default values for each port entry in rtlcomltable 43 Interfacing RTLinux Components to Linux RTLinux threads sharing a common address space with the Linux kernel can in principle call Linux kernel functions This is usually not a safe thing to do however because RTLinux threads may run even while Linux has interrupts disabled Unly functions that do not modify Linux kernel data structures eg vsprintf should be called from RTLinux threads RTLinux provides two delayed execution mechanisms to overcome this limitation soft interrupts and task queues The RTLihuce white paper discusses this topic in more detail 32 CHLAPTYH4 SPECHAL TOIUCS 44 Writing RTLinuX Schedulers Most users will never be required to write a scheduler Future versions of RTLinuX are expected to have a fully customizable scheduler but in the meantime here are some points to help the rest of you along 0 The scheduler is implemented in the schedulerrtllschedc file 0 The scheduler s architecture dependent files are located in includearch i386 and scheduleri386 o The scheduling decision is taken in the rtllschedule function Thus by modifying this function it is possible to change the scheduling policy Further questions in this area may be addressed directly to the FSM Labs Crew Appendix A Running RTLinuX Programs Your RTLinux distribution comes complete with several examples in the examples sub directory These examples are useful not only for testing your brand new RTLinux distribution but for helping get you started writing your own RTLinux programs A 1 General Before you will be able to run any RTLinux programs you must first insert the RTLinux scheduler and support modules in the modules into the Linux kernel Use any of the following o rt nux1 script the preferred method 0 insm0d8 o m0dpr0be8 or o the insrtl script file that has been supplied for you in the scripts directory For more information on Linux modules and how to manipulate them see the Linux Kernel HDWTU The following sections describe each of these methods in more detail 33 34 APPENDIX A RUNNING RTLINUX PROGRAMS A 2 Examples A2l Using rtlinux Beginning with RTLinuX 30 pre9 users can load and remove user modules by using the rtlinuX1 command To insert remove and obtain status information about RTLinuX modules use the following commands rtlinuX start mylprogram rtlinuX stop mylprogram rtlinuX staus mylprogram For further information on the the rtlinuX1 script type either man 1 rtlinuX or rt 1 inuX he lp A22 Using modprobe all the RTLinuX modules type the following modprobe a rtl rtltime rtlsched rtlposixio rtlfifo Using modprobe requires that modules be installed in libmoduleske39r neL39uersion A23 Using insmod and rmmod Suppose we have the appropriately named mylprogramo Assuming that all the appropriate RTLinuX modules have already been loaded all that s left to do is to load this module into the kernel insmod myprogramo To stop the program all we need do is type rmmod myprogram Appendix B The RTLinuX API at a Glance Some paths to be aware of RTLinuX is installed in the directory usrrtlinuX XXX where XXX is the version number To simplify future development a symbolic link has been created as usrrtlinuX which points to usrrtlinuX XXX Users are encouraged to specify their paths via this symbolic link to maintain future compatibility with new RTLinuX versions usrrtlinuXinclude contains all the include files necessary for development projects usrrtlinuXexamples contains the RTLinuX example programs which illustrate the use of much of the API usrdocrtlinuXman contains the manual pages for RTLinuX usrrtlinuXmodules contains the core RTLinuX modules usrrtlinuXbin contains RTLinuX scripts and utilities The following sections provide a listing of the various utilities and APIs available in RTLinuX 35 36 APPENDIX B RTLINUX API REFERENCE B 1 Getting Around There are several manual pages which give overviews on the technology and the APIs o rtllvl 3 RTLinuX facilities for RTLinuX V1X The RTLinum V1 API is presented eccelusiyely for backwards compatibility It is no longer recommended for new projects Users are strongly discouraged from starting any new projects with this API 0 rtf 4 realtime fifo devices 0 rtllindex 4 A comprehensive list of RTLinuX functions 0 rtlinuX 4 A general roadmap and description to RTLinuX B2 Scripts and Utilities The following utilities are designed to make your programming job easier 0 rtl config 1 script used to get information about the installed version of RTLinuX cflags include paths and documentation paths 0 rtlinuX 1 SysV compatible script used to start RTLinuX and load the user s RTLinuX modules B3 Core RTLinux API Here is the main RTLinuX API You are encouraged to use this API for all new projects 0 clocklgethrtime 3 get high resolution time using the specified clock B be CORERTHNUXAPI clocklgettime clock and timer functions clocklsettime clock and timer functions gethrtime 3 get high resolution time nanosleep high resolution sleep pthreadlattrlgetcpunp 3 examine and change the CPU pthread attribute pthreadlattrlgetschedparam access dynamic thread scheduling parameters pthreadlattrlgetdetachstate get detachstate attributes pthreadlattrlgetstacksize get stacksize attribute pthreadlattrlinit initialize threads attribute object pthreadlattrlsetcpujlp 3 attribute examine and change the CPU pthread pthreadlattrlsetdetachstate set detachstate attributes pthreadlattrlsetfplnp 3 attribute set and get floating point enable pthreadlattrlsetschedparam access dynamic thread scheduling parameters pthreadlattrlsetstacksize set stacksize attribute pthreadlcancel 3 stop and cancel a thread not recommended pthreadlcreate 3 create a thread pthreadlcondattrgdestroy object destroy condition variable attributes pthreadlcondattrlgetpshared variable attributes get the process shared condition 38 APPENDIX B RTLINUX API REFERENCE pthreadlcondattrlinit initialize condition variable attributes object pthreadlcondattrlsetpshared variable attributes set the process shared condition pthreadlcondlbroadcast broadcast a condition pthreadlcondgdestroy destroy condition variable pthreadlcondlinit initialize condition variable pthreadlcondlsignal signal a condition pthreadlcondltimedwait wait on a condition variable pthreadlcondlwait wait on a condition variable pthreadldeletelnp 3 delete a realtime thread pthreadlexit thread termination pthreadljoin 3 terminate a thread pthreadkill 3 send a signal to a thread pthreadllinux 3 thread get the thread identifier of the Linux pthreadJmakelperiodiclnp 3 mark a realtime thread as periodic pthreadJmutexattrldestroy3 Destroys a muteX attribute object pthreadJmutexattrlgetprioceiling of muteX attribute object get priority ceiling attribute pthreadJmutexattrlgetpshared of a muteX attribute object obtains the process shared setting pthreadJmutexattrlgettype get the muteX type pthreadJmutexattrlinit initializes a muteX attribute object B OJ CORE RTLINUX API 39 pthreadjmutexattrlsetprioceiling of mutex attribute object set priority ceiling attribute pthreadJmutexattrlsetpshared of a mutex attribute object sets the process shared attribute pthreadjmutexattrlsettype set the mutex type pthreadJmuteXJdestroy destroys a mutex pthreadJmutexlinit3 initializes a mutex with the attributes specified in the specified mutex attribute object pthreadjmutexllock locks an unlocked mutex If the mutex is already locked the calling thread blocks until the thread that currently holds the mutex releases it pthreadJmutexltrylock tries to lock a mutex If the mutex is already locked the calling thread returns without wating for the mutex to be freed pthreadjmutexlunlock unlocks a mutex pthreadgetschedparam get schedparam attribute pthreadlself get calling thread s ID pthreadlsetcancelstate set cancelability state pthreadlsetschedparam set schedparam attribute pthreadlsetfplnp 3 in a thread allow use of floating point operations pthreadlsuspendnp 3 suspend execution of a realtime thread pthreadlwaitlnp 3 next period suspend the current thread until the pthreadlwakeuplnp 3 wake up a realtime thread rtlcom 3 serial port driver for RTLinuX 40 APPENDIX B RTLINUX API REFERENCE rtlconLread 3 read data in realtime from a serial por rtlcouLsetup 3 dynamically change the parameters of each realtime serial port rtlconLtable 3 port an array of descriptions one per serial rtlcoanrite 3 write data in realtime to a serial port rtflcreate 3 create a realtime fifo rtflcreatelhandler 3 install a handler for realtime fifo data rtflcreatelrtlhandler 3 install a handler for realtime fifo data rtfgdestroy 3 remove a realtime fifo created with rtflcreate3 rtflflush 3 empty a realtime FIFU rtflget 3 read data from a realtime fifo rtfllinkluserlioctl 3 realtime FIFU install an ioctl 3 handler for a rtflput 3 write data to a realtime fifo rthmakeluserlpair 3 bidirectional FIFU make a pair of RT FIFDs act like a rtllallowlinterrupts 3 control the CPU interrupt state rtllfreelirq 3 install and remove realtime interrupt handlers rtllfreelsoftlirq 3 handlers install and remove software interrupt rtllgetlsoftlirq 3 handlers install and remove software interrupt B OJ CORE RTLINUX API rtllgetcpuid 3 get the current processor id rtllgetschedclock 3 get the current scheduler clock rtllgloballpendlirq 3 schedule a Linux interrupt rtllhardldisablelirq 3 interrupt control rtllhardlenablelirq 3 interrupt control rtllnolinterrupts 3 control the CPU interrupt state rtllprintf 3 print formatted output rtllrequestlirq 3 handlers install and remove realtime interrupt rtllrestorelinterrupts 3 control the CPU interrupt state rtllsetclockmode 3 set the RTLinuX clock mode rtllstoplinterrupts 3 control the CPU interrupt state rtlinuxlsigaction 3 functions RTLinuX v3 User Level signal handling rtlinuxlsignal 3 list of available RTLinuX User Level signals rtlinuxlsigprocmask 3 functions RTLinuX v3 User Level signal handling rtlinuxlsigsetops 3 RTLinuX User Level signal set operations schedgetprioritmeaX policy get priority limits for the scheduling schedgetprioritmein policy get priority limits for the scheduling senLinit initialize PDSIX semaphore seuLdestroy destroy an unnamed PDSIX semaphore seuLgetvalue get the value of a sempahore 42 APPENDIX B RTLINUX API REFERENCE seuLpost unlock a semaphore semltrywait lock a semaphore semlwait lock a semaphore sigaction 2 RTLinux PDSIX signal handling functions sysconf get configurable system variables time clock and timer functions uname get name of current system usleep suspend execution for an interval BA Version 1x API Not for New Projects The v1 API is exclusively for older RTLinux projects recommended for use with new projects It is NOT This listing is for backward compatibility only freelRTirq 3 uninstall an interrupt handler requesthTirq 3 install an interrupt handler rtlgetltime 3 get time in ticks rtltaskadelete 3 delete a realtime task rtltasklinit 3 create a realtime task rtltaskJmakelperiodic 3 mark a realtime task for execution rtltasklsuspend 3 suspend execution of a realtime task rtltasklwait 3 suspend execution for the current period until the next period rtltasklwakeup 3 task to run allow a previously suspended realtime rtluselfp 3 point unit setremove permission for task to use floating