Analyze the real-time operating system from the task scheduling mechanism

Source: Internet
Author: User
What is a real-time operating system?

I have been developing an embedded system for some time. I have worked on an embedded Linux system for the mobile phone platform, and I have been involved in the VxWorks for the switch and media gateway platforms. After practical application, I looked back at the theory and found that my understanding was superficial. I also found that many people on csdn were not familiar with the real-time and embedded concepts. After all, if you do not use similar products, there are very few opportunities to access them at ordinary times. Even if you do embedded product development, you just need to call the APIS encapsulated by the platform team. Therefore, I would like to summarize these concepts here to deepen my understanding and give new beginners a quick start. You are welcome to make a picture and try to write a serialization. This article first summarizes the concept of real-time, what is a real-time operating system?

1. First, let's talk about the real-time definition and requirements:

See Donal Gillies's definition in the realtime computing FAQ: a real-time system means that the computing correctness of the system depends not only onLogic correctness of CalculationDepends onResult generation time. If the time constraints of the system are not met, the system is considered invalid.

A real-time operating system is required for changing loads (from minimum to Worst Case)Guaranteed to meet time requirements in a deterministic manner. Please note that,Must meetOKSexInstead of requiring fast enough!For example, if you use a powerful enough CPU, Windows can provide a very short typical interrupt response when the CPU is idle. However, when some background tasks are running, sometimes the response will become very long, so that a simple File Reading task will not respond for a long time, or even die directly. This is a basic problem: not because windows is not fast enough or inefficient enough, but because it cannot provide certainty,Therefore, windows is not a real-time operating system..

Based on the actual application, you can choose either a hard real-time operating system or a soft real-time operating system. Hard Real-time is certainly better than soft real-time. However, if your company is preparing to develop a commercial software, please note that the industry recognizes it as a good VxWorks (WinDriver development ), you will have little money to spend, and soft real-time operating systems, such as some real-time Linux, are generally open-source and free, our company's original products are based on VxWorks, currently, cost functions is widely used in the industry. In response to this call, we are investigating how to replace the platform with a free embedded real-time Linux. Students, let's think about how to choose :-)

Hard Real-Time-product VxWorks

A frequently used example is the airbag used in medium and high-grade vehicles. When the sensor reporting a vehicle collision interrupts the CPU, the operating system should quickly allocate the tasks for launching the airbag, and do not allow any other non-real-time processing for interference, one second later, the expansion of the airbag is worse than the absence of the airbag, which is a typical system that must use hard real-time.

Hardware real-time system refers to the systemThere must be guaranteed service time in the worst case, That isFor the Event Response TimeThe deadline must be met in any case..

Soft Real-Time-represents the product soft real-time Linux

Another example is the IPTV digital TV set-top box, which requires real-time processing (Decoding) of video streams. If one or more video frames are lost, the video quality is obviously worse, but as long as you do something simpleJitter ProcessingThe loss of several video frames will not affect the entire system.

A Soft Real-Time System is an event from the statistical point of view that a task can get a guaranteed processing time and reach the system.It can also be processed before the deadline expires,Violation of the deadline does not cause fatal errors..

========================================================== ==============================

Note:: Here, I want to use some ink to differentiate the real-time and embedded concepts, because I have long time to confuse the two. The concept of a real-time operating system is clearly described above, mainly to meet the time requirements with certainty. It is difficult to define an embedded system. If you are interested, you can refer to the "embedded system". Generally, you can think of it as a board or a chip.Total Software and Hardware,Embedded systems must have strong support for real-time tasksTherefore, embedded systems generally adopt real-time operating systems, and choose hard or soft real-time based on different applications.

========================================================== ==============================

2. How to measure the real-time performance of a real-time operating system?

There are two important indicators:

Indicator 1. Interrupt response time (BLOCKED)

The computer receives the interrupt signal to the operating system to respond, and completes switching to the interrupted service program. For a preemptible kernel, you must call a specific function to notify the kernel that the service is about to be interrupted, so that the kernel can track interruption nesting. The interrupt response time of the preemptive kernel is given below:

