


































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



































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 POSIX.1b threads that will run at precisely specified 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 first “Hello World” program (Chapter 2). Third, we offer some of the more advanced API (Chapter 3), after which you’ll find some special considerations and concepts (Chapter 4). Finally, in the appendices, you find some different ways of running RTLinux programs (Appendix A) and, most importantly, a complete listing of the RTLinux API, utilities, and important paths (Appendix B).
The RTLinux white paper in doc/design.pdf explains the basic architecture in more detail and a summary of the design is presented in Section 1.3. As you progress in your use of RTLinux, you’ll find yourself wanting more information. Fortunately, there are many sources of help. For the most up-to-date information, see the http://www.fsmlabs.com , http://www.- rtlinux.com and http://www.rtlinux.org websites.
The RTLinux distribution itself contains documentation to help you along in your RTLinux projects:
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 subscribe/unsubscribe to these lists at www.rtlinux.org/mailing lists.html. Of course, you may not be the first person with your question. To ease your search for answers, the lists are both browseable and searchable.
1.2 Before You Begin: A Warning
Realtime programs in RTLinux are executed in kernel space and have little or no protection against bugs in the user’s 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- puter’s Floating Point Unit (FPU). You must explicitly set permissions for each of your RTLinux tasks that require the use of the FPU.
1.3 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 system’s ar- chitecture. Readers interested in the topic can start with Michael Bara- banov’s Master’s Thesis. (A postscript version is available for download at www.rtlinux.org/documents/papers/thesis.ps ). 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 benefit 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 1.1 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 (e.g. 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 1.2 shows a Linux kernel modified 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 fixed-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.
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 (ISR) 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 modifica- tions, it manages to convert the existing Linux kernel into a hard realtime environment without hindering future Linux development.
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 World” programming example, which is intended to help the user in developing their very first RTLinux program.
In the latest versions of RTLinux, programs are not created as standalone applications. Rather, they are modelled as modules which are loaded into the Linux kernel space. A Linux module is nothing but an object file, usually created with the -c flag argument to gcc. The module itself is created by compiling an ordinary C language file in which the main () function is replaced by a pair of init/cleanup functions:
int init_module(); void cleanup_module();
As its name implies, the init module () function is called when the module is first loaded into the kernel. It should return 0 on success and a negative value on failure. Similarly, the cleanup module is called when the module is unloaded.
To create a new realtime thread, we use the pthread create(3) func- tion. This function must only be called from the Linux kernel thread (i.e., using init module()):
#include <pthread.h> int pthread_create(pthread_t * thread, pthread_attr_t * attr, void (start_routine)(void *), void * arg);
The thread is created using the attributes specified in the “attr” thread attributes object. If attr is NULL, default attributes are used. For more detailed information, refer to the POSIX functions:
as well as these RTL-specific functions:
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 start routine is taken to be the thread code. It is passed the “arg” argument. To cancel a thread, use the POSIX function:
pthread cancel(pthread thread);
You should join the thread in cleanup module with pthread join() for its resources to be deallocated.
You must make sure the thread is cancelled before call- ing pthread join() from cleanup module(). Other- wise, Linux will hang waiting for the thread to fin- ish. If unsure, use pthread delete np(3) instead of pthread cancel()/pthread join().
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 API:
#include <rtl_time.h>
int clock_gettime(clockid_t clock_id, struct timespec *ts); hrtime_t clock_gethrtime(clockid_t clock);
struct timespec { time_t tv_sec; /* seconds / long tv_nsec; / nanoseconds */ };
To obtain the current clock reading, use the clock gettime(3) function where clock id is the clock to be read and ts is a structure which stores the value obtained. The hrtime t value is expressed as a single 64-bit number of nanoseconds. Thus, clock gethrtime(3) is the same as clock gettime, but returns the time as an hrtime t rather than as a timespec structure.
Several routines exist for converting from one form of time reporting to the other:
#include <rtl_time.h>
hrtime_t timespec_to_ns(const struct timespec *ts); struct timespec timespec_from_ns(hrtime_t t) const struct timespec * hrt2ts(hrtime_tvalue);
int sched_get_priority_min(int policy);
struct itimerspec { struct timespec it_interval; /* timer period / struct timespec it_value; / timer expiration */ };
Thread priority can be modified at thread creation time by using:
pthread attr setschedparam(3)
or afterwards by using
pthread setschedparam(3).
The policy argument is currently not used in RTLinux, but should be specified as SCHED FIFO for compatibility with future versions. The struc- ture sched param contains the sched priority member. Higher values cor- respond to higher priorities. Use:
to determine possible values of sched priority. To make a realtime thread execute periodically, users may use the non- portable^1 function:
pthread make periodic np(3)
which marks the thread as periodic. Timing is specified by the itimer struc- ture its. The it value member of the passed struct itimerspec specifies the time of the first invocation; the it interval is the thread period. Note that when setting up the period for task T, the period specified in the itimer structure can be 0. This means that task T will execute only once. The actual execution timing is performed by use of the function: (^1) It is possible to have threads execute periodically within RTLinux by using the pure POSIX API. However, this scheme is quite lengthy. This particular function has been added, therefore, to reduce user development time.
pthread wait np(3)
This function suspends the execution of the calling thread until the time specified by:
pthread make periodic np(3)
In the next section we’ll put the API to practical use.
2.3 A Simpl “Hello World” RTLinux program
We’ll now write a small program that uses all of the API that we’ve learned thus far. This program will execute two times per second, and during each iteration it will print the message:
I’m here, my arg is 0
Save the following code under the filename hello.c:
#include <rtl.h> #include <time.h> #include <pthread.h>
pthread_t thread; void * start_routine(void *arg) { struct sched_param p; p. sched_priority = 1; pthread_setschedparam (pthread_self(), SCHED_FIFO, &p); pthread_make_periodic_np (pthread_self(), gethrtime(), 500000000);
while (1) { pthread_wait_np(); rtl_printf("I’m here; my arg is %x\n", (unsigned) arg); } return 0;
the thread tells the scheduler to periodically execute this thread at a fre- quency of 2Hz (500 microseconds). This marks the end of the initialization section for the thread. The while() loop begins with a call to the function:
pthread wait np()
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:
pthread wait np()
Because we haven’t included any way to exit the loop, this thread will con- tinue to execute forever at a rate of 2Hz. The only way to stop the program is by removing it from the kernel with the rmmod(8) command.
In order to execute our program, we must first do the following:
Let’s look at these steps in some detail. We begin by creating the Makefile that will be used to compile our hello.c program. Type the following into a file called Makefile and put it in the same directory as your hello.c program:
hello.o: hello.c gcc $(CFLAGS) hello.c
If you haven’t already done so, locate the file rtl.mk and copy it into the same directory as your hello.c and Makefile files. The rtl.mk file can usually be found at /usr/include/rtlinux/rtl.mk.
cp /usr/include/rtlinux/rtl.mk.
(Note the trailing dot (.).) Now, type the following:
make -f rtl.mk hello.o
This compiles the hello.c program and produces an object file named hello.o. We now need to load the RTLinux modules. There are several ways to do this. The easiest is to use the rtlinux(1) 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 rtlinux(1) command, refer to its man page, or type:
rtlinux help
You should now be able to see your hello.o program printing its message twice per second. Depending on the configuration 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 first RTLinux program!