You get a bonus - 1 coin for daily activity. Now you have 1 coin

Soft and hard real-time operating system and general purpose OS

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.

  • 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.

Good 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 .

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:

  • loss of relevance of results;
  • big financial losses;
  • accidents and disasters.

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:

  • 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.

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 complex 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 a task.
  • 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:
  1. Increased reliability, since each service is, in fact, an independent application and it is easier to debug and track errors.
  2. Improved scalability, as unnecessary services can be excluded from the system without affecting its performance.
  3. Increased fault tolerance, since the "frozen" service can be restarted without rebooting the system.

Real-Time Operating System Architectures

Soft and hard real-time operating system and general purpose OS

Soft and hard real-time operating system and general purpose OS

Soft and hard real-time operating system and general purpose OS

Monolithic architecture

Layered (layered) architecture

Client-server architecture

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 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] .

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] .

Scheduling tasks

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] :

  1. Determines whether the currently running task should continue to run.
  2. Sets which task should run next.
  3. Saves the context of the stopped task (so that it resumes work from the stop point).
  4. Sets the context for the next task.
  5. Runs this task.

These five steps of the algorithm are also called task switching .

Task performance

In ordinary RTOS, a task can be in 3 possible states [9] :

  • 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 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] .

Planning algorithms

Currently, two approaches are being developed most intensively to solve the problem of effective planning in the RTOS [10] :

  • Static scheduling algorithms (RMS, Rate Monotonic Scheduling). Use priority preemptive planning. Priority is assigned to each task before it starts. The advantage is given to tasks with the shortest execution periods.
  • Dynamic scheduling algorithms (EDF, Earliest Deadline First Scheduling). Priority to tasks is assigned dynamically, with preference 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. 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] :

  • interrupt blocking temporarily;
  • binary semaphores;
  • sending signals.

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
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Operating Systems and System Programming

Terms: Operating Systems and System Programming