Interrupt response time= Maximum disconnection time + time to protect the internal registers of the CPU + execution time to enter the interrupt service function + the first instruction time to start executing the interrupt service routine (ISR)

Note:: The interrupt response time is SystemIn the worst caseResponse interruption time: 99 out of 100 system interruptions within 50 ms, only one response interruption time is 250 ms, and the response interruption time can only be considered as 250 ms.

Indicator 2. Task Switching time

In addition to providing certainty for interrupt processing, real-time processing also needs to support periodic interval task scheduling. A large number of control systems require periodic sampling and processing. A specific task must be executed at a fixed period (p) To ensure system stability. Consider the anti-lock braking system (ABS) of a car ). The control system samples the rotation speed of each wheel of a vehicle (up to 20 times per second) and controls the pressure of each brake (to prevent it from locking ). To ensure the normal operation of the control system, the sampling and control of the sensor must follow a certain interval. This meansMust be preemptibleOther processing, so that ABS tasks can be executed according to the expected cycle.

When the multi-task kernel decides to run another task, it saves the current status of the running task (that is, all the content in the CPU register) to its stack. Then, reload the current status of the next task from the stack of the task to the CPU register, and start running the next task. This process is calledTask Switching. The time required for Task Switching depends on the number of registers on the CPU that need to be written into the stack. The more registers the CPU has, the heavier the extra load.

Typical values of important real-time system performance indicators

--------------------------------------------------------------

VxWorks uC/OS-II RT-Linux2.0 qnx6

Hardware PlatformMc68000 33mhz-rj60mhz-rj33mhz-w.

Task Switching3.8us <9us unknown 12.57us

Interrupt response<3us <7.5us 25us 7.54us

--------------------------------------------------------------

References: Analysis and Comparison of real-time performance of four real-time operating systems.

The core of the real-time operating system is task scheduling. Next we will analyze the typical hard real-time representation of product VxWorks and Soft Real-Time Representation of product Linux's task scheduling mechanism.

3. Task Scheduling in VxWorks

Since real-time performance is so important to real-time operating systems, let's take a look at the core module for real-time performance --Task Scheduling. My company spent a lot of money buying the Wind River's VxWorks, but in order to achieve their own controllability, in addition to the task scheduling module, all rewrite, including memory management, file management and other core modules, except for the task scheduling module, This is a magic tool for people to press the box :-)

An independent and interactive program unit in an assembly that forms an application software system.TaskFrom the system perspective,A task is the minimum operating unit of competing system resources.. In a single CPU, the multitasking mechanism creates the illusion that multiple tasks are executed simultaneously. In fact, the system only inserts the kernel into these tasks based on a multi-task scheduling algorithm for execution. A task in Real-Time System VxWorks can have multiple states, but the most basic states are as follows:

(1)Readiness(Ready): The task only waits for the system to allocate cup resources.

(2)Pending state(Pend): the task must be blocked by waiting for some resources that are not available.

(3)Sleep state(Sleep): if the system does not need a job, the job is in sleep state.

(4)Latency(Delay): The status when the task is delayed.

You can search for articles related to VxWorks Task Scheduling on the Internet. Generally, the state machine diagram is configured.

--------------------------------------------------------------

Note:The concepts of tasks, processes, and threads are interrelated and different, because they are not the focus of this article, for more information, see "windows
Kernel programming ". In VxWorks, because each task does not have its own virtual memory space,You can setTaskUnderstoodThread.

--------------------------------------------------------------

A task is scheduled to run for a fixed period of time by the system kernel.Time slice(Time slice, quantum ). Scheduling refers to allocating resources and time for tasks so that the system can meet specific performance requirements.Scheduling AlgorithmIn normal cases,Meet the time limit of all tasks as much as possible: Ensure that strong real-time tasks meet the time limit under peak load conditions. BecauseTime LimitIt is a key factor for distinguishing real-time and non-real-time systems. Therefore, scheduling algorithms are the basic problems of real-time systems. The running performance of the real-time operating system, such as the throughput size, the length of the turnaround time, the timeliness and predictability of the system depend largely on the real-time scheduling.

