A relatively high number of tasks supported wouldresult in m2= 1, while few task supported would suggest a lower valueform2.. Recognizing that the importance of individual criteria will
Trang 1technique can be used, however, in conjunction with supplemental informationfrom actual experience and third-party reports.
Consider thirteen selection criteria,m1· · · m13, each having a rangem i ∈ [0, 1]
where unity represents the highest possible satisfaction of the criterion and zerorepresents complete nonsatisfaction
1 The minimum interrupt latency,m1, measures the time between the rences of hardware interrupt and when the interrupt’s service routinebegins executing A low value represents relatively high interrupt latency,while a high value represents a low latency This criterion is impor-tant because, if the minimum latency is greater than that required bythe embedded system, a different operating system must be selected
occur-2 This criterion, m2, defines the most processes the operating system cansimultaneously support Even though the operating system can support
a large number of tasks, this metric may be further limited by availablememory This criterion is important for systems that need numerous simul-taneous processes A relatively high number of tasks supported wouldresult in m2= 1, while few task supported would suggest a lower valueform2
3 Criterionm3 specifies the system memory required to support the ing system It does not include the amount of additional memory required
operat-to run the system’s application software Criterionm3= 1 suggests a imal memory requirement, whilem3= 0 would represent a larger memoryrequirement
min-4 The scheduling mechanism criterion,m4, enumerates whether preemptive,round-robin, or some other task-scheduling mechanism is used by theoperating system If many mechanisms were supported, then a high valuewould be assigned tom4
5 Criterionm5 refers to the available methods the operating system has toallow processes to communicate with each other Among possible choicesare mutual exclusion (mutexes), binary and counting semaphores, POSIXpipes, message queues, shared memory, FIFO buffers, control sockets,and signals and scheduling Each mechanism has advantages and disad-vantages, and they have been discussed Letm5 = 1 if the RTOS providesall desired scheduling mechanisms A lower value for m5 implies thatfewer scheduling mechanisms are available
6 Criterion m6 refers to the after-sale support a company puts behind itsproduct Most vendors offer some sort of free technical support for ashort period of time after the sale, with the option of purchasing additionalsupport if required Some even offer on-site consultation A high valuemight be assigned to a strong support program, whilem6= 0 if no support
is provided
7 Application availability, m7, refers to the amount of software available(either that ships with the operating system or is available elsewhere)
Trang 2to develop applications to run on the operating system For example,RTLinux is supported by the GNU’s suite of software, which includes thegcc C compiler and many freely available software debuggers, and othersupporting software This is an important consideration, especially whenusing an unfamiliar operating system Letm7= 1 if a large amount of soft-ware were available, while 0 would mean that little or none was available.
8 Criterion m8 refers to the different processors that the operating systemsupports This is important in terms of portability and compatibility withoff-the-shelf hardware and software This criterion also encompasses therange of peripherals that the operating system can support, such as video,audio, SCSI, and such A high value for the criterion represents a highlyportable and compatible RTOS
9 Criterion m9 refers to whether the code of the operating system will beavailable to the developer, for tweaking or changes The source also givesinsight to the RTOS architecture, which is quite useful for debuggingpurposes and systems integration Setting m9 = 1 would suggest opensource code or free source code, while a lower value might be assigned
in proportion to the purchase price of the source code Letm9= 0 if thesource code were unavailable
10 Criterionm10 refers to the time it takes for the kernel to save the contextwhen it needs to switch from one task to another A relatively fast contextswitch time would result in a higher value for m10
11 This criterion is directly related to the cost of the RTOS alone This iscritical because for some systems, the RTOS cost may be disproportion-ately high In any case, a relatively high cost would be assigned a verylow value, while a low cost would merit a higher value form11
12 This criterion, m12, rates which development platforms are available Inother words, it is a listing of the other operating systems that are com-patible with the given RTOS A high value form12would represent widecompatibility, while a lowerm12 would indicate compatibility with onlyone platform
13 This criterion, m13, is based on a listing of what networks and networkprotocols are supported by the given RTOS This would be useful to knowbecause it rates what communication methods the software running on thisoperating system would be able to use to communicate to other comput-ers within the same computer network A high value for the criterionrepresents a relatively large number of networks supported
Recognizing that the importance of individual criteria will differ depending onthe application, a weighting factor, w i ∈ [0, 1], will be used for each criterion
m i, where unity is assigned if the criterion has highest importance, and zero ifthe criterion is unimportant for a particular application Then a fitness metric,
Trang 3Clearly, a higher value of M means that the RTOS is well suited to the
appli-cation, while a lower value means that the RTOS is not well suited for theapplication
While selection of the values for m i andw i will be subjective for any givenRTOS and any given application, the availability of this heuristic metric provides
a handle for objective comparison, historical perspective, and other uses
3.4.15.1 A Case Study in Selecting a Commercial Real-Time Operating System A typical commercial RTOS is now examined based on the criteriaintroduced Although the data are real, the manufacturer name is omitted, as theintention is not to imply a recommendation of any product
The following assumptions are made:
ž For all the sample RTOS, assume that the calculations for the number ofinterrupt, the minimum time that it takes, and other system analysis based
on the metrics chosen are performed under the same conditions, that is,sampling, time constraints, and number of processors
ž Maximum or minimum of tasks refers to the operating system object, such
as the memory management unit (MMU), device drivers, and other tem tasks
sys-ž Assume that interrupt refers to “hardware interrupt.” “Software interrupts,”together with hardware interrupts and other vectoring mechanisms provided
by the processor, are referred to as “exception handling.”
ž Thread switching latency time is equivalent to the measurement of contextswitching latency time
In the cases where a criterion value can be assigned, this is done Where thecriteria are “processor dependent” or indeterminate, absent a real application,assignment of a rating is postponed, and a value of * is given This “uncertain”value is fixed at the time of application analysis Note too that the values betweentables need to be consistent So, for example, if a 6-microsecond latency yields
m1= 1 for RTOS X, the same 6-microsecond latency should yield m1 = 1 forRTOS Y
Consider commercial RTOS A Table 3.10 summarizes the criteria and ratings,which were based on the following rationale The product literature indicatedthat the minimum interrupt latency is CPU dependent, therefore a * value isassigned here (which will be later resolved as 0.5 for the purposes of evaluatingthe metric) Context switch time is not given, and so a * is also indicated.The RTOS supports 32-thread priority levels, but it is not known if there is alimit on the total number of tasks, so a value of 0.5 is assigned The RTOS
Trang 4Table 3.10 Summary data for real-time operating system A a
a Some of the specific details have been deliberately omitted to preserve the identity of the product.
itself requires 60 K of memory, which is somewhat more than some of thealternatives, so a value of 0.7 is assigned The system provides only one form
of scheduling, preemptive priority, so a lower value, 0.25, is assigned here than
if other forms, such as round-robin, were available Intertask synchronizationand communication is available only through message passing, so a relative low
of one are given for these three criteria
3.4.15.2 Matching an Operating System to an Application Consider thefollowing application and a set of RTOS, including A just described and RTOSB–E, whose criteria were determined in a similar manner
The software controlling an inertial measurement system requires tial input/output processing, which inherently causes large amounts of systeminterrupts This is a highly reactive and mission-critical system that requiresfast context switching, minimal interrupt latency, a high degree of synchroniza-tion and a well-supported and reliable system Thereforem1= m2= m5= m6 =
substan-m7 = m10= m11= 1 Hardware compatibility is not critical because there is tle need to port the system and the number of tasks supported is relatively low,therefore,m2 = m8= 0.1 The other criteria are set to 0.4 or 0.5 because they are
lit-only moderately important The ratings assigned are summarized in Table 3.11.The metric suggests that RTOS D is the best match for the internal measurementsystem
Trang 5Table 3.11 Decision table for inertial measurement system
POSIX is the IEEE’s Portable Operating System Interface for Computer ments The standard provides compliance criteria for operating system services and
Environ-is designed to allow applications programs to write applications that can easily portacross operating systems POSIX compliant systems are used widely in real-timeapplications It is the intention here to describe the POSIX standard for the purposes
of further explicating the concepts of RTOS with a robust and useful example
Real-time POSIX provides a mechanism for creating concurrent activities byallowing for each process to contain several threads of execution POSIX threadsare very similar to Java’s threads and Ada’s tasks models
POSIX threads (orPthreads) are defined as a set of C language programmingtypes and procedure calls, implemented with apthread.hheader/include file and
a thread library, though this library may be part of another library, such aslibc.The following is the C interface for thread management in POSIX.6
Types are defined in #include <sys/types.h>
pthread_t /* Used to identify a thread */
phread_attr_t /* Used to identify a thread attribute object */
size_t /* Used for sizes of objects */
/* initialize and destroy threads attribute object */
int pthread_attr_init(pthread_attr_t *);
int pthread_attr_destroy(pthread_attr_t *);
6 Refer to the UNIX man (online manual) pages to get further details on C interfaces to various POSIX functions.
Trang 6/* cancel execution of a thread */
int pthread_cancel(pthread_t);
/* detach a thread */
int pthread_detach(pthread_t);
/* compare thread IDs */
int pthread_equal(pthread_t, pthread_t);
/* thread termination */
void pthread_exit(void *);
/* wait for thread termination */
int pthread_join(pthread_t, void **);
/* get calling thread’s ID */
pthread_t pthread_self(void);
/** Stack and scheduling related **/
/* set and get detachstate attribute */
int pthread_attr_setdetachstate(pthread_attr_t *, int);
int pthread_attr_getdetachstate(const pthread_attr_t *, int *);
/* set and get inheritsched attribute */
int pthread_attr_setinheritsched(pthread_attr_t *, int);
int pthread_attr_getinheritsched(const pthread_attr_t *, int *);
/* set and get schedparam attribute */
int pthread_attr_setschedparam(pthread_attr_t *, const struct sched_param
*);
int pthread_attr_getschedparam(const pthread_attr_t *, struct sched_param
*);
/* dynamic thread scheduling parameters access */
int pthread_getschedparam(pthread_t, int *, struct sched_param *);
int pthread_setschedparam(pthread_t, int , const struct sched_param *); /* set and get schedpolicy attribute */
int pthread_attr_setschedpolicy(pthread_attr_t *, int);
int pthread_attr_getschedpolicy(const pthread_attr_t *, int *);
/* set and get stackaddr attribute */
int pthread_attr_setstackaddr(pthread_attr_t *, void *);
int pthread_attr_getstackaddr(const pthread_attr_t *, void **);
/* set and get stacksize attribute */
int pthread_attr_setstacksize(pthread_attr_t *, size_t);
int pthread_attr_getstacksize(const pthread_attr_t *, size_t *);
Trang 7Table 3.12 POSIX naming scheme
pthread Threads themselves and miscellaneous subroutines pthread attr Thread attributes objects
pthread mutex Mutexes
pthread mutexattr Mutex attributes objects
pthread cond Condition variables
pthread condattr Condition attributes objects
pthread key Thread-specific data keys
printf("Completed join with thread %d \n",counter);
/*printf("Completed join with thread %d status= %d \n",counter, status);*/ }
pthread_exit(NULL);
}
Trang 83.5.2 POSIX Mutexes and Condition Variables
Mutex variables are one of the primary means of implementing thread nization The basic concept of a mutex as used in Pthreads is that only onethread is allowed to lock (or own) a mutex variable at any given time Thus,even if several threads try to lock a mutex, only one thread will be successful
synchro-No other thread can own/lock that mutex until the owning thread unlocks thatmutex, and only the owner can unlock it POSIX mutexes application programinterfaces (APIs) are given below
As compared to mutexes, condition variables provide an alternative for threads
to synchronize The basic difference between mutexes and condition variables isthat while mutexes implement synchronization by controlling thread access to data,condition variables allow threads to synchronize based upon the actual value of data.Without condition variables, threads need to continually poll (possibly in acritical section) to check if the condition is met This could lead to unnecessaryresource consumption, as the thread would be continuously busy in this activity
A condition variable facilitates to achieve the same goal without polling./** POSIX Condition Variables **/
/* Creating/Destroying Condition Variables */
Trang 9printf("In read user \n");
/* simulation the read operation by a wait (sleep(2)) */
printf("In write user \n");
/* simulation the write operation by a wait (sleep(2)) */
Trang 10int sem_init(sem_t *sem, int pshared, unsigned int value);
/* Initializes the semaphore object pointed by ‘sem’ */
int sem_destroy(sem_t *sem);
/* Destroys a semaphore object and frees up the resources it might hold */ /* The following three functions are used in conjunction with other
processes See man pages for more details.
*/
sem_t *sem_open(const char *name, int oflag, );
int sem_close(sem_t *sem);
int sem_unlink(const char *name);
int sem_wait(sem_t *sem);
/* Suspends the calling thread until the semaphore pointed to by ‘sem’ has non-zero count Decreases the semaphore count */
int sem_trywait(sem_t *sem);
/* A non-blocking variant of sem_wait */
int sem_post(sem_t *sem);
/* Increases the count of the semaphore pointed to by ‘sem’ */
int sem_getvalue(sem_t *sem, int *sval);
/* Stores the current count of the semaphore ‘sem’ in ‘sval’ */
It is important that two processes not write to the same area of shared-memory
at the same time, and this is where the semaphores are useful Before writing to
a shared memory region, a process can lock the semaphore to prevent anotherprocess from accessing the region until the write operation is completed Whenthe process is finished with the shared-memory region, the process unlocks thesemaphore and frees the shared-memory region for use by another process
/* simulate read operation by a delay*/
printf("in reader task \n");
Trang 11while(1) {
sem_wait(&writer_lock);
/* simulate read operation by a delay*/
printf("in writer task \n");
mqd_t mq_open(const char *name, int oflag, );
/* Connects to, and optionally creates, a named message queue */
int mq_send(mqd_t mqdes, const char *msg_ptr, oskit_size_t msg_len,
unsigned int msg_prio);
/* Places a message in the queue */
int mq_receive(mqd_t mqdes, char *msg_ptr, oskit_size_t msg_len,
unsigned int *msg_prio);
/* Receives (removes) the oldest, highest priority message from the queue */ int mq_close(mqd_t mqdes);
/* Ends the connection to an open message queue */
int mq_unlink(const char *name);
/* Ends the connection to an open message queue and causes the
queue to be removed when the last process closes it */
int mq_setattr(mqd_t mqdes, const struct mq_attr *mqstat, struct mq_attr
*omqstat);
int mq_getattr(mqd_t mqdes, struct mq_attr *mqstat);
/* Set or get message queue attributes */
Trang 12int mq_notify(mqd_t mqdes, const struct sigevent *notification);
/* Notifies a process or thread that a message is available in the queue */The following example illustrates sending and receiving messages betweentwo processes using a message queue [Marshall96] The following two programsshould be compiled and run at the same time to illustrate the basic principle ofmessage passing:
the queue
The full code listing formessage_send.c is as follows:
/* Declare the message structure */
typedef struct msgbuf {
Trang 13buf_length = strlen(sbuf.mtext) + 1 ;
/* Send a message */
if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) {
printf ("%d, %d, %s, %d \n", msqid, sbuf.mtype, sbuf.mtext, buf_length); perror("msgsnd");
The essential points to note here are:
ž The Message queue is created with a basic key and message flag
appendable by all
ž A message of type (sbuf.mtype) 1 is sent to the queue with the message
“Did you get this?”
Receiving the preceding message as sent using message_send program isillustrated below The full code listing for message_send.c’s companion pro-cess,message_rec.c is as follows:
/* Declare the message structure */
typedef struct msgbuf {
Trang 14/* Receive an answer of message type 1 */
The essential points to note here are:
ž The Message queue is opened with msgget (message flag 0666) and thesame key asmessage_send.c}
ž A message of the same type 1 is received from the queue with the message
“Did you get this?” stored inrbuf.mtext.
Signals are software representation of interrupts or exception occurrences Signalsasynchronously alter the control flow of a task It is important to point out that
no routine should be called from a signal handler that might cause the handler toblock – it makes it impossible to predict which resources might be unavailable.Signals are used for many purposes:
ž Exception handling
ž Process notification of asynchronous event occurrence
ž Process termination in abnormal situations
ž Interprocess communication
However, there are several limitations of standard POSIX signals on their use inreal-time applications These include:
ž Lack of signal queueing
ž No signal delivery order
ž Poor information content
ž Asynchrony
POSIX real-time extensions (POSIX.4) improves the POSIX signals to cations POSIX.4 defines a new set of application-defined real-time signals,and these signals are numbered from SIGRTMIN to SIGRTMAX There must be
signal arrives As real-time signals can be queued, the queueing option for areal-time signal is chosen by setting bit SA_SIGINFOin the sa_flags field of
Trang 15struct sigaction{
void (*sa_handler)();
sigset_t sa_mask;
int sa_flags;//SA_NOCLDSTOP or SA_SIGINFO
void (*sa_sigaction)(int, siginfo_t*, void*);
/*used for real-time signals!! Also, ‘‘SA_SIGINFO’’
is set in ‘‘sa_flags.’’
*/
};
int sigaction(int sig, const struct sigaction *reaction,
struct sigaction *oldreaction);
Real-time signals can carry extra data SA_SIGINFOincreases the amount ofinformation delivered by each signal If SA_SIGINFO is set, then the signalhandlers have as an additional parameter a pointer to a data structure called
that is sent as a part of the signal It enables the queuing of multiple signals forany task Real-time signals can be specified as offsets fromSIGRTMIN All sig-nals delivered withsigqueue()are queued by numeric order, lowest numberedsignals delivered first
POSIX.4 provides a new and more responsive (or fast) synchronous wait function called sigwaitinfo Upon arrival of the signal, it does not callthe signal handler (unlikesigsuspend), but unblocks the calling process
In developing real-time applications, clearly it is desirable to have facilities to setand get the time For example, suppose a diagnostic program checks the health
of the system periodically Essentially, the program would execute one round ofdiagnostics and then wait for a notification to execute again, with the processrepeating forever This is accomplished by having a timer that is set to expire at
a particular time interval When the time interval expires, the program that setthe timer is notified, usually through a signal delivery
3.5.7.1 Time Management In order to generate a time reference, a timercircuit is programmed to interrupt the processor at a fixed rate The internalsystem time is incremented at each timer interrupt The interval of time withwhich the timer is programmed to interrupt defines the unit of time (also called
“tick”) in the system (time resolution) Typically, the system time is represented
by a long integer (unsigned 32 bits) variable, whereas the value of the tick isstored in a float variable
The values of the system lifetime (range) for some tick values (granularity) isshown in the Table 3.13 At any time, “sys_clock,” a variable holding systemtime, contains the number of interrupts generated by the timer since the Epoch
Trang 16Table 3.13 System lifetime
visi-ble to all processes running on the system TheCLOCK_REALTIMEclock measuresthe amount of time that has elapsed since 00:00:00 January 1, 1970
As mentioned,CLOCK_REALTIMEis commonly used as theclock_idargument
in all clock functions Some of the common clock functions and their descriptionsare given in the Table 3.14 The value returned by a clock function is stored in
a data structure called timespec that has two fields of the long-integer type,namely tv_secrepresenting the value in number of seconds since the Epoch,
Table 3.14 POSIX clock functions
clock getres Returns the resolution of the specified clock
int clock getres(clockid t clock id, struct timespec *res) Clock gettime Returns the current value for the specified value
int clock gettime(clockid t clock id, struct timespec *tp) Clock settime Sets the specified clock to the specified value
int clock settime(clockid t clock id, const struct timespec
*tp)
Trang 173.5.7.3 Determining Clock Resolution The following example calls the
stat = clock_getres(CLOCK_REALTIME, &clock_resolution);
printf(‘‘Clock resolution is %d seconds, %ld nanoseconds \n’’,
clock_resolution.tv_sec, clock_resolution.tv_nsec); }
3.5.7.4 Retrieving System Time Theclock_gettimefunction returns thevalue of the systemwide clock as the number of elapsed seconds since the Epoch
con-tains a member to hold the value of the number of elapsed nanoseconds notcomprising a full second
printf(‘‘%d seconds and %ld nanoseconds \n’’, ts.tv_sec, ts.tv_nsec); }
3.5.7.5 System Clock Resolution The system clock resolution on DEC’sAlpha system is 1/1024 seconds or 976 microseconds),7that is, the system main-tains time by adding 976 microseconds at every clock interrupt The actualtime period between clock ticks is exactly 976.5625 microseconds The miss-ing 576 microseconds (1024 * 0.5625) are added at the end of the 1024th tick,that is the 1024th tick advances the system time by 1552 microseconds.Note that if an application program requests a timer value that is not an exactmultiple of the system clock resolution (an exact multiple of 976.5625 microsec-onds), the actual time period counted down by the system will be slightly largerthan the requested time period A program that asks for a periodic timer of
50 milliseconds will actually get a time period of 50.78 milliseconds
3.5.7.6 Timer So far, mechanisms that allow setting and getting the time
in POSIX have been discussed Beyond this, it is desirable to time a process’sexecution so that it gets to run on the processor at a specific time interval Asdiscussed earlier, POSIX timers provide a mechanism to control the frequency of
a program execution In order to use a timer to time a process it is necessary to:
ž Create the time object within the kernel
ž Generate a signal to get notification
ž Choose either relative or absolute timer
7Guide to Realtime Programming, Digital Equipment Corp., March 1996.
Trang 183.5.7.7 Creating a Timer The first step is to create a timer for the application
by using the timer_create()function
needed concerning the signal to be generated This is essentially used to informthe kernel about what kind of event the timer should deliver whenever it “fires.”
By setting itNULL, the system is forced to use default delivery, which is defined
struct itimerspec{
struct timespec it_value,
it_interval;
};
int timer_settime (timer_t timerid, int flag,
struct itimerspec *value, struct itimerspec *oldvalue);
This function sets the next expiration time for the timer specified If flag is set to
value specified by *value.it_value If flag is not set to TIMER_ABSTIME,the timer will expire when the interval specified by value->it_value passes
setting is returned in *oldvalue For example, to specify a timer that executesonly once, 10.5 seconds from now, specify the following values for the members
of theitimerspecstructure:
newtimer_setting.it_value.tv_sec = 10;
Trang 19I/O operation is a key component in any real-time application The real-time gram is usually responsible for tracking or controlling the external environment
pro-in some desired way Some of the common I/O operations typically found pro-inreal-time systems include:
ž Data gathering/output from/to devices
ž Data logging (e.g., for monitoring purposes)
ž Multimedia applications (playback or recording)
ž Operations on (real-time) databases, keyboards, mice, etc
ž I/O devices: joysticks, keyboards
It is important to note that UNIX I/O is synchronous, that is, the execution
of a program has to wait while the I/O takes place For example, UNIX read
calls blocks the calling process until the user buffer is filled up with data beingrequested, or an error occurs during the I/O operation However, many real-timeapplications, and those applications requiring high-speed or high-volume datacollection and/or low-priority journaling functions, need to perform I/O asyn-chronously, that is, the system performs the I/O in parallel with the application,which is free to perform other tasks while the data are read in or written Whenthe I/O completes, the application receives some kind of notification, usually bythe delivery of asignal
3.5.8.1 Associated Data Structures Asynchronous I/O (AIO) operationsare submitted using a structure called the AIO control block, or aiocb Thiscontrol block contains asynchronous operation information, such as the initialpoint for the read operation, the number of bytes to be read, and the file descriptor
on which the AIO operation will be performed Theaiocbstructure contains thefollowing members:
struct aiocb{
int aio_fildes; // File descriptor
off_t aio_offset; // File offset
volatile void *aio_buf; // Pointer to buffer
Trang 20int aio_reqprio; // Request priority offset
struct sigevent aio_sigevent; // Signal structure
int aio_lio_opcode;// Specifies type of I/O operation
};
It is important to understand what actually happens when the aio_read/
lseek(a.aio_fildes, ); // Seek to position
read(a.aio_fildes, ); // Read data
sigqueue( ); // Queue a signal to a process
The AIO operation is depicted in Figure 3.23 Error handling for synchronousI/O is simplified by looking at errno For AIO, the system maintains a returnvalue, and anerrnovalue, for each asynchronous operation separately These twovalues from the system are obtained via functionsaio_returnandaio_error.Each function gives back the return value, or errno value, associated with theasynchronous operation at that moment
Multiple I/O operations are permitted in the POSIX AIO specification AIOallows a combination of severalreadandwriteoperations into a single systemcall, lio_listio The functionlio_listio permits transfer of large amounts
of I/O simultaneously The functionaio_suspendwaits for particular AIO ations to complete It does not say which I/O completed, it just returns 0 when
oper-it has determined that one of the asynchronous operations has finished AIO can
be canceled using aio_cancel, though it is not recommended
Virtual memory, which allows for mapping of virtual addresses to different ical locations, is useful in real-time systems In addition to paging (and associatedthrashing problems), the key disadvantage of page swapping in real-time systems
phys-is the lack of predictable execution time It phys-is not uncommon that an applicationdemands responsiveness that may be measured in microseconds, and the pro-gram is waiting milliseconds or more while the operating system is involved in
Process calls
aio_read or
aio_write
Process continues with other work
Process gets notified via signal Process
Trang 21disk access and in fetching the desired instructions in the memory In a real-timesystem, it is often desirable to lock the important process’s memory down so thatthe operating system does not page it, thereby making the execution times morepredictable In the case of many large processes, it is desirable to lock just thetime-critical portions of these processes.
POSIX allows for a simple procedure to lock the entire process down
pro-be using Depending on the flags pro-being specified, it will either lock all process’scurrent mappings (MCL_CURRENT), or the process’s current mapping and any futuremappings that it may make (MCL_CURRENT|MCL_FUTURE) The functionmunlock- allunlocks all locked memory and notifies the system that it is okay to page thisprocess’s memory if the system must do so Assuming thatmlockallis called with
effect of memory locking upon execution ofmalloc Instead of locking down theentire process, POSIX permits the user to lock down part of the process:
#include <unistd.h>
#ifdef _POSIX_MEMLOCK_RANGE
#include<sys/mman.h>
int mlock(void *address, size_t length);
int munlock(void *address, size_t length);
#endif
The functionmlocklocks down the address range being specified, andmunlock
unlocks a range (Figure 3.25) If mlock is called for a range of memory, then
Stack Heap
Data Text
Heap Stack
Data Text
Heap Stack
Data Text
Unmapped
Pageable
Locked Before mlockall Call After mlockall Call After malloc Call
Figure 3.24 mlockall operation.
Trang 22Stack Heap
Data Text
Stack Heap
Data Text Pageable
Locked char buf[100] char buf[100]
Before mlock Call After mlock(buf, 100) Call
Figure 3.25 mlock operation.
callingmunlockallunlocks the memory that has been locked withmlock It isnot possible to lock memory for all of a small section of code, then unlock it.Memory locking is a global technique that should not be performed by small,transient sections of code In general, once a memory is locked, it should belocked down until the application is out of “real-time mode.” The functionmlock
can cause a segmentation fault if an address is passed to it where there is notany memory for executable code
As can be seen from this example, memory locking decreases execution timesfor the locked modules and, more importantly, can be used to guarantee execu-tion time At the same time, it makes fewer pages available for the application,encouraging contention
3.6 EXERCISES
architecture is most appropriate.
Make whatever assumptions you like, but document them.
multiple-interrupt system? What safety precautions are necessary?
development of different mission- and safety-critical applications.
predictabil-ity in time-critical applications?
and heuristic scheduling algorithms.
Trang 233.7 Construct a cyclic executive with four procedures,A, B, C, D Procedure A runs
versa.
preemption is not allowed.
in the RM and EDF schedulability tests.
only 32 priorities levels for their messages exchanged through message queues Suppose that each sending thread chooses the priority of its messages by mapping the 256 thread priority levels to 32 message priority levels Discuss some potential problems associated with this uniform mapping scheme What kind of approach would you take?
Trang 243.15 Give two different explanations why the following periodic tasks are schedulable
cyclic schedule Draw an execution trace (timeline) showing two occurances of each task.
fol-lowing task set in the interval (0,20).
τ i r i e i p i D i
τ3 0 4 12 10
Trang 25(d) τ4= (0, 11, 4; [A; 5[B; 2]][C; 1]), where the task executes for two time units,
R and the execution time t Also note that the representation [R; t[S; w]] denotes
Construct the schedule for the system using (a) the Priority Inheritance Protocol, (b) the Priority Ceiling Protocol.
you determine the optimal size?
implementation given in this chapter has any critical-region problems That is, can the semaphore itself be interrupted in a harmful way?
operation were not atomic?
(R0 – R7) and the program counter are to be saved on a stack Do this for
head and tail of a ring buffer, respectively.
( BMOVE ) and restore ( BRESTORE ) instructions are available Make the necessary assumptions about the format of the instructions.
that 100 pages of size 1 megabyte, 2 megabytes, and 4 megabyte are available The algorithm should take the size of the page requested as an argument, and return a pointer to the desired page The smallest available page should be used, but if the smallest size is unavailable, the next smallest should be used.
into 1-megabyte pages Use a pointer scheme.
are five tasks in the system, and the maximum amount of resources A, B, and
C needed for each task is known Implement a banker’s algorithm scheme in the language of your choice.
Trang 263.30 Show how priority inheritance can cause deadlock and also multiple blocking For
τ1: LockS1; LockS2; UnlockS2; UnlockS1
τ2: LockS2; LockS1; UnlockS1; UnlockS2
Here two tasks use two semaphores in a nested fashion but in reverse order.
ring buffer The routines should use semaphores to allow more than one user to access the buffer.
three can be implemented with the fourth It was shown how binary semaphores can be used to implement counting semaphores and vice versa, how mailboxes can be used to implement binary semaphores, and how mailboxes can be used to implement queues For the remaining pairs, show how one can be used it implement the other.
simul-taneous access to a global semaphore by two processors The instruction is made indivisible by the CPU refusing to issue a DMA acknowledge (DMACK) signal
in response to a DMA request (DMARQ) signal during execution of the tion The other processors sharing the bus are locked out of accessing memory What are the real-time implications for a processor trying to access memory when another processor is executing a process that is looping for a semaphore using the following code?
instruc-getlock: TANDS semaphore
JNE getlock
If this busy wait must be used, is there a better way to test the semaphore in process
2 so that the bus is not tied up?
systems as you can Summarize your findings for each operating system, briefly,
in narrative form.
of features by-products In other words, present the findings you describe in step
2 more succinctly in tabular form.
likely commercial real-time operating system to use based on the selection criteria you developed
Make whatever assumptions you like, but document them.