Lecture
Real-time operating system, real-time operating system (RTOS ) - 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 work on specific hardware.
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.
Good RTOS has predictable behavior under all load scenarios, including simultaneous interruptions and execution of threads [3] .
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 .
An operating system that can provide the required time to perform 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:
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, a 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 did not manage to process the next received packet, it will stop at the transmitting side and resend (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:
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.
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 complex | Perceived by the user as a set of applications ready to use. |
Who is it intended for? | Qualified developer | User of medium qualification |
In its development, the RTOS was built on the basis of the following architectures:
Monolithic architecture |
Layered (layered) architecture |
Client-server architecture |
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] .
The specified abstract level provides for the application software five main categories of services [7] [8] :
In addition to kernel services, many RTOS offer additional component lines for organizing such high-level concepts as the file system, network interaction, network management, database management, graphical user interface, etc. Although many of these components are much larger and more complex than the very core of the RTOS, 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] .
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] .
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] :
These five steps of the algorithm are also called task switching .
In ordinary RTOS, a task can be in 3 possible states [9] :
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 ready-to-run tasks for the latter, then 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 [9] .
Currently, two approaches are being developed most intensively to solve the problem of effective planning in the RTOS [10] :
With large system loads, the EDF is more efficient than the RMS.
Multitasking systems need to distribute access to resources. The simultaneous access of two or more processes to any area of memory or other resources represents a certain threat. There are 3 ways to solve this problem [9] :
RTOS usually does not use the first method, because the user application cannot control the processor as much as it wants. However, in many embedded systems and RTOS, it is allowed to run applications in kernel mode to access system calls and gives control over the execution environment without OS intervention.
On uniprocessor systems, the best solution is an application running in kernel mode [9] , which is allowed to block interrupts. As long as the interrupt is blocked, the application uses the resources of the process alone and no other task or interruption can be performed. Thus all critical resources are protected. After the application completes the critical actions, it should unlock interrupts, if any. Временное блокирование прерывания позволено только тогда, когда самый долгий промежуток выполнениякритической секции меньше, чем допустимое время реакции на прерывание. Обычно этот метод защиты используется, только когда длина критического кода не превышает нескольких строк и не содержит циклов. Этот метод идеально подходит для защиты регистров.
Когда длина критического участка больше максимальной или содержит циклы, программист должен использовать механизмы, идентичные или имитирующие поведение систем общего назначения, такие, как семафоры и посылка сигналов.
Следующим проблемам выделения памяти в ОСРВ уделяется больше внимания, нежели в операционных системах общего назначения.
Во-первых, скорости выделения памяти. Стандартная схема выделения памяти предусматривает сканирование списка неопределённой длины для нахождения свободной области памяти заданного размера, а это неприемлемо, так как в ОСРВ выделение памяти должно происходить за фиксированное время.
Во-вторых, память может стать фрагментированной в случае разделения свободных её участков уже запущенными процессами. Это может привести к остановке программы из-за её неспособности задействовать новый участок памяти. Алгоритм выделения памяти, постепенно увеличивающий фрагментированность памяти, может успешно работать на настольных системах, если те перезагружаются не реже одного раза в месяц, но является неприемлемым для встроенных систем, которые работают годами без перезагрузки.
A simple algorithm with a fixed length of memory runs very well in simple embedded systems.
Also, this algorithm works well on desktop systems, especially when, during processing of a section of memory with one core, the next section of memory is processed by another core. Desktop-optimized RTOSs such as the Unison Operating System or DSPnano RTOS provide this capability.
продолжение следует...
Часть 1 Soft and hard real-time operating system and general purpose OS
Comments
To leave a comment
Operating Systems and System Programming
Terms: Operating Systems and System Programming