You can use either of the following methods to schedule a task::

(1)Non-preemption Mode. In this scheduling mode, once the processor is assigned to a task, the task will be executed until the task is completed or an event is blocked, then, the processor is assigned to other tasks. A task is never allowed to seize the allocated processor. Obviously, it is difficult to meet the requirements of urgent tasks. This scheduling method is not suitable in real-time systems.

(2)Preemption Method. Allow the scheduler to stop a running task, assign the processor assigned to the task to another task, according to certain principles. The preemption principles include:

-Time slice Principle. Each task runs by time slice. After a time slice is used up, the task is stopped and rescheduled.

-Priority Principle. When a task arrives, if it has a higher priority than the task being executed, it stops the task being executed and assigns the processor to the task with a higher priority for execution. In real-time systems, priority-based preemptible scheduling and rotation scheduling are generally used in combination with task scheduling and Middle-process scheduling. Therefore, it can have great flexibility and a very small scheduling latency.

The default scheduling mechanism of wind kernel in VxWorks isPriority-based preemptible Scheduling. When this mechanism is used, the system assigns the processor to the task with the highest priority for execution. Once another task with a higher priority occurs, the task scheduler will deprive the current task of execution and assign the processor to the high-priority task. WhileUseTime slice rotation scheduling mechanism. When this mechanism is used, when a task arrives, it is placed behind the rotation queue, waiting for the arrival of the time slice allocated to itself. If it does not end in the time slice, then wait for the arrival of your own time slice until the task is completed.

-Preemptible priority

Priority-based preemptible scheduling is adopted. In the system, each task has a priority ranging from 0 to 255. At any time, once the system kernel finds a task with a higher priority to the ready state, the kernel will save the context of the current task and convert the current task state to the blocking state, switch to the context of the high-priority task for execution.

-Rotation Scheduling Algorithm

Using the rotation scheduling algorithm, the system allows a group of tasks with the same priority in the ready state to execute predetermined time slices in turn. This is a method for average processor allocation. If the rotation scheduling algorithm is not used, the first task to obtain the processor in a group of tasks with the same priority will not be blocked and the processor will be exclusive. If it is not blocked or otherwise occurs, it will not give up the right to use the processor.

-Preemptible scheduling and rotation scheduling

Sometimes, priority-based preemptible scheduling can be combined with rotation scheduling. When a group of tasks with the same priority are evenly distributed in turn, if a task with the same priority is changed to a ready state, the group can be preemptible. This group of tasks will not be able to share the processor again until the execution conditions are met again.

For the flexibility of task control, the VxWorks kernel also providesDynamic Priority MechanismThe task priority can be dynamically changed during running. At the same time,To prevent priority inversionInheritanceMechanismBy using mutex semaphores, you can prevent high-priority tasks from waiting for an uncertain period until a low-priority task is completed.

References: Study on Kernel task scheduling of real-time operating system VxWorks.

4. Linux Task Scheduling

General Linux System SupportReal-timeAndNon-Real-TimeReal-time processes have absolute priority over normal processes. Correspondingly, real-time processes adoptSched_fifoOrSched_rrScheduling Policy, which is used by common processesSched_otherScheduling Policy.

In terms of scheduling algorithm implementation, each task in Linux has four scheduling-related parameters: rt_priority, policy, priority (NICE), and counter. The scheduler schedules processes based on these four parameters.

