Real-time operating system (RTOS ) is a type of operating system , the main purpose of which is to provide the necessary and sufficient set of functions for real-time systems to operate on specific hardware.
The UNIX Specification in revision 2 gives the following definition:
Real time in operating systems is the ability of the operating system to provide the required level of service for a certain period of time. [one]
Original Text (Eng.)There is a need for a response time. [2]
Ideal RTOS has predictable behavior under all load scenarios, including simultaneous interruptions and execution of threads [3] .
Hard and soft real-time systems
Real-time operating systems are sometimes divided into two types — hard real-time systems and soft real-time systems [4] .
An operating system that can provide the required time to perform a real-time task, even in the worst cases, is called a hard real-time operating system . A system that can provide the required time for performing a real-time task on average is called a soft real-time operating system .
Hard real-time systems do not allow system response delays, as this can lead to loss of relevance of results, large financial losses or even accidents and catastrophes. The situation in which the processing of events takes place in the time longer than specified in the hard real-time system is considered a fatal error. When such a situation arises, the operating system interrupts the operation and blocks it so that, as far as possible, the reliability and readiness of the rest of the system will not suffer. Examples of hard real-time systems can be onboard control systems (on an airplane, spacecraft, ship, etc.), emergency protection systems, emergency event recorders [5] .
In a soft real-time system, delayed response is considered to be a recoverable error, which can lead to an increase in the cost of results and a decrease in performance, but is not fatal. An example is the work of a computer network [6] . If the system does not have time to process the next received packet, it will lead to a stop at the transmitting side and re-sending (depending on the protocol ). No data is lost, but network performance decreases.
The main difference between hard and soft real-time systems can be characterized as follows: a hard real-time system will never be late in reacting to an event, a soft real-time system should not be late in reacting to an event [6] .
Often, the real-time operating system is considered only a system that can be used to solve hard real-time tasks. This definition means that the RTOS has the necessary tools, but also means that these tools need to be properly used [5] .
Most software is focused on soft real time. For such systems is typical:
- guaranteed response time to external events ( interruptions from equipment);
- rigid process planning subsystem (high-priority tasks should not be superseded by low-priority ones, with some exceptions);
- increased requirements for reaction time to external events or reactivity (the delay in calling the interrupt handler is no more than tens of microseconds, the delay in switching tasks is no more than hundreds of microseconds).
A classic example of a task where an RTOS is required is the control of a robot taking a part from a conveyor belt . The part moves, and the robot has only a small amount of time when it can take it. If he is late, the part will no longer be in the right part of the conveyor, and therefore, the work will not be done, despite the fact that the robot is in the right place. If he prepares earlier, the part will not have time to drive up, and he will block her way.
Also for operating systems, the concept of “ interactive real time ” is sometimes used, in which the minimum threshold for reaction to graphical interface events is defined, during which the operator — a person — is able to calmly, without nervousness, expect the system to respond to the instructions given to them.
Distinctive Features of RTOS
Comparison table of RTOS and conventional operating systems [5] :
| Real time OS | General Purpose OS | |
|---|---|---|
| The main task | Have time to react to events occurring on the equipment | Optimum distribution of computer resources between users and tasks |
| What is focused on | Handling external events | Processing user actions |
| How positioned | A tool for creating a specific real-time hardware and software | Perceived by the user as a set of applications ready to use. |
| Who is it intended for? | Qualified developer | User of medium qualification |
RTOS Architecture
In its development, the RTOS was built on the basis of the following architectures :
- Monolithic architecture . An operating system is defined as a set of modules that interact with each other within the core of the system and provide application software with input interfaces for accessing hardware. The main disadvantage of this principle of building an OS is the poor predictability of its behavior caused by the complex interaction of modules with each other.
- Layered (layered) architecture . Application software has the ability to access the hardware not only through the core of the system and its services, but also directly. Compared to monolithic, such an architecture provides a much greater degree of predictability of system responses, and also allows quick application access to hardware. The main disadvantage of such systems is the lack of multitasking .
- Client-server architecture . Its main principle is to bring the OS services in the form of servers to the user level and the microkernel to perform the functions of the message manager between client user programs and servers - system services. The advantages of this architecture:
- Increased reliability, since each service is, in fact, an independent application and it is easier to debug and track errors.
- Improved scalability , as unnecessary services can be excluded from the system without affecting its performance.
- Increased fault tolerance, since the "frozen" service can be restarted without rebooting the system.
Kernel Features
The kernel of the RTOS ensures the functioning of the intermediate abstract OS level, which hides from the application software the specifics of the technical device of the processor (several processors) and the associated hardware [7] .
Basic Services
The specified abstract level provides for the application software five main categories of services [7] [8] :
- Task management . The most important group of services. Allows application developers to design software products in the form of sets of separate software fragments, each of which may relate to its own thematic area, perform a separate function, and have its own quantum of time allotted for it to work. Each such fragment is called a task . Services in this group have the ability to run tasks and assign priorities to them. The main service here is a task scheduler . He exercises control over the implementation of current tasks, launches new ones in the appropriate period of time and monitors the mode of their work.
- Dynamic memory allocation . Many (but not all) RTOS cores support this group of services. It allows tasks to borrow areas of RAM for temporary use in the operation of applications. Often, these areas subsequently move from task to task, and through this, a large amount of data is quickly transferred between them. Some very small RTOS cores that are supposed to be used in hardware environments with a strict limit on the amount of memory used do not support dynamic memory allocation services.
- Timer management . Since embedded systems impose stringent requirements on the time frame for performing tasks, the RTOS core includes a group of services that provide control over timers to track the time limit during which the task should be executed. These services measure and set different time intervals (from 1 μs and above), generate interrupts after expiration of time intervals and create one-time and cyclical alarm clocks.
- Interaction between tasks and synchronization . Services of this group allow tasks to share information and ensure its safety. They also enable software fragments to coordinate their work with each other to increase efficiency. If we exclude these services from the core RTOS, then the tasks will begin to exchange distorted information and may become a hindrance to the work of neighboring tasks.
- Control I / O device . Services of this group provide a single software interface that interacts with the entire set of device drivers that are typical for most embedded systems.
In addition to kernel services, many RTOS offer additional component lines for organizing high-level concepts such as the file system , networking, network management, database management, graphical user interface , etc. Although many of these components are much larger and more complex. than the RTOS core itself, they are nonetheless based on its services. Each of these components is included in the embedded system only if its services are necessary for the execution of the embedded application and only in order to minimize the memory consumption [7] .
Differences from general purpose operating systems
Many general-purpose operating systems also support the above services. However, the key difference in RTOS core services is the deterministic , time-based, nature of their work. In this case, determinism means that the execution of a single service of an operating system requires a time interval of a known known duration. Theoretically, this time can be calculated by mathematical formulas , which should be strictly algebraic and should not include any temporary parameters of a random nature. Any random variable that determines the task execution time in the RTOS can cause an undesirable delay in the operation of the application, then the next task will not fit into its time slice, which will cause the error [7] .
In this sense, general-purpose operating systems are not deterministic. Their services may allow random delays in their work, which may slow down the application's response to user actions at a known unknown time. When designing conventional operating systems, developers do not focus their attention on the mathematical apparatus for calculating the time to perform a specific task and service. This is not critical for this kind of systems [7] .
Task Planning
Job Scheduler
Most RTOSs perform task scheduling based on the following scheme [7] . Each task in the application is assigned a priority. The higher the priority, the higher should be the reactivity of the task. High reactivity is achieved by implementing the preemptive priority scheduling approach, the essence of which is that the scheduler is allowed to stop the execution of any task at an arbitrary time, if it is established that another task must be started immediately.
The described scheme works according to the following rule: if two tasks are simultaneously ready for launch, but the first one has a high priority and the second one low, then the scheduler will prefer the first one. The second task will be launched only after the first is completed.
It is possible that a task with a low priority is already running, and the scheduler receives a message that another task with a higher priority is ready to start. The reason for this may be some external influence (interruption from equipment), such as, for example, a change in the state of a device switch controlled by an RTOS. In such a situation, the task scheduler will behave according to the priority preemptive planning approach as follows. A low priority task will be allowed to execute the current machine command to the end (but not the command described in the high-level source of the program), after which the task is suspended [7] . Next, a high priority task starts. After working on it, the scheduler starts the interrupted first task from the machine command following the last completed task.
Each time the task scheduler receives a signal about the onset of some external event (trigger), the cause of which can be both hardware and software, it operates according to the following algorithm [7] :
- Determines whether the currently running task should continue to run.
- Sets which task should run next.
- Saves the context of the stopped task (so that it resumes work from the stop point).
- Sets the context for the next task.
- Runs this task.
These five steps of the algorithm are also called task switching.
Task Execution
In normal RTOS, a task can be in three possible states:
- the task is being performed;
- the task is ready for execution;
- the task is blocked.
Most of the time, most tasks are blocked. Only one task can be executed on the central processor at the current time. In a primitive RTOS, the list of tasks ready for execution is usually very short, it may consist of no more than two or three items.
The main function of the RTOS administrator is to create such a task scheduler.
If there are no more than two or three in the list of tasks that are ready to be performed, it is assumed that all tasks are in the optimal order. If there are such situations that the number of tasks in the list exceeds the allowed limit, then the tasks are sorted in order of priority.
Planning Algorithms
Currently, two approaches are being developed most intensively to solve the problem of effective planning in the RTOS [9] :
- static scheduling algorithms ( RMS, Rate Monotonic Scheduling ) - use priority preemptive scheduling, priority is assigned to each task before it starts to be performed, the priority is given to tasks with the shortest execution periods;
- Dynamic scheduling algorithms ( EDF, Earliest Deadline First Scheduling ) - priority is assigned to tasks dynamically, with preference being given to tasks with the earliest limit start (completion) time.
With large system loads, the EDF is more efficient than the RMS.
Interaction between tasks and resource sharing
Multitasking systems need to distribute access to resources. Одновременный доступ двух и более процессов к какой-либо области памяти или другим ресурсам представляет определённую угрозу. Существует три способа решения этой проблемы: временное блокирование прерываний , двоичные семафоры , посылка сигналов. ОСРВ обычно не используют первый способ, потому что пользовательское приложение не может контролировать процессор столько, сколько хочет. Однако во многих встроенных системах и ОСРВ позволяется запускать приложения в режиме ядра для доступа к системным вызовам и даётся контроль над окружением исполнения без вмешательства ОС.
На однопроцессорных системах наилучшим решением является приложение, запущенное в режиме ядра, которому позволено блокирование прерываний. Пока прерывание заблокировано, приложение использует ресурсы процесса единолично и никакая другая задача или прерывание не может выполняться. Таким образом защищаются все критичные ресурсы. После того как приложение завершит критические действия, оно должно разблокировать прерывания, если таковые имеются. Временное блокирование прерывания позволено только тогда, когда самый долгий промежуток выполнения критической секции меньше, чем допустимое время реакции на прерывание. Обычно этот метод защиты используется, только когда длина критического кода не превышает нескольких строк и не содержит циклов . Этот метод идеально подходит для защиты регистров .
Когда длина критического участка больше максимальной или содержит циклы, программист должен использовать механизмы, идентичные или имитирующие поведение систем общего назначения, такие, как семафоры и посылка сигналов.
Выделение памяти
Следующим проблемам выделения памяти в ОСРВ уделяется больше внимания, нежели в операционных системах общего назначения.
Во-первых, скорости выделения памяти. Стандартная схема выделения памяти предусматривает сканирование списка неопределённой длины для нахождения свободной области памяти заданного размера, а это неприемлемо, так как в ОСРВ выделение памяти должно происходить за фиксированное время.
Во-вторых, память может стать фрагментированной в случае разделения свободных её участков уже запущенными процессами. Это может привести к остановке программы из-за её неспособности задействовать новый участок памяти. Алгоритм выделения памяти, постепенно увеличивающий фрагментированность памяти, может успешно работать на настольных системах, если те перезагружаются не реже одного раза в месяц, но является неприемлемым для встроенных систем, которые работают годами без перезагрузки.
Простой алгоритм с фиксированной длиной участков памяти очень хорошо работает в несложных встроенных системах.
Также этот алгоритм отлично функционирует и в настольных системах, особенно тогда, когда во время обработки участка памяти одним ядром следующий участок памяти обрабатывается другим ядром. Такие оптимизированные для настольных систем ОСРВ, как Unison Operating System или DSPnano RTOS , предоставляют указанную возможность.
Notes
- ↑ С. Золотарев. Операционные системы реального времени для 32-разрядных микропроцессоров
- ↑ The Open Group The Single UNIX Specification, version 2
- ↑ What makes a good RTOS , Dedicated Systems Experts NV, June 11, 2001
- ↑ И. Б. Бурдонов, А. С. Косачев, В. Н. Пономаренко. Операционные системы реального времени п. 1. Введение: Особенности операционных систем реального времени
- ↑ 1 2 3 А. А. Жданов. Операционные системы реального времени
- ↑ 1 2 Е. Хухлаев. Операционные системы реального времени и Windows NT
- ↑ 1 2 3 4 5 6 7 8 D. Kalinsky. Basic concepts of real-time operating systems . Архивировано 28 января 2013 года. (eng.)
- ↑ А. А. Блискавицкий, С. В. Кабаев. Операционные системы реального времени (обзор)
- ↑ И. Б. Бурдонов, А. С. Косачев, В. Н. Пономаренко. Операционные системы реального времени п. 1.2. Планирование, приоритеты
Literature
- Зыль С. Операционная система реального времени QNX: от теории к практике. - 2nd ed. - SPb. : БХВ-Петербург, 2004. — 192 с. — ISBN 5-94157-486-X .
- Зыль С. QNX Momentics. Основы применения. - SPb. : БХВ-Петербург, 2004. — 256 с. — ISBN 5-94157-430-4 .
- Кёртен Р. Введение в QNX/Neutrino 2. — СПб. : Петрополис, 2001. — 512 с. — ISBN 5-94656-025-9 .
- Oslender, D. M., Ridgeley, J. R., Ringenberg, J. D. Control programs for mechanical systems: Object-oriented design of real-time systems. - M .: Bean. Laboratory of Knowledge, 2004. - 416 p. - ISBN 5-94774-097-4 .
Links
- Real Time Operating Systems
- Series of articles about FreeRTOS
- Overview of real-time operating systems (inaccessible link) (English) (inaccessible link from 01-04-2014 [1942 days])
- National Instruments, What is a Real-Time Operating System (RTOS)? (white paper) 2013 (eng.)