Galería de mapas mentales OpenHarmony lightweight kernel
The kernel is the computing core of a one-person operating system and determines the performance and stability of the system. It is the first layer of software expansion based on hardware, provides the basic functions of the operating system, and is the basis for the operation of the operating system. It is responsible for managing the system's processes, memory, peripheral drivers, components, and network systems.
Editado a las 2024-02-08 16:08:42,OpenHarmony lightweight kernel
Overview
The kernel is the computing core of a one-person operating system and determines the performance and stability of the system. It is the first layer of software expansion based on hardware, provides the basic functions of the operating system, and is the basis for the operation of the operating system. It is responsible for managing the system's processes, memory, peripheral drivers, components and network systems
LiteOS-M
Overview
HundredK level memory device
Support memory protection unit
Suitable for lightweight systems
Applied to lightweight systems, MCUs generally have hundreds of K-level memory and can support MPU isolation. Similar kernels in the industry include FreeRToS or Threadx, etc.
Kernel overview
The LiteOS-M kernel architecture includes hardware-related layers and hardware-independent layers. The hardware-related layers are classified according to different compilation tool chains and chip architectures. Provide unified HAL (Hardware Abstraction Layer) Other modules of the interface belong to the hardware-independent layer. Among them, the basic kernel module provides basic capabilities. Extension modules provide network, file system and other component capabilities KAL (Kernel Abstraction Layer) module provides a unified standard interface
HAL (HardwareAbstractionLayer) interface improves the adaptability of hardware and meets the expansion of AloT's rich types of hardware and compilation tool chains
Memory management
static memory
dynamic memory
communication mechanism
event
interlock
message queue
signal
CMSIS (Cortex Microcontroller Software InterfaceStandard, microcontroller software interface standard) and POSIX (Portable Operating System Interface, Portable Operating System Interface) They are all standards for portable operating interfaces and belong to the application interface layer, which can enhance the portability of application software and reduce development difficulty.
CMSIS (Cortex Microcontroller Software InterfaceStandard, microcontroller software interface standard)
CMSIS is a vendor-independent hardware abstraction layer for microcontrollers based on ARM Cortex processors. It contains multiple component layers, one of which is the RTOS layer, which defines a set of common and standardized RTOSAPI interfaces, reducing application developers' dependence on specific RTOSs and facilitating the transplantation and reuse of user software. This set of APIs has 2 versions, namely version 1 (CMSIS-RTOSv1) and version 2 (CMSIS-RTOSv2). OpenHarmonyLiteos-M only provides the implementation of version 2.
POSIX (Portable Operating System Interface, Portable Operating System Interface)
The OpenHarmony kernel uses the musl libc library and self-developed interfaces, and supports some standard POSIX interfaces. Developers can develop components and applications on the kernel based on POSIX standard interfaces.
LiteOS-M kernel startup process
1. Configure the system clock and ticks per second in the development board configuration file targetconfig.h. You can tailor the configuration of tasks, memory, IPC, and exception handling modules.
2. When the system is restarted, the root configuration will initialize the specified module.
3. The kernel startup process includes peripheral initialization, system clock configuration, kernel initialization, operating system startup, etc. For details, see the kernel startup process.
LiteOS-M already supports mainstream architectures such as ARMCortex-M3, ARMCortex-M4, ARMCortex-M7, ARM Cortex-M33, and RISc-V.
Kernel basics
task management
describe
From a system perspective, a task is the smallest running unit that competes for system resources. Tasks can wait for the CPU, use memory space and other system resources, and run independently of other tasks
The task module of Liteos-M can provide users with multiple tasks, realize switching between tasks, and help users manage business program processes.
The task module has the following characteristics
Support multitasking
A task represents a thread
Preemptive scheduling mechanism
High-priority tasks can interrupt low-priority tasks, and low-priority tasks must be blocked or terminated before they can be scheduled.
Tasks with the same priority support time slice rotation scheduling.
There are 32 priorities [0-31], the highest priority is 0 and the lowest priority is 31
Task status
Blocked state includes tasks that are suspended (suspend state), tasks that are delayed (delay state), tasks that are waiting for semaphores, read-write queues, or waiting events, etc.
Ready state -> Running state: After the task is created, it enters the ready state. When a task switch occurs, the highest priority task in the ready queue is executed and enters the running state. At the same time, the task is removed from the ready queue.
Running state -> Ready state: After a higher priority task is created or restored, task scheduling will occur. At this time, the highest priority task in the ready queue changes to the running state, then the originally running task changes from the running state to the ready state, and still in ready queue
Ready state -> Blocked state: The task may also be blocked (suspended) in the ready state. At this time, the task status changes from the ready state to the blocking state. The task is deleted from the ready queue and will not participate in task scheduling until the task be restored
Blocked state -> Ready state: After the blocked task is recovered (task recovery, delay time timeout, read semaphore timeout or read semaphore, etc.), the recovered task will be added to the ready queue, thus changing from the blocked state Becomes ready: If the priority of the resumed task is higher than the priority of the running task, task switching will occur and the task will change from ready to running.
Running state -> Blocked state: When a running task is blocked (suspended, delayed, read semaphore, etc.), the task is inserted into the corresponding blocking queue, and the task state changes from running state to blocking state, and then occurs Task switching runs the highest priority task in the ready queue
Running state -> Exit state: The running task ends and the task status changes from running state to exit state. The exit status includes the normal exit status and nvalid status when the task ends. For example, if the task ends but does not delete itself, the lnyalid status is displayed to the outside world, that is, the exit status.
Blocked state -> Exited state: The blocked task calls the delete interface, and the task state changes from blocked to exited.
Task management related concepts
Task ID
It is returned to the user through parameters when the task is created, which is an important identification of the task.
Task priority
Indicates the priority order of task execution
Task entry function
The function that will be executed after the new task is scheduled. This function is implemented by the user and is set through the task creation structure when the task is created.
task stack
Each task has its own independent stack space, which we call a task stack. The information saved in the stack space includes local variables, registers, function parameters, function return addresses, etc.
task context
Some resources used by tasks during running, such as registers, etc., are called task context
Task control block TCB
Each task contains a task control block (TCB)
Task switching
Including actions such as obtaining the highest priority task in the ready queue, saving the task context when switching out, and restoring the task context when switching in.
Task development process
1. Lock task scheduling LOs_TaskLock to prevent high-priority task scheduling. 2. Create the task Los_TaskCreate. 3. Unlock the task LOs_TaskUnlock and allow tasks to be scheduled according to priority. 4. Delay task LOs_TaskDelay, task delay waiting. 5. Suspend the specified task Los_TaskSuspend, and the task is suspended waiting for recovery operations. 6. Resume the suspended task Los_TaskResume.
Task management instructions
Task management module interface
time management
describe
Based on system clock
Time management is based on the system clock and provides all time-related services to applications.
The system clock is generated by an interrupt triggered by an output pulse generated by a timer counter. One is defined as an integer or a long integer. The period of the output pulse is called a "clock tick". The system clock is also called the time stamp or Tick
The operating system times in ticks
The user measures time in seconds and milliseconds, while the operating system measures time in Tick. When the user needs to operate the system, such as task suspension, delay, etc., the time management module is required to convert Tick and seconds/milliseconds.
The LiteOS-M kernel time management module provides time conversion and statistical functions
time management unit
The smallest timing unit of the Cycle system
The length of Cycle is determined by the system main clock frequency. The system main clock frequency is the number of cycles per second.
Tick is the basic time unit of the operating system, determined by the number of ticks per second configured by the user.
Time management is not a separate functional module and relies on the two configuration options OS_SYS_CLOCK and LOSCFGBASE_CORE_TICKPERSECOND
The number of ticks in the system is not counted when interrupts are turned off, so the number of ticks in the operating system cannot be used as an accurate time.
The relationship between cycle and tick. Cycle is the timing unit of the system kernel, and tick is the timing unit of the operating system. The two do not belong to the same type of timing. Users only need to operate tick, but generally do not operate cycle.
The default value of LOSCFG_BASE_CORE_TICK_PER_SECOND in the LiteOS-M kernel is 100, 100 ticks per second
Time management module interface
Interrupt management
describe
During the running of the program, when a transaction occurs that needs to be processed immediately by the CPU, the CPU temporarily suspends the execution of the current program and processes the transaction. This process is called an interrupt.
Through the interrupt mechanism, the CPU can perform other tasks when the peripheral does not require CPU intervention: when the peripheral requires the CPU, the CPU will interrupt the current task to respond to the interrupt request. This can prevent the CPU from spending a lot of time waiting and querying the status of peripherals, effectively improving the real-time performance and hot-running efficiency of the system.
When the hardware generates an interrupt, its corresponding interrupt handler is found through the interrupt number, and the interrupt handler is executed to complete the interrupt processing.
Basic concepts of interrupt management
interrupt number
A specific flag for the interrupt request signal. The computer can determine which device made the interrupt request based on the interrupt number.
interrupt request
An "emergency event" applies to the CPU (sends an electrical pulse signal) and requests an interrupt, which requires the CPU to suspend the currently executing task to process the "emergency event". This process is called an interrupt request.
Interrupt priority
In order to enable the system to respond to and handle all interrupts in a timely manner, the system divides interrupt sources into several levels based on the importance and urgency of the interrupt event, called interrupt priorities.
Interrupt handler
When the peripheral sends an interrupt request, the CPU suspends the current task and responds to the interrupt request, that is, executing the interrupt handler. Each device that generates an interrupt has a corresponding interrupt handler
Interrupt trigger
The interrupt source sends an interrupt signal to the interrupt controller, and the interrupt controller arbitrates the interrupt, determines the priority, and sends the interrupt signal to the CPU.
Interrupt vector table
Store interrupt vectors, which correspond to interrupt numbers. Interrupt vectors are stored in the interrupt vector table in the order of interrupt numbers.
interrupt vector
Entry address of interrupt service routine
Interrupt management instructions
The interrupt handler cannot take too long, otherwise it will affect the CPU's timely response to interrupts.
During the interrupt response process, functions such as LOS_Schedule that cause scheduling cannot be executed directly or indirectly.
The input parameter of interrupt recovery LOsIntRestore() must be the return value of the corresponding LOSIntLock() (that is, the CPSR value before turning off the interrupt)
Interrupt management module interface
Software timer
describe
It is a timer based on the system Tick clock interrupt and simulated by software. When the set Tick clock count value passes, a user-defined callback function will be triggered. Timing accuracy is related to the period of the system Tick clock
Hardware timers are limited by hardware, and the number is not enough to meet the actual needs of users. Therefore, in order to meet user needs, more timers are provided. The LiteOS-M kernel provides software timer functions.
Software timer expands the number of timers, allowing the creation of more scheduled services
Software timers are system resources. A piece of continuous memory has been allocated during module initialization. The maximum number of timers supported by the system is configured by the LOSCFG BASE_CORE_SWTMR_LIMIT macro in los_config.h.
Software timer features
Static cropping, software timer function can be turned off through macro
Software timer creation, software timer start
The software timer is stopped and the software timer is deleted.
Obtain the number of remaining ticks of the software timer
Software timer operating mechanism
The software timer uses a queue and a task resource in the system: its triggering follows the queue rules, first in, first out. A timer with a short timing time is always closer to the head of the queue than a timer with a timing time longer, meeting the criterion of being triggered first.
Software timers use Tick as the basic timing unit: when the user creates and starts a software timer, the LiteOS-M kernel will determine the expiration Tick time of the timer based on the current system Tick time and the user-set timing interval, and will The timer control structure is linked to the timing global linked list
When a Tick interrupt arrives: Scan the global timing linked list of software timers in the Tick interrupt processing function to see if any timer times out. If so, record the timeout timer.
After the Tick interrupt processing function ends: the software timer task (with the highest priority) is awakened, and the timeout callback function of the previously recorded timer is called in the task.
Software timer status
OS_SWTMR_STATUS_UNUSED (unused)
The system initializes all timer resources in the system to this state when the timer module is initialized.
OS_SWTMR_STATUS_CREATED (Create not started/stopped)
After calling the LOS_SwtmrCreate interface in an unused state or calling the LOS_SwtmrStop interface after startup, the timer will change to this state.
OS_SWTMR STATUS_TICKING (count)
After the timer is created, the LOS_SwtmrStart interface is called, and the timer will become this state, indicating the state when the timer is running.
Software timer mode
One shot timer
This type of timer will only trigger a timer event once after it is started, and then the timer will be automatically deleted.
Periodic trigger timer
This type of timer will periodically trigger timer events until the user manually stops the timer, otherwise it will continue to execute forever.
Single trigger timer (will not be automatically deleted)
The difference from the first type is that this type of timer will not be automatically deleted after timeout. You need to call the timer deletion interface to delete the timer.
Software timer usage instructions
Do not do too many operations in the callback function of the software timer, and do not use interfaces or operations that may cause task suspension or blocking.
The software timer uses a queue and a task resource of the system. The priority of the software timer task is set to 0 and no modification is allowed.
The number of software timer resources that can be configured in the system refers to the total number of software timer resources that can be used by the entire system, not the number of software timer resources that can be used by users. For example, if the system software timer occupies one more software timer resource, the number of software timer resources that the user can use will be reduced by one.
To create a timer with a one-time non-self-deleting attribute, the user needs to call the timer deletion interface to delete the timer and recycle timer resources to avoid resource leakage.
Create a one-shot software timer. After the timer times out and executes the callback letter, the system will automatically delete the software timer and recycle resources.
Software timer development process
Configure software timers
Confirm that the configuration items LOSCFG_BASE_CORE_SWTMR and LOSCFG_BASE_IPC_QUEUE are 1 and open.
Configure the maximum number of software timers supported by LOSCFG_BASE_CORE_SWTMR_LIMIT
Configure OS_SWTMR_HANDLE_QUEUE_SIZE software timer queue maximum length
Create timer LOS_SwtmrCreate
Create a software timer that specifies the timing duration, timeout processing function, and trigger mode.
Returns the function execution result, success or failure
Start timer LOS_SwtmrStart
Get the number of remaining ticks of the software timer LOS_SwtmrTimeGet
Stop timer LOs_SwtmrStop
Delete timer LOS SwtmrDelete
Software timer module interface
Memory management
describe
The memory management module manages the memory resources of the system. It is one of the core modules of the operating system and mainly includes the initialization, allocation and release of memory.
During the operation of the system, the memory management module manages the use of memory by users and the OS by powering/releasing the memory, so as to optimize the utilization and efficiency of the memory, and at the same time solve the memory fragmentation problem of the system to the greatest extent.
LiteOS-M's memory management is divided into static memory management and dynamic memory management, providing functions such as memory initialization, allocation, and release.
Static memory management
Static memory is essentially a static array. The block size in the static memory pool is set during initialization. The block size cannot be changed after initialization.
The static memory pool consists of a control block LOS_MEMBOX_INFO and several memory blocks LOS_MEMBOX_NODE of the same size.
The number of memory blocks in the initialized memory pool is not equal to the total size divided by the memory block size, because there is memory overhead in the control block of the memory pool and the control header of each memory block. When setting the total size, these factors need to be considered. go in
scenes to be used
When users need to use fixed-length memory, they can obtain the memory through static memory allocation. Once used, the occupied memory is returned through the static memory release function so that it can be reused.
The control block is located at the head of the memory pool and is used for memory block management. It includes the memory block size uwBlkSize, the number of memory blocks uwBlkNum, the number of allocated memory blocks uwBlkCnt and the free memory block list stFreeList. The application and release of memory blocks are based on the block size. Each memory block contains a pointer pstNext pointing to the next memory block.
Static memory development process
Plan a memory area as a static memory pool
Call LOS_Memboxlnit to initialize the static memory pool. Initialization will divide the memory area specified by the input parameter into N blocks (the N value depends on the total size of the static memory and the block size), hang all memory blocks to the free linked list, and place the control header at the beginning of the memory.
Call the LOS_MemboxAlloc interface to allocate static memory. The system will obtain the first free block from the free linked list and return the starting address of the memory block.
Call the LOS_MemboxClr interface. Clear the memory block corresponding to the input parameter address.
Call the LOs MemboxFree interface. Add the memory block to the free linked list
branch topic
Static memory module interface
Dynamic memory management
describe
Dynamic memory management: When memory resources are sufficient, memory blocks of any size are allocated from a larger continuous memory (memory pool, also heap memory) configured in the system according to user needs. When the user does not need the memory block, it can be released back to the system for next use.
LiteOS-M dynamic memory optimizes the division of intervals based on the TLSF algorithm to obtain better performance and reduce the fragmentation rate.
scenes to be used
The main job of dynamic memory management is to dynamically allocate and manage the memory range requested by the user. Dynamic memory management is mainly used in scenarios where users need to use memory blocks of varying sizes. When users need to use memory, they can request a memory block of a specified size through the dynamic memory application function of the operating system. Once used, the user can request a memory block of a specified size through the dynamic memory release function. Return the occupied memory so that it can be reused
TLSF: Two-Level Segregated Fit two-level segmentation strategy algorithm
Comparison between dynamic memory and static memory
dynamic memory
advantage
Allocate on demand
shortcoming
Fragmentation may occur in the memory pool
static memory
advantage
High allocation and release efficiency, no fragmentation in the static memory pool
shortcoming
You can only apply for memory blocks with initialized preset sizes, and cannot apply on demand.
Dynamic memory core algorithm
Based on the TLSF (Two Level Segregated Fit memory allocator) algorithm, the OpenHarmony heap memory has optimized the interval division, achieving better performance and reducing the fragmentation rate.
According to the size of the free memory block, multiple free lotus tables are used to manage it. According to the size of the free memory block, it is divided into two parts: [4, 127] and [2^7, 2^31]
Divide the memory in the [4,127] interval equally, as shown in the lower half of the figure, into 31 small intervals. Each small interval corresponds to a memory block size that is a multiple of 4 bytes. Each small interval corresponds to a free memory The linked list and a bit are used to mark whether the corresponding free memory linked list is empty. When the value is 1, the free linked list is not empty. The corresponding 31 bits in the [4,127] interval mark whether the linked list is empty.
Free memory blocks larger than 127 bytes are managed by the free linked list according to the power of 2 interval size. It is divided into 24 cells in total, and each cell is equally divided into 8 secondary cells. See the Size Class and Size Subclass parts in the upper part of the figure. Each secondary cell corresponds to a free linked list and a bit used to mark whether the corresponding free memory linked list is empty. A total of 24*8=192 secondary cell intervals, corresponding to 192 free linked lists and 192 bits to mark whether the linked list is empty
Dynamic memory management structure
Based on the TLSF algorithm, OpenHarmonyLiteOS-M dynamic memory optimizes the division of intervals to obtain better performance and reduce the fragmentation rate.
Dynamic memory usage instructions
Since dynamic memory management requires management control block data structures to manage memory, these data structures will consume additional memory, so the total amount of memory available to the actual user is less than the size of the configuration item OS_SYS_MEM_SIZE.
The aligned allocation memory interface LOs_MemAllocAlign/LOs_MemMallocAlign may consume additional memory due to address alignment, so there is some lost memory. When the system releases the aligned memory, it also reclaims the lost memory caused by the alignment.
The non-contiguous memory areas passed in by the LosMemRegion array parameter of the non-contiguous memory area interface LOS_MemRegionsAdd need to be in ascending order according to the memory start address of each memory area, and the memory areas cannot overlap.
Dynamic memory development process
1.Initialize Los_Memlnit
After initializing a memory pool, a memory pool control head and tail node EndNode is generated, and the remaining memory is marked as FreeNode memory node. Note: EndNode is the end node of the memory pool, and its size is o.
2. Apply for dynamic memory of any size Los_MemAlloc
Determine whether there is free memory block space in the dynamic memory pool that is larger than the requested size. If it exists, set aside a memory block and return it in the form of a pointer. If it does not exist, return NULL. If the free memory block is larger than the requested amount, the memory block needs to be divided, and the remaining part is mounted on the free memory list as a free memory block.
3. Release dynamic memory LOS_MemFree
The memory block can be collected for next use. Calling LOS_MemFree to release the memory block will reclaim the memory block and mark it as FreeNode. When memory blocks can be collected, adjacent FreeNodes will be automatically merged.
dynamic memory interface
Kernel communication mechanism
event
describe
Events are a mechanism to achieve communication between tasks and can be used to achieve synchronization between tasks. However, event communication can only be event type communication without data transmission. A task can wait for the occurrence of multiple events: it can wake up the task for event processing when any event occurs; it can also wake up the task for event processing after several events occur. The event collection is represented by a 32-bit unsigned integer variable, and each bit represents an event.
The 25th bit of the event is a reserved bit and cannot be set.
How events work
Event is a communication mechanism between tasks and can be used for synchronization operations between tasks
event handling pattern
LOS_WAITMODE_AND
Logical AND, only when these events have occurred can the reading be successful, otherwise the task will block waiting or return an error code.
LOS_WAITMODE_OR
Logical OR, as long as any one of these events occurs, the reading can be successful, otherwise the task will block waiting or return an error code
LOS_WAITMODE_CLR
This is an additional read mode that needs to be used in conjunction with all event mode or any one event mode ( LOS_WAITMODE AND I LOS_ WAITMODE CLR or LOS_WAITMODE_OR / LOS_WAITMODE CLR ) In this mode, when all event mode or any one event is set After the pattern is read successfully, the corresponding event type bit in the event control block will be automatically cleared.
Event development instructions and development process
Event synchronization between tasks can be one-to-many or many-to-many.
One-to-many: Indicates that a task can wait for multiple events
Many-to-many: Indicates that multiple tasks can wait for multiple events. A write event can trigger at most one task to wake up from blocking.
Event read timeout mechanism
Only synchronizes between tasks and does not transmit specific data
event interface
mutex lock
describe
Mutex lock, also known as mutual exclusion semaphore, is a special binary semaphore used to achieve exclusive processing of shared resources.
There are only two states of a mutex lock at any time, unlocked or locked. When a task holds the mutex, the mutex is in a locked state, and the task acquires ownership of the mutex. When the task releases it, the interlock is unlocked and the task loses ownership of the interlock. When a task holds a mutual lock, other tasks will no longer be able to unlock or hold the mutual lock.
In a multi-tasking environment, there are often application scenarios where multiple tasks compete for the same shared resource. Mutex locks can be used to protect shared resources to achieve exclusive access. In addition, mutex locks can solve the problem of priority flipping of semaphores.
Instructions for use of mutual back lock
Two tasks cannot lock the same mutex. If a task locks a mutex that is already held, the task will be suspended until the task holding the lock unlocks the mutex before the mutex can be locked.
Mutex locks cannot be used in interrupt service routines
As a real-time operating system, the LiteOS-M kernel needs to ensure the real-time nature of task scheduling and try to avoid long-term blocking of tasks. Therefore, after obtaining the mutex lock, the mutex lock should be released as soon as possible.
During the process of holding the mutex lock, interfaces such as LOS_TaskPriSet must not be called to change the priority of the task holding the mutex lock.
Mutex lock development process
non-blocking mode
The task needs to apply for a mutex lock. If no task currently holds the mutex lock, or the task holding the mutex lock and the task applying for the mutex lock are the same person's tasks, the call will be successful.
permanent blocking mode
The task needs to apply for a mutex lock. If the mutex lock is not currently occupied, the application is successful. Otherwise, the task enters the blocking state, and the system switches to the ready task with the highest priority to continue execution. After the task enters the blocked state, the blocked task will not be executed again until other tasks release the mutual responsibility lock.
timed blocking mode
The task needs to apply for a mutex lock. If the interlock is not currently occupied, please succeed. Otherwise, the task enters the blocking state, and the system switches to the ready task with the highest priority to continue execution. After the task enters the blocked state, other tasks will release the mutex lock before the specified time times out, or the blocked task will be re-executed after the specified time times out.
Mutex lock interface
message queue
describe
Queue text is called message queue, which is a data structure commonly used for communication between tasks. The queue receives messages of variable length from tasks or interrupts, and determines whether the delivered message is stored in the queue space according to different interfaces.
The task can read messages from the queue. When the message in the queue is empty, the reading task is suspended; when there is a new message in the queue, the suspended reading task is awakened and processes the new message. Tasks can also write messages to the queue. When the queue is full of messages, the writing task is suspended; when there are idle message nodes in the queue, the suspended writing task is awakened and writes the message.
You can adjust the blocking mode of the read and write interface by adjusting the timeout of the read queue and write queue. If the timeout of the read queue and write queue is set to 0, the task will not be suspended and the interface will return directly. This is non-blocking. model. On the contrary, if the timeout of both the queue and the write queue is set to a time greater than 0, it will run in plug mode.
Message queue features
Messages are queued in a first-in-first-out manner and support asynchronous reading and writing.
Each time a message is read, the message node is set to idle
The type of message sent is agreed upon by both communicating parties, and messages of different lengths (not exceeding the message node size of the queue) can be allowed.
A task can receive and send messages from any message queue
Multiple tasks can receive and send messages from the same message queue
The queue space required when creating a queue. The system in the interface dynamically applies for memory on its own.
Both read queue and write queue support timeout mechanism
Message queue usage instructions
The maximum number of queues supported by the system: the total number of queue resources in the entire system, not the number that users can use. For example, if the system software timer occupies one more queue resource, the queue resources available to the user will be reduced by one.
The queue name and flaqs passed in when creating the queue are not used for the time being and are used as reserved parameters for the future.
The input parameter timeOut in the queue interface function is relative time
LOS_QueueReadCopy, LOS_QueueWriteCopy and LOS_QueueWriteHeadCopy are a set of interfaces. LOS_QueueRead, LOS_QueueWrite and LOS_QueueWriteHead are a set of interfaces. Each set of interfaces needs to be used together.
timeOut is relative time: the relative time between the message queue and the read and write tasks
In view of the fact that the interfaces LOS_QueueWrite, LOS_QueueWriteHead and LOS_QueueRead actually operate on data addresses, the user must ensure that the memory area pointed to by the pointer obtained by calling LOS_QueueRead is not abnormally modified or released during the queue reading, otherwise it may lead to unpredictable consequences.
Since the LOS_QueueWrite, LOS_QueueWriteHead and LOS_QueueRead interfaces actually operate on data addresses, which means that the actual length of the message written and read is only a pointer data, so before using this set of interfaces, users need to ensure that the message length when creating the queue is The node size is the length of a pointer to avoid unnecessary waste and read failure.
The read length of the LOS_QueueReadCopy interface must be greater than the actual length, otherwise the message will be truncated
message queue interface
signal
describe
Semaphore is a mechanism for communication between tasks, which can achieve synchronization between tasks or mutual access to shared resources.
A semaphore data structure usually has a count value, Used to count the number of effective resources, indicating that the remaining ones can be used The number of shared resources has two meanings:
0, indicating that the semaphore is currently unavailable, so there may be tasks waiting for the semaphore.
Positive value, indicating that the semaphore can currently be obtained
There are the following differences in usage between semaphores for synchronization and semaphores for mutual exclusion:
When used as mutual exclusion
When used as a mutual exclusion, the initial semaphore count value is not 0, indicating the number of available shared resources. Before you need to use a shared resource, first obtain the semaphore, then use a shared resource, and release the semaphore after use. In this way, when the shared resources are fetched, that is, when the semaphore count is reduced to 0, other tasks that need to obtain the semaphore will be blocked, thus ensuring mutually exclusive access to the shared resources. In addition, when the number of shared resources is 1, it is recommended to use a binary semaphore, a mechanism similar to a mutex lock.
When used for synchronization
When used for synchronization, the initial semaphore count value is 0. Task 1 is blocked because it cannot obtain the semaphore. Until task 2 or an interrupt releases the semaphore, task 1 can enter the Ready or Running state, thus achieving synchronization between tasks.
Semaphore development process
semaphore initialization
Apply for memory for the configured N semaphores (the N value can be configured by the user and implemented through the LOSCFG_BASE_IPC_SEM_LIMIT macro), and initialize all semaphores to be unused, and add them to the unused linked list for system use.
Create semaphore LOS_SemCreate
To create a binary semaphore, call LOs_BinarySemCreate, obtain a semaphore from the unused semaphore list, and set the initial value.
Apply for semaphore LOS_SemPend
If the counter value is greater than 0, it is directly decremented by 1 and returns success. Otherwise, the task is blocked and waits for other tasks to release the semaphore. The waiting timeout can be set. When a task is blocked by a semaphore, the task is placed at the end of the semaphore waiting task queue.
Release the semaphore LOS_SemPost
If there is no task waiting for the semaphore, the counter is directly increased by 1 and returned. Otherwise, wake up the semaphore and wait for the first person task on the task queue.
Delete the semaphore LOS_SemDelete
Set the semaphore in use to an unused semaphore and hang it back to the unused linked list
Semaphore interface
Kernel extensions
CPU usage
describe
CPU (Central Processing Unit, Central Processing Unit) occupancy is divided into system CPU occupancy and task CPU occupancy
System CPU usage (CPU Percent)
System CPU occupancy (CPUPerCent) refers to the system's CPU occupancy within a period. It is used to indicate the idleness and busyness of the system within a period of time, and also indicates the load of the CPU. The valid range of system CPU usage is 0 to 100, and its precision (can be adjusted through configuration) is a percentage. 100 means the system is operating at full capacity
Task CPU usage
Task CPU usage refers to the CPU usage of a single task and is used to indicate how busy a single task is within a period of time. The effective representation range of task CPU usage is 0 to 100, and its precision (can be adjusted through configuration) is a percentage. 100 means that the system has been running the task for a period of time
Users can use system-level CPU usage to determine whether the current system load exceeds the design specifications.
Through the CPU usage of each task in the system, determine whether the CPU usage of each task meets the design expectations.
CPU usage operating mechanism
LiteOS-M's CPUP (CPUPercent, system CPU usage) uses task-level recording. When tasks are switched, the task startup time, task cut-out or exit time are recorded. Each time a task exits, the system will accumulate the total number of tasks. Take up time
LiteOS-M provides the following two types of CPU usage information queries:
System CPU usage
Task CPU usage
How to calculate CPU usage
System CPU usage = total running time of other tasks in the system except idle tasks/total system running time
Task CPU usage = total task running time/total system running time
CPU usage operation can be configured in target_config.h
dynamic loading
describe
In small devices with limited hardware resources, it is necessary to solve the problem of being unable to program multiple algorithms at the same time through the dynamic deployment capability of the algorithm. Taking ease of use for developers as the main consideration and considering multi-platform versatility, LiteOS-M chooses the industry-standard ELF loading solution to facilitate the expansion of the algorithm ecosystem.
LiteOS-M provides interfaces similar to dlopen, dlsym, etc. APP can load and unload the corresponding algorithm library through the interface provided by the dynamic loading module.
Dynamically loaded symbol table export
Shared libraries calling kernel interfaces require the kernel to actively expose the interfaces required by the dynamic library. This mechanism compiles the symbol information into the specified segment, and calling the SYM_EXPORT macro can complete the export of the specified symbol information.
Symbol information is described through the structure Symlnfo, and its members include symbol name and symbol address information. The macro SYM EXPORT imports the symbol information into the .Sym.* section through the _attribute_ compilation attribute.
Dynamically load ELF file loading
During the loading process, the LOAD segment that needs to be loaded into the memory can be obtained based on the handle of the ELF file and the segment offset of the program header table. There are generally two segments, a read-only segment and a read-write segment. You can use readelf -L to view the ELF file. LOAD segment information
Apply for physical memory according to the corresponding alignment attributes, and write the code segment or data segment into the memory through the loading base address and offset of each segment.
Dynamically load ELF file links
Obtain the relocation table through the .dynamic section of the ELF file, traverse each entry in the table that needs to be relocated, and then search for the corresponding symbol in the shared library and the export symbol table provided by the kernel according to the symbol name that needs to be relocated, and update the corresponding relocation. Positioning information.
ELE support types
When compiling a shared library, add -fPIC to compile position-independent code (-fPIC is the compilation option). At this time, the shared library file type is ET_DYN, which can be loaded into any valid address range.
Example: arm-none-eabi-gcc -fPic -shared -o lib.so lib.c
Liteos-A
M-class memory device
Support memory management unit
Suitable for small systems
It is mainly used in small systems. The devices generally use M-class memory and can support MMU isolation. Similar kernels in the industry include Zircon or Dawin, etc.