In sched_other scheduling policy, the scheduler always selects the process with the highest priority + counter value for scheduling and execution. Logically, the sched_other scheduling policy has a scheduling cycle (EPOCH). In each scheduling cycle, the priority and counter values of a process affect which process should be scheduled for execution at the current time.PriorityIs a fixed value, which has been determined at the process creation. It represents the priority of the process, and also represents the process inThe number of time slices that can be obtained in each scheduling cycle;CounterIs a dynamically changing value, which reflects a process in the current scheduling cycleRemaining time slice. At the beginning of each scheduling cycle, the value of priority is assigned to counter, and the value of counter is reduced every time the process is scheduled and executed. When the counter value is zero, the process runs out of its own time slice in this scheduling cycle and no longer participates in the process scheduling in this scheduling cycle. When the time slice of all processes is used up, a scheduling cycle ends and then repeats. In addition, we can see the scheduling cycle in Linux.Not static, It isDynamic ChangesFor example, the number of processes in a running state and their priority value can affect the length of an epoch. It is worth noting that in kernels over 2.4, priority is replaced by nice, but the two have similar functions.

It can be seen that sched_other scheduling policy is essentiallyProportional sharingThis design method can ensure the fairness of the process during scheduling-a low-priority process will also obtain its own in each epoch.DeserveIn addition, it also provides priority for different processes, and processes with a high priority value can get more execution time. For real-time processes, they use a real-time priority rt_priority-based priority scheduling policy. However, based on different scheduling policies, the scheduling methods for processes with the same real-time priority are different:

-Sched_fifo: Different processes Queue according to the static priority, and then in the queue of the same priority, who is prepared to run and who is scheduled first, and the running process will not be terminated until: (1 ). CPU occupied by processes with higher priority; (2 ). self-blocking due to resource requests; (3 ). automatically discard the CPU (call sched_yield ).

-Sched_rr: This scheduling policy is exactly the same as sched_fifo. In addition to assigning a time slice to each process, the time slice stops executing when it reaches the executing process. The length of the time slice can be obtained through sched_rr_get_interval.

Since Linux is a desktop-oriented system, the following problems exist when applying it to real-time applications:

-In Linux, the scheduling unit is10 ms, So it cannot provide accurate timing;

-When a process calls a system call and runs in kernel mode, it cannot be preemptible;

-A large number of locks interrupt operations in the Linux Kernel implementation may cause loss of interruptions;

-Due to the use of virtual memory technology, when a page error occurs, you need to read and exchange data from the hard disk. However, random read/write time may occur due to Random storage locations, in some cases, the deadline for some real-time tasks may be affected;

-Although Linux Process Scheduling supports real-time priority, there is no effective scheduling mechanism and Scheduling Algorithm for real-time tasks; the protocol processing of its network subsystem and the interrupt processing of other devices are not associated with the scheduling of its corresponding processes, and they do not have a clear scheduling mechanism;

References: Linux-based real-time system.

5. Real-Time Linux Research

After writing for half a day, Hu HU finally came to the headlines, real-time Linux research. As mentioned above, although the performance of Wind River's VxWorks is very good, it will take a lot of money. For general soft real-time application systems, it is better to use open-source Free Real-Time Linux. My company is also studying how to convert the platform to Linux. There are many ways to give normal Linux real-time capabilities:

5.1 thin kernel (micro kernel)-thin-Kernel

The thin kernel (or microkernel) method uses the second kernel as the abstract interface between the hardware and the Linux kernel. The non-real-time Linux kernel runs in the background. As a low-priority task of the thin kernel, it hosts all non-real-time tasks. Real-time tasks run directly on the thin kernel. The thin kernel is mainly used for interrupt management (in addition to hosting real-time tasks. Thin KernelIntercept interruptionTo ensure that the non-real-time kernel cannot seize the running of the thin kernel. This allows the thin kernel to provide hard real-time support.


Although the thin kernel method has its own advantages (hard real-time support and standard Linux kernel coexist), this method also has disadvantages. Real-time tasks and non-real-time tasks are independent, resulting inDifficult debugging. Moreover, non-real-time tasks are not fully supported by the Linux platform (thin kernel is calledThin). Examples of using this method include RTLinux (now proprietary to Wind River Systems), real-time application interfaces (rtai), and xenomai.

5.2 ultra-micro kernel

Here, the thin kernel method depends onMinimum KernelThe kernel is further reduced by the ultra-micro kernel method. In this way, it is not like a kernel, but more likeHardware Abstraction Layer(HAL ). The ultra-micro kernel provides hardware resource sharing for multiple operating systems running at a higher level. Because the ultra-micro kernel abstracts the hardware, it can provide priority for higher-level operating systems and support real-time performance.


Note that this method is similar to the virtualization method that runs multiple operating systems. When this method is used, the ultra-micro kernel abstracts hardware in real-time and non-real-time kernels. This is similar to how hypervisor abstracts bare metal machines from the customer's (guest) operating system.

An example of an ultra-micro kernel is the adaptive domain environment for operating systems (ADEOS) of the operating system ). ADEOS supports synchronous running of multiple concurrent operating systems. When a hardware event occurs, ADEOS queries each operating system in the chain to determine which system is used to process the event.

5.3 Resource-Kernel)

Another real-time architecture is the resource kernel method. This method adds a module to the kernel for various resourcesReserved(Reservation ). This mechanism ensures thatTime division multiplexing(Time-multiplexed) access to system resources (CPU, network, or disk bandwidth ). These resources have multiple reserved parameters, such as the cycle, the processing time required (that is, the time required to complete the processing), and the deadline.


The resource Kernel provides a set of application programming APIs that allow tasks to request these reserved resources. Then, the resource kernel can merge these requests and define a scheduling using the constraints defined by the task to provide a definite access (if the certainty cannot be provided, an error is returned ). Through scheduling algorithms such as earliest-Deadline-first (EDF), the kernel can handle dynamic scheduling loads.

An example of implementing the resource kernel method is CMU's Linux/rk. It integrates the portable resource kernel into Linux as A loadable module. This implementation evolved into a commercial timesys Linux/RT product.

5.4 standard Linux kernel latest version 2.6 added Real-Time Functions

These methods are very interesting in architecture, but they are all in the kernelPeripheralRun. However, what will happen if necessary modifications are made to the standard Linux kernel to make it support real-time performance?

In the 2.6 kernelFully PreemptionTo obtain the soft real-time function. In the standard 2.6 Linux kernel, a user-space process cannot be preemptible when it executes a kernel call (called by the system. This means that after a system call is performed for a low-priority process, the high-priority process can access the CPU only after the call is completed.

New configuration optionsConfig_preemptThis kernel behavior is changed. When a high-priority task is available (even if the process is being called by the system), it allows the process to be preemptible.


However, this configuration option is also a compromise. Although this option achieves soft real-time performance and allows the operating system to run smoothly even under load conditions, it also pays a price.The cost is a slight reduction in throughput and kernel performance., BecauseConfig_preemptOverhead is added. This option is useful for desktop and embedded systems, but not in any scenario (such as servers ).

Another useful configuration option in the 2.6 kernel is the high-precision timer. This new option allows the timer to run with a precision of 1 μs (if the underlying hardware supports it) and efficient timer management through the red/black tree. Using the red/black tree, you can use a large number of timers without affecting the performance of the timer subsystem (O (log n.

You can use the preempt_rt patch to implement hard real-time processing. The preempt_rt patch provides multiple modifications to Support Hardware in real time. Some of the modifications include:Re-implement some kernel lock primitives to achieve full preemption, Implement Priority Inheritance of kernel mutex, and convert interrupt handlers into kernel threads to achieve thread Preemption.

References: Real-Time Linux Architecture Analysis-M. Tim Jones, consultant engineer, emulex Corp.

 

--------------------------------------------------------------

This article has come to an end, and summarizes the concepts, performance indicators, task scheduling methods, and real-time comparison between VxWorks and Linux based on your actual project experience, and the corresponding introduction. For the author's own learning, and for the reference of csdn, most of the content comes from the network, not a rigorous paper. If there is any leakage, please point out that we can make progress together.

 

Refer:

From Soft Real-Time to hard real-time

Differences between hard time and Soft Real Time

"Hard Real-Time" injects new vitality into Linux

Real-Time Analysis of T-kernel Task Scheduling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.