@@ -196,14 +196,14 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
...
@@ -196,14 +196,14 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
#### Available APIs
#### Available APIs
**Table 1** APIs for process management
**Table 11** APIs for process management
| Header File| API| Description|
| Header File| API| Description|
| -------- | -------- | -------- |
| -------- | -------- | -------- |
| \#include <stdlib.h> | void abort(void); | Terminates the thread.|
| \#include <stdlib.h> | void abort(void); | Terminates the thread.|
| \#include <assert.h> | void assert(scalar expression); | Terminates the thread if the assertion is false.|
| \#include <assert.h> | void assert(scalar expression); | Terminates the thread if the assertion is false.|
| \#include <pthread.h> | int pthread_cond_destroy(pthread_cond_t *cond); | Destroys a condition variable.|
| \#include <pthread.h> | int pthread_cond_destroy(pthread_cond_t \*cond); | Destroys a condition variable.|
| \#include <pthread.h> | int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t \*restrict attr); | Initializes a condition variable.|
| \#include <pthread.h> | int pthread_cond_init(pthread_cond_t \*restrict cond, const pthread_condattr_t \*restrict attr); | Initializes a condition variable.|
| \#include <pthread.h> | int pthread_cond_timedwait(pthread_cond_t \*restrict cond, pthread_mutex_t \*restrict mutex, const struct timespec \*restrict abstime); | Waits for the condition.|
| \#include <pthread.h> | int pthread_cond_timedwait(pthread_cond_t \*restrict cond, pthread_mutex_t \*restrict mutex, const struct timespec \*restrict abstime); | Waits for the condition.|
| \#include <pthread.h> | int pthread_condattr_init(pthread_condattr_t \*attr); | Initializes the condition variable attribute.|
| \#include <pthread.h> | int pthread_condattr_init(pthread_condattr_t \*attr); | Initializes the condition variable attribute.|
| \#include <pthread.h> | int pthread_mutex_unlock(pthread_mutex_t \*mutex); | Unlocks a mutex.|
| \#include <pthread.h> | int pthread_mutex_unlock(pthread_mutex_t \*mutex); | Unlocks a mutex.|
...
@@ -212,13 +212,13 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
...
@@ -212,13 +212,13 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include <pthread.h> | pthread_t pthread_self(void); | Obtains the ID of the current thread.|
| \#include <pthread.h> | pthread_t pthread_self(void); | Obtains the ID of the current thread.|
| \#include <pthread.h> | int pthread_getschedparam(pthread_t thread, int \*policy, struct sched_param \*param); | Obtains the scheduling policy and parameters of a thread.|
| \#include <pthread.h> | int pthread_getschedparam(pthread_t thread, int \*policy, struct sched_param \*param); | Obtains the scheduling policy and parameters of a thread.|
| \#include <pthread.h> | int pthread_setschedparam(pthread_t thread, intpolicy, const struct sched_param \*param); | Sets a scheduling policy and parameters for a thread.|
| \#include <pthread.h> | int pthread_setschedparam(pthread_t thread, intpolicy, const struct sched_param \*param); | Sets a scheduling policy and parameters for a thread.|
| \#include <pthread.h> | int pthread_mutex_init(pthread_mutex_t \*__restrict m, const pthread_mutexattr_t \*__restrict a); | Initializes a mutex.|
| \#include <pthread.h> | int pthread_mutex_init(pthread_mutex_t *\_restrict m, const pthread_mutexattr_t \*__restrict a); | Initializes a mutex.|
| \#include <pthread.h> | int pthread_mutex_lock(pthread_mutex_t \*m); | Locks a mutex.|
| \#include <pthread.h> | int pthread_mutex_lock(pthread_mutex_t \*m); | Locks a mutex.|
| \#include <pthread.h> | int pthread_mutex_trylock(pthread_mutex_t \*m); | Attempts to lock a mutex.|
| \#include <pthread.h> | int pthread_mutex_trylock(pthread_mutex_t \*m); | Attempts to lock a mutex.|
| \#include <pthread.h> | int pthread_mutex_destroy(pthread_mutex_t \*m); | Destroys a mutex.|
| \#include <pthread.h> | int pthread_mutex_destroy(pthread_mutex_t \*m); | Destroys a mutex.|
| \#include <pthread.h> | int pthread_attr_init(pthread_attr_t \*attr); | Initializes a thread attribute object.|
| \#include <pthread.h> | int pthread_attr_init(pthread_attr_t \*attr); | Initializes a thread attribute object.|
| \#include <pthread.h> | int pthread_attr_destroy(pthread_attr_t \*attr); | Destroys a thread attribute object.|
| \#include <pthread.h> | int pthread_attr_destroy(pthread_attr_t \*attr); | Destroys a thread attribute object.|
| \#include <pthread.h> | int pthread_attr_getstacksize(const pthread_attr_t \*attr, size_t \*stacksize); | Obtains the stack size of a thread attribute object.|
| \#include <pthread.h> | int pthread_attr_getstacksize(const pthread_attr*t \*attr, size*t \*stacksize); | Obtains the stack size of a thread attribute object.|
| \#include <pthread.h> | int pthread_attr_setstacksize(pthread_attr_t \*attr, size_t stacksize); | Sets the stack size for a thread attribute object.|
| \#include <pthread.h> | int pthread_attr_setstacksize(pthread_attr_t \*attr, size_t stacksize); | Sets the stack size for a thread attribute object.|
| \#include <pthread.h> | int pthread_attr_getschedparam(const pthread_attr_t \*attr, struct sched_param \*param); | Obtains scheduling parameter attributes of a thread attribute object.|
| \#include <pthread.h> | int pthread_attr_getschedparam(const pthread_attr_t \*attr, struct sched_param \*param); | Obtains scheduling parameter attributes of a thread attribute object.|
| \#include <pthread.h> | int pthread_attr_setschedparam(pthread_attr_t \*attr, const struct sched_param \*param); | Sets scheduling parameter attributes for a thread attribute object.|
| \#include <pthread.h> | int pthread_attr_setschedparam(pthread_attr_t \*attr, const struct sched_param \*param); | Sets scheduling parameter attributes for a thread attribute object.|
...
@@ -226,9 +226,9 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
...
@@ -226,9 +226,9 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include <pthread.h> | int pthread_setname_np(pthread_t pthread, constchar \*name); | Sets the thread name.|
| \#include <pthread.h> | int pthread_setname_np(pthread_t pthread, constchar \*name); | Sets the thread name.|
| \#include <pthread.h> | int pthread_cond_broadcast(pthread_cond_t \*c); | Unblocks all threads that are currently blocked on the condition variable **cond**.|
| \#include <pthread.h> | int pthread_cond_broadcast(pthread_cond_t \*c); | Unblocks all threads that are currently blocked on the condition variable **cond**.|
| \#include <pthread.h> | int pthread_cond_signal(pthread_cond_t \*c); | Unblocks a thread.|
| \#include <pthread.h> | int pthread_cond_signal(pthread_cond_t \*c); | Unblocks a thread.|
| \#include <pthread.h> | int pthread_cond_wait(pthread_cond_t \*__restrictc, pthread_mutex_t \*__restrict m); | Waits for the condition.|
| \#include <pthread.h> | int pthread_cond_wait(pthread_cond_t *\__restrictc, pthread_mutex_t \*__restrict m); | Waits for the condition.|
**Table 2** APIs for file system management
**Table 12** APIs for file system management
| Header File| API| Description|
| Header File| API| Description|
| -------- | -------- | -------- |
| -------- | -------- | -------- |
...
@@ -250,7 +250,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
...
@@ -250,7 +250,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include <sys/stat.h> | int fstat(int fd, struct stat \*buf); | Obtains file status.|
| \#include <sys/stat.h> | int fstat(int fd, struct stat \*buf); | Obtains file status.|
| \#include <sys/statfs.h> | int statfs(const char \*path, struct statfs \*buf); | Obtains the file system information for a file in a specified path.|
| \#include <sys/statfs.h> | int statfs(const char \*path, struct statfs \*buf); | Obtains the file system information for a file in a specified path.|
**Table 3** APIs for time management
**Table 13** APIs for time management
| Header File| API| Description|
| Header File| API| Description|
| -------- | -------- | -------- |
| -------- | -------- | -------- |
...
@@ -265,19 +265,19 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
...
@@ -265,19 +265,19 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include <unistd.h> | int usleep(useconds_t usec); | Goes to hibernation, in microseconds.|
| \#include <unistd.h> | int usleep(useconds_t usec); | Goes to hibernation, in microseconds.|
| \#include <time.h> | int nanosleep(const struct timespec \*tspec1, structtimespec \*tspec2); | Suspends the current thread till the specified time.|
| \#include <time.h> | int nanosleep(const struct timespec \*tspec1, structtimespec \*tspec2); | Suspends the current thread till the specified time.|
| \#include <time.h> | int clock_gettime(clockid_t id, struct timespec \*tspec); | Obtains the clock time.|
| \#include <time.h> | int clock_gettime(clockid_t id, struct timespec \*tspec); | Obtains the clock time.|
| \#include <time.h> | int timer_create(clockid_t id, struct sigevent \*__restrict evp, timer_t \*__restrict t); | Creates a timer for a thread.|
| \#include <time.h> | int timer_create(clockid_t id, struct sigevent *\__restrict evp, timer_t \*__restrict t); | Creates a timer for a thread.|
| \#include <time.h> | int timer_delete(timer_t t); | Deletes the timer for a thread.|
| \#include <time.h> | int timer_delete(timer_t t); | Deletes the timer for a thread.|
| \#include <time.h> | int timer_settime(timer_t t, int flags, const structitimerspec \*__restrict val, struct itimerspec \*__restrict old); | Sets a timer for a thread.|
| \#include <time.h> | int timer_settime(timer_t t, int flags, const struct itimerspec *\__restrict val, struct itimerspec \*_restrict old); | Sets a timer for a thread.|
| \#include <time.h> | time_t time (time_t \*t); | Obtains the time.|
| \#include <time.h> | time_t time (time_t \*t); | Obtains the time.|
| \#include <time.h> | char \*strptime(const char \*s, const char \*format, struct tm \*tm); | Converts the time string into the time **tm** structure.|
| \#include <time.h> | char \*strptime(const char \*s, const char \*format, struct tm \*tm); | Converts the time string into the time **tm** structure.|
**Table 4** APIs for util
**Table 14** APIs for util
| Header File| API| Description|
| Header File| API| Description|
| -------- | -------- | -------- |
| -------- | -------- | -------- |
| \#include <stdlib.h> | int atoi(const char \*nptr); | Converts the string pointed to by **nptr** into an integer (**int** type).|
| \#include <stdlib.h> | int atoi(const char \*nptr); | Converts a string into an integer (**int** type).|
| \#include <stdlib.h> | long atol(const char \*nptr); | Converts the string pointed to by **nptr** into a long Integer (long type).|
| \#include <stdlib.h> | long atol(const char \*nptr); | Converts the string into a long Integer (**long** type).|
| \#include <stdlib.h> | long long atoll(const char \*nptr); | Converts the string pointed to by **nptr** into a long long Integer (long long type).|
| \#include <stdlib.h> | long long atoll(const char \*nptr); | Converts a string into a long longer integer (**long long** type).|
| \#include <ctype.h> | int isalnum(int c); | Checks whether the passed character is alphanumeric.|
| \#include <ctype.h> | int isalnum(int c); | Checks whether the passed character is alphanumeric.|
| \#include <ctype.h> | int isascii(int c); | Checks whether the passed character is an ASCII character.|
| \#include <ctype.h> | int isascii(int c); | Checks whether the passed character is an ASCII character.|
| \#include <ctype.h> | int isdigit(int c); | Checks whether the passed character is a digit.|
| \#include <ctype.h> | int isdigit(int c); | Checks whether the passed character is a digit.|
...
@@ -302,17 +302,17 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
...
@@ -302,17 +302,17 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include <strings.h> | int strncasecmp(const char \*s1, const char \*s2, size_t n); | Compares the bytes of the specified length in two strings, ignoring case.|
| \#include <strings.h> | int strncasecmp(const char \*s1, const char \*s2, size_t n); | Compares the bytes of the specified length in two strings, ignoring case.|
| \#include <strings.h> | int strcasecmp(const char \*s1, const char \*s2); | Compares two strings, ignoring case.|
| \#include <strings.h> | int strcasecmp(const char \*s1, const char \*s2); | Compares two strings, ignoring case.|
| \#include <string.h> | int strncmp(const char \*s1, const char \*s2, size_t n); | Compares the bytes of the specified length in two strings.|
| \#include <string.h> | int strncmp(const char \*s1, const char \*s2, size_t n); | Compares the bytes of the specified length in two strings.|
| \#include <string.h> | char \*strrchr(const char \*s, int c); | Searches for the last occurrence of a character in a string.|
| \#include <string.h> | char \*strrchr(const char \*s, int c); | Searches for a character in a string.|
| \#include <string.h> | char \*strstr(const char \*haystack, const char \*needle); | Searches for the specified substring in a string.|
| \#include <string.h> | char \*strstr(const char \*haystack, const char \*needle); | Searches for the specified substring in a string.|
| \#include <stdlib.h> | long int strtol(const char \*nptr, char \*\*endptr, int base); | Converts the string pointed to by **nptr** into a **long int** value according to the given **base**.|
| \#include <stdlib.h> | long int strtol(const char \*nptr, char \*\*endptr, int base); | Converts the string pointed to by **nptr** into a **long int** value according to the given **base**.|
| \#include <stdlib.h> | unsigned long int strtoul(const char \*nptr, char\*\*endptr, int base); | Converts the string pointed to by **nptr** into an unsigned long integer.|
| \#include <stdlib.h> | unsigned long int strtoul(const char \*nptr, char\*\*endptr, int base); | Converts a string into an unsigned long integer.|
| \#include <stdlib.h> | unsigned long long int strtoull(const char \*nptr,char \*\*endptr, int base); | Converts the string pointed to by **nptr** into an unsigned long long integer.|
| \#include <stdlib.h> | unsigned long long int strtoull(const char \*nptr,char \*\*endptr,int base); | Converts a string into an unsigned long long integer.|
| \#include <regex.h> | int regcomp(regex_t \*preg, const char \*regex,int cflags); | Compiles a regular expression.|
| \#include <regex.h> | int regcomp(regex_t \*preg, const char \*regex,int cflags); | Compiles a regular expression.|
| \#include <regex.h> | int regexec(const regex_t \*preg, const char \*string, size_t nmatch, regmatch_t pmatch[], int eflags); | Executes the compiled regular expression.|
| \#include <regex.h> | int regexec(const regex_t \*preg, const char \*string, size_t nmatch, regmatch_t pmatch[], int eflags); | Executes the compiled regular expression.|
| \#include <stdio.h> | int fseek(FILE \*stream, long offset, int whence); | Sets the position of the stream pointer.|
| \#include <stdio.h> | int fseek(FILE \*stream, long offset, int whence); | Sets the position of the stream pointer.|
| \#include <stdio.h> | long ftell(FILE \*stream); | Obtains the position of the stream pointer.|
| \#include <stdio.h> | long ftell(FILE \*stream); | Obtains the position of the stream pointer.|
| \#include <stdio.h> | size_t fwrite(const void \*ptr, size_t size, size_tnmemb,FILE \*stream); | Writes data to a stream.|
| \#include <stdio.h> | size_t fwrite(const void \*ptr, size_t size, size_tnmemb,FILE \*stream); | Writes data to a stream.|
| \#include <stdio.h> | void perror(const char \*s); | Prints system error information.|
| \#include <stdio.h> | void perror(const char \*s); | Prints system error information.|
| \#include <stdio.h> | void rewind(FILE \*stream); | Sets the position to the beginning of the file of the specified stream.|
| \#include <stdio.h> | void rewind(FILE \*stream); | Sets the position to the beginning of the file of the specified stream.|
| \#include <unistd.h> | ssize_t write(int fd, const void \*buf, size_t size); | Writes data a file.|
| \#include <unistd.h> | ssize_t write(int fd, const void \*buf, size_t size); | Writes data a file.|
| \#include <unistd.h> | ssize_t read(int fd, void \*buf, size_t size); | Reads data from a file.|
| \#include <unistd.h> | ssize_t read(int fd, void \*buf, size_t size); | Reads data from a file.|
**Table 7** APIs for network
**Table 17** APIs for network
| Header File| API| Description|
| Header File| API| Description|
| -------- | -------- | -------- |
| -------- | -------- | -------- |
...
@@ -363,7 +363,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
...
@@ -363,7 +363,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include <sys/socket.h> | ssize_t sendto(int sockfd, const void \*buf, size_t len, intflags,const struct sockaddr \*dest_addr, socklen_t addrlen); | Sends a message on a socket.|
| \#include <sys/socket.h> | ssize_t sendto(int sockfd, const void \*buf, size_t len, intflags,const struct sockaddr \*dest_addr, socklen_t addrlen); | Sends a message on a socket.|
| \#include <sys/socket.h> | int setsockopt(int sockfd, int level, int optname,constvoid \*optval, socklen_t optlen); | Sets options associated with a socket.|
| \#include <sys/socket.h> | int setsockopt(int sockfd, int level, int optname,constvoid \*optval, socklen_t optlen); | Sets options associated with a socket.|
**Table 8** APIs for memory management
**Table 18** APIs for memory management
| Header File| API| Description|
| Header File| API| Description|
| -------- | -------- | -------- |
| -------- | -------- | -------- |
...
@@ -374,7 +374,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
...
@@ -374,7 +374,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include <stdlib.h> | void free(void \*ptr); | Release the memory space pointed to by **ptr**.|
| \#include <stdlib.h> | void free(void \*ptr); | Release the memory space pointed to by **ptr**.|
**Table 9** APIs for IPC
**Table 19** APIs for IPC
| Header File| API| Description|
| Header File| API| Description|
| -------- | -------- | -------- |
| -------- | -------- | -------- |
...
@@ -386,11 +386,11 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
...
@@ -386,11 +386,11 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include <mqueue.h> | mqd_t mq_open(const char \*mqName, int openFlag, ...); | Opens an existing message queue with the specified name or creates a message queue.|
| \#include <mqueue.h> | mqd_t mq_open(const char \*mqName, int openFlag, ...); | Opens an existing message queue with the specified name or creates a message queue.|
| \#include <mqueue.h> | int mq_close(mqd_t personal); | Closes a message queue with the specified descriptor.|
| \#include <mqueue.h> | int mq_close(mqd_t personal); | Closes a message queue with the specified descriptor.|
| \#include <mqueue.h> | int mq_unlink(const char \*mqName); | Deletes the message queue of the specified name.|
| \#include <mqueue.h> | int mq_unlink(const char \*mqName); | Deletes the message queue of the specified name.|
| \#include <mqueue.h> | int mq_send(mqd_t personal, const char \*msg,size_t msgLen, unsigned int msgPrio); | Puts a message with the specified content and length into a message queue.|
| \#include <mqueue.h> | int mq_send(mqd_t personal, const char \*msg,size_t msgLen, unsigned int msgPrio); | Puts a message with the specified content and length into a message queue.|
| \#include <mqueue.h> | ssize_t mq_receive(mqd_t personal, char \*msg,size_t msgLen, unsigned int \*msgPrio); | Deletes the oldest message from a message queue and puts it in the buffer pointed to by **msg_ptr**.|
| \#include <mqueue.h> | ssize_t mq_receive(mqd_t personal, char \*msg,size_t msgLen, unsigned int \*msgPrio); | Deletes the oldest message from a message queue and puts it in the buffer pointed to by **msg_ptr**.|
| \#include <mqueue.h> | int mq_timedsend(mqd_t personal, const char\*msg, size_t msgLen, unsigned int msgPrio, const struct timespec \*absTimeout) | Puts a message with the specified content and length into a message queue at the specified time.|
| \#include <mqueue.h> | int mq_timedsend(mqd_t personal, const char\*msg, size_t msgLen, unsigned int msgPrio, const struct timespec \*absTimeout) | Puts a message with the specified content and length into a message queue at the specified time.|
| \#include <mqueue.h> | ssize_t mq_timedreceive(mqd_t personal, char\*msg, size_t msgLen, unsigned int \*msgPrio, const struct timespec \*absTimeout); | Obtains a message with the specified content and length from a message queue.|
| \#include <mqueue.h> | ssize_t mq_timedreceive(mqd_t personal, char\*msg, size_t msgLen, unsigned int \*msgPrio, const struct timespec \*absTimeout); | Obtains a message with the specified content and length from a message queue.|
| \#include <mqueue.h> | int mq_setattr(mqd_t mqdes, const struct mq_attr \*__restrict newattr, struct mq_attr \*__restrict oldattr); | Sets the message queue attributes specified by the descriptor.|
| \#include <mqueue.h> | int mq_setattr(mqd_t mqdes, const struct mq_attr \*\_\_restrict newattr, struct mq_attr *\__restrict oldattr); | Sets the message queue attributes specified by the descriptor.|
| \#include <libc.h> | const char \*libc_get_version_string(void); | Obtains the libc version string.|
| \#include <libc.h> | const char \*libc_get_version_string(void); | Obtains the libc version string.|
| \#include <libc.h> | int libc_get_version(void); | Obtains the libc version.|
| \#include <libc.h> | int libc_get_version(void); | Obtains the libc version.|
...
@@ -459,6 +459,8 @@ Example:
...
@@ -459,6 +459,8 @@ Example:
Creates a thread, transfers the information in the parent thread to the child thread, and prints the transferred information and the thread ID in the child thread.
Creates a thread, transfers the information in the parent thread to the child thread, and prints the transferred information and the thread ID in the child thread.
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **DemoForTest** function is called in **TestTaskEntry**.
An event is a mechanism for communication between tasks. It can be used to synchronize tasks. The events have the following features:
An event is a communication mechanism used to synchronize tasks. Events have the following features:
- Events can be synchronized in one-to-many or many-to-many mode. In one-to-many mode, a task can wait for multiple events. In many-to-many mode, multiple tasks can wait for multiple events. However, a write event wakes up only one task from the block.
- Events can be synchronized in one-to-many or many-to-many mode. In one-to-many mode, a task can wait for multiple events. In many-to-many mode, multiple tasks can wait for multiple events. However, a write event wakes up only one task from the block.
- Event read timeout mechanism is used.
- Event read timeout mechanism is used.
- Events are used only for task synchronization, but not for data transmission.
- Events are used for task synchronization, but not for data transmission.
APIs are provided to initialize, read/write, clear, and destroy events.
APIs are provided to initialize, read/write, clear, and destroy events.
...
@@ -18,7 +18,7 @@ APIs are provided to initialize, read/write, clear, and destroy events.
...
@@ -18,7 +18,7 @@ APIs are provided to initialize, read/write, clear, and destroy events.
### Event Control Block
### Event Control Block
The event control block is a struct configured in the event initialization function. It is passed in as an input parameter to identify the event for operations such as event read and write. The data structure of the event control block is as follows:
The event control block is a structure in the event initialization function. It passes in event identifies for operations such as event read and write. The data structure of the event control block is as follows:
```
```
...
@@ -31,23 +31,33 @@ typedef struct tagEvent {
...
@@ -31,23 +31,33 @@ typedef struct tagEvent {
### Working Principles
### Working Principles
**Initializing an event**: An event control block is created to maintain a collection of processed events and a linked list of tasks waiting for specific events.
**Initializing an Event**
**Writing an event**: When a specified event is written to the event control block, the event control block updates the event set, traverses the task linked list, and determines whether to wake up related task based on the task conditions.
An event control block is created to maintain a set of processed events and a linked list of tasks waiting for specific events.
**Reading an event**: If the read event already exists, it is returned synchronously. In other cases, the return time is determined based on the timeout period and event triggering status. If the wait event condition is met before the timeout period expires, the blocked task will be directly woken up. Otherwise, the blocked task will be woken up only after the timeout period has expired.
**Writing an Event**
The input parameters **eventMask** and **mode** determine whether the condition for reading an event is met. **eventMask** indicates the mask of the event. **mode** indicates the handling mode, which can be any of the following:
When an event is written to the event control block, the event control block updates the event set, traverses the task linked list, and determines whether to wake up related tasks based on the task conditions.
-**LOS_WAITMODE_AND**: Event reading is successful only when all the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned.
**Reading an Event**
-**LOS_WAITMODE_OR**: Event reading is successful when any of the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned.
If the event to read already exists, it is returned synchronously. In other cases, the event is returned based on the timeout period and event triggering conditions. If the wait condition is met before the timeout period expires, the blocked task will be directly woken up. Otherwise, the blocked task will be woken up only after the timeout period has expired.
The parameters **eventMask** and **mode** determine whether the condition for reading an event is met. **eventMask** specifies the event mask. **mode** specifies the handling mode, which can be any of the following:
-**LOS_WAITMODE_AND**: Read the event only when all the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned.
-**LOS_WAITMODE_OR**: Read the event only when any of the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned.
-**LOS_WAITMODE_CLR**: This mode must be used with one or all of the event modes (LOS_WAITMODE_AND | LOS_WAITMODE_CLR or LOS_WAITMODE_OR | LOS_WAITMODE_CLR). In this mode, if all event modes or any event mode is successful, the corresponding event type bit in the event control block will be automatically cleared.
-**LOS_WAITMODE_CLR**: This mode must be used with one or all of the event modes (LOS_WAITMODE_AND | LOS_WAITMODE_CLR or LOS_WAITMODE_OR | LOS_WAITMODE_CLR). In this mode, if all event modes or any event mode is successful, the corresponding event type bit in the event control block will be automatically cleared.
**Clearing events**: Clear the event set of the event control block based on the specified mask. If the mask is **0**, the event set will be cleared. If the mask is **0xffff**, no event will be cleared, and the event set remains unchanged.
**Clearing Events**
The events in the event set of the event control block can be cleared based on the specified mask. The mask **0** means to clear the event set; the mask **0xffff** means the opposite.
**Destroying Events**
**Destroying an event**: Destroy the specified event control block.
The event control block can be destroyed to release resources.
**Figure 1** Event working mechanism for a mini system
**Figure 1** Event working mechanism for a mini system
...
@@ -58,12 +68,12 @@ The input parameters **eventMask** and **mode** determine whether the condition
...
@@ -58,12 +68,12 @@ The input parameters **eventMask** and **mode** determine whether the condition
| Category| API| Description|
| Category| API| Description|
| -------- | -------- | -------- |
| -------- | -------- | -------- |
| Event check| LOS_EventPoll | Checks whether the expected event occurs based on **eventID**, **eventMask**, and **mode**.<br>**NOTICE**<br><br>If **mode** contains **LOS_WAITMODE_CLR** and the expected event occurs, the event that meets the requirements in **eventID** will be cleared. In this case, **eventID** is an input parameter and an output parameter. In other cases, **eventID** is used only as an input parameter.|
| Checking an event | LOS_EventPoll | Checks whether the expected event occurs based on **eventID**, **eventMask**, and **mode**.<br>**NOTE**<br>If **mode** contains **LOS_WAITMODE_CLR** and the expected event occurs, the event that meets the requirements in **eventID** will be cleared. In this case, **eventID** is an input parameter and an output parameter. In other cases, **eventID** is used only as an input parameter. |
| Initialization| LOS_EventInit | Initializes an event control block.|
| Initializing an event control block | LOS_EventInit | Initializes an event control block.|
| Event read| LOS_EventRead | Reads an event (wait event). The task will be blocked to wait based on the timeout period (in ticks).<br>If no event is read, **0** is returned.<br>If an event is successfully read, a positive value (event set) is returned.<br>In other cases, an error code is returned.|
| Reading an event | LOS_EventRead | Reads an event (wait event). The task will be blocked to wait based on the timeout period (in ticks).<br>If no event is read, **0** is returned.<br>If an event is successfully read, a positive value (event set) is returned.<br>In other cases, an error code is returned.|
| Event write| LOS_EventWrite | Writes an event to the event control block.|
| Writing an event | LOS_EventWrite | Writes an event to the event control block.|
| Event clearance| LOS_EventClear | Clears an event in the event control block based on the event mask.|
| Clearing events | LOS_EventClear | Clears events in the event control block based on the event mask. |
| Event destruction| LOS_EventDestroy | Destroys an event control block.|
| Destroying events | LOS_EventDestroy | Destroys an event control block.|
## How to Develop
## How to Develop
...
@@ -72,11 +82,11 @@ The typical event development process is as follows:
...
@@ -72,11 +82,11 @@ The typical event development process is as follows:
1. Initialize an event control block.
1. Initialize an event control block.
2. Block a read event control block.
2. Block a read event.
3. Write related events.
3. Write events.
4. Wake up a blocked task, read the event, and check whether the event meets conditions.
4. Wake up the blocked task, read the event, and check whether the event meets conditions.
5. Handle the event control block.
5. Handle the event control block.
...
@@ -84,7 +94,7 @@ The typical event development process is as follows:
...
@@ -84,7 +94,7 @@ The typical event development process is as follows:
> **NOTE**
> **NOTE**
> - When an event is read or written, the 25th bit of the event is reserved and cannot be set.
> - For event read and write operations, the 25th bit (`0x02U << 24`) of the event is reserved and cannot be set.
>
>
> - Repeated writes of the same event are treated as one write.
> - Repeated writes of the same event are treated as one write.
...
@@ -111,7 +121,7 @@ In the **ExampleEvent** task, create an **EventReadTask** task with a timout per
...
@@ -111,7 +121,7 @@ In the **ExampleEvent** task, create an **EventReadTask** task with a timout per
The sample code is as follows:
The sample code is as follows:
The sample code is compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. Call **ExampleEvent()** in **TestTaskEntry**.
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleEvent()** function is called in **TestTaskEntry**.
@@ -77,7 +77,7 @@ The preceding figure illustrates how to write data to the tail node only. Writin
...
@@ -77,7 +77,7 @@ The preceding figure illustrates how to write data to the tail node only. Writin
## Available APIs
## Available APIs
| Category| Description|
| Category| API Description |
| -------- | -------- |
| -------- | -------- |
| Creating or deleting a message queue| **LOS_QueueCreate**: creates a message queue. The system dynamically allocates the queue space.<br>**LOS_QueueCreateStatic**: creates a static message queue. You need to pass in the queue space.<br>**LOS_QueueDelete**: deletes a message queue. After a static message queue is deleted, you need to release the queue space.|
| Creating or deleting a message queue| **LOS_QueueCreate**: creates a message queue. The system dynamically allocates the queue space.<br>**LOS_QueueCreateStatic**: creates a static message queue. You need to pass in the queue space.<br>**LOS_QueueDelete**: deletes a message queue. After a static message queue is deleted, you need to release the queue space.|
| Reading or writing data (address without the content) in a queue| **LOS_QueueRead**: reads data in the head node of the specified queue. The data in the queue node is an address.<br>**LOS_QueueWrite**: writes the **bufferAddr** (buffer address) to the tail node of the specified queue.<br>**LOS_QueueWriteHead**: writes the **bufferAddr** (buffer address) to the head node of the specified queue.|
| Reading or writing data (address without the content) in a queue| **LOS_QueueRead**: reads data in the head node of the specified queue. The data in the queue node is an address.<br>**LOS_QueueWrite**: writes the **bufferAddr** (buffer address) to the tail node of the specified queue.<br>**LOS_QueueWriteHead**: writes the **bufferAddr** (buffer address) to the head node of the specified queue.|
...
@@ -136,7 +136,7 @@ Create a queue and two tasks. Enable task 1 to write data to the queue, and task
...
@@ -136,7 +136,7 @@ Create a queue and two tasks. Enable task 1 to write data to the queue, and task
The sample code is as follows:
The sample code is as follows:
The sample code is compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. Call **ExampleQueue** in **TestTaskEntry**.
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleQueue** function is called in **TestTaskEntry**.
The shell provided by the OpenHarmony kernel supports basic debugging functions and provides commands related to the system, files, and network. It also supports commands customized based on service requirements.
The shell function is used for debugging only. Currently, it does not support the functions such as tab completion and undo with a key.
Some commands can be used only after the corresponding options are enabled by using **make menuconfig**.
## Common Shell Commands
### cat
Displays the content of a text file. This command can be used only after **LOSCFG_FS_VFS** is enabled.
#### Format
cat [FILE]
#### Parameters
| Parameter| Description | Value Range |
| ---- | ---------- | -------------- |
| FILE | File path.| An existing file.|
### cd
Changes the current directory. This command can be used only after **LOSCFG_FS_VFS** is enabled.
#### Format
cd [path]
#### Parameters
| Parameter| Description | Value Range |
| ---- | ---------- | -------------- |
| path | File path.| Path of the new directory.|
### cp
Copies a file. This command can be used only after **LOSCFG_FS_VFS** is enabled.
| SOURCEFILE | Path of the file to copy. | Currently, only files are supported. Directories are not supported. The file cannot be empty.|
| DESTFILE | Path of the file created.| Directory and file names are supported. The directory must exist. |
### date
Queries the system date and time.
#### Format
date
#### Parameters
None.
### free
Displays the memory usage of the system.
#### Format
free [ -k | -m ]
#### Parameters
| Parameter| Description | Value Range|
| ---- | ----------------- | -------- |
| -k | Display the memory usage in KiB.| N/A |
| -m | Display the memory usage in MiB.| N/A |
### help
Displays all commands in this operating system.
#### Format
help
#### Parameters
None.
### ifconfig
Displays the IP address, network mask, gateway, and MAC address of a network adapter. This command can be used only after **LWIP_SHELLCMD_ENABLE** is enabled.
#### Format
ifconfig
#### Parameters
None.
### ls
Displays the content of a directory. This command can be used only after **LOSCFG_FS_VFS** is enabled.
| DIRECTORY | Path of the directory.| If **DIRECTORY** is not specified, the content of the current directory is displayed.<br>If **DIRECTORY** is a valid directory, the content of the specified directory is displayed.<br>Currently, LiteOS-M does not support the root directory /.|
### memusage
Displays the memory waterline.
#### Format
memusage [-k/-m]
#### Parameters
| Parameter| Description | Value Range|
| ---- | ----------------- | -------- |
| -k | Display the memory usage in KiB.| N/A |
| -m | Display the memory usage in MiB.| N/A |
### mkdir
Creates a directory. This command can be used only after **LOSCFG_FS_VFS** is enabled.
| FILE | File name.| The value of **FILE** can be an absolute path or a relative path.|
### stack
Displays the stack information of a task. This command can be used only after **LOSCFG_DEBUG_TOOLS** is enabled. Enabling this function affects the performance.
#### Format
stack [ID]
#### Parameters
| Parameter| Description| Value Range |
| ---- | -------- | ------------------------ |
| ID | Task ID.| The task corresponding to the task ID must exist.|
### hwi
Queries the interrupt usage. This command can be used only after **LOSCFG_DEBUG_TOOLS** is enabled. Enabling this function affects the performance.
#### Format
hwi
### st
Queries scheduling information. This command can be used only afterf **LOSCFG_DEBUG_TOOLS** is enabled. Enabling this function affects the performance.
#### Format
st -s | st -e
#### Parameters
| Parameter| Description | Value Range|
| ---- | ---------------------- | -------- |
| -s | Start to record scheduling information. | N/A |
The central processing unit percent \(CPUP\) includes the system CPUP and task CPUP.
The central processing unit percent (CPUP) includes the system CPUP and task CPUP.
The system CPUP is the CPU usage of the system within a period of time. It reflects the CPU load and the system running status \(idle or busy\) in the given period of time. The valid range of the system CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the system runs with full load.
**System CPUP**
Task CPUP refers to the CPU usage of a single task. It reflects the task status, busy or idle, in a period of time. The valid range of task CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the task is being executed for the given period of time.
The system CPUP is the CPU usage of the system within a period of time. It reflects the CPU load and the system running status (idle or busy) in the given period of time. The CPUP ranges from 0 to 100, in percentage. The value **100** indicates that the system runs with full load.
With the system CPUP, you can determine whether the current system load exceeds the designed specifications.
With the system CPUP, you can determine whether the current system load exceeds the designed specifications.
**Task CPUP**
Task CPUP refers to the CPU usage of a single task. It reflects the task status, busy or idle, in a period of time. The task CPUP ranges from 0 to 100, in percentage. The value **100** indicates that the task is being executed for the given period of time.
With the CPUP of each task, you can determine whether the CPU usage of each task meets expectations of the design.
With the CPUP of each task, you can determine whether the CPU usage of each task meets expectations of the design.
**Interrupt CPUP**
In addition, you can enable the interrupt usage statistics function after the CPUP function is enabled.
Interrupt CPUP indicates the CPU usage of a single interrupt out of the total interrupt duration. The interrupt CPUP ranges from 0 to 100. The value **100** indicates that only the interrupt is triggered within a period of time.
## Working Principles
## Working Principles
The OpenHarmony LiteOS-M CPUP records the system CPU usage on a task basis. When task switching occurs, the task start time and task switch-out or exit time are recorded. Each time when a task exits, the system accumulates the CPU time used by the task.
The OpenHarmony LiteOS-M CPUP records the system CPU usage on a task basis. When task switching occurs, the task start time and task switch-out or exit time are recorded. Each time when a task exits, the system accumulates the CPU time used by the task.
You can configure this function in **target\_config.h**.
You can configure this function in **target_config.h**.
The OpenHarmony LiteOS-M provides the following types of CPUP information:
The OpenHarmony LiteOS-M provides the following types of CPUP information:
- System CPUP
- System CPUP
- Task CPUP
- Task CPUP
In addition, the system provides the capability of querying the interrupt CPUP (the CPUP and timer must be enabled).
The CPUP is calculated as follows:
The CPUP is calculated as follows:
System CPUP = Total running time of all tasks except idle tasks/Total running time of the system
System CPUP = Total running time of all tasks except idle tasks/Total running time of the system
Task CPUP = Total running time of the task/Total running time of the system
Task CPUP = Total running time of the task/Total running time of the system
## Available APIs<a name="section158501652121514"></a>
Interrupt CPUP = Running time of a single interrupt/Total running time of all interrupts
| Obtaining the system CPUP| **LOS_SysCpuUsage**: obtains the current system CPUP.<br>**LOS_HistorySysCpuUsage**: obtains the historical CPUP of the system.|
</th>
| Obtaining the task CPUP| **LOS_TaskCpuUsage**: obtains the CPUP of a task.<br>**LOS_HistoryTaskCpuUsage**: obtains the historical CPUP of a task.<br>**LOS_AllTaskCpuUsage**: obtains the CPUP of all tasks.|
</tr>
| Outputting the task CPUP| **LOS_CpupUsageMonitor**: outputs the historical CPUP of a task.|
</thead>
| Obtaining the interrupt CPUP| **LOS_GetAllIrqCpuUsage**: obtains the CPUP of all interrupts.|
<tbody><trid="row1143613475615"><tdclass="cellrowborder"rowspan="2"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p942993405610"><aname="p942993405610"></a><aname="p942993405610"></a>Obtaining the system CPU usage</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p7429163416565"><aname="p7429163416565"></a><aname="p7429163416565"></a>Obtains the current system CPUP.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p542953465617"><aname="p542953465617"></a><aname="p542953465617"></a>Obtains the historical CPUP of the system.</p>
</td>
</tr>
<trid="row143610342562"><tdclass="cellrowborder"rowspan="3"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p174295347568"><aname="p174295347568"></a><aname="p174295347568"></a>Obtaining the task CPUP</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p1042963410568"><aname="p1042963410568"></a><aname="p1042963410568"></a>Obtains the CPUP of a specified task.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p74302034175614"><aname="p74302034175614"></a><aname="p74302034175614"></a>Obtains the historical CPUP of a specified task.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p4430134185614"><aname="p4430134185614"></a><aname="p4430134185614"></a>Obtains the CPUP of all tasks.</p>
</td>
</tr>
<trid="row15435934155618"><tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p1543033435615"><aname="p1543033435615"></a><aname="p1543033435615"></a>Outputting the task CPUP</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p84301234115617"><aname="p84301234115617"></a><aname="p84301234115617"></a>Outputs the historical CPUP of a task.</p>
</td>
</tr>
</tbody>
</table>
## How to Develop
## How to Develop
In the **kernel/liteos_m** directory, run the **make menuconfig** command and choose **Kernel > Enable Cpup** to enable CPUP.
Choose **Enable Cpup include irq** to enable interrupt CPUP.
The typical CPUP development process is as follows:
The typical CPUP development process is as follows:
1. Call **LOS\_SysCpuUsage** to obtain the system CPUP.
1. Call **LOS_SysCpuUsage** to obtain the system CPUP.
2. Call **LOS\_HistorySysCpuUsage** to obtain the historical CPUP of the system.
3. Call **LOS\_TaskCpuUsage** to obtain the CPUP of a specified task.
2. Call **LOS_HistorySysCpuUsage** to obtain the historical CPUP of the system.
3. Call **LOS_TaskCpuUsage** to obtain the CPUP of a task.
- If the task has been created, disable interrupt, obtain the CPUP, and then enable interrupt.
- If the task has been created, disable interrupt, obtain the CPUP, and then enable interrupt.
- If the task is not created, return an error code.
- If the task is not created, return an error code.
4. Call **LOS\_HistoryTaskCpuUsage** to obtain the historical CPUP of a specified task.
4.Call **LOS_HistoryTaskCpuUsage** to obtain the historical CPUP of a task.
- If the task has been created, disable interrupt, obtain the CPUP in different modes, and then enable interrupt.
- If the task has been created, disable interrupt, obtain the CPUP in different modes, and then enable interrupt.
- If the task is not created, return an error code.
- If the task is not created, return an error code.
5. Call **LOS\_AllCpuUsage** to obtain the CPUP of all tasks.
5.Call **LOS_AllCpuUsage** to obtain the CPUP of all tasks.
- If the CPUP is initialized, disable interrupt, obtain the CPUP in different modes, and then enable interrupt.
- If CPUP has been initialized, disable interrupt, obtain the CPUP in different modes, and then enable interrupt.
- If CPUP is not initialized or has invalid input parameters, return an error code.
- If CPUP is not initialized or has invalid input parameters, return an error code.
## Development Example
## Development Example
### Example Description
### Example Description
This example implements the following:
This example implements the following:
1. Create a task for the CPUP test.
1. Create a task for the CPUP test.
2. Obtain the CPUP of the current system.
2. Obtain the CPUP of the current system.
3. Obtain the historical system CPUP in different modes.
3. Obtain the historical system CPUP in different modes.
4. Obtain the CPUP of the created test task.
5. Obtain the CPUP of the created test task in different modes.
4. Obtain the CPUP of the created task.
5. Obtain the CPUP of the created task in different modes.
### Sample Code
### Sample Code
Prerequisites
**Prerequisites**
In **target\_config.h**, the **LOSCFG\_BASE\_CORE\_CPUP** parameter is enabled.
CPUP is enabled.<br>To enable CPUP, run **make menuconfig** in the **kernel/liteos_m** directory and choose **Kernel->Enable Cpup** to enable CPUP.
The sample code is as follows:
The sample code is as follows:
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleCpup** function is called in **TestTaskEntry**.
The OpenHarmony LiteOS-M kernel supports File Allocation Table file system (FATFS) and LittleFS file systems. Like the OpenHarmony LiteOS-A kernel, the OpenHarmony LiteOS-M kernel provides POSIX over the virtual file system (VFS) to ensure interface consistency. However, the VFS of the LiteOS-M kernel is light due to insufficient resources and does not provide advanced functions (such as pagecache). Therefore, the VFS of the LiteOS-M kernel implements only API standardization and adaptation. The file systems handle specific transactions.
## VFS
The following tables list the APIs supported by the file systems of the LiteOS-M kernel.
### Basic Concepts
**Table 1** File management operations
The Virtual File System (VFS) is not a real file system. It is an abstract layer on top of a heterogeneous file system and provides you with a unified Unix-like interface for file operations. Different types of file systems use different file operation interfaces. If there are multiple types of file systems in a system, different and non-standard interfaces are required for accessing these file systems. The VFS is introduced as an abstract layer to shield the differences between these heterogeneous file systems. With the VFS, you do not need to care about the underlying storage medium and file system type.
| API| Description| FATFS | LITTLEFS |
The OpenHarmony LiteOS-M kernel supports the File Allocation Table (FAT) and LittleFS file systems. It provides the Portable Operating System Interface (POSIX) over the VFS to ensure interface consistency. However, the VFS of the LiteOS-M kernel is light and does not provide advanced functions (such as pagecache) due to insufficient resources. Therefore, the VFS of the LiteOS-M kernel implements only API standardization and adaptation. The file systems handle specific transactions. The following tables describe the APIs supported by the file systems of the LiteOS-M kernel.
### Available APIs
**Table 1** APIs for file operations
| API| Description| FAT | LittleFS |
| -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- |
| open | Opens a file.| Supported| Supported|
| open | Opens a file.| Supported| Supported|
| close | Closes a file.| Supported| Supported|
| close | Closes a file.| Supported| Supported|
| read | Reads the file content.| Supported| Supported|
| stat | Obtains file information based on the file path name.| Supported | Supported |
| unlink | Deletes a file.| Supported| Supported|
| unlink | Deletes a file.| Supported| Supported|
| rename | Renames the file.| Supported| Supported|
| rename | Renames the file.| Supported| Supported|
| fstat | Obtains file information based on the file handle.| Supported| Supported|
| fstat | Obtains file information based on the file handle. | Supported | Supported |
| stat | Obtains file information based on the file path name.| Supported| Supported|
| fsync | Saves a file to a storage device. | Supported | Supported |
| fsync | Saves file updates to a storage device.| Supported| Supported|
**Table 2** Directory management operations
**Table 2** APIs for directory operations
| API| Description| FATFS | LITTLEFS |
| API| Description| FATFS | LITTLEFS |
| -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- |
...
@@ -31,8 +36,7 @@ The following tables list the APIs supported by the file systems of the LiteOS-M
...
@@ -31,8 +36,7 @@ The following tables list the APIs supported by the file systems of the LiteOS-M
| closedir | Closes a directory.| Supported| Supported|
| closedir | Closes a directory.| Supported| Supported|
| rmdir | Deletes a directory.| Supported| Supported|
| rmdir | Deletes a directory.| Supported| Supported|
**Table 3** APIs for partition operations
**Table 3** Partition operations
| API| Description| FATFS | LITTLEFS |
| API| Description| FATFS | LITTLEFS |
| -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- |
...
@@ -41,14 +45,18 @@ The following tables list the APIs supported by the file systems of the LiteOS-M
...
@@ -41,14 +45,18 @@ The following tables list the APIs supported by the file systems of the LiteOS-M
| umount2 | Forcibly unmounts a partition using the **MNT_FORCE** parameter.| Supported| Not supported|
| umount2 | Forcibly unmounts a partition using the **MNT_FORCE** parameter.| Supported| Not supported|
| statfs | Obtains partition information.| Supported| Not supported|
| statfs | Obtains partition information.| Supported| Not supported|
Interfaces, such as **ioctl** and **fcntl**, are supported by different libraries and are irrelevant to the underlying file system.
## FAT
## FAT
### Basic Concepts
### Basic Concepts
File Allocation Table (FAT) is a file system developed for personal computers. It consists of the DOS Boot Record (DBR) region, FAT region, and Data region. Each entry in the FAT region records information about the corresponding cluster in the storage device. The cluster information includes whether the cluster is used, number of the next cluster of the file, whether the file ends with the cluster. The FAT file system supports multiple formats, such as FAT12, FAT16, and FAT32. The numbers 12, 16, and 32 indicate the number of bits per cluster within the FAT, respectively. The FAT file system supports multiple media, especially removable media (such as USB flash drives, SD cards, and removable hard drives). The FAT file system ensures good compatibility between embedded devices and desktop systems (such as Windows and Linux) and facilitates file management.
As a file system designed for personal computers, the FAT file system consists of the DOS Boot Record (DBR) region, FAT region, and Data region. Each entry in the FAT region records information about the corresponding cluster in the storage device. The cluster information includes whether the cluster is used, number of the next cluster of the file, whether the file ends with the cluster.
The OpenHarmony kernel supports FAT12, FAT16, and FAT32 file systems. These file systems require a tiny amount of code to implement, use less resources, support a variety of physical media, and are tailorable and compatible with Windows and Linux systems. They also support identification of multiple devices and partitions. The kernel supports multiple partitions on hard drives and allows creation of the FAT file system on the primary partition and logical partition.
The FAT file system supports a variety of formats, including FAT12, FAT16, and FAT32. The numbers 12, 16, and 32 indicate the number of bits per cluster within the FAT, respectively. The FAT file system also supports diversified storage media, especially removable media (such as USB flash drives, SD cards, and removable hard drives). It features good compatibility between embedded devices and desktop systems (such as Windows and Linux) and facilitates file management.
The OpenHarmony kernel supports FAT12, FAT16, and FAT32 file systems. These file systems require a tiny amount of code to implement, use less resources, support a variety of physical media, and are tailorable and compatible with Windows and Linux systems. They also support identification of multiple devices and partitions. The kernel supports multiple partitions on hard drives and allows creation of the FAT file system on the primary and logical partitions.
### Development Guidelines
### Development Guidelines
...
@@ -56,11 +64,13 @@ The OpenHarmony kernel supports FAT12, FAT16, and FAT32 file systems. These file
...
@@ -56,11 +64,13 @@ The OpenHarmony kernel supports FAT12, FAT16, and FAT32 file systems. These file
#### Driver Adaptation
#### Driver Adaptation
The use of the FAT file system requires support from the underlying MultiMediaCard (MMC) drivers. To run FatFS on a board with an MMC storage device, you must:
The use of a FAT file system requires support from the underlying MultiMediaCard (MMC) driver. Before using a FAT file system on a board with an MMC, you must perform the following operations:
1. Implement the **disk_status**, **disk_initialize**, **disk_read**, **disk_write**, and **disk_ioctl** APIs to adapt to the embedded MMC (eMMC) driver on the board.
1. Implement the **disk_status**, **disk_initialize**, **disk_read**, **disk_write**, and **disk_ioctl** APIs to adapt to the embedded MMC (eMMC) drivers on the board.
2. Add the **fs_config.h** file with information such as **FS_MAX_SS** (maximum sector size of the storage device) and **FF_VOLUME_STRS** (partition names) configured.
2. Add the **fs_config.h** file with information such as **FS_MAX_SS** (maximum sector size of the storage device) and **FF_VOLUME_STRS** (partition names) configured. The following is an example:
The following is an example:
```
```
...
@@ -69,29 +79,115 @@ The use of the FAT file system requires support from the underlying MultiMediaCa
...
@@ -69,29 +79,115 @@ The use of the FAT file system requires support from the underlying MultiMediaCa
#define FAT_MAX_OPEN_FILES 50
#define FAT_MAX_OPEN_FILES 50
```
```
#### Mounting Partitions
Before using a FAT file system on a device, you need to initialize the flash drive and partition the device storage.
API for partitioning the storage:
**int LOS_DiskPartition(const char \*dev, const char \*fsType, int \*lengthArray, int \*addrArray, int partNum);**
-**dev**: pointer to the device name, for example, **spinorblk0**.
-**fsType**: pointer to the file system type, which is **vfat** for the FAT file system.
-**lengthArray**: pointer to a list of partition lengths (in percentage for a FAT file system) of the device.
-**addrArray**: pointer to a list of partition start addresses of the device.
-**source**: pointer to the partition name, in the *Device_name*+**p**+*Partition_ number* format. For example, **spinorblk0p0**.
-**target**: pointer to the target path to mount.
-**filesystemtype**: pointer to the file system type, which is **vfat** for the FAT file system.
-**mountflags**: parameters used for the mount operation.
-**data**: pointer to the private data that passes in **(VOID \*) formatType**, for example, **FMT_FAT** or **FMT_FAT32**.
The sample code is implemented in **./device/qemu/arm_mps2_an386/liteos_m/board/fs/fs_init.c** and can be directly used on the Quick EMUlator (QEMU) that uses the LiteOS-M kernel. You can modify the code based on the hardware you use.
HalLogicPartition *halPartitionsInfo = getPartitionInfo(); /* Function for obtaining the partition lengths and start addresses. Modify it as required. */
INT32 lengthArray[FF_VOLUMES] = {25, 25, 25, 25};
INT32 addrArray[FF_VOLUMES];
/* Set the address and length for each partition. */
for (i = 0; i < FF_VOLUMES; i++) {
addr = halPartitionsInfo[FLASH_PARTITION_DATA1].partitionStartAddr + i * 0x10000;
addrArray[i] = addr;
FlashInfoInit(i, addr);
}
/* Set partition information. */
SetupDefaultVolToPartTable();
ret = LOS_DiskPartition("spinorblk0", "vfat", lengthArray, addrArray, FF_VOLUMES);
ret = mount("spinorblk0p0", "/system", "vfat", 0, &data);
printf("%s: mount fs on '%s' %s\n", __func__, pathName[0], (ret == 0) ? "succeed" : "failed");
if (ret != 0) {
return -1;
}
return 0;
}
#### How to Develop
#### How to Develop
Note the following when managing FatFS files and directories:
Observe the following when managing files and directories in a FAT file system:
- A file cannot exceed 4 GB.
- A file cannot exceed 4 GB.
-**FAT_MAX_OPEN_FILES** specifies the maximum number files you can open at a time, and **FAT_MAX_OPEN_DIRS** specifies the maximum number of folders you can open at a time.
-**FAT_MAX_OPEN_FILES** specifies the maximum number files you can open at a time, and **FAT_MAX_OPEN_DIRS** specifies the maximum number of folders you can open at a time.
- Root directory management is not supported. File and directory names start with the partition name. For example, **user/testfile** indicates the file or directory **testfile** in the **user** partition.
- Root directory management is not supported. File and directory names start with the partition name. For example, **user/testfile** indicates the **testfile** file or directory in the **user** partition.
- To open a file multiple times, use **O_RDONLY** (read-only mode). **O_RDWR** or **O_WRONLY** (writable mode) can open a file only once.
- To open a file multiple times at the same time, use **O_RDONLY** (read-only mode). **O_RDWR** or **O_WRONLY** (writable mode) can open a file only once at a time.
- The read and write pointers are not separated. If a file is open in **O_APPEND** mode, the read pointer is also at the end of the file. If you want to read the file from the beginning, you must manually set the position of the read pointer.
- The read and write pointers are not separated. If a file is open in **O_APPEND** mode, the read pointer is also at the end of the file. If you want to read the file from the beginning, you must manually set the position of the read pointer.
- File and directory permission management is not supported.
- File and directory permission management is not supported.
- The **stat** and **fstat** APIs do not support query of the modification time, creation time, and last access time. The Microsoft FAT protocol does not support time before A.D. 1980.
- The **stat** and **fstat** APIs do not support query of the modification time, creation time, and last access time. The Microsoft FAT protocol does not support time before A.D. 1980.
Note the following when mounting and unmounting FatFS partitions:
Observe the following when managing files and directories in a FAT file system:
- Partitions can be mounted with the read-only attribute. When the input parameter of the **mount** function is **MS_RDONLY**, all APIs with the write attribute, such as **write**, **mkdir**, **unlink**, and **open** with **non-O_RDONLY** attributes, will be rejected.
- You can use the **MS_REMOUNT** flag with **mount** to modify the permission for a mounted partition.
- Partitions can be mounted with the read-only attribute. If the input parameter of **mount()** is **MS_RDONLY**, all APIs with the write attribute, such as **write()**, **mkdir()**, **unlink()**, and **open()** with **non-O_RDONLY** attributes, will be rejected.
- You can use the **MS_REMOUNT** flag in **mount()** to modify the permissions for a mounted partition.
- Before unmounting a partition, ensure that all directories and files in the partition are closed.
- Before unmounting a partition, ensure that all directories and files in the partition are closed.
- You can use **umount2** with the **MNT_FORCE** parameter to forcibly close all files and folders and unmount the partition. However, this may cause data loss. Therefore, exercise caution when running **umount2**.
- You can use **umount2** with the **MNT_FORCE** parameter to forcibly close all files and folders and unmount the partition. However, this may cause data loss. Therefore, exercise caution when using **umount2**.
The FAT file system supports re-partitioning and formatting of storage devices using **fatfs_fdisk** and **fatfs_format**.
You can use **fatfs_fdisk()** and **fatfs_format()** to re-partition the device storage and format the partitions. Observe the following:
- If a partition is mounted before being formatted using **fatfs_format**, you must close all directories and files in the partition and unmount the partition first.
- Before calling **fatfs_fdisk**, ensure that all partitions in the device are unmounted.
- Before using **fatfs_format()**, ensure that the target partition is unmounted and all directories and files in the partition are closed.
- Before using **fatfs_fdisk**, ensure that all partitions in the device are unmounted.
- Using **fatfs_fdisk** and **fatfs_format** may cause data loss. Exercise caution when using them.
- Using **fatfs_fdisk** and **fatfs_format** may cause data loss. Exercise caution when using them.
...
@@ -102,9 +198,9 @@ The FAT file system supports re-partitioning and formatting of storage devices u
...
@@ -102,9 +198,9 @@ The FAT file system supports re-partitioning and formatting of storage devices u
This example implements the following:
This example implements the following:
1. Create the **user/test** directory.
1. Create a **system/test** directory.
2. Create the **file.txt** file in the **user/test** directory.
2. Create a **file.txt** file in the **system/test** directory.
3. Write **Hello OpenHarmony!** at the beginning of the file.
3. Write **Hello OpenHarmony!** at the beginning of the file.
...
@@ -123,99 +219,103 @@ This example implements the following:
...
@@ -123,99 +219,103 @@ This example implements the following:
#### Sample Code
#### Sample Code
**Prerequisites**
**Prerequisites**
The MMC device partition is mounted to the **user** directory.
The sample code is as follows:
- The **system** partition is mounted to the QEMU.
- FAT is enabled.
1. In the **kernel/liteos_m** directory, run the **make menuconfig** command and choose **FileSystem->Enable FS VFS** to enable VFS.
2. Select **Enable FAT** to enable the FAT file system.
```
**Implementation**
#include <stdio.h>
#include <string.h>
#include "sys/stat.h"
#include "fcntl.h"
#include "unistd.h"
#define LOS_OK 0
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleFatfs** function is called in **TestTaskEntry**.
#define LOS_NOK -1
int FatfsTest(void)
```
{
#include <stdio.h>
#include <string.h>
#include "sys/stat.h"
#include "fcntl.h"
#include "unistd.h"
#define BUF_SIZE 20
#define TEST_ROOT "system" /* Set the test root directory. */
/* Create a readable and writable file named file.txt in the user/test/ directory. */
/* Create a file that is readable and writable. */
fd = open(fileName, O_RDWR | O_CREAT, 0777);
fd = open(fileName, O_RDWR | O_CREAT, 0777);
if (fd < 0) {
if (fd < 0) {
printf("open file failed.\n");
printf("open file failed.\n");
return LOS_NOK;
return;
}
}
/* Write the content from writeBuf to the file. */
/* Write the content from writeBuf to the file. */
len = write(fd, writeBuf, strlen(writeBuf));
len = write(fd, writeBuf, strlen(writeBuf));
if (len != strlen(writeBuf)) {
if (len != strlen(writeBuf)) {
printf("write file failed.\n");
printf("write file failed.\n");
return LOS_NOK;
return;
}
}
/* Save the file to a storage device. */
/* Save the file to a storage device. */
ret = fsync(fd);
ret = fsync(fd);
if (ret != LOS_OK) {
if (ret != LOS_OK) {
printf("fsync failed.\n");
printf("fsync failed.\n");
return LOS_NOK;
return;
}
}
/* Move the read/write pointer to the beginning of the file. */
/* Move the read/write pointer to the beginning of the file. */
off = lseek(fd, 0, SEEK_SET);
off = lseek(fd, 0, SEEK_SET);
if (off != 0) {
if (off != 0) {
printf("lseek failed.\n");
printf("lseek failed.\n");
return LOS_NOK;
return;
}
}
/* Read the file content with the length of readBuf to readBuf. */
/* Read the file content with the length of readBuf to readBuf. */
len = read(fd, readBuf, sizeof(readBuf));
len = read(fd, readBuf, sizeof(readBuf));
if (len != strlen(writeBuf)) {
if (len != strlen(writeBuf)) {
printf("read file failed.\n");
printf("read file failed.\n");
return LOS_NOK;
return;
}
}
printf("%s\n", readBuf);
printf("%s\n", readBuf);
/* Close the file. */
/* Close the test file. */
ret = close(fd);
ret = close(fd);
if (ret != LOS_OK) {
if (ret != LOS_OK) {
printf("close failed.\n");
printf("close failed.\n");
return LOS_NOK;
return;
}
}
/* Delete file.txt from the user/test directory. */
/* Delete the test file. */
ret = unlink(fileName);
ret = unlink(fileName);
if (ret != LOS_OK) {
if (ret != LOS_OK) {
printf("unlink failed.\n");
printf("unlink failed.\n");
return LOS_NOK;
return;
}
}
/* Delete the user/test directory. */
/* Delete the test directory. */
ret = rmdir(dirName);
ret = rmdir(dirName);
if (ret != LOS_OK) {
if (ret != LOS_OK) {
printf("rmdir failed.\n");
printf("rmdir failed.\n");
return LOS_NOK;
return;
}
}
return LOS_OK;
return;
}
}
```
```
...
@@ -232,102 +332,219 @@ Hello OpenHarmony!
...
@@ -232,102 +332,219 @@ Hello OpenHarmony!
### Basic Concepts
### Basic Concepts
LittleFS is a small file system designed for flash. By combining the log-structured file system and the copy-on-write (COW) file system, LittleFS stores metadata in log structure and data in the COW structure. This special storage empowers LittleFS high power-loss resilience. LittleFS uses the statistical wear leveling algorithm when allocating COW data blocks, effectively prolonging the service life of flash devices. LittleFS is designed for small-sized devices with limited resources, such as ROM and RAM. All RAM resources are allocated through a buffer with the fixed size (configurable). That is, the RAM usage does not grow with the file system.
LittleFS is a small file system designed for the flash drive. It stores metadata in log structure and data in the copy-on-write (COW) structure. This feature empowers LittleFS high power-loss resilience. LittleFS uses the statistical wear leveling algorithm when allocating COW data blocks, effectively prolonging the service life of flash devices. LittleFS is designed for small-sized devices with limited resources, such as ROM and RAM. All RAM resources are allocated through a buffer with the fixed size (configurable). That is, the RAM usage does not grow with the file system.
LittleFS is a good choice when you look for a flash file system that is power-cut resilient and has wear leveling support on a small device with limited resources.
LittleFS is a good choice when you look for a flash file system that is power-cut resilient and has wear leveling support on a small device with limited resources.
### Development Guidelines
### Development Guidelines
Before porting LittleFS to a new hardware device, you need to declare **lfs_config**:
Before using a LittleFS to a device, you need to initialize the flash drive and partition the device storage
API for partitioning the storage:
**int LOS_DiskPartition(const char \*dev, const char \*fsType, int \*lengthArray, int \*addrArray, int partNum);**
-**dev**: pointer to the device name.
-**fsType**: pointer to the file system type, which is **littlefs** for LittleFS.
-**lengthArray**: pointer to a list of partition lengths of the device.
-**addrArray**: pointer to a list of partition start addresses of the device.
-**filesystemtype**: pointer to the file system type, which is **littlefs** for LittleFS.
-**mountflags**: parameters used for the mount operation.
-**data**: pointer to the private data that passes in **void pass (VOID \*) struct fs_cfg**.
The sample code is implemented in **./device/qemu/arm_mps2_an386/liteos_m/board/fs/fs_init.c** and can be directly used on the QEMU that uses the LiteOS-M kernel. You can modify the code based on the hardware you use.
HalLogicPartition *halPartitionsInfo = getPartitionInfo(); /* Function for obtaining the partition lengths and start addresses. You can modify the function to match your development. */
ret = mount(NULL, fs[0].mount_point, "littlefs", 0, &fs[0].partCfg);
printf("%s: mount fs on '%s' %s\n", __func__, fs[0].mount_point, (ret == 0) ? "succeed" : "failed");
if (ret != 0) {
return -1;
}
return 0;
}
```
```
**.read**, **.prog**, **.erase**, and **.sync** correspond to the read, write, erase, and synchronization APIs at the bottom layer of the hardware platform, respectively.
The **.readFunc**, **.writeFunc**, and **.eraseFunc** functions correspond to **read()**, **write()**, and **erase()** of the underlying hardware platform.
**read_size** indicates the number of bytes read each time. You can set it to a value greater than the physical read unit to improve performance. This value determines the size of the read cache. However, if the value is too large, more memory is consumed.
**readSize** indicates the number of bytes read each time. You can set it to a value greater than the physical read unit to improve performance. This value determines the size of the read cache. However, if the value is too large, more memory is consumed.
**prog_size** indicates the number of bytes written each time. You can set it to a value greater than the physical write unit to improve performance. This value determines the size of the write cache and must be an integral multiple of **read_size**. However, if the value is too large, more memory is consumed.
**writeSize** indicates the number of bytes written each time. You can set it to a value greater than the physical write unit to improve performance. This value determines the size of the write cache and must be an integral multiple of **readSize**. However, if the value is too large, more memory is consumed.
**block_size**: indicates the number of bytes in each erase block. The value can be greater than that of the physical erase unit. However, a smaller value is recommended because each file occupies at least one block. The value must be an integral multiple of **prog_size**.
**blockSize** indicates the number of bytes in each erase block. The value can be greater than that of the physical erase unit. However, a smaller value is recommended because each file occupies at least one block. The value must be an integral multiple of **writeSize**.
**block_count** indicates the number of blocks that can be erased, which depends on the capacity of the block device and the size of the block to be erased (**block_size**).
**blockCount** indicates the number of blocks that can be erased, which depends on the capacity of the block device and the size of the block to be erased (**blockSize**).
### Sample Code
### Sample Code
The sample code is as follows:
**Prerequisites**
-**/littlefs** is mounted to the QEMU.
- LittleFS is enabled.
1. In the **kernel/liteos_m** directory, run the **make menuconfig** command and choose **FileSystem->Enable FS VFS** to enable VFS.
2. Select **Enable Little FS** to enable the LittleFS.
The sample code is as follows:
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleLittlefs** function is called in **TestTaskEntry**.
```
```
#include "lfs.h"
#include <stdio.h>
#include "stdio.h"
#include <string.h>
lfs_t lfs;
#include "sys/stat.h"
lfs_file_t file;
#include "fcntl.h"
const struct lfs_config cfg = {
#include "unistd.h"
// block device operations
.read = user_provided_block_device_read,
#define BUF_SIZE 20
.prog = user_provided_block_device_prog,
#define TEST_ROOT "/littlefs" /* Set the test root directory. */
@@ -11,16 +11,16 @@ The purpose of memory debugging is to locate problems related to dynamic memory.
...
@@ -11,16 +11,16 @@ The purpose of memory debugging is to locate problems related to dynamic memory.
Memory information includes the memory pool size, memory usage, remaining memory size, maximum free memory, memory waterline, number of memory nodes, and fragmentation rate.
Memory information includes the memory pool size, memory usage, remaining memory size, maximum free memory, memory waterline, number of memory nodes, and fragmentation rate.
- Memory waterline: indicates the maximum memory used in a memory pool. The waterline value is updated upon each memory allocation and release. The memory pool size can be optimized based on this value.
- Memory waterline indicates the maximum memory used in a memory pool. The waterline value is updated upon each memory allocation and release. The memory pool size can be optimized based on this value.
- Fragmentation rate: indicates the fragmentation degree of the memory pool. If the fragmentation rate is high, there are a large number of free memory blocks in the memory pool but each block is small. You can use the following formula to calculate the fragmentation rate:<br>Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size
- Fragmentation rate indicates the fragmentation degree of the memory pool. If the fragmentation rate is high, there are a large number of free memory blocks in the memory pool but each block is small. You can use the following formula to calculate the fragmentation rate:<br>Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size
-Other parameters: You can call APIs described in [Memory Management](../kernel/kernel-mini-basic-memory.md) to scan node information in the memory pool and collect statistics.
-You can use [APIs for memory management](kernel-mini-basic-memory.md) to scan node information in the memory pool and collect statistics.
### Function Configuration
### Function Configuration
**LOSCFG_MEM_WATERLINE**: specifies the setting of the memory information statistics function. This function is enabled by default. To disable the function, set this macro to **0** in **target_config.h**. If you want to obtain the memory waterline, you must enable this macro.
**LOSCFG_MEM_WATERLINE** specifies the setting of the memory information statistics function. This function is enabled by default. To disable the function, set this macro to **0** in **target_config.h**. If you want to obtain the memory waterline, you must enable this macro.
### Development Guidelines
### Development Guidelines
...
@@ -38,15 +38,15 @@ typedef struct {
...
@@ -38,15 +38,15 @@ typedef struct {
UINT32 maxFreeNodeSize; // Maximum size of the free memory block in the memory pool.
UINT32 maxFreeNodeSize; // Maximum size of the free memory block in the memory pool.
UINT32 usedNodeNum; // Number of non-free memory blocks in the memory pool.
UINT32 usedNodeNum; // Number of non-free memory blocks in the memory pool.
UINT32 freeNodeNum; // Number of free memory blocks in the memory pool.
UINT32 freeNodeNum; // Number of free memory blocks in the memory pool.
#if (LOSCFG_MEM_WATERLINE == 1) //The function is enabled by default. To disable it, set this macro to 0 in target_config.h.
#if (LOSCFG_MEM_WATERLINE == 1) // The function is enabled by default. To disable it, set this macro to 0 in target_config.h.
UINT32 usageWaterLine; // Waterline of the memory pool.
UINT32 usageWaterLine; // Waterline of the memory pool.
#endif
#endif
} LOS_MEM_POOL_STATUS;
} LOS_MEM_POOL_STATUS;
```
```
-To obtain the memory waterline, call **LOS_MemInfoGet**. The first parameter in the API is the start address of the memory pool, and the second parameter is the handle of the **LOS_MEM_POOL_STATUS** type. The **usageWaterLine** field indicates the waterline.
To obtain the memory waterline, call **LOS_MemInfoGet**. The first parameter in the API is the start address of the memory pool, and the second parameter is the handle of the **LOS_MEM_POOL_STATUS** type. The **usageWaterLine** field indicates the waterline.
-To calculate the memory fragmentation rate, call **LOS_MemInfoGet** to obtain the remaining memory size and the maximum free memory block size in the memory pool, and then calculate the fragmentation rate of the dynamic memory pool as follows:<br>Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size
To calculate the memory fragmentation rate, call **LOS_MemInfoGet** to obtain the remaining memory size and the maximum free memory block size in the memory pool, and then calculate the fragmentation rate of the dynamic memory pool as follows:<br>Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size
#### Development Example
#### Development Example
...
@@ -62,7 +62,9 @@ This example implements the following:
...
@@ -62,7 +62,9 @@ This example implements the following:
#### Sample Code
#### Sample Code
The sample code is as follows:
The sample code is as follows:
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **MemTest** function is called in **TestTaskEntry**.
```
```
#include <stdio.h>
#include <stdio.h>
...
@@ -71,7 +73,7 @@ This example implements the following:
...
@@ -71,7 +73,7 @@ This example implements the following:
#include "los_memory.h"
#include "los_memory.h"
#include "los_config.h"
#include "los_config.h"
#define TEST_TASK_PRIO 5
void MemInfoTaskFunc(void)
void MemInfoTaskFunc(void)
{
{
LOS_MEM_POOL_STATUS poolStatus = {0};
LOS_MEM_POOL_STATUS poolStatus = {0};
...
@@ -80,11 +82,11 @@ void MemInfoTaskFunc(void)
...
@@ -80,11 +82,11 @@ void MemInfoTaskFunc(void)
void *pool = OS_SYS_MEM_ADDR;
void *pool = OS_SYS_MEM_ADDR;
LOS_MemInfoGet(pool, &poolStatus);
LOS_MemInfoGet(pool, &poolStatus);
/* Calculate the fragmentation rate of the memory pool. */
/* Calculate the fragmentation rate of the memory pool. */
The preceding data may vary depending on the running environment.
```
```
## Memory Leak Check
## Memory Leak Check
...
@@ -124,14 +128,15 @@ As an optional function of the kernel, memory leak check is used to locate dynam
...
@@ -124,14 +128,15 @@ As an optional function of the kernel, memory leak check is used to locate dynam
### Function Configuration
### Function Configuration
1.**LOSCFG_MEM_LEAKCHECK**: specifies the setting of the memory leak check. This function is disabled by default. To enable the function, set this macro to **1** in **target_config.h**.
**LOSCFG_MEM_LEAKCHECK** specifies the setting of the memory leak check. This function is disabled by default. To enable the function, set this macro to **1** in **target_config.h**.
**LOSCFG_MEM_RECORD_LR_CNT** specifies the number of LRs recorded. The default value is **3**. Each LR consumes the memory of **sizeof(void \*)** bytes.
2.**LOSCFG_MEM_RECORD_LR_CNT**: specifies the number of LRs recorded. The default value is **3**. Each LR consumes the memory of **sizeof(void\*)** bytes.
**LOSCFG_MEM_OMIT_LR_CNT** specifies the number of ignored LRs. The default value is **4**, which indicates that LRs are recorded from the time when **LOS_MemAlloc** is called. You can change the value based on actual requirements. This macro is configured because:
3.**LOSCFG_MEM_OMIT_LR_CNT**: specifies the number of ignored LRs. The default value is **4**, which indicates that LRs are recorded from the time when **LOS_MemAlloc** is called. You can change the value based on actual requirements. This macro is configured because:
-**LOS_MemAlloc** is also called internally.
-**LOS_MemAlloc** is also called internally.
-**LOS_MemAlloc** may be encapsulated externally.
-**LOS_MemAlloc** may be encapsulated externally.
- The number of LRs configured by **LOSCFG_MEM_RECORD_LR_CNT** is limited.
- The number of LRs configured by **LOSCFG_MEM_RECORD_LR_CNT** is limited.
Correctly setting this macro can ignore invalid LRs and reduce memory consumption.
Correctly setting this macro can ignore invalid LRs and reduce memory consumption.
> Enabling memory leak check affects memory application performance. LR addresses will be recorded for each memory node, increasing memory overhead.
> Enabling memory leak check affects memory application performance. LR addresses will be recorded for each memory node, increasing memory overhead.
...
@@ -179,6 +185,12 @@ This example implements the following:
...
@@ -179,6 +185,12 @@ This example implements the following:
The sample code is as follows:
The sample code is as follows:
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **MemLeakTest** function is called in **TestTaskEntry**.
When QEMU is running, ensure that the value of **LOSCFG_MEM_FREE_BY_TASKID** in **target_config.h** is **0**.
After the memory check function is enabled, other tasks running on certain platforms may frequently print memory-related information such as "psp, start = xxxxx, end = xxxxxxx". Ignore the information or delete the print information called by **OsStackAddrGet**.
```
```
#include <stdio.h>
#include <stdio.h>
...
@@ -217,6 +229,8 @@ node size LR[0] LR[1] LR[2]
...
@@ -217,6 +229,8 @@ node size LR[0] LR[1] LR[2]
0x20002aac: 0x56 0x08000e0c 0x08000e56 0x08004220
0x20002aac: 0x56 0x08000e0c 0x08000e56 0x08004220
0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6
0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6
0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000
0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000
The preceding data may vary depending on the running environment.
```
```
The difference between the two logs is as follows. The following memory nodes are suspected to have blocks with a memory leak.
The difference between the two logs is as follows. The following memory nodes are suspected to have blocks with a memory leak.
...
@@ -225,6 +239,8 @@ The difference between the two logs is as follows. The following memory nodes ar
...
@@ -225,6 +239,8 @@ The difference between the two logs is as follows. The following memory nodes ar
```
```
0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6
0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6
0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000
0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000
The preceding data may vary depending on the running environment.
```
```
The following is part of the assembly file:
The following is part of the assembly file:
...
@@ -246,6 +262,8 @@ The following is part of the assembly file:
...
@@ -246,6 +262,8 @@ The following is part of the assembly file:
The preceding data may vary depending on the running environment.
```
```
The memory node addressed by **0x080041ee** is not released after being requested in **MemLeakTest**.
The memory node addressed by **0x080041ee** is not released after being requested in **MemLeakTest**.
...
@@ -260,15 +278,16 @@ As an optional function of the kernel, memory corruption check is used to check
...
@@ -260,15 +278,16 @@ As an optional function of the kernel, memory corruption check is used to check
### Function Configuration
### Function Configuration
**LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK**: specifies the setting of the memory corruption check. This function is disabled by default. To enable the function, set this macro to **1** in **target_config.h**.
**LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK** specifies the setting of the memory corruption check. This function is disabled by default. To enable the function, set this macro to **1** in **target_config.h**.
1. If this macro is enabled, the memory pool integrity will be checked in real time upon each memory allocation.
1. If this macro is enabled, the memory pool integrity will be checked in real time upon each memory allocation.
2. If this macro is not enabled, you can call **LOS_MemIntegrityCheck** to check the memory pool integrity when required. Using **LOS_MemIntegrityCheck** does not affect the system performance. In addition, the check accuracy decreases because the node header does not contain the magic number (which is available only when **LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK** is enabled).
2. If this macro is not enabled, you can call **LOS_MemIntegrityCheck** to check the memory pool integrity when required. Using **LOS_MemIntegrityCheck** does not affect the system performance. However, the check accuracy decreases because the node header does not contain the magic number (which is available only when **LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK** is enabled).
This check only detects the corrupted memory node and provides information about the previous node (because memory is contiguous, a node is most likely corrupted by the previous node). To further determine the location where the previous node is requested, you need to enable the memory leak check and use LRs to locate the fault.
This check only detects the corrupted memory node and provides information about the previous node (because memory is contiguous, a node is most likely corrupted by the previous node). To further determine the location where the previous node is requested, you need to enable the memory leak check and use LRs to locate the fault.
> If memory corruption check is enabled, a magic number is added to the node header, which increases the size of the node header. The real-time integrity check has a great impact on the performance. In performance-sensitive scenarios, you are advised to disable this function and use **LOS_MemIntegrityCheck** to check the memory pool integrity.
> If memory corruption check is enabled, a magic number is added to the node header, which increases the size of the node header. The real-time integrity check has a great impact on the performance. In performance-sensitive scenarios, you are advised to disable this function and use **LOS_MemIntegrityCheck** to check the memory pool integrity.
...
@@ -295,6 +314,12 @@ This example implements the following:
...
@@ -295,6 +314,12 @@ This example implements the following:
The sample code is as follows:
The sample code is as follows:
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **MemIntegrityTest** function is called in **TestTaskEntry**.
When QEMU is running, ensure that the value of **LOSCFG_MEM_FREE_BY_TASKID** in **target_config.h** is **0**.
Because the exception is triggered intentionally, you need to restart QEMU when the execution is complete. For example, open a new terminal and run **killall qemu-system-arm**.
memory used but magic num wrong, magic num = 0x00000000 /* Error information, indicating that the first four bytes, that is, the magic number, of the next node are corrupted. */
/* Error information indicating the field corrupted. In this example, the first four bytes of the next node are cleared, that is, the magic number field is corrupted. */
/* Key information about the corrupted node and its previous node, including the address of the previous node, magic number of the node, and sizeAndFlag of the node. In this example, the magic number of the corrupted node is cleared. */
/* Key information about the corrupted node and its previous node, including the address of the previous node, magic number of the node, and sizeAndFlag of the node. In this example, the magic number of the corrupted node is cleared. */
broken node head LR info: /* The node LR information can be output only after the memory leak check is enabled. */
/*The node LR information can be output only after the memory leak check is enabled. */
LR[2]:0x00000000
broken node head LR info:
LR[0]:0x2101906c
pre node head LR info: /* Based on the LR information, you can find where the previous node is requested in the assembly file and then perform further analysis. */
LR[1]:0x0
LR[0]:0x08004144
LR[2]:0x0
LR[1]:0x08000cc2
LR[2]:0x00000000
/* Based on the LR information, you can determine where the previous node in requsted in the assembly file and check the use of the node. */
[ERR]Memory integrity check error, cur node: 0x20003b10, pre node: 0x20003af0 /* Addresses of the corrupted node and its previous node */
pre node head LR info:
LR[0]:0x2101906c
LR[1]:0x0
LR[2]:0x0
/* Addresses of the corrupted node and its previous node. */
[ERR][IT_TST_INI]Memory integrity check error, cur node: 0x2103d784, pre node: 0x0
The preceding data may vary depending on the running environment.
The OpenHarmony LiteOS-M provides exception handling and debugging measures to help locate and analyze problems. Exception handling involves a series of actions taken by the OS to respond to exceptions occurred during the OS running, for example, printing the exception type, system status, call stack information of the current function, CPU information, and call stack information of tasks.
The OpenHarmony LiteOS-M provides exception handling and debugging measures to help locate and analyze problems. Exception handling involves a series of actions taken by the OS to respond to exceptions occurred during the OS running, for example, printing the exception type, system status, call stack information of the current function, CPU information, and call stack information of tasks.
## Working Principles
## Working Principles
A stack frame contains information such as function parameters, variables, and return value in a function call process. When a function is called, a stack frame of the subfunction is created, and the input parameters, local variables, and registers of the function are stored into the stack. Stack frames grow towards lower addresses. The ARM32 CPU architecture is used as an example. Each stack frame stores the historical values of the program counter \(PC\), LR \(link register\), stack pointer \(SP\), and frame pointer \(FP\) registers. The LR points to the return address of a function, and the FP points to the start address of the stack frame of the function's parent function. The FP helps locate the parent function's stack frame, which further helps locate the parent function's FP. The parent function's FP helps locate the grandparent function's stack frame and FP... In this way, the call stack of the program can be traced to obtain the relationship between the functions called.
A stack frame contains information such as function parameters, variables, and return value in a function call process. When a function is called, a stack frame of the subfunction is created, and the input parameters, local variables, and registers of the function are stored into the stack. Stack frames grow towards lower addresses. The ARM32 CPU architecture is used as an example. Each stack frame stores the historical values of the program counter (PC), link register (LR), stack pointer (SP), and frame pointer (FP) registers. The LR points to the return address of a function, and the FP points to the start address of the stack frame of the function's parent function. The FP helps locate the parent function's stack frame, which further helps locate the parent function's FP. The parent function's FP helps locate the grandparent function's stack frame and FP... In this way, the call stack of the program can be traced to obtain the relationship between the functions called.
When an exception occurs in the system, the system prints the register information in the stack frame of the abnormal function as well as the LRs and FPs in the stack frames of its parent function and grandfather function. The relationships between the functions help you locate the cause of the exception.
When an exception occurs in the system, the system prints the register information in the stack frame of the abnormal function as well as the LRs and FPs in the stack frames of its parent function and grandfather function. The relationships between the functions help you locate the cause of the exception.
The following figure illustrates the stack analysis mechanism for your reference. The actual stack information varies depending on the CPU architecture.
The following figure illustrates the stack analysis mechanism for your reference. The actual stack information varies depending on the CPU architecture.
In the figure, the registers in different colors indicate different functions. The registers save related data when functions are called. The FP register helps track the stack to the parent function of the abnormal function and further presents the relationships between the functions called.
In the figure, the registers in different colors indicate different functions. The registers save related data when functions are called. The FP register helps track the stack to the parent function of the abnormal function and further presents the relationships between the functions called.
## Available APIs
## Available APIs
The following table describes APIs available for the OpenHarmony LiteOS-M stack trace module. For more details about the APIs, see the API reference.
The following table describes APIs available for the OpenHarmony LiteOS-M stack trace module. For more details about the APIs, see the API reference.
| Stack tracing| **LOS_BackTrace**: prints the call stack relationship at the calling point.<br>**LOS_RecordLR**: obtains the call stack relationship at the calling point when print is unavailable.|
<tdclass="cellrowborder"valign="top"width="57.34573457345735%"headers="mcps1.2.4.1.3 "><pid="p1516617282165"><aname="p1516617282165"></a><aname="p1516617282165"></a>Prints the call stack relationship at the function calling point.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p4969192715710"><aname="p4969192715710"></a><aname="p4969192715710"></a>Obtains the call stack relationship at the function calling point when print is unavailable.</p>
</td>
</tr>
</tbody>
</table>
## Usage Guidelines
### How to Develop
### How to Develop
The typical process for enabling exception debugging is as follows:
The typical process for enabling exception debugging is as follows:
1. Configure the macros related to exception handling.
1. Configure the macros related to exception handling
in the **target_config.h** file.
Modify the configuration in the **target\_config.h** file.
| Configuration Item| Description| Value|
| -------- | -------- | -------- |
<a name="table1078714915105"></a>
| LOSCFG_BACKTRACE_DEPTH | Depth of the function call stack. The default value is **15**.| 15 |
| LOSCFG_BACKTRACE_TYPE | Type of the stack tracing.<br>**0**: The stack tracing is disabled.<br>**1**: supports call stack analysis of the Cortex-M series hardware.<br>**2**: supports call stack analysis of the RISC-V series hardware.| Set this parameter to **1** or **2** based on the toolchain type.|
<td class="cellrowborder" valign="top" width="37.47%" headers="mcps1.1.4.1.2 "><p id="p198061196105"><a name="p198061196105"></a><a name="p198061196105"></a>Depth of the function call stack. The default value is <strong id="b1041811416176"><a name="b1041811416176"></a><a name="b1041811416176"></a>15</strong>.</p>
<p id="p1133122212183"><a name="p1133122212183"></a><a name="p1133122212183"></a><strong id="b1863620373182"><a name="b1863620373182"></a><a name="b1863620373182"></a>1</strong>: supports function call stack analysis of the Cortex-m series hardware.</p>
<p id="p1133822101814"><a name="p1133822101814"></a><a name="p1133822101814"></a><strong id="b106211355191914"><a name="b106211355191914"></a><a name="b106211355191914"></a>2</strong>: supports function call stack analysis of the RISC-V series hardware.</p>
</td>
<td class="cellrowborder" valign="top" width="42.43%" headers="mcps1.1.4.1.3 "><p id="p780614919107"><a name="p780614919107"></a><a name="p780614919107"></a>Set this parameter to <strong id="b1926720398209"><a name="b1926720398209"></a><a name="b1926720398209"></a>1</strong> or <strong id="b149341042172017"><a name="b149341042172017"></a><a name="b149341042172017"></a>2</strong> based on the toolchain type.</p>
</td>
</tr>
</tbody>
</table>
1. Use the error code in the example to build and run a project, and check the error information displayed on the serial port terminal. The sample code simulates error code. During actual product development, use the exception debugging mechanism to locate exceptions.
1. Use the error code in the example to build and run a project, and check the error information displayed on the serial port terminal. The sample code simulates error code. During actual product development, use the exception debugging mechanism to locate exceptions.
The following example demonstrates the exception output through a task. The task entry function simulates calling of multiple functions and finally calls a function that simulates an exception. The sample code is as follows:
The following example demonstrates the exception output through a task. The task entry function simulates calling of multiple functions and finally calls a function that simulates an exception. The sample code is as follows:
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleExcEntry** function is called in **TestTaskEntry**.
```
```
#include <stdio.h>
#include <stdio.h>
#include "los_config.h"
#include "los_config.h"
...
@@ -100,30 +60,31 @@ The typical process for enabling exception debugging is as follows:
...
@@ -100,30 +60,31 @@ The typical process for enabling exception debugging is as follows:
interrupt enable register, base address: 0xe000e100, size: 0x20
interrupt enable register, base address: 0xe000e100, size: 0x20
0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0
0x2001 0x0 0x0 0x0 0x0 0x0 0x0 0x0
interrupt pending register, base address: 0xe000e200, size: 0x20
interrupt pending register, base address: 0xe000e200, size: 0x20
0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0
0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0
interrupt active register, base address: 0xe000e300, size: 0x20
interrupt active register, base address: 0xe000e300, size: 0x20
...
@@ -244,13 +194,15 @@ The typical process for enabling exception debugging is as follows:
...
@@ -244,13 +194,15 @@ The typical process for enabling exception debugging is as follows:
interrupt exception register, base address: 0xe000ed18, size: 0xc
interrupt exception register, base address: 0xe000ed18, size: 0xc
0x0 0x0 0xf0f00000
0x0 0x0 0xf0f00000
interrupt shcsr register, base address: 0xe000ed24, size: 0x4
interrupt shcsr register, base address: 0xe000ed24, size: 0x4
0x70008
0x70002
interrupt control register, base address: 0xe000ed04, size: 0x4
interrupt control register, base address: 0xe000ed04, size: 0x4
0x400f806
0x1000e805
memory pools check:
memory pools check:
system heap memcheck over, all passed!
system heap memcheck over, all passed!
memory pool check end!
memory pool check end!
The preceding data may vary depending on the running environment.
```
```
...
@@ -258,64 +210,68 @@ The typical process for enabling exception debugging is as follows:
...
@@ -258,64 +210,68 @@ The typical process for enabling exception debugging is as follows:
The procedure for locating the exception is as follows:
The procedure for locating the exception is as follows:
1. Open the image disassembly file \(.asm\) generated after compilation. If the file is not generated by default, use the objdump tool to generate it. Run the following command:
1. Ensure that the compiler optimization is disabled. Otherwise, the following problems may be optimized during the compilation process.
2. Open the image disassembly file (.asm) generated. If the file is not generated, use the objdump tool to generate it. The command is as follows:
```
```
arm-none-eabi-objdump -S -l XXX.elf
arm-none-eabi-objdump -S -l XXX.elf
```
```
3. Search for the PC (pointing to the instruction being executed) in the .asm file to locate the abnormal function.
1. Search for the PC \(pointing to the instruction being executed\) in the ASM file to locate the abnormal function.
The PC address directs to the instruction being executed when the exception occurs. In the .asm file corresponding to the currently executed binary file, search for the PC value **0x2101c61a** and locate the instruction being executed by the CPU. Disassemble the code as follows:
The PC address directs to the instruction being executed when the exception occurs. In the ASM file corresponding to the currently executed binary file, search for the PC value **0x80037da** and locate the instruction being executed by the CPU. Disassemble the code as follows:
The previous line of LR **2101c648** is **bl2101c60c <GetResultException0>**, which calls the abnormal function. The parent function is **GetResultException1**.
1. The previous line of LR **80037fe** is **bl 80037c8 <Get\_Result\_Exception\_0\>**, which calls the abnormal function. The parent function that calls the abnormal function is **Get\_Result\_Exception\_1\(\)**.
5. Parse the LR value between **backtrace start** and **backtrace end** in the exception information to obtain the call stack relationship where the exception occurs and find the cause of the exception.
2. Repeat [3](#li18973161743110) to analyze the LR values between **backtrace start** and **backtrace end** in the exception information to obtain the call stack relationship and find the exception cause.
Lite Memory Sanitizer \(LMS\) is a tool used to detect memory errors on a real-time basis. LMS can detect buffer overflow, Use-After-Free \(UAF\), and double free errors in real time, and notify the operating system immediately. Together with locating methods such as Backtrace, LMS can locate the code line that causes the memory error. It greatly improves the efficiency of locating memory errors.
Lite Memory Sanitizer (LMS) is a tool used to detect memory errors on a real-time basis. It can detect buffer overflow, Use-After-Free (UAF), and double free errors in real time, and notify the operating system immediately. Together with Backtrace, the LMS can locate the code line that causes the memory error. It greatly improves the efficiency of locating memory errors.
The LMS module of the OpenHarmony LiteOS-M kernel provides the following functions:
The LMS module of the OpenHarmony LiteOS-M kernel provides the following functions:
- Supports check of multiple memory pools.
- Supports check of multiple memory pools.
- Checks the memory allocated by **LOS\_MemAlloc**, **LOS\_MemAllocAlign**, and **LOS\_MemRealloc**.
- Checks the memory when bounds-checking functions are called \(enabled by default\).
- Checks the memory allocated by **LOS_MemAlloc**, **LOS_MemAllocAlign**, and **LOS_MemRealloc**.
- Checks the memory when bounds-checking functions are called (enabled by default).
- Checks the memory when libc frequently accessed functions, including **memset**, **memcpy**, **memmove**, **strcat**, **strcpy**, **strncat** and **strncpy**, are called.
- Checks the memory when libc frequently accessed functions, including **memset**, **memcpy**, **memmove**, **strcat**, **strcpy**, **strncat** and **strncpy**, are called.
## Working Principles
## Working Principles
LMS uses shadow memory mapping to mark the system memory state. There are three states: **Accessible**, **RedZone**, and **Freed**. The shadow memory is located in the tail of the memory pool.
The LMS uses shadow memory mapping to mark the system memory state. There are three states: **Accessible**, **RedZone**, and**Freed**. The shadow memory is located in the tail of the memory pool.
- After memory is allocated from the heap, the shadow memory in the data area is set to the **Accessible** state, and the shadow memory in the head node area is set to the **RedZone** state.
- After memory is allocated from the heap, the shadow memory in the data area is set to the **Accessible** state, and the shadow memory in the head node area is set to the **RedZone** state.
- When memory is released from the heap, the shadow memory of the released memory is set to the **Freed** state.
- When memory is released from the heap, the shadow memory of the released memory is set to the **Freed** state.
- During code compilation, a function is inserted before the read/write instructions in the code to check the address validity. The tool checks the state value of the shadow memory that accesses the memory. If the shadow memory is in the **RedZone** statue, an overflow error will be reported. If the shadow memory is in the **Freed** state, a UAF error will be reported.
- During code compilation, a function is inserted before the read/write instructions in the code to check the address validity. The tool checks the state value of the shadow memory that accesses the memory. If the shadow memory is in the **RedZone** statue, an overflow error will be reported. If the shadow memory is in the **Freed** state, a UAF error will be reported.
- When memory is released, the tool checks the state value of the shadow memory at the released address. If the shadow memory is in the **RedZone** state, a double free error will be reported.
- When memory is released, the tool checks the state value of the shadow memory at the released address. If the shadow memory is in the **RedZone** state, a double free error will be reported.
## Available APIs
## Available APIs
The LMS module of the OpenHarmony LiteOS-M kernel provides the following APIs. For more details about the APIs, see the [API](https://gitee.com/openharmony/kernel_liteos_m/blob/master/components/lms/los_lms.h) reference.
The LMS module of the OpenHarmony LiteOS-A kernel provides the following APIs. For more details, see [API reference](https://gitee.com/openharmony/kernel_liteos_m/blob/master/components/lms/los_lms.h).
| Adding a memory pool to be checked| LOS_LmsCheckPoolAdd | Adds the address range of a memory pool to the LMS check linked list. LMS performs a validity check when the accessed address is within the linked list. In addition, **LOS_MemInit** calls this API to add the initialized memory pool to the LMS check linked list by default.|
| Deleting a memory pool from the LMS check linked list| LOS_LmsCheckPoolDel | Cancels the validity check on the specified memory pool.|
</th>
| Protecting a specified memory chunk| LOS_LmsAddrProtect | Locks a memory chunk to prevent it from being read or written. Once the locked memory chunk is accessed, an error will be reported.|
| Disabling protection of a specified memory chunk| LOS_LmsAddrDisableProtect | Unlocks a memory chunk to make it readable and writable.|
</th>
</tr>
</thead>
<tbody><trid="row12671943185014"><tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p926044310503"><aname="p926044310503"></a><aname="p926044310503"></a>Adding a memory pool to be checked</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p1226024365018"><aname="p1226024365018"></a><aname="p1226024365018"></a>Adds the address range of a memory pool to the LMS check linked list. LMS performs a validity check when the accessed address is within the linked list. In addition, <strongid="b126321851183511"><aname="b126321851183511"></a><aname="b126321851183511"></a>LOS_MemInit</strong> calls this API to add the initialized memory pool to the LMS check linked list by default.</p>
</td>
</tr>
<trid="row4267104318501"><tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p926164395017"><aname="p926164395017"></a><aname="p926164395017"></a>Deleting a memory pool from the LMS check linked list</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p62611438504"><aname="p62611438504"></a><aname="p62611438504"></a>Cancels the validity check on the specified memory pool.</p>
</td>
</tr>
<trid="row1226794310500"><tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p2026154317502"><aname="p2026154317502"></a><aname="p2026154317502"></a>Protecting a specified memory chunk</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p9261134365018"><aname="p9261134365018"></a><aname="p9261134365018"></a>Locks a memory chunk to prevent it from being read or written. Once the locked memory chunk is accessed, an error will be reported.</p>
</td>
</tr>
<trid="row32662437507"><tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p1261164325018"><aname="p1261164325018"></a><aname="p1261164325018"></a>Disabling protection of a specified memory chunk</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p426194395019"><aname="p426194395019"></a><aname="p426194395019"></a>Unlocks a memory chunk to make it readable and writable.</p>
</td>
</tr>
</tbody>
</table>
## Development Guidelines
## Development Guidelines
### How to Develop
### How to Develop
The typical process for enabling LMS is as follows:
The typical process for enabling LMS is as follows:
1. Configure the macros related to the LMS module.
1. Configure the macros related to the LMS module.
Configure the LMS macro **LOSCFG_KERNEL_LMS**, which is disabled by default.
Run the **make menuconfig** command in the **kernel/liteos_m** directory, and set **Kernel->Enable Lite Memory Sanitizer** to **YES**. If this option is unavailable, select **Enable Backtrace**.
Configure the LMS macro **LOSCFG\_KERNEL\_LMS**, which is disabled by default. Run the **make update\_config** command in the **kernel/liteos\_m** directory, choose **Kernel**, and set **Enable Lite Memory Sanitizer** to **Yes**.
<td class="cellrowborder" valign="top" width="25%" headers="mcps1.1.5.1.2 "><p id="p12459135823316"><a name="p12459135823316"></a><a name="p12459135823316"></a>Lms check pool max num</p>
</td>
<td class="cellrowborder" valign="top" width="25%" headers="mcps1.1.5.1.3 "><p id="p445975819335"><a name="p445975819335"></a><a name="p445975819335"></a>Maximum number of memory pools that can be checked by LMS.</p>
2. Modify the compile script of the target module.
Add "-fsanitize=kernel-address" to insert memory access checks, and add the **-O0** option to disable optimization performed by the compiler.
The modifications vary depending on the compiler \(GCC or Clang\) used. The following is an example:
```
```
if ("$ohos_build_compiler_specified" == "gcc") {
if ("$ohos_build_compiler_specified" == "gcc") {
...
@@ -161,20 +88,30 @@ The typical process for enabling LMS is as follows:
...
@@ -161,20 +88,30 @@ The typical process for enabling LMS is as follows:
}
}
```
```
3. Recompile the code and check the serial port output. The memory problem detected will be displayed.
3. Recompile the code and check the serial port output.
The memory problem detected will be displayed.
### Development Example
### Development Example
This example implements the following:
This example implements the following:
1. Create a task for LMS.
1. Create a task for LMS.
2. Construct a buffer overflow error and a UAF error.
2. Construct a buffer overflow error and a UAF error.
3. Add "-fsanitize=kernel-address", execute the compilation, and check the output.
3. Add "-fsanitize=kernel-address", execute the compilation, and check the output.
### Sample Code
### Sample Code
The code is as follows:
The code is as follows:
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **Example_Lms_test** function is called in **TestTaskEntry**.
Modify **./kernel/liteos_m/testsuites/BUILD.gn** corresponding to **osTest.c**.
Trace helps you learn about the kernel running process and the execution sequence of modules and tasks. With the information, you can better understand the code running process of the kernel and locate time sequence problems.
Trace helps you learn about the kernel running process and the execution sequence of modules and tasks. With the traced information, you can better understand the code running process of the kernel and locate time sequence problems.
## Working Principles
## Working Principles
...
@@ -16,142 +18,86 @@ In offline mode, trace frames are stored in a circular buffer. If too many frame
...
@@ -16,142 +18,86 @@ In offline mode, trace frames are stored in a circular buffer. If too many frame


The online mode must be used with the integrated development environment \(IDE\). Trace frames are sent to the IDE in real time. The IDE parses the records and displays them in a visualized manner.
The online mode must be used with the integrated development environment (IDE). Trace frames are sent to the IDE in real time. The IDE parses the records and displays them in a visualized manner.
## Available APIs
## Available APIs
The trace module of the OpenHarmony LiteOS-M kernel provides the following functions. For more details about the APIs, see the API reference.
The trace module of the OpenHarmony LiteOS-M kernel provides the following APIs. For more details about the APIs, see the API reference.
| Managing trace records| - **LOS_TraceRecordDump**: dumps data from the trace buffer.<br>- **LOS_TraceRecordGet**: obtains the start address of the trace buffer.<br>- **LOS_TraceReset**: clears events in the trace buffer.|
</th>
| Filtering trace records| **LOS_TraceEventMaskSet**: sets the event mask to trace only events of the specified modules.|
| Masking events of specified interrupt IDs| **LOS_TraceHwiFilterHookReg**: registers a hook to filter out events of specified interrupt IDs.|
</th>
| Performing function instrumentation| - **LOS_TRACE_EASY**: performs simple instrumentation.<br>- **LOS_TRACE**: performs standard instrumentation.|
</tr>
</thead>
<tbody><trid="row7235182719585"><tdclass="cellrowborder"rowspan="2"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p92241727105816"><aname="p92241727105816"></a><aname="p92241727105816"></a>Starting and stopping trace</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p16224427125810"><aname="p16224427125810"></a><aname="p16224427125810"></a>Exports data in the trace buffer.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p1422412274584"><aname="p1422412274584"></a><aname="p1422412274584"></a>Obtains the start address of the trace buffer.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p1222413276581"><aname="p1222413276581"></a><aname="p1222413276581"></a>Clears events in the trace buffer.</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p122242272585"><aname="p122242272585"></a><aname="p122242272585"></a>Sets the event mask to trace only events of the specified modules.</p>
</td>
</tr>
<trid="row5234627145818"><tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p152244272589"><aname="p152244272589"></a><aname="p152244272589"></a>Masking events of specified interrupt IDs</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p12224627135819"><aname="p12224627135819"></a><aname="p12224627135819"></a>Registers a hook to filter out events of specified interrupt IDs.</p>
</td>
</tr>
<trid="row22341027115815"><tdclass="cellrowborder"rowspan="2"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p1222462716588"><aname="p1222462716588"></a><aname="p1222462716588"></a>Performing function instrumentation</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p2225527185810"><aname="p2225527185810"></a><aname="p2225527185810"></a>Performs standard instrumentation.</p>
</td>
</tr>
</tbody>
</table>
- You can perform function instrumentation in the source code to trace specific events. The system provides the following APIs for instrumentation:
- You can perform function instrumentation in the source code to trace specific events. The system provides the following APIs for instrumentation:
-**LOS\_TRACE\_EASY\(TYPE, IDENTITY, params...\)** for simple instrumentation
-**LOS_TRACE_EASY(TYPE, IDENTITY, params...)** for simple instrumentation
- You only need to insert this API into the source code.
- You only need to insert this API into the source code.
-**TYPE** specifies the event type. The value range is 0 to 0xF. The meaning of each value is user-defined.
-**TYPE** specifies the event type. The value range is 0 to 0xF. The meaning of each value is user-defined.
-**IDENTITY** specifies the object of the event operation. The value is of the **UIntPtr** type.
-**IDENTITY** specifies the object of the event operation. The value is of the **UIntPtr** type.
-**Params** specifies the event parameters. The value is of the **UIntPtr** type.
-**Params** specifies the event parameters. The value is of the **UIntPtr** type.
- Example:
- Example of simple instrumentation for reading and writing data based on the file FDs:
```
```
Perform simple instrumentation for reading and writing files fd1 and fd2.
/* Set TYPE to 1 for read operation and 2 for write operations. */
Set TYPE to 1 for read operations and 2 for write operations.
LOS_TRACE_EASY(1, fd, flag, size); /* Add it to a proper position. */
Insert the following to the position where the fd1 file is read:
LOS_TRACE_EASY(2, fd, flag, size); /* Add it to a proper position. */
LOS_TRACE_EASY(1, fd1, flag, size);
Insert the following to the position where the fd2 file is read:
LOS_TRACE_EASY(1, fd2, flag, size);
Insert the following to the position where the fd1 file is written:
LOS_TRACE_EASY(2, fd1, flag, size);
Insert the following in the position where the fd2 file is written:
LOS_TRACE_EASY(2, fd2, flag, size);
```
```
-**LOS_TRACE(TYPE, IDENTITY, params...)** for standard instrumentation.
- **LOS\_TRACE\(TYPE, IDENTITY, params...\)** for standard instrumentation.
- Compared with simple instrumentation, standard instrumentation supports dynamic event filtering and parameter tailoring. However, you need to extend the functions based on rules.
- Compared with simple instrumentation, standard instrumentation supports dynamic event filtering and parameter tailoring. However, you need to extend the functions based on rules.
- **TYPE** specifies the event type. You can define the event type in **enum LOS\_TRACE\_TYPE** in the header file **los\_trace.h**. For details about methods and rules for defining events, see other event types.
-**TYPE** specifies the event type. You can define the event type in **enum LOS_TRACE_TYPE** in the header file **los_trace.h**. For details about methods and rules for defining events, see other event types.
- The **IDENTITY** and **Params** are the same as those of simple instrumentation.
- The **IDENTITY** and **Params** are the same as those of simple instrumentation.
- Example:
- Example:
1. Define the type of the FS module (event mask of the FS module) in **enum LOS_TRACE_MASK**.
```
```
1. Set the event mask (module-level event type) in enum LOS_TRACE_MASK.
/* Define the event mask in the format of TRACE_#MOD#_FLAG, where #MOD# indicates the module name. */
Format: TRACE_#MOD#_FLAG (MOD indicates the module name)
Example:
TRACE_FS_FLAG = 0x4000
TRACE_FS_FLAG = 0x4000
2. Define the event type in enum LOS_TRACE_TYPE.
Format: #TYPE# = TRACE_#MOD#_FLAG | NUMBER
Example:
FS_READ = TRACE_FS_FLAG | 0; // Read files
FS_WRITE = TRACE_FS_FLAG | 1; // Write files
3. Set event parameters in the #TYPE#_PARAMS(IDENTITY, parma1...) IDENTITY, ... format.
>The trace event types and parameters can be modified as required. For details about the parameters, see **kernel\\include\\los\_trace.h**.
```
/* Define the event type in the format: #TYPE# = TRACE_#MOD#_FLAG | NUMBER */
FS_READ = TRACE_FS_FLAG | 0; /* Read data. */
FS_WRITE = TRACE_FS_FLAG | 1; /* Write data. */
```
3. Define event parameters.
```
/* Define the parameters in the format: #TYPE#_PARAMS(IDENTITY, parma1...) IDENTITY, ... */
#define FS_READ_PARAMS(fp, fd, flag, size) fp, fd, flag, size /* The parameters defined by the macro correspond to the event parameters recorded in the trace buffer. You can tailor the parameters as required. */
#define FS_READ_PARAMS(fp, fd, flag, size) /* If no parameters are defined, events of this type are not traced. */
> You can modify the traced event types and parameters as required. For details about the parameters, see **kernel\include\los_trace.h**.
- For **LOS_TraceEventMaskSet(UINT32 mask)**, only the most significant 28 bits (corresponding to the enable bit of the module in **LOS_TRACE_MASK**) of the mask take effect and are used only for module-based tracing. Currently, fine-grained event-based tracing is not supported. For example, in **LOS_TraceEventMaskSet(0x202)**, the effective mask is **0x200 (TRACE_QUE_FLAG)** and all events of the QUE module are collected. The recommended method is **LOS_TraceEventMaskSet(TRACE_EVENT_FLAG | TRACE_MUX_FLAG | TRACE_SEM_FLAG | TRACE_QUE_FLAG);**.
- To enable trace of only simple instrumentation events, set **Trace Mask** to **TRACE_MAX_FLAG**.
- The trace buffer has limited capacity. When the trace buffer is full, events will be overwritten. You can use **LOS_TraceRecordDump** to export data from the trace buffer and locate the latest records by **CurEvtIndex**.
- For **LOS\_TraceEventMaskSet\(UINT32 mask\)**, only the most significant 28 bits \(corresponding to the enable bit of the module in **LOS\_TRACE\_MASK**\) of the mask take effect and are used only for module-based tracing. Currently, fine-grained event-based tracing is not supported. For example, in **LOS\_TraceEventMaskSet\(0x202\)**, the effective mask is **0x200 \(TRACE\_QUE\_FLAG\)** and all events of the QUE module are collected. The recommended method is **LOS\_TraceEventMaskSet\(TRACE\_EVENT\_FLAG | TRACE\_MUX\_FLAG | TRACE\_SEM\_FLAG | TRACE\_QUE\_FLAG\);**.
- The typical trace operation process includes **LOS_TraceStart**, **LOS_TraceStop**, and **LOS_TraceRecordDump**.
- To enable trace of only simple instrumentation events, set **Trace Mask** to **TRACE\_MAX\_FLAG**.
- The trace buffer has limited capacity. When the trace buffer is full, events will be overwritten. You can use **LOS\_TraceRecordDump** to export data from the trace buffer and locate the latest records by **CurEvtIndex**.
- The typical trace operation process includes **LOS\_TraceStart**, **LOS\_TraceStop**, and **LOS\_TraceRecordDump**.
- You can filter out interrupt events by interrupt ID to prevent other events from being overwritten due to frequent triggering of a specific interrupt in some scenarios. You can customize interrupt filtering rules.
- You can filter out interrupt events by interrupt ID to prevent other events from being overwritten due to frequent triggering of a specific interrupt in some scenarios. You can customize interrupt filtering rules.<br>
The sample code is as follows:
The sample code is as follows:
```
```
...
@@ -165,116 +111,75 @@ The trace module of the OpenHarmony LiteOS-M kernel provides the following funct
...
@@ -165,116 +111,75 @@ The trace module of the OpenHarmony LiteOS-M kernel provides the following funct
LOS_TraceHwiFilterHookReg(Example_HwiNumFilter);
LOS_TraceHwiFilterHookReg(Example_HwiNumFilter);
```
```
The interrupt events with interrupt ID of **TIMER\_INT** or **DMA\_INT** are not traced.
The interrupt events with interrupt ID of **TIMER_INT** or **DMA_INT** are not traced.
## Development Guidelines
## Development Guidelines
### How to Develop
### How to Develop
The typical trace process is as follows:
The typical development process is as follows:
1. Configure the macro related to the trace module.
1. Configure the macros related to the trace module in the **target_config.h** file.
| Configuration Item| Description| Value|
Modify the configuration in the **target\_config.h** file.
| -------- | -------- | -------- |
| LOSCFG_KERNEL_TRACE | Whether to enable the trace feature. | YES/NO |
<a name="table86631147151516"></a>
| LOSCFG_RECORDER_MODE_OFFLINE | Whether to enable the online trace mode. | YES/NO |
| LOSCFG_RECORDER_MODE_ONLINE | Whether to enable the offline trace mode. | YES/NO |
</th>
| LOSCFG_TRACE_CLIENT_INTERACT | Whether to enable interaction with Trace IDE (dev tools), including data visualization and process control. | YES/NO |
3. (Optional) Call **LOS_TraceStop** to stop trace and **LOS_TraceReset** to clear the trace buffer. (Trace is started by default.)
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.1.4.1.2 "><p id="p72519205167"><a name="p72519205167"></a><a name="p72519205167"></a>Specifies whether to enable the trace feature.</p>
</td>
4. (Optional) Call **LOS_TraceEventMaskSet** to set the event mask for trace (only the interrupts and task events are enabled by default). For details about the event mask, see **LOS_TRACE_MASK** in **los_trace.h**.
6. Call **LOS_TraceStop** at the end of the code where the event needs to be traced.
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.1.4.1.2 "><p id="p4251620111614"><a name="p4251620111614"></a><a name="p4251620111614"></a>Specifies whether to enable the online trace mode.</p>
7. Call **LOS_TraceRecordDump** to output the data in the buffer. (The input parameter of the function is of the Boolean type. The value **FALSE** means to output data in the specified format, and the value **TRUE** means to output data to a Windows client.)
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.1.4.1.2 "><p id="p225182016163"><a name="p225182016163"></a><a name="p225182016163"></a>Specifies whether to enable interaction with Trace IDE (dev tools), including data visualization and process control.</p>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.1.4.1.2 "><p id="p425192015165"><a name="p425192015165"></a><a name="p425192015165"></a>Specifies whether to enable recording of the CPU ID, interruption state, and lock task state.</p>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.1.4.1.2 "><p id="p172511020141611"><a name="p172511020141611"></a><a name="p172511020141611"></a>Specifies the maximum number of parameters for event recording.</p>
2.\(Optional\) Preset event parameters and stubs \(or use the default event parameter settings and event stubs\).
3.\(Optional\) Call **LOS\_TraceStop** to stop trace and call **LOS\_TraceReset** to clear the trace buffer. \(Trace is started by default.\)
4.\(Optional\) Call **LOS\_TraceEventMaskSet** to set the event mask for trace \(only the interrupts and task events are enabled by default\). For details about the event mask, see **LOS\_TRACE\_MASK** in **los\_trace.h**.
5. Call **LOS\_TraceStart** at the start of the code where the event needs to be traced.
6. Call **LOS\_TraceStop** at the end of the code where the event needs to be traced.
7. Call **LOS\_TraceRecordDump** to output the data in the buffer. \(The input parameter of the function is of the Boolean type. The value **FALSE** means to output data in the specified format, and the value **TRUE** means to output data to a Windows client.\)
The methods in steps 3 to 7 are encapsulated with shell commands. After the shell is enabled, the corresponding commands can be executed. The mapping is as follows:
The methods in steps 3 to 7 are encapsulated with shell commands. After the shell is enabled, the corresponding commands can be executed. The mapping is as follows:
- LOS\_TraceReset —— trace\_reset
- LOS_TraceReset —— trace_reset
- LOS\_TraceEventMaskSet —— trace\_mask
- LOS\_TraceStart —— trace\_start
- LOS_TraceEventMaskSet —— trace_mask
- LOS\_TraceStop —— trace\_stop
- LOS\_TraceRecordDump —— trace\_dump
- LOS_TraceStart —— trace_start
- LOS_TraceStop —— trace_stop
- LOS_TraceRecordDump —— trace_dump
### Development Example
### Development Example
This example implements the following:
This example implements the following:
1. Create a trace task.
1. Create a trace task.
2. Set the event mask.
2. Set the event mask.
3. Start trace.
3. Start trace.
4. Stop trace.
4. Stop trace.
5. Output trace data in the specified format.
5. Output trace data in the specified format.
### Sample Code
### Sample Code
The sample code is as follows:
The sample code is as follows:
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleTraceTest** function is called in **TestTaskEntry**.
Index Time(cycles) EventType CurTask Identity params
Index Time(cycles) EventType CurTask Identity params
...
@@ -337,36 +244,43 @@ Index Time(cycles) EventType CurTask Identity params
...
@@ -337,36 +244,43 @@ Index Time(cycles) EventType CurTask Identity params
5 0x36eec810 0x45 0xc 0x1 0x9 0x8 0x1f
5 0x36eec810 0x45 0xc 0x1 0x9 0x8 0x1f
6 0x3706f804 0x45 0x1 0x0 0x1f 0x4 0x0
6 0x3706f804 0x45 0x1 0x0 0x1f 0x4 0x0
7 0x37070e59 0x45 0x0 0x1 0x0 0x8 0x1f
7 0x37070e59 0x45 0x0 0x1 0x0 0x8 0x1f
*******TraceInfo end*******
***TraceInfo end***
The preceding data may vary depending on the running environment.
```
```
The output event information includes the occurrence time, event type, task in which the event occurs, object of the event operation, and other parameters of the event.
The output event information includes the occurrence time, event type, task in which the event occurs, object of the event operation, and other parameters of the event.
-**EventType**: event type. For details, see **enum LOS\_TRACE\_TYPE** in the header file **los\_trace.h**.
-**EventType**: event type. For details, see **enum LOS_TRACE_TYPE** in the header file **los_trace.h**.
-**CurrentTask**: ID of the running task.
-**CurrentTask**: ID of the running task.
-**Identity**: object of the event operation. For details, see **\#TYPE\#\_PARAMS** in the header file **los\_trace.h**.
-**params**: event parameters. For details, see **\#TYPE\#\_PARAMS** in the header file **los\_trace.h**.
-**Identity**: object of the event operation. For details, see **#TYPE#_PARAMS** in the header file **los_trace.h**.
-**params**: event parameters. For details, see **#TYPE#_PARAMS** in the header file **los_trace.h**.
The following uses output No. 0 as an example.
The following uses output No. 0 as an example.
```
```
Index Time(cycles) EventType CurTask Identity params
Index Time(cycles) EventType CurTask Identity params
0 0x366d5e88 0x45 0x1 0x0 0x1f 0x4
0 0x366d5e88 0x45 0x1 0x0 0x1f 0x4
```
```
-**Time \(cycles\)** can be converted into time \(in seconds\) by dividing the cycles by clockFreq.
-**Time (cycles)** can be converted into time (in seconds) by dividing the cycles by clockFreq.
-**0x45** indicates the task switching event. **0x1** is the ID of the task in running.
-**0x45** indicates the task switching event. **0x1** is the ID of the task in running.
- For details about the meanings of **Identity** and **params**, see the **TASK\_SWITCH\_PARAMS** macro.
- For details about the meanings of **Identity** and **params**, see the **TASK_SWITCH_PARAMS** macro.
Because of **\#TYPE\#\_PARAMS\(IDENTITY, parma1...\) IDENTITY, ...**, **Identity** is **taskId \(0x0\)** and the first parameter is **oldPriority \(0x1f\)**.
**Identity** is **taskId (0x0)**, and the first parameter is **oldPriority (0x1f)**.
> The number of parameters in **params** is specified by **LOSCFG_TRACE_FRAME_MAX_PARAMS**. The default value is **3**. Excess parameters are not recorded. Set **LOSCFG_TRACE_FRAME_MAX_PARAMS** based on service requirements.
>The number of parameters in **params** is specified by the **LOSCFG\_TRACE\_FRAME\_MAX\_PARAMS** parameter. The default value is **3**. Excess parameters are not recorded. You need to set **LOSCFG\_TRACE\_FRAME\_MAX\_PARAMS** based on service requirements.
Task 0x1 is switched to Task 0x0. The priority of task 0x1 is **0x1f**, and the state is **0x4**. The priority of the task 0x0 is **0x0**.
Task 0x1 is switched to Task 0x0. The priority of task 0x1 is **0x1f**, and the state is **0x4**. The priority of task 0x0 is **0x0**.
A bitwise operation operates on a binary number at the level of its individual bits. For example, a variable can be set as a program status word \(PSW\), and each bit \(flag bit\) in the PSW can have a self-defined meaning.
A bitwise operation operates on the bits of a binary number. A variable can be set as a program status word (PSW), and each bit (flag bit) in the PSW can have a self-defined meaning.
## Available APIs<a name="section848334511411"></a>
## **Available APIs**
The system provides operations for setting the flag bit to **1** or **0**, changing the flag bit content, and obtaining the most significant bit and least significant bit of the flag bit 1 in a PSW. You can also perform bitwise operations on system registers. The following table describes the APIs available for the bitwise operation module. For more details about the APIs, see the API reference.
The system provides operations for setting the flag bit to **1** or **0**, changing the flag bit content, and obtaining the most significant bit (MSB) and least significant bit (LSB) of the flag bit 1 in a PSW. You can also perform bitwise operations on system registers. The following table describes the APIs available for the bitwise operation module. For more details about the APIs, see the API reference.
| Setting a flag bit| - **LOS_BitmapSet**: sets a flag bit of a PSW to **1**.<br>- **LOS_BitmapClr**: sets a flag bit of a PSW to **0**. |
</th>
| Obtaining the bit whose flag bit is **1**| -**LOS_HighBitGet**: obtains the most significant bit of 1 in a PSW.<br>- **LOS_LowBitGet**: obtains the least significant bit of 1 in a PSW. |
| Operating continuous bits| - **LOS_BitmapSetNBits**: sets the consecutive flag bits of a PSW to **1**.<br>- **LOS_BitmapClrNBits**: sets the consecutive flag bits of a PSW to **0**.<br>- **LOS_BitmapFfz**: obtains the first 0 bit starting from the LSB. |
</th>
</tr>
</thead>
## Development Example
<tbody><trid="row18801722069"><tdclass="cellrowborder"rowspan="2"valign="top"width="16.89168916891689%"headers="mcps1.2.4.1.1 "><pid="p108717579612"><aname="p108717579612"></a><aname="p108717579612"></a>Setting the flag bit to <strongid="b129301229122320"><aname="b129301229122320"></a><aname="b129301229122320"></a>1</strong> or <strongid="b1899463182312"><aname="b1899463182312"></a><aname="b1899463182312"></a>0</strong></p>
<tdclass="cellrowborder"valign="top"width="47.56475647564757%"headers="mcps1.2.4.1.3 "><pid="p16871957668"><aname="p16871957668"></a><aname="p16871957668"></a>Sets a flag bit of a PSW to <strongid="b1283195411179"><aname="b1283195411179"></a><aname="b1283195411179"></a>1</strong>.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p14871155718618"><aname="p14871155718618"></a><aname="p14871155718618"></a>Sets a flag bit of a PSW to <strongid="b15267438112312"><aname="b15267438112312"></a><aname="b15267438112312"></a>0</strong>.</p>
</td>
</tr>
<trid="row16880112663"><tdclass="cellrowborder"rowspan="2"valign="top"width="16.89168916891689%"headers="mcps1.2.4.1.1 "><pid="p158710579615"><aname="p158710579615"></a><aname="p158710579615"></a>Obtaining the bit whose flag bit is <strongid="b58742415239"><aname="b58742415239"></a><aname="b58742415239"></a>1</strong></p>
<tdclass="cellrowborder"valign="top"width="47.56475647564757%"headers="mcps1.2.4.1.3 "><pid="p168713571468"><aname="p168713571468"></a><aname="p168713571468"></a>Obtains the most significant bit of <strongid="b485014714235"><aname="b485014714235"></a><aname="b485014714235"></a>1</strong> in the PSW.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p148719571569"><aname="p148719571569"></a><aname="p148719571569"></a>Obtains the least significant bit of <strongid="b9907125542319"><aname="b9907125542319"></a><aname="b9907125542319"></a>1</strong> in the PSW.</p>
<tdclass="cellrowborder"valign="top"width="47.56475647564757%"headers="mcps1.2.4.1.3 "><pid="p10871135714613"><aname="p10871135714613"></a><aname="p10871135714613"></a>Sets the continuous flag bits of a PSW to <strongid="b145631313234"><aname="b145631313234"></a><aname="b145631313234"></a>1</strong>.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p1387145711610"><aname="p1387145711610"></a><aname="p1387145711610"></a>Sets the continuous flag bits of a PSW to <strongid="b185031722103115"><aname="b185031722103115"></a><aname="b185031722103115"></a>0</strong>.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p187115571369"><aname="p187115571369"></a><aname="p187115571369"></a>Obtains the first 0 bit starting from the least significant bit (LSB).</p>
</td>
</tr>
</tbody>
</table>
## Development Example<a name="section67569495514"></a>
### Example Description<a name="section33551554391"></a>
This example implements the following:
This example implements the following:
1. Set a flag bit to **1**.
1. Set a flag bit to **1**.
2. Obtain the most significant bit of flag bit 1.
2. Obtain the MSB of flag bit 1.
3. Set a flag bit to **0**.
3. Set a flag bit to **0**.
4. Obtain the least significant bit of the flag bit 1.
4. Obtain the LSB of flag bit 1.
### Sample Code
The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **BitSample** function is called in **TestTaskEntry**.
| Initializing a DLL| - **LOS_ListInit**: initializes a node as a DLL node.<br>- **LOS_DL_LIST_HEAD**: defines a node and initializes it as a DLL node.|
| Initializing a DLL | - **LOS_ListInit**: initializes a node as a DLL node.<br>- **LOS_DL_LIST_HEAD**: defines a node and initializes it as a DLL node.|
| Adding a node| - **LOS_ListAdd**: adds a node to the head of a DLL.<br>- **LOS_ListHeadInsert**: same as **LOS_ListAdd**.<br>- **LOS_ListTailInsert**: inserts a node to the tail of a DLL.|
| Adding a node | - **LOS_ListAdd**: adds a node to the head of a DLL.<br>- **LOS_ListHeadInsert**: same as **LOS_ListAdd**.<br>- **LOS_ListTailInsert**: inserts a node to the tail of a DLL.|
| Adding a DLL| - **LOS_ListAddList**: adds the head of a DLL to the head of this DLL.<br>- **LOS_ListHeadInsertList**: inserts the head of a DLL to the head of this DLL.<br>- **LOS_ListTailInsertList**: Inserts the end of a DLL to the head of this DLL.|
| Adding a DLL | - **LOS_ListAddList**: adds the head of a DLL to the head of this DLL.<br>- **LOS_ListHeadInsertList**: inserts the head of a DLL to the head of this DLL.<br>- **LOS_ListTailInsertList**: inserts the end of a DLL to the head of this DLL.|
| Deleting a node| - **LOS_ListDelete**: deletes a node from this DLL.<br>- **LOS_ListDelInit**: deletes a node from this DLL and uses this node to initialize the DLL.|
| Deleting a node | - **LOS_ListDelete**: deletes a node from this DLL.<br>- **LOS_ListDelInit**: deletes a node from this DLL and uses this node to initialize the DLL.|
| Checking a DLL| - **LOS_ListEmpty**: checks whether a DLL is empty.<br>- **LOS_DL_LIST_IS_END**: checks whether a node is the tail of the DLL.<br>- **LOS_DL_LIST_IS_ON_QUEUE**: checks whether a node is in the DLL.|
| Checking a DLL | - **LOS_ListEmpty**: checks whether a DLL is empty.<br>- **LOS_DL_LIST_IS_END**: checks whether a node is the tail of the DLL.<br>- **LOS_DL_LIST_IS_ON_QUEUE**: checks whether a node is in the DLL.|
| Obtains structure information.| - **LOS_OFF_SET_OF**: obtains the offset of a member in the specified structure relative to the start address of the structure.<br>- **LOS_DL_LIST_ENTRY**: obtains the address of the structure that contains the first node in the DLL. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure.<br>- **LOS_ListPeekHeadType**: obtains the address of the structure that contains the first node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Null will be returned if the DLL is empty.<br>- **LOS_ListRemoveHeadType**: obtains the address of the structure that contains the first node in the linked list, and deletes the first node from the list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Null will be returned if the DLL is empty.<br>- **LOS_ListNextType**: obtains the address of the structure that contains the next node of the specified node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the specified node, the third parameter indicates the name of the structure to be obtained, and the fourth input parameter indicates the name of the linked list in the structure. If the next node of the linked list node is the head node and is empty, NULL will be returned.|
| Obtaining structure information | - **LOS_OFF_SET_OF**: obtains the offset of a member in the specified structure relative to the start address of the structure.<br>- **LOS_DL_LIST_ENTRY**: obtains the address of the structure that contains the first node in the DLL. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure.<br>- **LOS_ListPeekHeadType**: obtains the address of the structure that contains the first node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Null will be returned if the DLL is empty.<br>- **LOS_ListRemoveHeadType**: obtains the address of the structure that contains the first node in the linked list, and deletes the first node from the list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Null will be returned if the DLL is empty.<br>- **LOS_ListNextType**: obtains the address of the structure that contains the next node of the specified node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the specified node, the third parameter indicates the name of the structure to be obtained, and the fourth input parameter indicates the name of the linked list in the structure. If the next node of the linked list node is the head node and is empty, NULL will be returned.|
| Traversing a DLL| - **LOS_DL_LIST_FOR_EACH**: traverses a DLL.<br>- **LOS_DL_LIST_FOR_EACH_SAFE**: traverses the DLL and stores the subsequent nodes of the current node for security verification.|
| Traversing a DLL | - **LOS_DL_LIST_FOR_EACH**: traverses a DLL.<br>- **LOS_DL_LIST_FOR_EACH_SAFE**: traverses the DLL and stores the subsequent nodes of the current node for security verification.|
| Traversing the structure that contains the DLL| - **LOS_DL_LIST_FOR_EACH_ENTRY**: traverses a DLL and obtains the address of the structure that contains the linked list node.<br>- **LOS_DL_LIST_FOR_EACH_ENTRY_SAFE**: traverses a DLL, obtains the address of the structure that contains the linked list node, and stores the address of the structure that contains the subsequent node of the current node.|
| Traversing the structure that contains a DLL| - **LOS_DL_LIST_FOR_EACH_ENTRY**: traverses a DLL and obtains the address of the structure that contains the linked list node.<br>- **LOS_DL_LIST_FOR_EACH_ENTRY_SAFE**: traverses a DLL, obtains the address of the structure that contains the linked list node, and stores the address of the structure that contains the subsequent node of the current node.|
## How to Develop
## How to Develop
...
@@ -30,7 +29,7 @@ The typical development process of the DLL is as follows:
...
@@ -30,7 +29,7 @@ The typical development process of the DLL is as follows:
2. Call **LOS_ListAdd** to add a node into the DLL.
2. Call **LOS_ListAdd** to add a node into the DLL.
3. Call **LOS_ListTailInsert** to insert a node to the tail of the DLL.
3. Call **LOS_ListTailInsert** to insert a node into the tail of the DLL.
4. Call **LOS_ListDelete** to delete the specified node.
4. Call **LOS_ListDelete** to delete the specified node.
...
@@ -39,18 +38,19 @@ The typical development process of the DLL is as follows:
...
@@ -39,18 +38,19 @@ The typical development process of the DLL is as follows:
6. Call **LOS_ListDelInit** to delete the specified node and initialize the DLL based on the node.
6. Call **LOS_ListDelInit** to delete the specified node and initialize the DLL based on the node.
> - Pay attention to the operations operations of the front and back pointer of the node.
>
> - Pay attention to the operations before and after the node pointer.
>
>
> - The DLL APIs are underlying interfaces and do not check whether the input parameters are empty. You must ensure that the input parameters are valid.
> - The DLL APIs are underlying interfaces and do not check whether the input parameters are empty. You must ensure that the input parameters are valid.
>
>
> - If the memory of a linked list node is dynamically allocated, release the memory when deleting the node.
> - If the memory of a linked list node is dynamically allocated, release the memory when deleting the node.
**Development Example**
## Development Example
**Example Description**
### Example Description
This example implements the following:
This example implements the following:
...
@@ -63,7 +63,11 @@ This example implements the following:
...
@@ -63,7 +63,11 @@ This example implements the following:
4. Check the operation result.
4. Check the operation result.
### Sample Code
The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **ListSample** function is called in **TestTaskEntry**.
The OpenHarmony kernel uses the musl libc library that supports the Portable Operating System Interface \(POSIX\). You can develop components and applications working on the kernel based on the POSIX.
The OpenHarmony kernel uses the musl libc library that supports the Portable Operating System Interface (POSIX). You can develop components and applications working on the kernel based on the POSIX.
The musl libc library supports POSIX standards. The OpenHarmony kernel adapts the related system call APIs to implement external functions.
The musl libc library supports POSIX standards. The OpenHarmony kernel adapts the related system call APIs to implement external functions.
For details about the APIs supported by the standard library, see the API document of the C library, which also covers the differences between the standard library and the POSIX standard library.
For details about the APIs supported by the standard library, see the API document of the C library, which also covers the differences between the standard library and the POSIX standard library.
## Development Example
In this example, the main thread creates **THREAD\_NUM** child threads. Once a child thread is started, it enters the standby state. After the main thread successfully wakes up all child threads, they continue to execute until the lifecycle ends. The main thread uses the **pthread\_join** method to wait until all child threads are executed.
### Development Example
#### Example Description
In this example, the main thread creates THREAD_NUM child threads. Once a child thread is started, it enters the standby state. After the main thread successfully wakes up all child threads, they continue to execute until the lifecycle ends. The main thread uses the **pthread_join** method to wait until all child threads are executed.
#### Sample Code
The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **ExamplePosix** function is called in **TestTaskEntry**.
The sample code is as follows:
```
```
#include <stdio.h>
#include <stdio.h>
#include <unistd.h>
#include <unistd.h>
#include <pthread.h>
#include <pthread.h>
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif /* __cplusplus */
#endif /* __cplusplus */
#define THREAD_NUM 3
#define THREAD_NUM 3
int g_startNum = 0; /* Number of started threads */
int g_startNum = 0; /* Number of threads to start */
int g_wakenNum = 0; /* Number of wakeup threads */
int g_wakenNum = 0; /* Number of threads to wake up */
printf("ERROR: pthread create failed, error code is %d!\n", rc);
dprintf("ERROR: pthread create failed, error code is %d!\n", rc);
goto ERROROUT;
goto ERROROUT;
}
}
}
}
dprintf("pthread_create ok\n");
/* Wait until all child threads lock a mutex. */
/* Wait until all child threads obtain a mutex. */
while (g_startNum < THREAD_NUM) {
while (g_startNum < THREAD_NUM) {
usleep(100);
usleep(100);
}
}
...
@@ -118,14 +123,14 @@ static int testcase(void)
...
@@ -118,14 +123,14 @@ static int testcase(void)
/* Acquire a mutex and block all threads using pthread_cond_wait. */
/* Acquire a mutex and block all threads using pthread_cond_wait. */
rc = pthread_mutex_lock(&g_td.mutex);
rc = pthread_mutex_lock(&g_td.mutex);
if (rc != 0) {
if (rc != 0) {
printf("ERROR: mutex lock failed, error code is %d\n", rc);
dprintf("ERROR: mutex lock failed, error code is %d\n", rc);
goto ERROROUT;
goto ERROROUT;
}
}
/* Release a mutex. */
/* Release the mutex. */
rc = pthread_mutex_unlock(&g_td.mutex);
rc = pthread_mutex_unlock(&g_td.mutex);
if (rc != 0) {
if (rc != 0) {
printf("ERROR: mutex unlock failed, error code is %d!\n", rc);
dprintf("ERROR: mutex unlock failed, error code is %d!\n", rc);
goto ERROROUT;
goto ERROROUT;
}
}
...
@@ -133,7 +138,7 @@ static int testcase(void)
...
@@ -133,7 +138,7 @@ static int testcase(void)
/* Broadcast signals on the cond variable. */
/* Broadcast signals on the cond variable. */
rc = pthread_cond_signal(&g_td.cond);
rc = pthread_cond_signal(&g_td.cond);
if (rc != 0) {
if (rc != 0) {
printf("ERROR: pthread condition failed, error code is %d!\n", rc);
dprintf("ERROR: pthread condition failed, error code is %d!\n", rc);
goto ERROROUT;
goto ERROROUT;
}
}
}
}
...
@@ -142,73 +147,69 @@ static int testcase(void)
...
@@ -142,73 +147,69 @@ static int testcase(void)
/* Check whether all child threads are woken up. */
/* Check whether all child threads are woken up. */
if (g_wakenNum != THREAD_NUM) {
if (g_wakenNum != THREAD_NUM) {
printf("ERROR: not all threads awaken, only %d thread(s) awaken!\n", g_wakenNum);
dprintf("ERROR: not all threads awaken, only %d thread(s) awaken!\n", g_wakenNum);
goto ERROROUT;
goto ERROROUT;
}
}
dprintf("all threads awaked\n");
/* Wait for all threads to terminate. */
/* Join all child threads, that is, wait for the end of all child threads. */
for (i = 0; i < THREAD_NUM; i++) {
for (i = 0; i < THREAD_NUM; i++) {
rc = pthread_join(thread[i], NULL);
rc = pthread_join(thread[i], NULL);
if (rc != 0) {
if (rc != 0) {
printf("ERROR: pthread join failed, error code is %d!\n", rc);
dprintf("ERROR: pthread join failed, error code is %d!\n", rc);
goto ERROROUT;
goto ERROROUT;
}
}
}
}
dprintf("all threads join ok\n");
/* Destroy the cond variable. */
/* Destroy the cond variable. */
rc = pthread_cond_destroy(&g_td.cond);
rc = pthread_cond_destroy(&g_td.cond);
if (rc != 0) {
if (rc != 0) {
printf("ERROR: pthread condition destroy failed, error code is %d!\n", rc);
dprintf("ERROR: pthread condition destroy failed, error code is %d!\n", rc);
goto ERROROUT;
goto ERROROUT;
}
}
return 0;
return 0;
ERROROUT:
ERROROUT:
return -1;
return -1;
}
}
```
/*
#### Verification
* Main function
*/
int main(int argc, char *argv[])
{
int rc;
/* Start the test function. */
The output is as follows:
rc = testcase();
if (rc != 0) {
printf("ERROR: testcase failed!\n");
}
return 0;
```
}
pthread_create ok
#ifdef __cplusplus
all threads awaked
#if __cplusplus
all threads join ok
}
#endif /* __cplusplus */
#endif /* __cplusplus */
```
```
## Differences from the Linux Standard Library
## Differences from the Linux Standard Library
This section describes the key differences between the standard library carried by the OpenHarmony kernel and the Linux standard library. For more differences, see the API document of the C library.
The following describes the key differences between the standard library supported by the OpenHarmony kernel and the Linux standard library. For more differences, see the API document of the C library.
### Process
### Process
1. The OpenHarmony user-mode processes support only static priorities, which range from 10 \(highest\) to 31 \(lowest\).
- The OpenHarmony user-mode processes support only static priorities, which range from 10 (highest) to 31 (lowest).
2. The OpenHarmony user-mode threads support only static priorities, which range from 0 \(highest\) to 31 \(lowest\).
3. The OpenHarmony process scheduling supports **SCHED\_RR** only, and thread scheduling supports **SCHED\_RR** or **SCHED\_FIFO**.
- The OpenHarmony user-mode threads support only static priorities, which range from 0 (highest) to 31 (lowest).
- The OpenHarmony process scheduling supports **SCHED_RR** only, and thread scheduling supports **SCHED_RR** or **SCHED_FIFO**.
### Memory
### Memory
**h2****Difference with Linux mmap**
**Differences from Linux mmap**
mmap prototype: **void \*mmap \(void \*addr, size\_t length, int prot, int flags, int fd, off\_t offset\)**
mmap prototype: **void \*mmap (void \*addr, size_t length, int prot, int flags, int fd, off_t offset)**
The lifecycle implementation of **fd** is different from that of Linux glibc. glibc releases the **fd** handle immediately after successfully invoking **mmap** for mapping. In the OpenHarmony kernel, you are not allowed to close the **fd** immediately after the mapping is successful. You can close the **fd** only after **munmap** is called. If you do not close **fd**, the OS reclaims the **fd** when the process exits.
The lifecycle implementation of **fd** is different from that of Linux glibc. glibc releases the **fd** handle immediately after successfully invoking **mmap** for mapping. In the OpenHarmony kernel, you are not allowed to close the **fd** immediately after the mapping is successful. You can close the **fd** only after **munmap** is called. If you do not close **fd**, the OS reclaims the **fd** when the process exits.
**h2****Sample Code**
**Example**
Linux OS:
Linux:
```
```
int main(int argc, char *argv[])
int main(int argc, char *argv[])
...
@@ -226,13 +227,14 @@ int main(int argc, char *argv[])
...
@@ -226,13 +227,14 @@ int main(int argc, char *argv[])
perror("mmap");
perror("mmap");
exit(EXIT_FAILURE);
exit(EXIT_FAILURE);
}
}
close(fd); /* OpenHarmony does not support close fd immediately after the mapping is successful. */
close(fd); /* OpenHarmony does not support closing fd immediately after the mapping is successful. */
...
...
exit(EXIT_SUCCESS);
exit(EXIT_SUCCESS);
}
}
```
```
OpenHarmony:
OpenHarmony:
```
```
int main(int argc, char *argv[])
int main(int argc, char *argv[])
...
@@ -257,22 +259,27 @@ int main(int argc, char *argv[])
...
@@ -257,22 +259,27 @@ int main(int argc, char *argv[])
}
}
```
```
### File System
### File System
**System directories**: You cannot modify system directories and device mount directories, which include **/dev**, **/proc**, **/app**, **/bin**, **/data**, **/etc**, **/lib**, **/system** and **/usr**.
System directories: You cannot modify system directories and device mount directories, which include **/dev**, **/proc**, **/app**, **/bin**, **/data**, **/etc**, **/lib**, **/system**, and**/usr**.
**User directory**: The user directory refers to the **/storage** directory. You can create, read, and write files in this directory, but cannot mount devices.
User directory: The user directory refers to the **/storage** directory. You can create, read, and write files in this directory, but cannot mount it to a device.
Except in the system and user directories, you can create directories and mount them to devices. Note that nested mount is not allowed, that is, a mounted folder and its subfolders cannot be mounted repeatedly. A non-empty folder cannot be mounted.
Except in the system and user directories, you can create directories and mount devices. Note that nested mount is not allowed, that is, a mounted folder and its subfolders cannot be mounted repeatedly. A non-empty folder cannot be mounted.
### Signal
### Signal
- The default behavior for signals does not include **STOP**, **CONTINUE**, or **COREDUMP**.
- The default behavior for signals does not include **STOP**, **CONTINUE**, or **COREDUMP**.
- A sleeping process \(for example, a process enters the sleeping status by calling the sleep function\) cannot be woken up by a signal. The signal mechanism does not support the wakeup function. The behavior for a signal can be processed only when the process is scheduled by the CPU.
- A sleeping process (for example, a process enters the sleeping status by calling the sleep function) cannot be woken up by a signal. The signal mechanism does not support the wakeup function. The behavior for a signal can be processed only when the process is scheduled by the CPU.
- After a process exits, **SIGCHLD** is sent to the parent process. The sending action cannot be canceled.
- After a process exits, **SIGCHLD** is sent to the parent process. The sending action cannot be canceled.
- Only signals 1 to 30 are supported. The callback is executed only once even if the same signal is received multiple times.
### Time
- Only signals 1 to 30 are supported. The callback is invoked only once even if the same signal is received multiple times.
The OpenHarmony time precision is based on tick. The default value is 10 ms/tick. The time error of the **sleep** and **timeout** functions is less than or equal to 20 ms.
### Time
The default time precision of OpenHarmony is 10 ms/tick. The time error of the **sleep** and **timeout** functions is less than or equal to 20 ms.
In an OS that supports multiple tasks, modifying data in a memory area requires three steps: read data, modify data, and write data. However, data in a memory area may be simultaneously accessed by multiple tasks. If the data modification is interrupted by another task, the execution result of the operation is unpredictable.
In an OS that supports multiple tasks, modifying data in memory involves three steps: read data, modify data, and write data. However, the data may be simultaneously accessed by multiple tasks. If the data modification is interrupted by another task, an unexpected result will be caused.
Although you can enable or disable interrupts to ensure that the multi-task execution results meet expectations, the system performance is affected.
Although you can enable or disable interrupts to ensure expected results of multiple tasks, the system performance is affected.
The ARMv6 architecture has introduced the **LDREX** and **STREX** instructions to support more discreet non-blocking synchronization of the shared memory. The atomic operations implemented thereby can ensure that the "read-modify-write" operations on the same data will not be interrupted, that is, the operation atomicity is ensured.
The ARMv6 architecture has introduced the **LDREX** and **STREX** instructions to support more discreet non-blocking synchronization of the shared memory. The atomic operations implemented thereby can ensure that the "read-modify-write" operations on the same data will not be interrupted, that is, the operation atomicity is ensured.
## Working Principles
The OpenHarmony system has encapsulated the **LDREX** and **STREX** in the ARMv6 architecture to provide a set of atomic operation APIs.
## Working Principles
- LDREX Rx, \[Ry\]
OpenHarmony has encapsulated the **LDREX** and **STREX** in the ARMv6 architecture to provide a set of atomic operation APIs.
- LDREX Rx, [Ry]
Reads the value in the memory and marks the exclusive access to the memory segment.
Reads the value in the memory and marks the exclusive access to the memory segment.
- Reads the 4-byte memory data pointed by the register **Ry** and saves the data to the **Rx** register.
- Reads the 4-byte memory data pointed by the register **Ry** and saves the data to the **Rx** register.
- Adds an exclusive access flag to the memory area pointed by **Ry**.
- Adds an exclusive access flag to the memory area pointed by **Ry**.
- STREX Rf, Rx, \[Ry\]
- STREX Rf, Rx, [Ry]
Checks whether the memory has an exclusive access flag. If yes, the system updates the memory value and clears the flag. If no, the memory is not updated.
Checks whether the memory has an exclusive access flag. If yes, the system updates the memory value and clears the flag. If no, the memory is not updated.
- If there is an exclusive access flag, the system:
- If there is an exclusive access flag, the system:
- Updates the **Rx** register value to the memory pointed to by the **Ry** register.
- Updates the **Rx** register value to the memory pointed to by the **Ry** register.
- Sets the **Rf** register to **0**.
- Sets the **Rf** register to **0**.
- If there is no exclusive access flag:
- If there is no exclusive access flag:
- The memory is not updated.
- The memory is not updated.
- The system sets the **Rf** register to **1**.
- The system sets the **Rf** register to **1**.
- Flag register
- Flag register
- If the flag register is **0**, the system exits the loop and the atomic operation is complete.
- If the flag register is **0**, the system exits the loop and the atomic operation is complete.
- If the flag register is **1**, the system continues the loop and performs the atomic operation again.
- If the flag register is **1**, the system continues the loop and performs the atomic operation again.
...
@@ -40,179 +35,66 @@ The OpenHarmony system has encapsulated the **LDREX** and **STREX** in the A
...
@@ -40,179 +35,66 @@ The OpenHarmony system has encapsulated the **LDREX** and **STREX** in the A
## Development Guidelines
## Development Guidelines
### Available APIs
### Available APIs
The following table describes the APIs available for the OpenHarmony LiteOS-A kernel atomic operation module. For more details about the APIs, see the API reference.
The following table describes the APIs available for the OpenHarmony LiteOS-A kernel atomic operation module.
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p59414511172"><aname="p59414511172"></a><aname="p59414511172"></a>Adds 1 to 32-bit atomic data and returns the data.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p1194951111713"><aname="p1194951111713"></a><aname="p1194951111713"></a>Adds 1 to 64-bit atomic data and returns the data.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p198222414349"><aname="p198222414349"></a><aname="p198222414349"></a>Subtracts 1 from 32-bit atomic data and returns the result.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p198221841103419"><aname="p198221841103419"></a><aname="p198221841103419"></a>Subtracts 1 from 64-bit atomic data and returns the result.</p>
<trid="row149616511175"><tdclass="cellrowborder"rowspan="4"valign="top"width="21.21212121212121%"headers="mcps1.2.4.1.1 "><pid="p49615120172"><aname="p49615120172"></a><aname="p49615120172"></a>Compare and swap</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p1296205118179"><aname="p1296205118179"></a><aname="p1296205118179"></a>Compares and swaps 64-bit memory data.</p>
</td>
</tr>
</tbody>
</table>
### How to Develop
### How to Develop
When multiple tasks perform addition, subtraction, and swap operations on the same memory data, use atomic operations to ensure predictability of results.
When multiple tasks perform addition, subtraction, and swap operations on the same memory data, use atomic operations to ensure predictability of results.
An interrupt is a signal to the processor emitted by hardware or software indicating an event that needs immediate attention. An interrupt alerts the processor of a high-priority condition requiring interruption of the code being executed by the processor. In this way, the CPU does not need to spend a lot of time in waiting and querying the peripheral status, which effectively improves the real-time performance and execution efficiency of the system.
An interrupt is a signal to the processor emitted by hardware or software indicating an event that needs immediate attention. An interrupt alerts the processor of a high-priority condition requiring interruption of the code being executed by the processor. In this way, the CPU does not need to spend a lot of time in waiting and querying the peripheral status, which effectively improves the real-time performance and execution efficiency of the system.
Exception handling involves a series of actions taken by the OS to respond to exceptions \(chip hardware faults\) that occurred during the OS running, for example, printing the call stack information of the current function, CPU information, and call stack information of tasks when the virtual memory page is missing.
OpenHarmony supports the following interrupt operations:
## Working Principles<a name="section2792838318"></a>
+ Initializing an interrupt.
+ Creating an interrupt.
+ Enabling or disabling interrupts.
+ Restoring the system status before interrupts are disabled.
+ Deleting an interrupt.
Peripherals can complete certain work without the intervention of the CPU. In some cases, however, the CPU needs to perform certain work for peripherals. With the interrupt mechanism, the CPU responds to the interrupt request from a peripheral only when required, and execute other tasks when the peripherals do not require the CPU. The interrupt controller receives the input of other peripheral interrupt pins and sends interrupt signals to the CPU. You can enable or disable the interrupt source and set the priority and trigger mode of the interrupt source by programming the interrupt controller. Common interrupt controllers include vector interrupt controllers \(VICs\) and general interrupt controllers \(GICs\). The ARM Cortex-A7 uses GICs. After receiving an interrupt signal sent by the interrupt controller, the CPU interrupts the current task to respond to the interrupt request.
Exception handling involves a series of actions taken by the OS to respond to exceptions (chip hardware faults) that occurred during the OS running, for example, printing the call stack information of the current function, CPU information, and call stack information of tasks when the virtual memory page is missing.
Exception handling interrupts the normal running process of the CPU to handle exceptions, such as, undefined instructions, an attempt to modify read-only data, and unaligned address access. When an exception occurs, the CPU suspends the current program, handles the exception, and then continues to execute the program interrupted by the exception.
## Working Principles
Peripherals can complete certain work without the intervention of the CPU. In some cases, however, the CPU needs to perform certain work for peripherals. With the interrupt mechanism, the CPU responds to the interrupt request from a peripheral only when required, and execute other tasks when the peripherals do not require the CPU.
The interrupt controller receives the input from the interrupt pins of other peripherals and sends interrupt signals to the CPU. You can enable or disable the interrupt source and set the priority and trigger mode of the interrupt source by programming the interrupt controller. Common interrupt controllers include vector interrupt controllers (VICs) and general interrupt controllers (GICs). The ARM Cortex-A7 uses GICs.
After receiving an interrupt signal sent by the interrupt controller, the CPU interrupts the current task to respond to the interrupt request.
An exception interrupts the normal running process of the CPU to handle exceptions, such as, undefined instructions, an attempt to modify read-only data, and unaligned address access. When an exception occurs, the CPU suspends the current program, handles the exception, and then continues to execute the program interrupted by the exception.
The following uses the ARMv7-a architecture as an example. The interrupt vector table is the entry for interrupt and exception handling. The interrupt vector table contains the entry function for each interrupt and exception handling.
The following uses the ARMv7-a architecture as an example. The interrupt vector table is the entry for interrupt and exception handling. The interrupt vector table contains the entry function for each interrupt and exception handling.
## Development Guidelines<a name="section15415165510110"></a>
## Development Guidelines
### Available APIs<a name="section57441612024"></a>
Exception handling is an internal mechanism and does not provide external APIs. The following table describes APIs available for the interrupt module.
### Available APIs
<aname="table11657113333110"></a>
Exception handling is an internal mechanism and does not provide external APIs. The following tables describe the APIs available for the interrupt module.
| LOS_HwiCreate | Creates an interrupt and registers the interrupt ID, triggering mode, priority, and interrupt handler. When the interrupt is triggered, the interrupt handler will be called.|
</tr>
| LOS_HwiDelete | Deletes an interrupt based on the interrupt number. |
</thead>
<tbody><trid="row8706123317311"><tdclass="cellrowborder"rowspan="2"valign="top"width="19.900000000000002%"headers="mcps1.1.4.1.1 "><pid="p4706193319318"><aname="p4706193319318"></a><aname="p4706193319318"></a>Creating or deleting interrupts</p>
<tdclass="cellrowborder"valign="top"width="61.67%"headers="mcps1.1.4.1.3 "><pid="p15706833163110"><aname="p15706833163110"></a><aname="p15706833163110"></a>Creates an interrupt and registers the interrupt ID, interrupt triggering mode, interrupt priority, and interrupt handler. When an interrupt is triggered, the interrupt handler will be called.</p>
| LOS_IntUnlock | Enables all interrupts for the current processor. |
</td>
| LOS_IntLock | Disables all interrupts for the current processor. |
</tr>
| LOS_IntRestore | Restores the status in which the system was before **LOS_IntLock** is called.|
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p770616333313"><aname="p770616333313"></a><aname="p770616333313"></a>Deletes an interrupt.</p>
<trid="row1370633316316"><tdclass="cellrowborder"rowspan="3"valign="top"width="19.900000000000002%"headers="mcps1.1.4.1.1 "><pid="p970611333318"><aname="p970611333318"></a><aname="p970611333318"></a>Enabling and disabling all interrupts</p>
| LOS_GetSystemHwiMaximum | Obtains the maximum number of interrupts supported by the system.|
<tdclass="cellrowborder"valign="top"width="61.67%"headers="mcps1.1.4.1.3 "><pid="p93681327171713"><aname="p93681327171713"></a><aname="p93681327171713"></a>Enables all interrupts of the current processor.</p>
2. Call **LOS_HwiDelete** to delete the specified interrupt. Use this API based on actual requirements.
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p1161283971712"><aname="p1161283971712"></a><aname="p1161283971712"></a>Disables all interrupts for the current processor.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p1470643323112"><aname="p1470643323112"></a><aname="p1470643323112"></a>Restores to the status before all interrupts are disabled by using <strongid="b354311504226"><aname="b354311504226"></a><aname="b354311504226"></a>LOS_IntLock</strong>.</p>
</td>
</tr>
<trid="row870793320317"><tdclass="cellrowborder"valign="top"width="19.900000000000002%"headers="mcps1.1.4.1.1 "><pid="p1970763318316"><aname="p1970763318316"></a><aname="p1970763318316"></a>Obtaining the maximum number of interrupts supported</p>
<tdclass="cellrowborder"valign="top"width="61.67%"headers="mcps1.1.4.1.3 "><pid="p4707173323111"><aname="p4707173323111"></a><aname="p4707173323111"></a>Obtains the maximum number of interrupts supported by the system.</p>
</td>
</tr>
</tbody>
</table>
### How to Develop<a name="section64332181221"></a>
1. Call **LOS\_HwiCreate** to create an interrupt.
2. Call **LOS\_HwiDelete** to delete the specified interrupt. Use this API based on actual requirements.
### Development Example<a name="section204698276478"></a>
This example implements the following:
This example implements the following:
1. Create an interrupt.
1. Create an interrupt.
2. Delete an interrupt.
2. Delete an interrupt.
The following sample code shows how to create and delete an interrupt. When the interrupt **HWI\_NUM\_TEST** is generated, the interrupt handler function will be called.
The following sample code demostrates how to create and delete an interrupt, and call the interrupt handler when the specified interrupt **HWI_NUM_TEST** is triggered. You can add the test function of the sample code to **TestTaskEntry** in **kernel/liteos_a/testsuites/kernel/src/osTest.c** for testing.
```
The sample code is as follows:
```c
#include "los_hwi.h"
#include "los_hwi.h"
/* Interrupt handler function*/
/* Interrupt handler function*/
STATICVOIDHwiUsrIrq(VOID)
STATICVOIDHwiUsrIrq(VOID)
{
{
printf("in the func HwiUsrIrq \n");
PRINTK("in the func HwiUsrIrq \n");
}
}
staticUINT32Example_Interrupt(VOID)
staticUINT32Example_Interrupt(VOID)
{
{
UINT32ret;
UINT32ret;
HWI_HANDLE_T hwiNum = 7;
HWI_HANDLE_ThwiNum=7;// The interrupt number is 7.
HWI_PRIOR_T hwiPrio = 3;
HWI_PRIOR_ThwiPrio=3;// The interrupt priority is 3.
A process is the minimum unit for system resource management. The process module provided by the OpenHarmony LiteOS-A kernel is used to isolate user-mode processes. The kernel mode is considered as a process space and does not have other processes except KIdle, which is an idle process provided by the system and shares the same process space with KProcess.
A process is the minimum unit for system resource management. The process module provided by the OpenHarmony LiteOS-A kernel isolates user-mode processes. The kernel mode is considered as a process space and does not have other processes except KIdle, which is an idle process provided by the system and shares the same process space with KProcess. KProcess is the root process of kernel-mode processes, and KIdle is its child process.
- The process module provides multiple processes for users and implements switching and communication between processes, facilitating your management over service programs.
- The process module provides multiple processes for users and implements switching and communication between processes, facilitating your management over service programs.
- The processes use the preemption scheduling mechanism. The processes with a higher priority are scheduled first, and the processes with the same priority are scheduled using the time slice polling.
- The processes are assigned 32 priorities \(**0** to **31**\). Among them, user processes can be configured with 22 priorities from **10**\(highest\) to **31**\(lowest\).
- The processes use the preemption scheduling mechanism. The processes with a higher priority are scheduled first, and the processes with the same priority are scheduled using the time slice round robin.
- The processes are assigned 32 priorities (**0** to **31**). Among them, user processes can be configured with 22 priorities from **10** (highest) to **31** (lowest).
- A higher-priority process can preempt the resources of a lower-priority process. The lower-priority process can be scheduled only after the higher-priority process is blocked or terminated.
- A higher-priority process can preempt the resources of a lower-priority process. The lower-priority process can be scheduled only after the higher-priority process is blocked or terminated.
- Each user-mode process has its own memory space, which is invisible to other processes. In this way, processes are isolated from each other.
- Each user-mode process has its own memory space, which is invisible to other processes. In this way, processes are isolated from each other.
- The user-mode root process **init** is created by the kernel. Other user-mode processes are created by the **init** process via the **fork** call.
- The user-mode root process **init** is created by the kernel. Other user-mode processes are created by the **init** process via the **fork** call.
**Process States:**
**Process States**
- Init: The process is being created.
- Init: The process is being created.
- Ready: The process is in the Ready queue and waits for scheduling by the CPU.
- Ready: The process is in the Ready queue and waits for scheduling by the CPU.
- Running: The process is running.
- Running: The process is running.
- Pending: The process is blocked and suspended. When all threads in a process are blocked, the process is blocked and suspended.
- Pending: The process is blocked and suspended. When all threads in a process are blocked, the process is blocked and suspended.
- Zombies: The process stops running and waits for the parent process to reclaim its control block resources.
- Zombies: The process stops running and waits for the parent process to reclaim its control block resources.
**Figure 1** Process state transition<aname="fig536823565718"></a>
When a process is created, the process enters the Init state after obtaining the process control block to start initialization. After the process is initialized, the process is inserted into the scheduling queue and therefore enters the Ready state.
- Init→Ready:
When a process is created or forked, the process enters the Init state after obtaining the process control block. When the process initialization is complete, the process is added to the scheduling queue, and the process enters the Ready state.
- Ready→Running:
- Ready→Running:
When process switching occurs, the process that has the highest priority and time slice in the Ready queue is executed and enters the Running state. If this process has no thread in the Ready state, the process is deleted from the Ready queue and resides only in the Running state. If it has threads in the Ready state, the process still stays in the Ready queue. In this case, the process is in both the Ready and Running states, but presented as the Running state.
When a process switchover is triggered, the process with the highest priority in the Ready queue is executed and enters the Running state. If this process has no thread in the Ready state, the process is deleted from the Ready queue and resides only in the Running state. If it has threads in the Ready state, the process still stays in the Ready queue. In this case, the process is in both the Ready and Running states, but presented as the Running state.
- Running→Pending:
- Running→Pending:
When the last thread of a process enters the Pending state, all threads in the process are in the Pending state. Then, the process enters the Pending state, and process switching occurs.
When the last thread of a process enters the Pending state, all threads in the process are in the Pending state. Then, the process enters the Pending state, and process switching occurs.
- Pending→Ready:
- Pending→Ready:
When any thread in a Pending process restores to the Ready state, the process is added to the Ready queue and changes to the Ready state.
When any thread in a Pending process restores to the Ready state, the process is added to the Ready queue and changes to the Ready state.
- Ready→Pending:
- Ready→Pending:
When the last ready thread in a process enters the Pending state, the process is deleted from the Ready queue, and the process changes from the Ready state to the Pending state.
When the last ready thread in a process enters the Pending state, the process is deleted from the Ready queue, and the process changes from the Ready state to the Pending state.
- Running→Ready:
- Running→Ready:
A process may change from the Running state to the Ready state in either of the following scenarios:
A process may change from the Running state to the Ready state in either of the following scenarios:
1. After a process with a higher priority is created or restored, processes will be scheduled. The process with the highest priority in the Ready queue will change to the Running state, and the originally running process will change from the Running state to the Ready state.
1. After a process with a higher priority is created or restored, processes will be scheduled. The process with the highest priority in the Ready queue will change to the Running state, and the originally running process will change from the Running state to the Ready state.
2. If scheduling policy for a process is **LOS\_SCHED\_RR** and its priority is the same as that of another process in the Ready state, this process will change from the Running state to the Ready state after its time slices are used up, and the other process with the same priority will change from the Ready state to the Running state.
2. If scheduling policy for a process is **LOS_SCHED_RR** (time slice round robin) and its priority is the same as that of another process in the Ready state, this process will change from the Running state to the Ready state after its time slices are used up, and the other process with the same priority will change from the Ready state to the Running state.
- Running→Zombies:
- Running→Zombies:
After the main thread or all threads of a process are stopped, the process changes from the **Running** state to the **Zombies** state and waits for the parent process to reclaim resources.
After the main thread or all threads of a process are stopped, the process changes from the **Running** state to the **Zombies** state and waits for the parent process to reclaim resources.
## Working Principles<a name="section174514474512"></a>
## Working Principles
The OpenHarmony process module is used to isolate user-mode processes and supports the following functions: creating and exiting user-mode processes, reclaiming process resources, setting and obtaining scheduling parameters and process group IDs, and obtaining process IDs.
The OpenHarmony process module is used to isolate user-mode processes and supports the following functions: creating and exiting user-mode processes, reclaiming process resources, setting and obtaining scheduling parameters and process group IDs, and obtaining process IDs.
...
@@ -66,105 +68,65 @@ A user-mode process is created by forking a parent process. During forking, the
...
@@ -66,105 +68,65 @@ A user-mode process is created by forking a parent process. During forking, the
A process is only a resource management unit, and the actual running is executed by threads in the process. When switching occurs between threads in different processes, the process space will be switched.
A process is only a resource management unit, and the actual running is executed by threads in the process. When switching occurs between threads in different processes, the process space will be switched.
**Figure 2** Process management<aname="fig123709256334"></a>
| LOS_GetUserID | Obtains the user ID of the current process. |
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p205724410813"><aname="p205724410813"></a><aname="p205724410813"></a>Obtains the scheduling policy of the specified process.</p>
| LOS_GetGroupID | Obtains the user group ID of the current process. |
</td>
| LOS_CheckInGroups | Checks whether the specified user group ID is in the user group of the current process.|
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p18572443819"><aname="p18572443819"></a><aname="p18572443819"></a>Sets the scheduling parameters, including the priority and scheduling policy, for the specified process.</p>
| LOS_SetProcessScheduler | Sets scheduling parameters, including the priority and scheduling policy, for a process.|
</td>
| LOS_SetProcessPriority | Sets the process priority. |
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p95710448818"><aname="p95710448818"></a><aname="p95710448818"></a>Obtains the priority of the specified process.</p>
| LOS_GetProcessPriority | Obtains the priority of a process. |
</td>
</tr>
**Table 4** APIs for obtaining system process information
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p16573445819"><aname="p16573445819"></a><aname="p16573445819"></a>Sets the priority of the specified process.</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p5578441687"><aname="p5578441687"></a><aname="p5578441687"></a>Waits for the specified child process to terminate, and reclaims its resources.</p>
| ---------- | -------------------------- |
</td>
| LOS_Fork | Creates a child process. |
</tr>
| LOS_Wait | Waits for the child process to terminate, and reclaims its resources.|
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p145704416818"><aname="p145704416818"></a><aname="p145704416818"></a>Obtains the process group ID of the specified process.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p165816445819"><aname="p165816445819"></a><aname="p165816445819"></a>Obtains the process group ID of the current process.</p>
</td>
</tr>
<trid="row1260011213718"><tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p125818441781"><aname="p125818441781"></a><aname="p125818441781"></a>Obtaining the process ID.</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p1058644687"><aname="p1058644687"></a><aname="p1058644687"></a>Obtains the ID of the current process.</p>
</td>
</tr>
<trid="row060019121871"><tdclass="cellrowborder"rowspan="3"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p145810441285"><aname="p145810441285"></a><aname="p145810441285"></a>User and user group</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p7581944287"><aname="p7581944287"></a><aname="p7581944287"></a>Obtains the user ID of the current process.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p3581444382"><aname="p3581444382"></a><aname="p3581444382"></a>Obtains the user group ID of the current process.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p5581144689"><aname="p5581144689"></a><aname="p5581144689"></a>Checks whether the specified user group ID is in the user group of the current process.</p>
</td>
</tr>
<trid="row317461111812"><tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p105814419818"><aname="p105814419818"></a><aname="p105814419818"></a>Maximum number of processes supported</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p115818441187"><aname="p115818441187"></a><aname="p115818441187"></a>Obtains the maximum number of processes supported by the system.</p>
</td>
</tr>
</tbody>
</table>
### How to Develop<a name="section1533674618526"></a>
Kernel-mode processes cannot be created. Therefore, kernel-mode process development is not involved.
Kernel-mode processes cannot be created. Therefore, kernel-mode process development is not involved.
>- The number of idle threads depends on the number of CPU cores. Each CPU has a corresponding idle thread.
>
> - The number of idle threads depends on the number of CPU cores. Each CPU has a corresponding idle thread.
>- Except KProcess and KIdle, other kernel-mode processes cannot be created.
>- Except KProcess and KIdle, other kernel-mode processes cannot be created.
>- If a thread is created after a user-mode process enters the kernel mode by a system call, the thread belongs to a KProcess not a user-mode process.
> - If a thread is created after a user-mode process enters the kernel mode by a system call, the thread belongs to a KProcess not a user-mode process.
The OpenHarmony LiteOS-A kernel uses the preemptive scheduling mechanism for tasks. The tasks with a higher priority are scheduled first, and the tasks with the same priority are scheduled using the time slice polling. The system runs based on the real-time timeline from the startup, which ensures good real-time performance of the scheduling algorithm.
The OpenHarmony LiteOS-A kernel uses the preemptive scheduling mechanism for tasks. The tasks with a higher priority are scheduled first, and the tasks with the same priority are scheduled using the time slice polling. The system runs based on the real-time timeline from the startup, which ensures good real-time performance of the scheduling algorithm.
The OpenHarmony scheduling algorithm is embedded with the tickless mechanism, which ensures lower power consumption and on-demand response to tick interrupts. This minimizes useless tick interrupt response time and further improves the real-time performance of the system.
The OpenHarmony scheduling algorithm is embedded with the tickless mechanism, which ensures lower power consumption and on-demand response to tick interrupts. This minimizes useless tick interrupt response time and further improves the real-time performance of the system.
The OpenHarmony process scheduling policy is **SCHED\_RR**, and the thread scheduling policy can be **SCHED\_RR** or **SCHED\_FIFO**.
OpenHarmony supports **SCHED_RR** (time slice round robin) for process scheduling and **SCHED_RR** and **SCHED_FIFO** (first in, first out) for thread scheduling .
Threads are the minimum scheduling units in the OpenHarmony.
Threads are the minimum scheduling units in OpenHarmony.
## Working Principles<a name="section143015396572"></a>
The OpenHarmony uses process priority queue and thread priority queue for scheduling. The process priority ranges from 0 to 31, and there are 32 process priority bucket queues. Each bucket queue corresponds to a thread priority bucket queue. The thread priority ranges from 0 to 31, and a thread priority bucket queue also has 32 priority queues.
## Working Principles
OpenHarmony uses process priority queue and thread priority queue for scheduling. The process priority ranges from 0 to 31, and there are 32 process priority bucket queues. Each bucket queue corresponds to a thread priority bucket queue. The thread priority ranges from 0 to 31, and a thread priority bucket queue also has 32 priority queues.
The OpenHarmony system starts scheduling after the kernel initialization is complete. The processes or threads created during running are added to the scheduling queues. The system selects the optimal thread for scheduling based on the priorities of the processes and threads and the time slice consumption of the threads. Once a thread is scheduled, it is deleted from the scheduling queue. If a thread is blocked during running, the thread is added to the corresponding blocking queue and triggers scheduling of another thread. If no thread in the scheduling queue can be scheduled, the system selects the thread of the KIdle process for scheduling.
The OpenHarmony system starts scheduling after the kernel initialization is complete. The processes or threads created during running are added to the scheduling queues. The system selects the optimal thread for scheduling based on the priorities of the processes and threads and the time slice consumption of the threads. Once a thread is scheduled, it is deleted from the scheduling queue. If a thread is blocked during running, the thread is added to the corresponding blocking queue and triggers scheduling of another thread. If no thread in the scheduling queue can be scheduled, the system selects the thread of the KIdle process for scheduling.
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.1.4.1.3 "><pid="p181303297387"><aname="p181303297387"></a><aname="p181303297387"></a>Triggers system scheduling.</p>
</td>
</tr>
</tbody>
</table>
### How to Develop<a name="section1015110331584"></a>
Tasks are the minimum running units that compete for system resources. They can use or wait to use CPUs and use system resources such as memory. They run independently from one another.
Tasks are the minimum running units that compete for system resources. They can use or wait to use CPUs and use system resources such as memory. They run independently from one another.
In the OpenHarmony kernel, a task represents a thread.
In the OpenHarmony kernel, a task represents a thread.
Tasks in the processes of the same priority in the OpenHarmony kernel are scheduled and run in a unified manner.
Tasks for the processes of the same priority in the OpenHarmony kernel are scheduled and run in a unified manner.
The tasks in the kernel use the preemptive scheduling mechanism, either round-robin \(RR\) scheduling or First In First Out \(FIFO\) scheduling.
The tasks in the kernel use the preemptive scheduling mechanism, either round-robin (RR) scheduling or First In First Out (FIFO) scheduling.
Tasks are assigned 32 priorities, ranging from **0**\(highest\) to **31**\(lowest\).
Tasks are assigned 32 priorities, ranging from **0** (highest) to **31** (lowest).
In the same process, a higher-priority task can preempt resources of a lower-priority task. The lower-priority task can be scheduled only after the higher-priority task is blocked or terminated.
In the same process, a higher-priority task can preempt resources of a lower-priority task. The lower-priority task can be scheduled only after the higher-priority task is blocked or terminated.
**Task Status Description**
**Task States**
- Init: The task is being created.
- Init: The task is being created.
- Ready: The task is in the Ready queue and waits for scheduling by the CPU.
- Ready: The task is in the Ready queue and waits for scheduling by the CPU.
- Running: The task is running.
- Running: The task is running.
- Blocked: The task is blocked and suspended. The Blocked states include pending \(blocked due to lock, event, or semaphore issues\), suspended \(active pending\), delay \(blocked due to delays\), and pendtime \(blocked by waiting timeout of locks, events, or semaphores\).
- Blocked: The task is blocked and suspended. The Blocked states include pending (blocked due to lock, event, or semaphore issues), suspended (active pending), delay (blocked due to delays), and pendtime (blocked by waiting timeout of locks, events, or semaphores).
- Exit: The task is complete and waits for the parent task to reclaim its control block resources.
- Exit: The task is complete and waits for the parent task to reclaim its control block resources.
**Figure 1** Task state transition<aname="fig5251243193113"></a>
When a task is created, the task obtains the control block and enters the Init state (initialization). After the initialization is complete, the task is inserted into the scheduling queue and enters the Ready state.
When a task is created, the task obtains the control block and enters the Init state \(initialization\). After the initialization is complete, the task is inserted into the scheduling queue and enters the Ready state.
- Ready→Running:
- Ready→Running:
When a task switching is triggered, the task with the highest priority in the Ready queue is executed and enters the Running state. Then, this task is deleted from the Ready queue.
When a task switching is triggered, the task with the highest priority in the Ready queue is executed and enters the Running state. Then, this task is deleted from the Ready queue.
- Running→Blocked:
- Running→Blocked:
When a running task is blocked (for example, is pended, delayed, or reading semaphores), its state changes from Running to Blocked. Then, a task switching is triggered to run the task with the highest priority in the Ready queue.
When a running task is blocked \(for example, is pended, delayed, or reading semaphores\), its state changes from Running to Blocked. Then, a task switching is triggered to run the task with the highest priority in the Ready queue.
- Blocked→Ready:
- Blocked→Ready:
After the blocked task is restored (the task is restored, the delay times out, the semaphore reading times out, or the semaphore is read), the task is added to the Ready queue and will change from the Blocked state to the Ready state.
After the blocked task is restored \(the task is restored, the delay times out, the semaphore reading times out, or the semaphore is read\), the task is added to the Ready queue and will change from the Blocked state to the Ready state.
- Ready→Blocked:
- Ready→Blocked:
When a task in the Ready state is blocked (suspended), the task changes to the Blocked state and is deleted from the Ready queue. The blocked task will not be scheduled until it is recovered.
When a task in the Ready state is blocked \(suspended\), the task changes to the Blocked state and is deleted from the Ready queue. The blocked task will not be scheduled until it is recovered.
- Running→Ready:
- Running→Ready:
When a task with a higher priority is created or recovered, tasks will be scheduled. The task with the highest priority in the Ready queue changes to the Running state. The originally running task changes to the Ready state and is added to the Ready queue.
When a task with a higher priority is created or recovered, tasks will be scheduled. The task with the highest priority in the Ready queue changes to the Running state. The originally running task changes to the Ready state and is added to the Ready queue.
- Running→Exit:
- Running→Exit:
When a running task is complete, it changes to the Exit state. If the task has a detach attribute (set by **LOS_TASK_STATUS_DETACHED** in **los_task.h**), it will be destroyed directly.
When a running task is complete, it changes to the Exit state. If the task is set with a detach attribute \(**LOS\_TASK\_STATUS\_DETACHED**\), it will be directly destroyed after being terminated.
## Working Principles<a name="section1381918945512"></a>
## Working Principles
The OpenHarmony task management module provides the following functions: creating, delaying, suspending, and restoring tasks, locking and unlocking task scheduling, and querying task control block information by ID.
The OpenHarmony task management module provides the following functions: creating, delaying, suspending, and restoring tasks, locking and unlocking task scheduling, and querying task control block information by ID.
When a task is created, the system initializes the task stack and presets the context. The system also places the task entry function in the corresponding position so that the function can be executed when the task enters the running state for the first time.
When a user creates a task, the system initializes the task stack and presets the context. The system places the task entry function in the corresponding position so that the function can be executed when the task enters the running state for the first time.
## Development Guidelines<a name="section10649727135519"></a>
## Development Guidelines
### Available APIs<a name="section78333315555"></a>
| LOS_TaskCreate | Creates a task. If the priority of the created task is higher than that of the task in running and task scheduling is not locked, the task will be scheduled to run. |
</tr>
| LOS_TaskCreateOnly | Creates a task and blocks it. The task will not be added to the Ready queue unless it is resumed. |
</thead>
| LOS_TaskDelete | Deletes a task and reclaims the resources consumed by the task control block and task stack. |
<tbody><trid="row431611256303"><tdclass="cellrowborder"rowspan="3"valign="top"width="33.33333333333333%"headers="mcps1.1.4.1.1 "><pid="p0297202573015"><aname="p0297202573015"></a><aname="p0297202573015"></a>Task creation and deletion</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.1.4.1.3 "><pid="p12297825123016"><aname="p12297825123016"></a><aname="p12297825123016"></a>Creates a task and places the task in the Init state without scheduling.</p>
| LOS_TaskJoin | Blocks the current task until the specified task is complete, and reclaims its resources. |
</td>
| LOS_TaskDetach | Changes the task attribute from **joinable** to **detach**. When a task of the **detach** attribute is complete, the task control block resources will be automatically reclaimed.|
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p19297122518303"><aname="p19297122518303"></a><aname="p19297122518303"></a>Creates a task and places it in the Init state for scheduling.</p>
| LOS_TaskDelay | Delays the current task for the specified time (number of ticks). |
</td>
| LOS_TaskYield | Moves the current task from the queue of the tasks with the same priority to the end of the Ready queue.|
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p3297162517308"><aname="p3297162517308"></a><aname="p3297162517308"></a>Deletes the specified task.</p>
<trid="row13316112533020"><tdclass="cellrowborder"rowspan="6"valign="top"width="33.33333333333333%"headers="mcps1.1.4.1.1 "><pid="p172979255306"><aname="p172979255306"></a><aname="p172979255306"></a>Task status control</p>
| LOS_TaskUnlock | Unlocks task scheduling. After that, the task lock count decrements by 1. If a task is locked multiple times, the task can be scheduled only when the number of locks is reduced to 0. |
</td>
| LOS_GetTaskScheduler | Obtains the scheduling policy of a task. |
| LOS_SetTaskScheduler | Sets the scheduling parameters, including the priority and scheduling policy, for a task. |
</td>
| LOS_Schedule | Triggers active task scheduling. |
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.1.4.1.3 "><pid="p1929732593018"><aname="p1929732593018"></a><aname="p1929732593018"></a>Resumes a suspended task.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p8297182563015"><aname="p8297182563015"></a><aname="p8297182563015"></a>Suspends the specified task.</p>
| LOS_CurTaskIDGet | Obtains the ID of the current task. |
</td>
| LOS_TaskInfoGet | Obtains task information. |
</tr>
| LOS_GetSystemTaskMaximum | Obtains the maximum number of tasks supported by the system.|
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p28851313104213"><aname="p28851313104213"></a><aname="p28851313104213"></a>Suspends this task till the specified task is complete and the task control block resources are reclaimed.</p>
| LOS_CurTaskPriSet | Sets a priority for the current task.|
</td>
| LOS_TaskPriSet | Sets a priority for a task. |
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p188851813184219"><aname="p188851813184219"></a><aname="p188851813184219"></a>Changes the task attribute from <strongid="b1986175411125"><aname="b1986175411125"></a><aname="b1986175411125"></a>joinable</strong> to <strongid="b18996959101215"><aname="b18996959101215"></a><aname="b18996959101215"></a>detach</strong>. After the task of the <strongid="b15851429171317"><aname="b15851429171317"></a><aname="b15851429171317"></a>detach</strong> attribute is complete, the task control block resources will be automatically reclaimed.</p>
| LOS_TaskPriGet | Obtains the priority of a task. |
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p1297182517306"><aname="p1297182517306"></a><aname="p1297182517306"></a>Delays a task.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p2297325163019"><aname="p2297325163019"></a><aname="p2297325163019"></a>Adjusts the scheduling sequence of tasks that call the task priority.</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.1.4.1.3 "><pid="p142981925183020"><aname="p142981925183020"></a><aname="p142981925183020"></a>Sets the priority for the current task.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p629822563014"><aname="p629822563014"></a><aname="p629822563014"></a>Sets the priority for a specified task.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p19298182563018"><aname="p19298182563018"></a><aname="p19298182563018"></a>Obtains the priority of a specified task.</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.1.4.1.3 "><pid="p1029842519303"><aname="p1029842519303"></a><aname="p1029842519303"></a>Obtains the ID of the current task.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p122988259303"><aname="p122988259303"></a><aname="p122988259303"></a>Obtains information about the specified task.</p>
</td>
</tr>
<trid="row93146250305"><tdclass="cellrowborder"rowspan="2"valign="top"width="33.33333333333333%"headers="mcps1.1.4.1.1 "><pid="p82986256300"><aname="p82986256300"></a><aname="p82986256300"></a>Binding tasks to CPU cores</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.1.4.1.3 "><pid="p82981925163013"><aname="p82981925163013"></a><aname="p82981925163013"></a>Binds a specified task to the specified CPU. It is used only in multi-core scenarios.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p1729822513017"><aname="p1729822513017"></a><aname="p1729822513017"></a>Obtains the core binding information of the specified task. It is used only in multi-core scenarios.</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.1.4.1.3 "><pid="p1298182513010"><aname="p1298182513010"></a><aname="p1298182513010"></a>Obtains the scheduling policy of the specified task.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p11298172553015"><aname="p11298172553015"></a><aname="p11298172553015"></a>Sets the scheduling parameters, including the priority and scheduling policy, for the specified task.</p>
</td>
</tr>
<trid="row831492514307"><tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.1.4.1.1 "><pid="p12981250307"><aname="p12981250307"></a><aname="p12981250307"></a>Maximum number of tasks supported</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.1.4.1.3 "><pid="p6298525123017"><aname="p6298525123017"></a><aname="p6298525123017"></a>Obtains the maximum number of tasks supported by the system.</p>
</td>
</tr>
</tbody>
</table>
### How to Develop<a name="section16229657115514"></a>
The typical task development process is as follows:
The typical task development process is as follows:
1. Call **LOS\_TaskCreate** to create a task.
1.Call **LOS_TaskCreate** to create a task.
- Specify the execution entry function for the task.
- Specify the execution entry function for the task.
- Specifies the task name.
- Specifies the task name.
- Specify the task stack size.
- Specify the task stack size.
- Specify the priority of the task.
- Specify the priority of the task.
- Specify the task attribute, which can be **LOS\_TASK\_ATTR\_JOINABLE** or **LOS\_TASK\_STATUS\_DETACHED**.
- Specify the task attribute, which can be **LOS_TASK_ATTR_JOINABLE** or **LOS_TASK_STATUS_DETACHED**.
- Specify the task-core binding attribute for multi-core environment.
- Specify the task-core binding attribute for multi-core environment.
2. Run the service code to implement task scheduling.
2. Run the service code to implement task scheduling.
3. Reclaim resources when the task is complete. If the task attribute is **LOS\_TASK\_STATUS\_DETACHED**, the task resources are automatically reclaimed. If the task attribute is **LOS\_TASK\_ATTR\_JOINABLE**, call **LOS\_TaskJoin** to reclaim task resources. The default task attribute is **LOS\_TASK\_STATUS\_DETACHED**.
3. Reclaim resources when the task is complete. If the task attribute is **LOS_TASK_STATUS_DETACHED**, the task resources are automatically reclaimed. If the task attribute is **LOS_TASK_ATTR_JOINABLE**, call **LOS_TaskJoin** to reclaim task resources. The default task attribute is **LOS_TASK_STATUS_DETACHED**.
>- The kernel mode has the highest permission and can operate tasks in any process.
>- If a task is created after a user-mode process enters the kernel mode by a system call, the task belongs to a KProcess not a user-mode process.
### Development Example<a name="section2809723165612"></a>
> **NOTE**
>
> - The kernel mode has the highest permission and can operate tasks in any process.
>
> - If a task is created after a user-mode process enters the kernel mode by a system call, the task belongs to a KProcess not a user-mode process.
The sample code is as follows:
```
### Development Example
The sample code is as follows. You can add the test function of the sample code to **TestTaskEntry** in **kernel/liteos_a/testsuites/kernel/src /osTest.c** for testing
```c
UINT32g_taskLoID;
UINT32g_taskLoID;
UINT32g_taskHiID;
UINT32g_taskHiID;
#define TSK_PRIOR_HI 4
#define TSK_PRIOR_HI 4
...
@@ -231,15 +158,15 @@ UINT32 ExampleTaskHi(VOID)
...
@@ -231,15 +158,15 @@ UINT32 ExampleTaskHi(VOID)
{
{
UINT32ret;
UINT32ret;
PRINTK("Enter TaskHi Handler.\n");
PRINTK("Enter TaskHi Handler.\n");
/* Delay the task for 2 ticks. The task is then suspended, and the remaining task with the highest priority (g_taskLoID) will be executed.*/
/* Delay the task for 2 ticks. The task is suspended, and the remaining task with the highest priority (g_taskLoID) will be executed. */
ret=LOS_TaskDelay(2);
ret=LOS_TaskDelay(2);
if(ret!=LOS_OK){
if(ret!=LOS_OK){
PRINTK("Delay Task Failed.\n");
PRINTK("Delay Task Failed.\n");
returnLOS_NOK;
returnLOS_NOK;
}
}
/* After 2 ticks elapse, the task is resumed and executed.*/
/* After 2 ticks elapse, the task is resumed and executed.*/
PRINTK("TaskHi LOS_TaskDelay Done.\n");
PRINTK("TaskHi LOS_TaskDelay Done.\n");
/* Suspend the task.*/
/* Suspend the task.*/
ret=LOS_TaskSuspend(g_taskHiID);
ret=LOS_TaskSuspend(g_taskHiID);
if(ret!=LOS_OK){
if(ret!=LOS_OK){
PRINTK("Suspend TaskHi Failed.\n");
PRINTK("Suspend TaskHi Failed.\n");
...
@@ -249,19 +176,19 @@ UINT32 ExampleTaskHi(VOID)
...
@@ -249,19 +176,19 @@ UINT32 ExampleTaskHi(VOID)
returnLOS_OK;
returnLOS_OK;
}
}
/* Entry function of the lower-priority task */
/* Entry function of the low-priority task. */
UINT32ExampleTaskLo(VOID)
UINT32ExampleTaskLo(VOID)
{
{
UINT32ret;
UINT32ret;
PRINTK("Enter TaskLo Handler.\n");
PRINTK("Enter TaskLo Handler.\n");
/* Delay the task for 2 ticks. The task is then suspended, and the remaining task with the highest priority (background task) will be executed.*/
/* Delay the task for 2 ticks. The task is suspended, and the remaining task with the highest priority (background task) will be executed. */
ret=LOS_TaskDelay(2);
ret=LOS_TaskDelay(2);
if(ret!=LOS_OK){
if(ret!=LOS_OK){
PRINTK("Delay TaskLo Failed.\n");
PRINTK("Delay TaskLo Failed.\n");
returnLOS_NOK;
returnLOS_NOK;
}
}
PRINTK("TaskHi LOS_TaskSuspend Success.\n");
PRINTK("TaskHi LOS_TaskSuspend Success.\n");
/* Resume the suspended task g_taskHiID.*/
/* Resume the suspended task g_taskHiID.*/
ret=LOS_TaskResume(g_taskHiID);
ret=LOS_TaskResume(g_taskHiID);
if(ret!=LOS_OK){
if(ret!=LOS_OK){
PRINTK("Resume TaskHi Failed.\n");
PRINTK("Resume TaskHi Failed.\n");
...
@@ -270,22 +197,23 @@ UINT32 ExampleTaskLo(VOID)
...
@@ -270,22 +197,23 @@ UINT32 ExampleTaskLo(VOID)
PRINTK("TaskHi LOS_TaskDelete Success.\n");
PRINTK("TaskHi LOS_TaskDelete Success.\n");
returnLOS_OK;
returnLOS_OK;
}
}
/* Task test entry function, which is used to create two tasks with different priorities.*/
/* Create two tasks with different priorities in the task test entry function. */
UINT32ExampleTaskCaseEntry(VOID)
UINT32ExampleTaskCaseEntry(VOID)
{
{
UINT32ret;
UINT32ret;
TSK_INIT_PARAM_SinitParam={0};
TSK_INIT_PARAM_SinitParam={0};
/* Lock task scheduling.*/
/* Lock task scheduling.*/
LOS_TaskLock();
LOS_TaskLock();
PRINTK("LOS_TaskLock() Success!\n");
PRINTK("LOS_TaskLock() Success!\n");
/* Parameters used to initialize the high-priority task, the resources of which can be reclaimed by LOS_TaskJoin. */
The software timer is a software-simulated timer based on system tick interrupts. When the preset tick counter value has elapsed, the user-defined callback will be invoked. The timing precision is related to the cycle of the system tick clock. Due to the limitation in hardware, the number of hardware timers cannot meet users' requirements. Therefore, the OpenHarmony LiteOS-A kernel provides the software timer function. The software timer allows more timing services to be created, increasing the number of timers.
The software timer is a software-simulated timer based on system tick interrupts. When the preset tick counter value has elapsed, the user-defined callback will be invoked. The timing precision is related to the cycle of the system tick clock.
Due to the limitation in hardware, the number of hardware timers cannot meet users' requirements. The OpenHarmony LiteOS-A kernel provides the software timer function.
The software timer allows more timing services to be created, increasing the number of timers.
The software timer supports the following functions:
The software timer supports the following functions:
- Disabling the software timer using a macro
- Disabling the software timer using a macro
- Creating a software timer
- Creating a software timer
- Starting a software timer
- Starting a software timer
- Stopping a software timer
- Stopping a software timer
- Deleting a software timer
- Deleting a software timer
- Obtaining the number of remaining ticks of a software timer
- Obtaining the number of remaining ticks of a software timer
## Working Principles<a name="section31079397569"></a>
The software timer is a system resource. When modules are initialized, a contiguous section of memory is allocated for software timers. The maximum number of timers supported by the system is configured by the **LOSCFG\_BASE\_CORE\_SWTMR\_LIMIT** macro in **los\_config.h**. Software timers use a queue and a task resource of the system. The software timers are triggered based on the First In First Out \(FIFO\) rule. For the timers set at the same time, the timer with a shorter value is always closer to the queue head than the timer with a longer value, and is preferentially triggered. The software timer counts time in ticks. When a software timer is created and started, the OpenHarmony system determines the timer expiry time based on the current system time \(in ticks\) and the timing interval set by the user, and adds the timer control structure to the global timing list.
## Working Principles
When a tick interrupt occurs, the tick interrupt handler scans the global timing list for expired timers. If such timers are found, the timers are recorded.
The software timer is a system resource. When modules are initialized, a contiguous section of memory is allocated for software timers. The maximum number of timers supported by the system is configured by the **LOSCFG_BASE_CORE_SWTMR_LIMIT** macro in **los_config.h**.
When the tick interrupt handling function is complete, the software timer task \(with the highest priority\) is woken up. In this task, the timeout callback function for the recorded timer is called.
Software timers use a queue and a task resource of the system. The software timers are triggered based on the First In First Out (FIFO) rule. For the timers set at the same time, the timer with a shorter value is always closer to the queue head than the timer with a longer value, and is preferentially triggered.
Timer States
The software timer counts time in ticks. When a software timer is created and started, the OpenHarmony system determines the timer expiry time based on the current system time (in ticks) and the timing interval set by the user, and adds the timer control structure to the global timing list.
- OS\_SWTMR\_STATUS\_UNUSED
When a tick interrupt occurs, the tick interrupt handler scans the global timing list for expired timers. If such timers are found, the timers are recorded.
The timer is not in use. When the timer module is initialized, all timer resources in the system are set to this state.
When the tick interrupt handler is complete, the software timer task (with the highest priority) will be woken up. In this task, the timeout callback for the recorded timer is called.
- OS\_SWTMR\_STATUS\_CREATED
A software timer can be in any of the following states:
The timer is created but not started or the timer is stopped. When **LOS\_SwtmrCreate** is called for a timer that is not in use or **LOS\_SwtmrStop** is called for a newly started timer, the timer changes to this state.
- OS_SWTMR_STATUS_UNUSED
- OS\_SWTMR\_STATUS\_TICKING
The timer is not in use. When the timer module is initialized, all timer resources in the system are set to this state.
- OS_SWTMR_STATUS_CREATED
The timer is running \(counting\). When **LOS\_SwtmrStart** is called for a newly created timer, the timer enters this state.
The timer is created but not started or the timer is stopped. When **LOS_SwtmrCreate** is called for a timer that is not in use or **LOS_SwtmrStop** is called for a newly started timer, the timer changes to this state.
- OS_SWTMR_STATUS_TICKING
Timer Modes
The timer is running (counting). When **LOS_SwtmrStart** is called for a newly created timer, the timer enters this state.
The OpenHarmony provides three types of software timers:
OpenHarmony provides three types of software timers:
- One-shot timer: Once started, the timer is automatically deleted after triggering only one timer event.
- One-shot timer: Once started, the timer is automatically deleted after triggering only one timer event.
- Periodic timer: This type of timer periodically triggers timer events until it is manually stopped.
- Periodic timer: This type of timer periodically triggers timer events until it is manually stopped.
- One-shot timer deleted by calling an API
- One-shot timer deleted by calling an API
## Development Guidelines<a name="section18576131520577"></a>
## Development Guidelines
### Available APIs<a name="section3138019145719"></a>
The following table describes APIs available for the OpenHarmony LiteOS-A software timer module. For more details about the APIs, see the API reference.
### Available APIs
**Table 1** Software timer APIs
The following table describes the APIs of the software timer module of the OpenHarmony LiteOS-A kernel.
| Starting or stopping a timer | **LOS_SwtmrStart**: starts a software timer.<br>**LOS_SwtmrStop**: stops a software timer.|
</th>
| Obtaining remaining ticks of a software timer| **LOS_SwtmrTimeGet**: obtains the remaining ticks of a software timer. |
</tr>
</thead>
<tbody><trid="row1470413222429"><tdclass="cellrowborder"rowspan="2"valign="top"width="20.6020602060206%"headers="mcps1.2.4.1.1 "><pid="p8284115918428"><aname="p8284115918428"></a><aname="p8284115918428"></a>Creating or deleting timers</p>
<tdclass="cellrowborder"valign="top"width="49.85498549854985%"headers="mcps1.2.4.1.3 "><pid="p170422234213"><aname="p170422234213"></a><aname="p170422234213"></a>Creates a software timer.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p870442211421"><aname="p870442211421"></a><aname="p870442211421"></a>Deletes a software timer.</p>
</td>
</tr>
<trid="row57041422184215"><tdclass="cellrowborder"rowspan="2"valign="top"width="20.6020602060206%"headers="mcps1.2.4.1.1 "><pid="p1476172124318"><aname="p1476172124318"></a><aname="p1476172124318"></a>Starting or stopping timers</p>
<tdclass="cellrowborder"valign="top"width="49.85498549854985%"headers="mcps1.2.4.1.3 "><pid="p1570412229421"><aname="p1570412229421"></a><aname="p1570412229421"></a>Starts a software timer.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p17705122211426"><aname="p17705122211426"></a><aname="p17705122211426"></a>Stops a software timer.</p>
</td>
</tr>
<trid="row12705222154214"><tdclass="cellrowborder"valign="top"width="20.6020602060206%"headers="mcps1.2.4.1.1 "><pid="p0705622134214"><aname="p0705622134214"></a><aname="p0705622134214"></a>Obtaining remaining ticks of a software timer</p>
<tdclass="cellrowborder"valign="top"width="49.85498549854985%"headers="mcps1.2.4.1.3 "><pid="p3705122264210"><aname="p3705122264210"></a><aname="p3705122264210"></a>Obtains the number of remaining ticks of a software timer.</p>
</td>
</tr>
</tbody>
</table>
### How to Develop<a name="section1344817403575"></a>
The typical development process of software timers is as follows:
The typical development process of software timers is as follows:
1. Configure the software timer.
1. Configure the software timer.
- Check that **LOSCFG\_BASE\_CORE\_SWTMR** and **LOSCFG\_BASE\_IPC\_QUEUE** are enabled.
- Check that **LOSCFG_BASE_CORE_SWTMR** and **LOSCFG_BASE_IPC_QUEUE** are enabled.
- Configure **LOSCFG\_BASE\_CORE\_SWTMR\_LIMIT**\(maximum number of software timers supported by the system\).
- Configure **LOSCFG_BASE_CORE_SWTMR_LIMIT** (maximum number of software timers supported by the system).
- Configure **OS\_SWTMR\_HANDLE\_QUEUE\_SIZE**\(maximum length of the software timer queue\).
- Configure **OS_SWTMR_HANDLE_QUEUE_SIZE** (maximum length of the software timer queue).
2. Call **LOS\_SwtmrCreate** to create a software timer.
2.Call **LOS_SwtmrCreate** to create a software timer.
- Create a software timer with the specified timing duration, timeout handling function, and triggering mode.
- Create a software timer with the specified timing duration, timeout handling function, and triggering mode.
- Return the function execution result \(success or failure\).
- Return the function execution result (success or failure).
3. Call **LOS\_SwtmrStart** to start the software timer.
3. Call **LOS_SwtmrStart** to start the software timer.
4. Call **LOS\_SwtmrTimeGet** to obtain the remaining number of ticks of the software timer.
5. Call **LOS\_SwtmrStop** to stop the software timer.
6. Call **LOS\_SwtmrDelete** to delete the software timer.
4. Call **LOS_SwtmrTimeGet** to obtain the remaining number of ticks of the software timer.
>- Avoid too many operations in the callback function of the software timer. Do not use APIs or perform operations that may cause task suspension or blocking.
>- The software timers use a queue and a task resource of the system. The priority of the software timer tasks is set to **0** and cannot be changed.
>- The number of software timer resources that can be configured in the system is the total number of software timer resources available to the entire system, not the number of software timer resources available to users. For example, if the system software timer occupies one more resource, the number of software timer resources available to users decreases by one.
>- If a one-shot software timer is created, the system automatically deletes the timer and reclaims resources after the timer times out and the callback function is executed.
>- For a one-shot software timer that will not be automatically deleted after expiration, you need to call **LOS\_SwtmrDelete** to delete it and reclaim the timer resource to prevent resource leakage.
### Development Example<a name="section114416313585"></a>
5. Call **LOS_SwtmrStop** to stop the software timer.
Prerequisites:
6. Call **LOS_SwtmrDelete** to delete the software timer.
- In **los\_config.h**, **LOSCFG\_BASE\_CORE\_SWTMR** is enabled.
> **NOTE**<br>
- The maximum number of software timers supported by the system \(**LOSCFG\_BASE\_CORE\_SWTMR\_LIMIT**\) is configured.
>
- The maximum length of the software timer queue \(**OS\_SWTMR\_HANDLE\_QUEUE\_SIZE**\) is configured.
> - Avoid too many operations in the callback of the software timer. Do not use APIs or perform operations that may cause task suspension or blocking.
>
> - The software timers use a queue and a task resource of the system. The priority of the software timer tasks is set to **0** and cannot be changed.
>
> - The number of software timer resources that can be configured in the system is the total number of software timer resources available to the entire system, not the number of software timer resources available to users. For example, if the system software timer occupies one more resource, the number of software timer resources available to users decreases by one.
>
> - If a one-shot software timer is created, the system automatically deletes the timer and reclaims resources after the timer times out and the callback is invoked.
>
> - For a one-shot software timer that will not be automatically deleted after expiration, you need to call **LOS_SwtmrDelete** to delete it and reclaim the timer resource to prevent resource leakage.
### Development Example
**Prerequisites**
- In **los_config.h**, **LOSCFG_BASE_CORE_SWTMR** is enabled.
- The maximum number of software timers supported by the system (**LOSCFG_BASE_CORE_SWTMR_LIMIT**) is configured.
- The maximum length of the software timer queue (**OS_SWTMR_HANDLE_QUEUE_SIZE**) is configured.
**Sample Code**
**Sample Code**
...
@@ -164,14 +150,14 @@ void Timer_example(void)
...
@@ -164,14 +150,14 @@ void Timer_example(void)
UINT16 id2; // timer id
UINT16 id2; // timer id
UINT32 uwTick;
UINT32 uwTick;
/* Create a one-shot software timer, with the number of ticks set to 1000. When the number of ticks reaches 1000, callback function 1 is executed. */
/* Create a one-shot software timer, with the number of ticks set to 1000. Callback 1 will be invoked when the number of ticks reaches 1000. */
Time management provides all time-related services for applications based on the system clock. The system clock is generated by the interrupts triggered by the output pulse of a timer or counter. The system clock is generally defined as an integer or a long integer. The period of an output pulse is a "clock tick". The system clock is also called time scale or tick. The duration of a tick can be configured statically. People use second or millisecond as the time unit, while the operating system uses tick. When operations such as suspending a task or delaying a task are performed, the time management module converts time between ticks and seconds or milliseconds.
Time management is performed based on the system clock. It provides time-related services for applications. The system clock is generated by the interrupts triggered by the output pulse of a timer or counter. The system clock is generally defined as an integer or a long integer. The period of an output pulse is a "clock tick".
The system clock is also called time scale or tick. The duration of a tick can be configured statically. People use second or millisecond as the time unit, while the operating system uses tick. When operations such as suspending a task or delaying a task are performed, the time management module converts time between ticks and seconds or milliseconds.
The mapping between ticks and seconds can be configured.
The mapping between ticks and seconds can be configured.
-**Cycle**
-Cycle
Cycle is the minimum time unit in the system. The cycle duration is determined by the system clock frequency, that is, the number of cycles per second.
Cycle is the minimum time unit in the system. The cycle duration is determined by the system clock frequency, that is, the number of cycles per second.
- Tick
-**Tick**
Tick is the basic time unit of the operating system and is determined by the number of ticks per second configured by the user.
Tick is the basic time unit of the operating system and is determined by the number of ticks per second configured by the user.
The OpenHarmony time management module provides time conversion, statistics, and delay functions.
The OpenHarmony time management module provides time conversion, statistics, and delay functions to meet users' time requirements.
## Development Guidelines
## Development Guidelines
The time management module provides APIs to implement conversion between the system running time, ticks, and seconds/milliseconds.
Before you start, learn about the system time and the APIs for time management.
### Available APIs
### Available APIs
The following table describes APIs available for the OpenHarmony LiteOS-A time management. For more details about the APIs, see the API reference.
The following table describes APIs for OpenHarmony LiteOS-A time management. For more details about the APIs, see the API reference.
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p8504121996"><aname="p8504121996"></a><aname="p8504121996"></a>Converts milliseconds into ticks.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p161632181721"><aname="p161632181721"></a><aname="p161632181721"></a>Converts ticks into milliseconds.</p>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p615864811116"><aname="p615864811116"></a><aname="p615864811116"></a>Obtains the current number of ticks.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p151631718124"><aname="p151631718124"></a><aname="p151631718124"></a>Obtains the number of cycles per tick.</p>
>- The system tick count can be obtained only after the system clock is enabled.
>
>- The time management module depends on **OS\_SYS\_CLOCK** and **LOSCFG\_BASE\_CORE\_TICK\_PER\_SECOND** in **los\_config.h**.
> - The system tick count can be obtained only after the system clock is enabled.
>- The number of system ticks is not counted when the interrupt feature is disabled. Therefore, the number of ticks cannot be used as the accurate time.
>
> - The time management module depends on **OS_SYS_CLOCK** and **LOSCFG_BASE_CORE_TICK_PER_SECOND** in **los_config.h**.
>
> - The number of system ticks is not counted when the interrupt feature is disabled. Therefore, the number of ticks cannot be used as the accurate time.
### Development Example
### Development Example
**Prerequisites**<br>
**Prerequisites**
The following parameters are configured:
The following parameters are configured:
-**LOSCFG\_BASE\_CORE\_TICK\_PER\_SECOND**: number of ticks per second in the system. The value range is (0, 1000].
-**LOSCFG_BASE_CORE_TICK_PER_SECOND**: number of ticks/second. The value range is (0, 1000).
An event is a mechanism for communication between tasks. It can be used to synchronize tasks.
## Basic Concepts
An event is a communication mechanism used to synchronize tasks.
In multi-task environment, synchronization is required between tasks. Events can be used for synchronization in the following cases:
In multi-task environment, synchronization is required between tasks. Events can be used for synchronization in the following cases:
- One-to-many synchronization: A task waits for the triggering of multiple events. A task is woken up by one or multiple events.
- One-to-many synchronization: A task waits for the triggering of multiple events. A task can be woken up by one or multiple events.
- Many-to-many synchronization: Multiple tasks wait for the triggering of multiple events.
- Many-to-many synchronization: Multiple tasks wait for the triggering of multiple events.
The event mechanism provided by the OpenHarmony LiteOS-A event module has the following features:
The event mechanism provided by the OpenHarmony LiteOS-A event module has the following features:
- A task triggers or waits for an event by creating an event control block.
- A task triggers or waits for an event by creating an event control block.
- Events are independent of each other. The internal implementation is a 32-bit unsigned integer, and each bit indicates an event type. The 25th bit is unavailable. Therefore, a maximum of 31 event types are supported.
- Events are used only for synchronization between tasks, but not for data transmission.
- Events are independent of each other. The internal implementation is a 32-bit unsigned integer, and each bit indicates an event type. The value **0** indicates that the event type does not occur, and the value **1** indicates that the event type has occurred. There are 31 event types in total. The 25th bit (`0x02U << 24`) is reserved.
- Writing the same event type to the event control block for multiple times is equivalent to writing the event type only once before the event control block is cleared.
- Events are used for task synchronization, but not for data transmission.
- Writing the same event type to an event control block multiple times is equivalent to writing the event type only once before the event control block is cleared.
- Multiple tasks can read and write the same event.
- Multiple tasks can read and write the same event.
- The event read/write timeout mechanism is supported.
- The event read/write timeout mechanism is supported.
## Working Principles<a name="section94611116593"></a>
### Event Control Block<a name="section1161415384467"></a>
## Working Principles
### Event Control Block
```
```
/**
/**
* Event control block data structure
* Event control block data structure
*/
*/
typedef struct tagEvent {
typedef struct tagEvent {
UINT32 uwEventID; /* Event set, which is a collection of events processed (written and cleared). */
UINT32 uwEventID; /* Event set, which is a collection of events processed (written and cleared). */
LOS_DL_LIST stEventList; /* List of tasks waiting for specific events */
LOS_DL_LIST stEventList; /* List of tasks waiting for specific events. */
} EVENT_CB_S, *PEVENT_CB_S;
} EVENT_CB_S, *PEVENT_CB_S;
```
```
### Working Principles<a name="section187761153144617"></a>
**Initializing an event**: An event control block is created to maintain a collection of processed events and a linked list of tasks waiting for specific events.
### Working Principles
**Initializing an Event**
An event control block is created to maintain a set of processed events and a linked list of tasks waiting for specific events.
**Writing an event**: When a specified event is written to the event control block, the event control block updates the event set, traverses the task linked list, and determines whether to wake up related task based on the task conditions.
**Writing an Event**
**Reading an event**: If the read event already exists, it is returned synchronously. In other cases, the return time is determined based on the timeout period and event triggering status. If the wait event condition is met before the timeout period expires, the blocked task will be directly woken up. Otherwise, the blocked task will be woken up only after the timeout period has expired.
When an event is written to the event control block, the event control block updates the event set, traverses the task linked list, and determines whether to wake up related task based on the specified conditions.
The input parameters **eventMask** and **mode** determine whether the condition for reading an event is met. **eventMask** indicates the mask of the event. **mode** indicates the handling mode, which can be any of the following:
**Reading an Event**
-**LOS\_WAITMODE\_AND**: Event reading is successful only when all the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned.
If the event to read already exists, it is returned synchronously. In other cases, the event is returned based on the timeout period and event triggering conditions. If the wait condition is met before the timeout period expires, the blocked task will be directly woken up. Otherwise, the blocked task will be woken up only after the timeout period has expired.
-**LOS\_WAITMODE\_OR**: Event reading is successful when any of the events corresponding to **eventMask** occurs. Otherwise, the task will be blocked, or an error code will be returned.
-**LOS\_WAITMODE\_CLR**: This mode must be used with **LOS\_WAITMODE\_AND** or **LOS\_WAITMODE\_OR**\(LOS\_WAITMODE\_AND | LOS\_WAITMODE\_CLR or LOS\_WAITMODE\_OR | LOS\_WAITMODE\_CLR\). In this mode, if **LOS\_WAITMODE\_AND** or **LOS\_WAITMODE\_OR** is successful, the corresponding event type bit in the event control block will be automatically cleared.
**Clearing events**: Clear the event set of the event control block based on the specified mask. If the mask is **0**, the event set will be cleared. If the mask is **0xffff**, no event will be cleared, and the event set remains unchanged.
The parameters **eventMask** and **mode** determine whether the condition for reading an event is met. **eventMask** specifies the event mask. **mode** specifies the handling mode, which can be any of the following:
**Destroying an event**: Destroy the specified event control block.
-**LOS_WAITMODE_AND**: Read the event only when all the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned.
**Figure 1** Event working mechanism for small systems<aname="fig17799175324612"></a>
-**LOS_WAITMODE_OR**: Read the event only when any of the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned.
## Development Guidelines<a name="section44744471891"></a>
-**LOS_WAITMODE_CLR**: This mode must be used with one or all of the event modes (LOS_WAITMODE_AND | LOS_WAITMODE_CLR or LOS_WAITMODE_OR | LOS_WAITMODE_CLR). In this mode, if all event modes or any event mode is successful, the corresponding event type bit in the event control block will be automatically cleared.
### Available APIs<a name="section172373513919"></a>
**Clearing Events**
The events in the event set of the event control block can be cleared based on the specified mask. The mask **0** means to clear the event set; the mask **0xffff** means the opposite.
**Destroying Events**
The event control block can be destroyed to release resources.
**Figure 1** Event working mechanism for small systems
<tdclass="cellrowborder"valign="top"width="57.34573457345735%"headers="mcps1.2.4.1.3 "><pid="p2334141425515"><aname="p2334141425515"></a><aname="p2334141425515"></a>Initializes an event control block.</p>
<tdclass="cellrowborder"valign="top"width="57.34573457345735%"headers="mcps1.2.4.1.3 "><pid="p1621275475517"><aname="p1621275475517"></a><aname="p1621275475517"></a>Reads a specified type of event, with the timeout period of a relative time period in ticks.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p10271958567"><aname="p10271958567"></a><aname="p10271958567"></a>Writes a specified type of event.</p>
<tdclass="cellrowborder"valign="top"width="57.34573457345735%"headers="mcps1.2.4.1.3 "><pid="p14862153525620"><aname="p14862153525620"></a><aname="p14862153525620"></a>Clears a specified type of event.</p>
</td>
</tr>
<trid="row1525316428553"><tdclass="cellrowborder"valign="top"width="12.85128512851285%"headers="mcps1.2.4.1.1 "><pid="p4253144265519"><aname="p4253144265519"></a><aname="p4253144265519"></a>Checking the event mask</p>
<tdclass="cellrowborder"valign="top"width="57.34573457345735%"headers="mcps1.2.4.1.3 "><pid="p13998115465617"><aname="p13998115465617"></a><aname="p13998115465617"></a>Returns whether the event input by the user meets the expectation based on the event ID, event mask, and read mode passed by the user.</p>
<tdclass="cellrowborder"valign="top"width="57.34573457345735%"headers="mcps1.2.4.1.3 "><pid="p32592615573"><aname="p32592615573"></a><aname="p32592615573"></a>Destroys a specified event control block.</p>
</td>
</tr>
</tbody>
</table>
### How to Develop<a name="section1118215161013"></a>
The typical event development process is as follows:
The typical event development process is as follows:
1. Initialize an event control block.
1. Initialize an event control block.
2. Block a read event control block.
2. Block a read event.
3. Write related events.
3. Write related events.
4. Wake up a blocked task, read the event, and check whether the event meets conditions.
4. Wake up a blocked task, read the event, and check whether the event meets conditions.
>- When an event is read or written, the 25th bit of the event is reserved and cannot be set.
>
>- Repeated writes of the same event are treated as one write.
> - For event read and write operations, the 25th bit (`0x02U << 24`) of the event is reserved and cannot be set.
>
> - Repeated writes of the same event are treated as one write.
## Development Example
### Example Description
In this example, run the **Example_TaskEntry** task to create the **Example_Event** task. Run the **Example_Event** task to read an event to trigger task switching. Run the **Example_TaskEntry** task to write an event. You can understand the task switching during event operations based on the sequence in which logs are recorded.
## Development Example<a name="section5837165132911"></a>
1. Create the **Example_Event** task in the **Example_TaskEntry** task with a higher priority than the **Example_TaskEntry** task.
### Example Description<a name="section128221510145718"></a>
2. Run the **Example_Event** task to read event **0x00000001**. Task switching is triggered to execute the **Example_TaskEntry** task.
In this example, run the **Example\_TaskEntry** task to create the **Example\_Event** task, run the **Example\_Event** task to read an event to trigger task switching, and run the **Example\_TaskEntry** task to write an event. You can understand the task switching during event operations based on the sequence in which logs are recorded.
3. Run the **Example_TaskEntry** task to write event **0x00000001**. Task switching is triggered to execute the **Example_Event** task.
1. Create the **Example\_Event** task in the **Example\_TaskEntry** task with a higher priority than the **Example\_TaskEntry** task.
4. The **Example_Event** task is executed.
2. Run the **Example\_Event** task to read event **0x00000001**. Task switching is triggered to execute the **Example\_TaskEntry** task.
3. Run the **Example\_TaskEntry** task to write event **0x00000001**. Task switching is triggered to execute the **Example\_Event** task.
4. The **Example\_Event** task is executed.
5. The **Example\_TaskEntry** task is executed.
### Sample Code<a name="section71507479577"></a>
5. The **Example_TaskEntry** task is executed.
### Sample Code
The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **Example_EventEntry** function is called in **TestTaskEntry**.
The sample code is as follows:
The sample code is as follows:
...
@@ -149,28 +148,28 @@ The sample code is as follows:
...
@@ -149,28 +148,28 @@ The sample code is as follows:
#include "los_task.h"
#include "los_task.h"
#include "securec.h"
#include "securec.h"
/* Task ID*/
/* Task ID*/
UINT32 g_testTaskId;
UINT32 g_testTaskId;
/* Event control structure*/
/* Event control structure*/
EVENT_CB_S g_exampleEvent;
EVENT_CB_S g_exampleEvent;
/* Type of the wait event*/
/* Type of the wait event*/
#define EVENT_WAIT 0x00000001
#define EVENT_WAIT 0x00000001
#define EVENT_TIMEOUT 500
/* Example task entry function*/
/* Example task entry function*/
VOID Example_Event(VOID)
VOID Example_Event(VOID)
{
{
UINT32 event;
UINT32 event;
/* Set a timeout period for event reading to 100 ticks. If the specified event is not read within 100 ticks, the read operation times out and the task is woken up.*/
/* Set a timeout period for event reading to 100 ticks. If the specified event is not read within 100 ticks, the read operation times out and the task is woken up.*/
A mutual exclusion (mutex) is a special binary semaphore used for exclusive access to shared resources. When a task holds the mutex, the task obtains the ownership of the mutex. When the task releases the mutex, the task will lose the ownership of the mutex. When a task holds a mutex, other tasks cannot hold the mutex. In an environment where multiple tasks compete for shared resources, the mutex ensures exclusive access to the shared resources.
A mutual exclusion \(mutex\) is a special binary semaphore used for exclusive access to shared resources. When a task holds the mutex, the task obtains the ownership of the mutex. When the task releases the mutex, the task will lose the ownership of the mutex. When a task holds a mutex, other tasks cannot hold the mutex. In an environment where multiple tasks compete for shared resources, the mutex ensures exclusive access to the shared resources.
A mutex has three attributes: protocol attribute, priority upper limit attribute, and type attribute. The protocol attribute is used to handle a mutex requested by tasks of different priorities. The protocol attribute can be any of the following:
A mutex has three attributes: protocol attribute, priority upper limit attribute, and type attribute. The protocol attribute is used to handle a mutex requested by tasks of different priorities. The protocol attribute can be any of the following:
- LOS\_MUX\_PRIO\_NONE
-LOS_MUX_PRIO_NONE
Do not inherit or protect the priority of the task requesting the mutex.
Do not inherit or protect the priority of the task requesting the mutex.
- LOS\_MUX\_PRIO\_INHERIT
-LOS_MUX_PRIO_INHERIT
Inherits the priority of the task that requests the mutex. This is the default protocol attribute. When the mutex protocol attribute is set to this value: If a task with a higher priority is blocked because the mutex is already held by a task, the priority of the task holding the mutex will be backed up to the priority bitmap of the task control block, and then set to be the same as that of the task of a higher priority. When the task holding the mutex releases the mutex, its task priority is restored to its original value.
Inherits the priority of the task that requests the mutex. This is the default protocol attribute. When the mutex protocol attribute is set to this value: If a task with a higher priority is blocked because the mutex is already held by a task, the priority of the task holding the mutex will be backed up to the priority bitmap of the task control block, and then set to be the same as that of the task of a higher priority. When the task holding the mutex releases the mutex, its task priority is restored to its original value.
- LOS\_MUX\_PRIO\_PROTECT
-LOS_MUX_PRIO_PROTECT
Protects the priority of the task that requests the mutex. When the mutex protocol attribute is set to this value: If the priority of the task that requests the mutex is lower than the upper limit of the mutex priority, the task priority will be backed up to the priority bitmap of the task control block, and then set to the upper limit value of the mutex priority. When the mutex is released, the task priority is restored to its original value.
Protects the priority of the task that requests the mutex. When the mutex protocol attribute is set to this value: If the priority of the task that requests the mutex is lower than the upper limit of the mutex priority, the task priority will be backed up to the priority bitmap of the task control block, and then set to the upper limit value of the mutex priority. When the mutex is released, the task priority is restored to its original value.
The type attribute of a mutex specifies whether to check for deadlocks and whether to support recursive holding of the mutex. The type attribute can be any of the following:
The type attribute of a mutex specifies whether to check for deadlocks and whether to support recursive holding of the mutex. The type attribute can be any of the following:
- LOS_MUX_NORMAL
- LOS\_MUX\_NORMAL
Common mutex, which does not check for deadlocks. If a task repeatedly attempts to hold a mutex, the thread will be deadlocked. If the mutex type attribute is set to this value, a task cannot release a mutex held by another task or repeatedly release a mutex. Otherwise, unexpected results will be caused.
Common mutex, which does not check for deadlocks. If a task repeatedly attempts to hold a mutex, the thread will be deadlocked. If the mutex type attribute is set to this value, a task cannot release a mutex held by another task or repeatedly release a mutex. Otherwise, unexpected results will be caused.
- LOS\_MUX\_RECURSIVE
-LOS_MUX_RECURSIVE
Recursive mutex, which is the default attribute. If the type attribute of a mutex is set to this value, a task can hold the mutex for multiple times. Another task can hold this mutex only when the number of lock holding times is the same as the number of lock release times. However, any attempt to hold a mutex held by another task or attempt to release a mutex that has been released will return an error code.
Recursive mutex, which is the default attribute. If the type attribute of a mutex is set to this value, a task can hold the mutex for multiple times. Another task can hold this mutex only when the number of lock holding times is the same as the number of lock release times. However, any attempt to hold a mutex held by another task or attempt to release a mutex that has been released will return an error code.
- LOS\_MUX\_ERRORCHECK
-LOS_MUX_ERRORCHECK
Allows automatic check for deadlocks. When a mutex is set to this type, an error code will be returned if a task attempts to repeatedly hold the mutex, attempts to release the mutex held by another task, or attempts to release the mutex that has been released.
Mutex for error checks. When a mutex is set to this type, an error code will be returned if a task attempts to repeatedly hold the mutex, attempts to release the mutex held by another task, or attempts to release the mutex that has been released.
## Working Principles<a name="section8547454201819"></a>
## Working Principles
In a multi-task environment, multiple tasks may access the same shared resource. However, certain shared resources are not shared, and can only be accessed exclusively by tasks. A mutex can be used to address this issue.
In a multi-task environment, multiple tasks may access the same shared resources. However, certain shared resources are not shared, and can only be accessed exclusively by tasks. A mutex can be used to address this issue.
When non-shared resources are accessed by a task, the mutex is locked. Other tasks will be blocked until the mutex is released by the task. The mutex allows only one task to access the shared resources at a time, ensuring integrity of operations on the shared resources.
When non-shared resources are accessed by a task, the mutex is locked. Other tasks will be blocked until the mutex is released by the task. The mutex allows only one task to access the shared resources at a time, ensuring integrity of operations on the shared resources.
**Figure 1** Mutex working mechanism for small systems<aname="fig16821181173811"></a>
**Figure 1** Mutex working mechanism for the small system
| Requesting or releasing a mutex| - **LOS_MuxLock**: requests a mutex.<br>- **LOS_MuxTrylock**: requests a mutex without blocking.<br>- **LOS_MuxUnlock**: releases a mutex.|
</th>
| Verifying a mutex| - **LOS_MuxIsValid**: checks whether the mutex release is valid.<br>- **LOS_MuxAttrDestroy**: destroys the specified mutex attribute.|
</tr>
| Setting and obtaining mutex attributes| - **LOS_MuxAttrGetType**: obtains the type attribute of a mutex.<br>- **LOS_MuxAttrSetType**: sets the type attribute for a mutex.<br>- **LOS_MuxAttrGetProtocol**: obtains the protocol attribute of a mutex.<br>- **LOS_MuxAttrSetProtocol**: sets the protocol attribute for a mutex.<br>- **LOS_MuxAttrGetPrioceiling**: obtains the priority upper limit attribute of a mutex.<br>- **LOS_MuxAttrSetPrioceiling**: sets the priority upper limit attribute for a mutex.<br>- **LOS_MuxGetPrioceiling**: obtains the priority upper limit of this mutex.<br>- **LOS_MuxSetPrioceiling**: sets the priority upper limit for this mutex. |
</thead>
<tbody><trid="row332716281313"><tdclass="cellrowborder"rowspan="2"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p1795312108911"><aname="p1795312108911"></a><aname="p1795312108911"></a>Initializing or destroying a mutex</p>
<tdclass="cellrowborder"valign="top"width="33.35333533353336%"headers="mcps1.2.4.1.3 "><pid="p932762812319"><aname="p932762812319"></a><aname="p932762812319"></a>Initializes a mutex.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p137111129965"><aname="p137111129965"></a><aname="p137111129965"></a>Destroys the specified mutex.</p>
</td>
</tr>
<trid="row17711329268"><tdclass="cellrowborder"rowspan="3"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p18125182815396"><aname="p18125182815396"></a><aname="p18125182815396"></a>Requesting or releasing a mutex</p>
<tdclass="cellrowborder"valign="top"width="33.35333533353336%"headers="mcps1.2.4.1.3 "><pid="p20994162353515"><aname="p20994162353515"></a><aname="p20994162353515"></a>Requests the specified mutex.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p1271110291969"><aname="p1271110291969"></a><aname="p1271110291969"></a>Attempts to request the specified mutex in non-block mode.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p107118291660"><aname="p107118291660"></a><aname="p107118291660"></a>Releases the specified mutex.</p>
</td>
</tr>
<trid="row344193024114"><tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p16441730114110"><aname="p16441730114110"></a><aname="p16441730114110"></a>Verifying a mutex</p>
<tdclass="cellrowborder"valign="top"width="33.35333533353336%"headers="mcps1.2.4.1.3 "><pid="p3441193017416"><aname="p3441193017416"></a><aname="p3441193017416"></a>Checks whether the mutex release is valid.</p>
</td>
</tr>
<trid="row1065116418421"><tdclass="cellrowborder"rowspan="2"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.1 "><pid="p2189182734211"><aname="p2189182734211"></a><aname="p2189182734211"></a>Initializing or destroying mutex attributes</p>
<tdclass="cellrowborder"valign="top"width="33.35333533353336%"headers="mcps1.2.4.1.3 "><pid="p151444418461"><aname="p151444418461"></a><aname="p151444418461"></a>Obtains the type attribute of a specified mutex.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p51371843194813"><aname="p51371843194813"></a><aname="p51371843194813"></a>Sets the type attribute of a specified mutex.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p20871044144720"><aname="p20871044144720"></a><aname="p20871044144720"></a>Obtains the protocol attribute of a specified mutex.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p1690617554610"><aname="p1690617554610"></a><aname="p1690617554610"></a>Sets the protocol attribute of a specified mutex.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p559511469478"><aname="p559511469478"></a><aname="p559511469478"></a>Obtains the priority upper limit attribute of a specified mutex.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p16789126134614"><aname="p16789126134614"></a><aname="p16789126134614"></a>Sets the priority upper limit attribute of a specified mutex.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p177254713460"><aname="p177254713460"></a><aname="p177254713460"></a>Sets the mutex priority upper limit attribute.</p>
</td>
</tr>
</tbody>
</table>
### How to Develop<a name="section4201191122116"></a>
The typical mutex development process is as follows:
The typical mutex development process is as follows:
1. Call **LOS\_MuxInit** to initialize a mutex.
1. Call **LOS_MuxInit** to initialize a mutex.
2. Call **LOS\_MuxLock** to request a mutex.
2. Call **LOS_MuxLock** to request a mutex.
The following modes are available:
The following modes are available:
- Non-block mode: A task acquires the mutex if the requested mutex is not held by any task or the task holding the mutex is the same as the task requesting the mutex.
- Non-block mode: A task acquires the mutex if the requested mutex is not held by any task or the task holding the mutex is the same as the task requesting the mutex.
- Permanent block mode: A task acquires the mutex if the requested mutex is not occupied. If the mutex is occupied, the task will be blocked and the task with the highest priority in the ready queue will be executed. The blocked task can be unlocked and executed only when the mutex is released.
- Permanent block mode: A task acquires the mutex if the requested mutex is not occupied. If the mutex is occupied, the task will be blocked and the task with a highest priority in the ready queue will be executed. The blocked task can be unlocked and executed only when the mutex is released.
- Scheduled block mode: A task acquires the mutex if the requested mutex is not occupied. If the mutex is occupied, the task will be blocked and the task with the highest priority in the ready queue will be executed. The blocked task can be executed only when the mutex is released within the specified timeout period or when the specified timeout period expires.
- Scheduled block mode: A task acquires the mutex if the requested mutex is not occupied. If the mutex is occupied, the task will be blocked and the task with the highest priority in the ready queue will be executed. The blocked task can be executed only when the mutex is released within the specified timeout period or when the specified timeout period expires.
3. Call **LOS\_MuxUnlock** to release a mutex.
3. Call **LOS_MuxUnlock** to release a mutex.
- If tasks are blocked by the specified mutex, the task with a higher priority will be unblocked when the mutex is released. The unblocked task changes to the Ready state and is scheduled.
- If tasks are blocked by the specified mutex, the task with a higher priority will be unblocked when the mutex is released. The unblocked task changes to the Ready state and is scheduled.
- If no task is blocked by the specified mutex, the mutex is released successfully.
- If no task is blocked by the specified mutex, the mutex is released successfully.
4. Call **LOS\_MuxDestroy** to destroy a mutex.
4. Call **LOS_MuxDestroy** to destroy a mutex.
> **NOTE**<br>
> - Two tasks cannot lock the same mutex. If a task attempts to lock a mutex held by another task, the task will be blocked until the mutex is unclocked.
>
> - Mutexes cannot be used in the interrupt service program.
>
> - The system using the LiteOS-A kernel must ensure real-time task scheduling and avoid long-time task blocking. Therefore, a mutex must be released as soon as possible after use.
>- Two tasks cannot lock the same mutex. If a task attempts to lock a mutex held by another task, the task will be blocked until the mutex is unlocked.
>- Mutexes cannot be used in the interrupt service program.
>- When using the LiteOS-A kernel, the OpenHarmony must ensure real-time task scheduling and avoid long-time task blocking. Therefore, a mutex must be released as soon as possible after use.
### Development Example<a name="section10679328202117"></a>
### Development Example
Example Description
#### Example Description
This example implements the following:
This example implements the following:
1. Create a mutex in the **Example\_TaskEntry** task, and lock task scheduling. Create two tasks **Example\_MutexTask1** and **Example\_MutexTask2**. and unlock task scheduling.
1. Create the **Example_TaskEntry** task. In this task, create a mutex to lock task scheduling, and create two tasks **Example_MutexTask1** (with a lower priority) and **Example_MutexTask2** (with a higher priority) to unlock task scheduling.
2. When being scheduled, **Example\_MutexTask2** requests a mutex in permanent block mode. After acquiring the mutex, **Example\_MutexTask2** enters the sleep mode for 100 ticks. **Example\_MutexTask2** is suspended, and **Example\_MutexTask1** is woken up.
3.**Example\_MutexTask1** requests a mutex in scheduled block mode, and waits for 10 ticks. Because the mutex is still held by **Example\_MutexTask2**, **Example\_MutexTask1** is suspended. After 10 ticks, **Example\_MutexTask1** is woken up and attempts to request a mutex in permanent block mode. **Example\_MutexTask1** is suspended because the mutex is still held by **Example\_MutexTask2**.
2. When being scheduled, **Example_MutexTask2** requests a mutex in permanent block mode. After acquiring the mutex, **Example_MutexTask2** enters the sleep mode for 100 ticks. **Example_MutexTask2** is suspended, and **Example_MutexTask1** is woken up.
4. After 100 ticks, **Example\_MutexTask2** is woken up and releases the mutex, and then **Example\_MutexTask1** is woken up. **Example\_MutexTask1** acquires the mutex and then releases the mutex. At last, the mutex is deleted.
3.**Example_MutexTask1** requests a mutex in scheduled block mode, and waits for 10 ticks. Because the mutex is still held by **Example_MutexTask2**, **Example_MutexTask1** is suspended. After 10 ticks, **Example_MutexTask1** is woken up and attempts to request a mutex in permanent block mode. **Example_MutexTask1** is suspended because the mutex is still held by **Example_MutexTask2**.
4. After 100 ticks, **Example_MutexTask2** is woken up and releases the mutex, and then **Example_MutexTask1** is woken up. **Example_MutexTask1** acquires the mutex and then releases the mutex. At last, the mutex is deleted.
**Sample Code**
#### Sample Code
The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **Example_MutexEntry** function is called in **TestTaskEntry**.
The sample code is as follows:
The sample code is as follows:
...
@@ -199,7 +117,7 @@ The sample code is as follows:
...
@@ -199,7 +117,7 @@ The sample code is as follows:
#include "los_mux.h"
#include "los_mux.h"
/* Mutex */
/* Mutex */
LosMux g_testMux;
LosMux g_testMutex;
/* Task ID*/
/* Task ID*/
UINT32 g_testTaskId01;
UINT32 g_testTaskId01;
UINT32 g_testTaskId02;
UINT32 g_testTaskId02;
...
@@ -207,28 +125,29 @@ UINT32 g_testTaskId02;
...
@@ -207,28 +125,29 @@ UINT32 g_testTaskId02;
VOID Example_MutexTask1(VOID)
VOID Example_MutexTask1(VOID)
{
{
UINT32 ret;
UINT32 ret;
LOS_TaskDelay(50);
printf("task1 try to get mutex, wait 10 ticks.\n");
dprintf("task1 try to get mutex, wait 10 ticks.\n");
/* Request a mutex.*/
/* Request a mutex.*/
ret = LOS_MuxLock(&g_testMux, 10);
ret = LOS_MuxLock(&g_testMutex, 10);
if (ret == LOS_OK) {
if (ret == LOS_OK) {
printf("task1 get mutex g_testMux.\n");
dprintf("task1 get mutex g_testMux.\n");
/* Release the mutex.*/
/* Release the mutex. */
LOS_MuxUnlock(&g_testMux);
LOS_MuxUnlock(&g_testMutex);
return;
return;
}
}
if (ret == LOS_ETIMEDOUT) {
if (ret == LOS_ETIMEDOUT) {
printf("task1 timeout and try to get mutex, wait forever.\n");
dprintf("task1 timeout and try to get mutex, wait forever.\n");
/* Request a mutex.*/
/* Request a mutex. */
ret = LOS_MuxLock(&g_testMux, LOS_WAIT_FOREVER);
ret = LOS_MuxLock(&g_testMutex, LOS_WAIT_FOREVER);
if (ret == LOS_OK) {
if (ret == LOS_OK) {
printf("task1 wait forever, get mutex g_testMux.\n");
dprintf("task1 wait forever, get mutex g_testMux.\n");
/*Release the mutex.*/
/* Release the mutex. */
LOS_MuxUnlock(&g_testMux);
LOS_MuxUnlock(&g_testMutex);
/* Delete the mutex. */
/* Delete the mutex. */
LOS_MuxDestroy(&g_testMux);
LOS_MuxDestroy(&g_testMutex);
printf("task1 post and delete mutex g_testMux.\n");
dprintf("task1 post and delete mutex g_testMux.\n");
A queue, also called a message queue, is a data structure used for communication between tasks. The queue receives messages of unfixed length from tasks or interrupts, and determines whether to store the transferred messages in the queue based on different APIs.
A queue, also called a message queue, is a data structure used for communication between tasks. The queue receives messages of unfixed length from tasks or interrupts, and determines whether to store the transferred messages in the queue based on different APIs.
...
@@ -11,17 +11,26 @@ You can adjust the timeout period of the read queue and write queue to adjust th
...
@@ -11,17 +11,26 @@ You can adjust the timeout period of the read queue and write queue to adjust th
An asynchronous processing mechanism is provided to allow messages in a queue not to be processed immediately. In addition, queues can be used to buffer messages and implement asynchronous task communication. Queues have the following features:
An asynchronous processing mechanism is provided to allow messages in a queue not to be processed immediately. In addition, queues can be used to buffer messages and implement asynchronous task communication. Queues have the following features:
- Messages are queued in FIFO mode and can be read and written asynchronously.
- Messages are queued in first-in-first-out (FIFO) mode and can be read and written asynchronously.
- Both the read queue and write queue support the timeout mechanism.
- Both the read queue and write queue support the timeout mechanism.
- Each time a message is read, the message node becomes available.
- Each time a message is read, the message node becomes available.
- The types of messages to be sent are determined by the parties involved in communication. Messages of different lengths \(not exceeding the message node size of the queue\) are allowed.
- The types of messages to be sent are determined by the parties involved in communication. Messages of different lengths (not exceeding the message node size of the queue) are allowed.
- A task can receive messages from and send messages to any message queue.
- A task can receive messages from and send messages to any message queue.
- Multiple tasks can receive messages from and send messages to the same queue.
- Multiple tasks can receive messages from and send messages to the same queue.
- When a queue is created, the required dynamic memory space is automatically allocated in the queue API.
- When a queue is created, the required dynamic memory space is automatically allocated in the queue API.
## Working Principles<a name="section1074515132316"></a>
### Queue Control Block<a name="section194431851201315"></a>
## Working Principles
### Queue Control Block
```
```
/**
/**
...
@@ -43,121 +52,94 @@ typedef struct {
...
@@ -43,121 +52,94 @@ typedef struct {
Each queue control block contains information about the queue status.
Each queue control block contains information about the queue status.
-**OS\_QUEUE\_UNUSED**: The queue is not in use.
-**OS_QUEUE_UNUSED**: The queue is not in use.
-**OS\_QUEUE\_INUSED**: The queue is in use.
-**OS_QUEUE_INUSED**: The queue is in use.
### Working Principles<a name="section89875741418"></a>
### Working Principles
- The queue ID is returned when a queue is created successfully.
- The queue ID is returned if a queue is created successfully.
- The queue control block contains **Head** and **Tail**, which indicate the storage status of messages in a queue. **Head** indicates the start position of occupied message nodes in the queue. **Tail** indicates the end position of the occupied message nodes and the start position of idle message nodes. When a queue is created, **Head** and **Tail** point to the start position of the queue.
- The queue control block contains **Head** and **Tail**, which indicate the storage status of messages in a queue. **Head** indicates the start position of occupied message nodes in the queue. **Tail** indicates the end position of the occupied message nodes and the start position of idle message nodes. When a queue is created, **Head** and **Tail** point to the start position of the queue.
- When data is to be written to a queue, **readWriteableCnt\[1\]** is used to determine whether data can be written to the queue. If **readWriteableCnt\[1\]** is **0**, the queue is full and data cannot be written to it. Data can be written to the head node or tail node of a queue. To write data to the tail node, locate the start idle message node based on **Tail** and write data to it. If **Tail** is pointing to the tail of the queue, the rewind mode is used. To write data to the head node, locate previous node based on **Head** and write data to it. If **Head** is pointing to the start position of the queue, the rewind mode is used.
- When a queue is to be read, **readWriteableCnt\[0\]** is used to determine whether the queue has messages to read. Reading an idle queue \(**readWriteableCnt\[0\]** is** 0**\) will cause task suspension. If the queue has messages to read, the system locates the first node to which data is written based on **Head** and read the message from the node. If **Head** is pointing to the tail of the queue, the rewind mode is used.
- When a queue is to be deleted, the system locates the queue based on the queue ID, sets the queue status to **OS\_QUEUE\_UNUSED**, sets the queue control block to the initial state, and releases the memory occupied by the queue.
**Figure 1** Reading and writing data in a queue<aname="fig139854471119"></a>
- When data is to be written to a queue, **readWriteableCnt[1]** is used to determine whether data can be written to the queue. If **readWriteableCnt[1]** is **0**, the queue is full and data cannot be written to it. Data can be written to the head node or tail node of a queue. To write data to the tail node, locate the start idle message node based on **Tail** and write data to it. If **Tail** is pointing to the tail of the queue, the rewind mode is used. To write data to the head node, locate previous node based on **Head** and write data to it. If **Head** is pointing to the start position of the queue, the rewind mode is used.
- When a queue is to be read, **readWriteableCnt[0]** is used to determine whether the queue has messages to read. Reading an idle queue (**readWriteableCnt[0]** is** 0**) will cause task suspension. If the queue has messages to read, the system locates the first node to which data is written based on **Head** and read the message from the node. If **Head** is pointing to the tail of the queue, the rewind mode is used.
- When a queue is to be deleted, the system locates the queue based on the queue ID, sets the queue status to **OS_QUEUE_UNUSED**, sets the queue control block to the initial state, and releases the memory occupied by the queue.
| Creating or deleting a message queue| - **LOS_QueueCreate**: creates a message queue. The system dynamically allocates the queue space.<br>- **LOS_QueueDelete**: deletes a queue.|
| Reading or writing data (address without the content) in a queue| - **LOS_QueueRead**: reads data in the head node of the specified queue. The data in the queue node is an address.<br>- **LOS_QueueWrite**: writes the value of **bufferAddr** (buffer address) to the tail node of a queue.<br>- **LOS_QueueWrite**: writes the value of **bufferAddr** (buffer address) to the head node of a queue.|
</th>
| Reading or writing data (data and address) in a queue| - **LOS_QueueReadCopy**: reads data from the head node of a queue.<br>- **LOS_QueueWriteCopy**: writes the data saved in **bufferAddr** to the tail node of a queue.<br>- **LOS_QueueWriteHeadCopy**: writes the data saved in **bufferAddr** to the head node of a queue.|
</tr>
| Obtaining queue information| **LOS_QueueInfoGet**: obtains queue information, including the queue ID, queue length, message node size, head node, tail node, number of readable/writable nodes, and tasks waiting for read/write operations.|
</thead>
<tbody><trid="row1693665613516"><tdclass="cellrowborder"rowspan="2"valign="top"width="23.56%"headers="mcps1.1.4.1.1 "><pid="p193675615514"><aname="p193675615514"></a><aname="p193675615514"></a>Creating or deleting a message queue</p>
1. Call **LOS_QueueCreate** to create a queue. The queue ID is returned when the queue is created.
<tdclass="cellrowborder"valign="top"width="52.15%"headers="mcps1.1.4.1.3 "><pid="p1593620562517"><aname="p1593620562517"></a><aname="p1593620562517"></a>Creates a message queue. The system dynamically allocates the queue space.</p>
</td>
2. Call **LOS_QueueWrite** or **LOS_QueueWriteCopy** to write data to the queue.
3. Call **LOS_QueueRead** or **LOS_QueueReadCopy** to read data from the queue.
</td>
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p4936155695111"><aname="p4936155695111"></a><aname="p4936155695111"></a>Deletes the specified queue based on the queue ID. </p>
4. Call **LOS_QueueInfoGet** to obtain queue information.
</td>
</tr>
5. Call **LOS_QueueDelete** to delete a queue.
<trid="row093614566519"><tdclass="cellrowborder"rowspan="3"valign="top"width="23.56%"headers="mcps1.1.4.1.1 "><pid="p1593685614513"><aname="p1593685614513"></a><aname="p1593685614513"></a>Reading or writing data in a queue (without the content contained in the address)</p>
> - The maximum number of queues supported by the system is the total number of queue resources of the system, not the number of queue resources available to users. For example, if the system software timer occupies one more queue resource, the number of queue resources available to users decreases by one.
</td>
>
<tdclass="cellrowborder"valign="top"width="52.15%"headers="mcps1.1.4.1.3 "><pid="p11936556155118"><aname="p11936556155118"></a><aname="p11936556155118"></a>Reads data in the head node of the specified queue. The data in the queue node is an address.</p>
> - The queue name and flags passed in when a queue is created are reserved for future use.
</td>
>
</tr>
> - The parameter **timeOut** in the queue function is relative time.
> - **LOS_QueueReadCopy**, **LOS_QueueWriteCopy**, and **LOS_QueueWriteHeadCopy** are a group of APIs that must be used together. **LOS_QueueRead**, **LOS_QueueWrite**, and **LOS_QueueWriteHead** are a group of APIs that must be used together.
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p12936256175120"><aname="p12936256175120"></a><aname="p12936256175120"></a>Writes the value of the input parameter <strongid="b9518118105313"><aname="b9518118105313"></a><aname="b9518118105313"></a>bufferAddr</strong> (buffer address) to the tail node of the specified queue.</p>
>
</td>
> - As **LOS_QueueWrite**, **LOS_QueueWriteHead**, and **LOS_QueueRead** are used to manage data addresses, you must ensure that the memory directed by the pointer obtained by calling **LOS_QueueRead** is not modified or released abnormally when the queue is being read. Otherwise, unpredictable results may occur.
> - If the length of the data to read in **LOS_QueueRead** or **LOS_QueueReadCopy** is less than the actual message length, the message will be truncated.
</td>
>
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p193620566515"><aname="p193620566515"></a><aname="p193620566515"></a>Writes the value of the input parameter <strongid="b16808172214534"><aname="b16808172214534"></a><aname="b16808172214534"></a>bufferAddr</strong> (buffer address) to the head node of the specified queue.</p>
> - **LOS_QueueWrite**, **LOS_QueueWriteHead**, and **LOS_QueueRead** are called to manage data addresses, which means that the actual data read or written is pointer data. Therefore, before using these APIs, ensure that the message node size is the pointer length during queue creation, to avoid waste and read failures.
</td>
</tr>
<trid="row593675635117"><tdclass="cellrowborder"rowspan="3"valign="top"width="23.56%"headers="mcps1.1.4.1.1 "><pid="p293675615111"><aname="p293675615111"></a><aname="p293675615111"></a>Reading or writing in a queue (with the content contained in the address)</p>
<tdclass="cellrowborder"valign="top"width="52.15%"headers="mcps1.1.4.1.3 "><pid="p11936155616510"><aname="p11936155616510"></a><aname="p11936155616510"></a>Reads data from the head node of the specified queue.</p>
</td>
Create a queue and two tasks. Enable task 1 to write data to the queue, and task 2 to read data from the queue.
1. Call **LOS_TaskCreate** to create task 1 and task 2.
</td>
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p6936155616515"><aname="p6936155616515"></a><aname="p6936155616515"></a>Writes the data saved in the input parameter <strongid="b14415194615537"><aname="b14415194615537"></a><aname="b14415194615537"></a>bufferAddr</strong> to the tail node of the specified queue.</p>
2. Call **LOS_QueueCreate** to create a message queue.
<tdclass="cellrowborder"valign="top"headers="mcps1.1.4.1.2 "><pid="p1193625675116"><aname="p1193625675116"></a><aname="p1193625675116"></a>Writes the data saved in the input parameter <strongid="b1030118493534"><aname="b1030118493534"></a><aname="b1030118493534"></a>bufferAddr</strong> to the head node of the specified queue.</p>
The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **ExampleQueue** function is called in **TestTaskEntry**.
<tdclass="cellrowborder"valign="top"width="52.15%"headers="mcps1.1.4.1.3 "><pid="p19371356175110"><aname="p19371356175110"></a><aname="p19371356175110"></a>Obtains information about the specified queue, including the queue ID, queue length, message node size, head node, tail node, number of readable nodes, number of writable nodes, tasks waiting for read operations, and tasks waiting for write operations.</p>
</td>
To avoid excessive printing, call **LOS_Msleep(5000)** to cause a short delay before calling **ExampleQueue**.
</tr>
</tbody>
</table>
### How to Develop<a name="section1390154210243"></a>
1. Call **LOS\_QueueCreate** to create a queue. The queue ID is returned when the queue is created.
2. Call **LOS\_QueueWrite** or **LOS\_QueueWriteCopy** to write messages to the queue.
3. Call **LOS\_QueueRead** or **LOS\_QueueReadCopy** to read messages from the queue.
4. Call **LOS\_QueueInfoGet** to obtain queue information.
>- The maximum number of queues supported by the system is the total number of queue resources of the system, not the number of queue resources available to users. For example, if the system software timer occupies one more queue resource, the number of queue resources available to users decreases by one.
>- The input parameters queue name and flags passed when a queue is created are reserved for future use.
>- The input parameter **timeOut** in the queue interface function is relative time.
>- **LOS\_QueueReadCopy**, **LOS\_QueueWriteCopy**, and **LOS\_QueueWriteHeadCopy** are a group of APIs that must be used together. **LOS\_QueueRead**, **LOS\_QueueWrite**, and **LOS\_QueueWriteHead** are a group of APIs that must be used together.
>- As **LOS\_QueueWrite**, **LOS\_QueueWriteHead**, and **LOS\_QueueRead** are used to manage data addresses, you must ensure that the memory directed by the pointer obtained by calling **LOS\_QueueRead** is not modified or released abnormally when the queue is being read. Otherwise, unpredictable results may occur.
>- If the input parameter **bufferSize** in **LOS\_QueueRead** and **LOS\_QueueReadCopy** is less than the length of the message, the message will be truncated.
>- **LOS\_QueueWrite**, **LOS\_QueueWriteHead**, and **LOS\_QueueRead** are called to manage data addresses, which means that the actual data read or written is pointer data. Therefore, before using these APIs, ensure that the message node size is the pointer length during queue creation, to avoid waste and read failures.
## Development Example<a name="section27132341285"></a>
### Example Description<a name="section197311443141017"></a>
Create a queue and two tasks. Enable task 1 to call the queue write API to send messages, and enable task 2 to receive messages by calling the queue read API.
1. Create task 1 and task 2 by calling **LOS\_TaskCreate**.
2. Create a message queue by calling **LOS\_QueueCreate**.
3. Enable messages to be sent in task 1 by calling **SendEntry**.
4. Enable messages to be received in task 2 by calling **RecvEntry**.
Semaphore is a mechanism for implementing inter-task communication. It implements synchronization between tasks or exclusive access to shared resources.
Semaphore is a mechanism used to implement synchronization between tasks or exclusive access to shared resources.
In the data structure of a semaphore, there is a value indicating the number of shared resources available. The value can be:
In the semaphore data structure, there is a value indicating the number of shared resources available. The value can be:
-**0**: The semaphore is unavailable. In this case, tasks waiting for the semaphore may exist.
-**0**: The semaphore is unavailable. Tasks waiting for the semaphore may exist.
- Positive number: The semaphore is available.
- Positive number: The semaphore is available.
The semaphore for exclusive access is different from the semaphore for synchronization:
The semaphore used for exclusive access to resources is different from the semaphore used for synchronization:
- Semaphore used for exclusive access: The initial semaphore counter value \(non-zero\) indicates the number of shared resources available. A semaphore must be acquired before a shared resource is used, and released when the resource is no longer required. When all shared resources are used, the semaphore counter is reduced to 0 and all tasks requiring the semaphore will be blocked. This ensures exclusive access to shared resources. In addition, if the number of shared resources is 1, a binary semaphore \(similar to the mutex mechanism\) is recommended.
- Semaphore used for synchronization: The initial semaphore counter value is **0**. A task without the semaphore will be blocked, and enters the Ready or Running state only when the semaphore is released by another task or an interrupt.
- Semaphore used for exclusive access: The initial semaphore counter value \(non-zero\) indicates the number of shared resources available. The semaphore counter value must be acquired before a shared resource is used, and released when the resource is no longer required. When all shared resources are used, the semaphore counter is reduced to 0 and the tasks that need to obtain the semaphores will be blocked. This ensures exclusive access to shared resources. In addition, when the number of shared resources is 1, a binary semaphore \(similar to the mutex mechanism\) is recommended.
- Semaphore used for synchronization: The initial semaphore counter value is **0**. Task 1 cannot acquire the semaphore and is blocked. Task 1 enters Ready or Running state only when the semaphore is released by task 2 or an interrupt. In this way, task synchronization is implemented.
## Working Principles<a name="section118423019134"></a>
## Working Principles
**Semaphore Control Block**
**Semaphore Control Block**
```
```
/**
/**
* Data structure of the semaphore control block
* Data structure of the semaphore control block
*/
*/
typedef struct {
typedef struct {
UINT16 semStat; /* Semaphore status */
UINT16 semStat; /* Semaphore status */
UINT16 semType; /* Semaphore type*/
UINT16 semType; /* Semaphore type*/
UINT16 semCount; /* Semaphore count*/
UINT16 semCount; /* Semaphore count*/
UINT16 semId; /* Semaphore index*/
UINT16 semId; /* Semaphore ID */
LOS_DL_LIST semList; /* Mount the task blocked by the semaphore.*/
LOS_DL_LIST semList; /* List of blocked tasks */
} LosSemCB;
} LosSemCB;
```
```
...
@@ -38,100 +42,87 @@ Semaphore allows only a specified number of tasks to access a shared resource at
...
@@ -38,100 +42,87 @@ Semaphore allows only a specified number of tasks to access a shared resource at
- Semaphore initialization
- Semaphore initialization
The system allocates memory for the semaphores configured \(you can configure the number of semaphores using the **LOSCFG\_BASE\_IPC\_SEM\_LIMIT** macro\), initializes all semaphores to be unused semaphores, and adds them to a linked list for the system to use.
Allocate memory for the semaphores (the number of semaphores is specified by the **LOSCFG_BASE_IPC_SEM_LIMIT** macro), set all semaphores to the unused state, and add them to a linked list.
- Semaphore creation
- Semaphore creation
The system obtains a semaphore from the linked list of unused semaphores and assigns an initial value to the semaphore.
Obtain a semaphore from the linked list of unused semaphores and assign an initial value to the semaphore.
- Semaphore request
- Semaphore request
If the counter value is greater than 0, the system allocates a semaphore, decreases the value by 1, and returns a success message. Otherwise, the system blocks the task and moves the task to the end of a task queue waiting for semaphores. The wait timeout period can be set.
If the counter value is greater than 0 when a semaphore is requsted, the counter is decreased by 1 and a success message is returned. Otherwise, the task is blocked and added to the end of a task queue waiting for semaphores. The wait timeout period can be set.
- Semaphore release
- Semaphore release
When a semaphore is released, if there is no task waiting for it, the counter value is increased by 1. Otherwise, the first task in the wait queue is woken up.
If no task is waiting for the semaphore, the counter is incremented by 1. Otherwise, wake up the first task in the wait queue.
- Semaphore deletion
- Semaphore deletion
The system sets a semaphore in use to unused state and inserts it to the linked list of unused semaphores.
Set a semaphore in use to the unused state and add it to the linked list of unused semaphores.
The following figure illustrates the semaphore working mechanism.
The following figure illustrates the semaphore working mechanism.
**Figure 1** Semaphore working mechanism for small systems<aname="fig467314634214"></a>
**Figure 1** Semaphore working mechanism for the small system
| LOS_BinarySemCreate | Creates a binary semaphore. The maximum counter value is **1**.|
</th>
| LOS_SemDelete | Deletes a semaphore.|
</tr>
</thead>
**Table 2** APIs for requesting and releasing a semaphore
<tbody><trid="row0415737175610"><tdclass="cellrowborder"rowspan="3"valign="top"width="12.85128512851285%"headers="mcps1.2.4.1.1 "><pid="p8866127195914"><aname="p8866127195914"></a><aname="p8866127195914"></a>Creating or deleting a semaphore</p>
| LOS_SemPend | Requests a semaphore and sets a timeout period.|
<tdclass="cellrowborder"valign="top"width="57.34573457345735%"headers="mcps1.2.4.1.3 "><pid="p48623102592"><aname="p48623102592"></a><aname="p48623102592"></a>Creates a semaphore and returns the semaphore ID.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p1886211011599"><aname="p1886211011599"></a><aname="p1886211011599"></a>Creates a binary semaphore. The maximum counter value is <strongid="b4125169919"><aname="b4125169919"></a><aname="b4125169919"></a>1</strong>.</p>
1. Call **LOS_SemCreate** to create a semaphore. To create a binary semaphore, call **LOS_BinarySemCreate**.
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p586261085913"><aname="p586261085913"></a><aname="p586261085913"></a>Deletes a semaphore.</p>
</td>
4. Call **LOS_SemDelete** to delete a semaphore.
</tr>
<trid="row73651459105815"><tdclass="cellrowborder"rowspan="2"valign="top"width="12.85128512851285%"headers="mcps1.2.4.1.1 "><pid="p16927183515593"><aname="p16927183515593"></a><aname="p16927183515593"></a>Requesting or releasing a semaphore</p>
> **NOTE**<br>
</td>
> As interrupts cannot be blocked, semaphores cannot be requested in block mode for interrupts.
<tdclass="cellrowborder"valign="top"width="57.34573457345735%"headers="mcps1.2.4.1.3 "><pid="p555221518598"><aname="p555221518598"></a><aname="p555221518598"></a>Requests a specified semaphore and sets the timeout period.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p1555261595915"><aname="p1555261595915"></a><aname="p1555261595915"></a>Posts (releases) a semaphore.</p>
</td>
</tr>
</tbody>
</table>
### How to Develop<a name="section154261711141419"></a>
1. Call **LOS\_SemCreate** to create a semaphore. To create a binary semaphore, call **LOS\_BinarySemCreate**.
>As interrupts cannot be blocked, semaphores cannot be requested in block mode for interrupts.
### Development Example<a name="section658135571417"></a>
### Example Description<a name="section125244411653"></a>
This example implements the following:
This example implements the following:
1. Create a semaphore in task **ExampleSem** and lock task scheduling. Create two tasks **ExampleSemTask1** and **ExampleSemTask2**\(with higher priority\). Enable the two tasks to request the same semaphore. Unlock task scheduling. Enable task **ExampleSem** to enter sleep mode for 400 ticks. Release the semaphore in task **ExampleSem**.
1. Create a semaphore in task **ExampleSem** and lock task scheduling. Create two tasks **ExampleSemTask1** and **ExampleSemTask2** (with higher priority). Enable the two tasks to request the same semaphore. Unlock task scheduling. Enable task **ExampleSem** to enter sleep mode for 400 ticks. Release the semaphore in task **ExampleSem**.
2. Enable** ExampleSemTask2** to enter sleep mode for 20 ticks after acquiring the semaphore. \(When **ExampleSemTask2** is delayed, **ExampleSemTask1** is woken up.\)
3. Enable **ExampleSemTask1** to request the semaphore in scheduled block mode, with a wait timeout period of 10 ticks. \(Because the semaphore is still held by **ExampleSemTask2**, **ExampleSemTask1** is suspended. **ExampleSemTask1** is woken up after 10 ticks.\) Enable **ExampleSemTask1** to request the semaphore in permanent block mode after it is woken up 10 ticks later. \(Because the semaphore is still held by **ExampleSemTask2**, **ExampleSemTask1** is suspended.\)
2. Enable **ExampleSemTask2** to enter sleep mode for 20 ticks after acquiring the semaphore. (When **ExampleSemTask2** is delayed, **ExampleSemTask1** is woken up.)
3. Enable **ExampleSemTask1** to request the semaphore in scheduled block mode, with a wait timeout period of 10 ticks. (Because the semaphore is still held by **ExampleSemTask2**, **ExampleSemTask1** is suspended. **ExampleSemTask1** is woken up after 10 ticks.) Enable **ExampleSemTask1** to request the semaphore in permanent block mode after it is woken up 10 ticks later. (Because the semaphore is still held by **ExampleSemTask2**, **ExampleSemTask1** is suspended.)
4. After 20 ticks, **ExampleSemTask2** is woken up and releases the semaphore. **ExampleSemTask1** acquires the semaphore and is scheduled to run. When **ExampleSemTask1** is complete, it releases the semaphore.
4. After 20 ticks, **ExampleSemTask2** is woken up and releases the semaphore. **ExampleSemTask1** acquires the semaphore and is scheduled to run. When **ExampleSemTask1** is complete, it releases the semaphore.
5. Task **ExampleSem** is woken up after 400 ticks and deletes the semaphore.
5. Task **ExampleSem** is woken up after 400 ticks. After that, delete the semaphore.
### Sample Code
The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **ExampleSem** function is called in **TestTaskEntry**.
Fast userspace mutex \(futex\) is a system call capability provided by the kernel. It is a basic component that combines with user-mode lock logic to form a user-mode lock. It is a lock working in both user mode and kernel mode, for example, userspace mutex, barrier and cond synchronization lock, and RW lock. The user-mode part implements lock logic, and the kernel-mode part schedules locks.
Fast userspace mutex (futex) is a system call capability provided by the kernel. It is a basic component that combines with user-mode lock logic to form a user-mode lock. It is a lock working in both user mode and kernel mode, for example, userspace mutex, barrier and cond synchronization lock, and RW lock. The user-mode part implements lock logic, and the kernel-mode part schedules locks.
When a user-mode thread requests a lock, the lock status is first checked in user space. If no lock contention occurs, the user-mode thread acquires the lock directly. If lock contention occurs, the futex system call is invoked to request the kernel to suspend the thread and maintain the blocking queue.
When a user-mode thread requests a lock, the lock status is first checked in user space. If no lock contention occurs, the user-mode thread acquires the lock directly. If lock contention occurs, the futex system call is invoked to request the kernel to suspend the thread and maintain the blocking queue.
When a user-mode thread releases a lock, the lock status is first checked in user space. If no other thread is blocked by the lock, the lock is directly released in user space. If there are threads blocked by the lock, the futex system call is invoked to request the kernel to wake up the threads in the blocking queue.
When a user-mode thread releases a lock, the lock status is first checked in user space. If no other thread is blocked by the lock, the lock is directly released in user space. If there are threads blocked by the lock, the futex system call is invoked to request the kernel to wake up the threads in the blocking queue.
## Working Principles<a name="section16834132502910"></a>
## Working Principles
When thread scheduling is required to resolve lock contention or lock release in user space, the futex system call is invoked to pass the user-mode lock address to the kernel. The user-mode locks are distinguished by lock address in the futex of the kernel. The available virtual address space in user space is 1 GiB. To facilitate search and management of lock addresses, the kernel futex uses hash buckets to store the user-mode locks.
When thread scheduling is required to resolve lock contention or lock release in user space, the futex system call is invoked to pass the user-mode lock address to the kernel. The user-mode locks are distinguished by lock address in the futex of the kernel. The available virtual address space in user space is 1 GiB. To facilitate search and management of lock addresses, the kernel futex uses hash buckets to store the user-mode locks.
There are 80 hash buckets. Buckets 0 to 63 are used to store private locks \(hashed based on virtual addresses\), and buckets 64 to 79 are used to store shared locks \(hashed based on physical addresses\). The private/shared attributes are determined by initialization of user-mode locks and the input parameters in the futex system call.
There are 80 hash buckets used to store shared locks (hashed based on physical addresses). The private/shared attributes are determined by initialization of user-mode locks and the input parameters in the futex system call.
As shown in the above figure, each futex hash bucket stores the futex nodes with the same hash value linked in a futex\_list. Each futex node corresponds to a suspended task. The key value of a node uniquely identifies a user-mode lock. The nodes with the same key value added to a queue\_list indicate a queue of tasks blocked by the same lock.
As shown in the above figure, each futex hash bucket stores the futex nodes with the same hash value linked in a futex_list. Each futex node corresponds to a suspended task. The key value of a node uniquely identifies a user-mode lock. The nodes with the same key value added to a queue_list indicate a queue of tasks blocked by the same lock.
The following table describes the APIs available for the futex module.
<tbody><trid="row04981218910"><tdclass="cellrowborder"valign="top"width="27.09270927092709%"headers="mcps1.2.4.1.1 "><pid="p6462616696"><aname="p6462616696"></a><aname="p6462616696"></a>Putting a thread to wait</p>
<tdclass="cellrowborder"valign="top"width="46.384638463846386%"headers="mcps1.2.4.1.3 "><pid="p8504121996"><aname="p8504121996"></a><aname="p8504121996"></a>Inserts a node representing a blocked thread into the futex list.</p>
</td>
</tr>
<trid="row7162101814216"><tdclass="cellrowborder"valign="top"width="27.09270927092709%"headers="mcps1.2.4.1.1 "><pid="p37331032985"><aname="p37331032985"></a><aname="p37331032985"></a>Waking up a thread</p>
<tdclass="cellrowborder"valign="top"width="46.384638463846386%"headers="mcps1.2.4.1.3 "><pid="p161632181721"><aname="p161632181721"></a><aname="p161632181721"></a>Wakes up a thread that is blocked by a specified lock.</p>
</td>
</tr>
<trid="row101631818620"><tdclass="cellrowborder"valign="top"width="27.09270927092709%"headers="mcps1.2.4.1.1 "><pid="p146111936887"><aname="p146111936887"></a><aname="p146111936887"></a>Modifying the lock address</p>
<tdclass="cellrowborder"valign="top"width="46.384638463846386%"headers="mcps1.2.4.1.3 "><pid="p151631718124"><aname="p151631718124"></a><aname="p151631718124"></a>Adjusts the position of a specified lock in the futex list.</p>
Signal is a common inter-process asynchronous communication mechanism. It uses software-simulated interrupt signals. When a process needs to communicate with another process, it sends a signal to the kernel. The kernel then transfers the signal to the destination process. The destination process does not need to wait for the signal.
Signal is a common asynchronous communication mechanism between processes. It uses software-simulated interrupt signals. When a process needs to communicate with another process, it sends a signal to the kernel. The kernel transfers the signal to the target process. The target process does not need to wait for the signal.
## Working Principles<a name="section1249693812301"></a>
The following table describes the APIs available for signal operations.
## Working Principles
**Table 1** Signal operation process and APIs \(user-mode APIs\)
The following table describes the APIs for signal operations.
<tbody><trid="row04981218910"><tdclass="cellrowborder"rowspan="2"valign="top"width="27.09270927092709%"headers="mcps1.2.4.1.1 "><pid="p6462616696"><aname="p6462616696"></a><aname="p6462616696"></a>Registering the signal callback</p>
<tdclass="cellrowborder"valign="top"width="46.41464146414641%"headers="mcps1.2.4.1.3 "><pid="p8504121996"><aname="p8504121996"></a><aname="p8504121996"></a>Registers the main signal entry, and registers and unregisters the callback function of a signal.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p1945083962113"><aname="p1945083962113"></a><aname="p1945083962113"></a>Same as <strongid="b1076755712371"><aname="b1076755712371"></a><aname="b1076755712371"></a>signal</strong>. This API is added with configuration options related to signal transmission. Currently, only some parameters in the <strongid="b18458105019218"><aname="b18458105019218"></a><aname="b18458105019218"></a>SIGINFO</strong> structure are supported.</p>
<tdclass="cellrowborder"rowspan="5"align="left"valign="top"width="46.41464146414641%"headers="mcps1.2.4.1.3 "><pid="p161632181721"><aname="p161632181721"></a><aname="p161632181721"></a>Sends a signal to a process or sends messages to a thread in a process, and sets signal flags for threads in a process.</p>
<trid="row101631818620"><tdclass="cellrowborder"valign="top"width="27.09270927092709%"headers="mcps1.2.4.1.1 "><pid="p146111936887"><aname="p146111936887"></a><aname="p146111936887"></a>Triggering a callback</p>
<tdclass="cellrowborder"valign="top"width="46.41464146414641%"headers="mcps1.2.4.1.3 "><pid="p1126941694213"><aname="p1126941694213"></a><aname="p1126941694213"></a>Triggered by a system call or an interrupt. Before the switching between the kernel mode and user mode, the specified function in user mode is entered, and the corresponding callbacks are processed. After that, the original user-mode program continues to run.</p>
| Registering/Unregistering a signal callback| signal | Registers the main signal entry, and registers or unregisters a callback for a signal. |
>```
| Registering a signal callback| sigaction | Same as **signal**. This API is added with configuration options related to signal transmission. Currently, only some parameters in the **SIGINFO** structure are supported.|
>void *signal(int sig, void (*func)(int))(int);
| Sending a signal | kill<br>pthread_kill<br>raise<br>alarm<br>abort | Sends a signal to a process or sends a message to a thread in a process, and sets the signal flag for a thread in a process. |
>```
| Invoking a callback | NA | Called by a system call or an interrupt. Before the switching between the kernel mode and user mode, the callback in the specified function in user mode is processed. After that, the original user-mode program continues to run.|
>a. Signal 31 is used to register the handling entry of the process callback. Repeated registration is not allowed.
>b. Signals 0 to 30 are used to register and unregister callbacks.
>You can obtain and modify the configuration of signal registration. Currently, only the **SIGINFO** options are supported. For details, see the description of the **sigtimedwait** API.
>Transmit a signal.
>a. Among the default signal-receiving behaviors, the process does not support **STOP**, **CONTINUE**, and **COREDUMP** defined in the POSIX standard.
>b. The **SIGSTOP**, **SIGKILL**, and **SIGCONT** signals cannot be shielded.
>c. If a process killed is not reclaimed by its parent process, the process becomes a zombie process.
>d. A process will not call back the signal received until the process is scheduled.
>e. When a process is killed, **SIGCHLD** is sent to its parent process. The signal sending action cannot be canceled.
>f. A process in the DELAY state cannot be woken up by a signal.
> **NOTE**<br>
> The signal mechanism enables communication between user-mode programs. The user-mode POSIX APIs listed in the above table are recommended.
>
> **Registering a Callback**
>
>
> ```
> void *signal(int sig, void (*func)(int))(int);
> ```
>
> - Signal 31 is used to register the handling entry of the process callback. Repeated registration is not allowed.
>
>
> - Signals 0 to 30 are used to register and unregister callbacks.
>
>
> **Registering a Callback**
>
>
> ```
> int sigaction(int, const struct sigaction ***restrict, struct sigaction ***restrict);
> ```
>
> You can obtain and modify the configuration of signal registration. Currently, only the **SIGINFO** options are supported. For details, see the description of the **sigtimedwait** API.
>
> **Sending a Signal**
>
> - Among the default signal-receiving behaviors, the process does not support **STOP**, **COTINUE**, and **COREDUMP** defined in POSIX.
>
>
> - The **SIGSTOP**, **SIGKILL**, and **SIGCONT** signals cannot be shielded.
>
>
> - If a process killed is not reclaimed by its parent process, the process becomes a zombie process.
>
>
> - A process will not call back the signal received until the process is scheduled.
>
>
> - When a process is killed, **SIGCHLD** is sent to its parent process. The signal sending action cannot be canceled.
>
>
> - A process in the DELAY state cannot be woken up by a signal.
LiteIPC is a new inter-process communication \(IPC\) mechanism provided by the OpenHarmony LiteOS-A kernel. Different from the traditional System V IPC, LiteIPC is designed for Remote Procedure Call \(RPC\). In addition, it provides APIs for the upper layer through device files, not through traditional API functions.
LiteIPC has two important concepts: ServiceManager and Service. The entire system can have one ServiceManager and multiple Services. ServiceManager is responsible for registering and unregistering Services, and managing Service access permission \(only authorized tasks can send IPC messages to corresponding Services\).
## Working Principles<a name="section849811592918"></a>
ServiceManager registers the task that needs to receive IPC messages as a Service, and sets the access permission for the Service task \(specifies the tasks that can send IPC messages to the Service\). LiteIPC maintains an IPC message queue for each Service task in kernel mode. The message queue provides the upper-layer user-mode programs with the read operation \(receiving IPC messages\) and the write operations \(sending IPC messages\) through LiteIPC device files.
## Development Guidelines<a name="section17571315171017"></a>
### Available APIs<a name="section725022011103"></a>
**Table 1** LiteIPC module APIs \(for LiteOS-A internal use only\)
<tdclass="cellrowborder"valign="top"width="57.34573457345735%"headers="mcps1.2.4.1.3 "><pid="p48623102592"><aname="p48623102592"></a><aname="p48623102592"></a>Initializes the LiteIPC module.</p>
<tdclass="cellrowborder"valign="top"width="57.34573457345735%"headers="mcps1.2.4.1.3 "><pid="p1886211011599"><aname="p1886211011599"></a><aname="p1886211011599"></a>Initializes the IPC message memory pool of processes.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p586261085913"><aname="p586261085913"></a><aname="p586261085913"></a>Re-initializes the IPC message memory pool of processes.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p555221518598"><aname="p555221518598"></a><aname="p555221518598"></a>Releases the IPC message memory pool of processes.</p>
<tdclass="cellrowborder"valign="top"width="57.34573457345735%"headers="mcps1.2.4.1.3 "><pid="p1555261595915"><aname="p1555261595915"></a><aname="p1555261595915"></a>Deletes the specified Service.</p>
>LiteIPC module APIs are used for LiteOS-A internal use only.
LiteIPC is a new inter-process communication (IPC) mechanism provided by the OpenHarmony LiteOS-A kernel. Different from the traditional System V IPC, LiteIPC is designed for Remote Procedure Call (RPC). In addition, it provides APIs for the upper layer through device files, not through traditional API functions.
LiteIPC has two important concepts: ServiceManager and Service. The entire system can have one ServiceManager and multiple Services.
ServiceManager provides the following functions:
- Registers and deregisters services.
- Manages the access permission of services. Only authorized tasks can send IPC messages to the service.
## Working Principles
ServiceManager registers the task that needs to receive IPC messages as a Service, and sets the access permission for the Service task (specifies the tasks that can send IPC messages to the Service).
LiteIPC maintains an IPC message queue for each Service task in kernel mode. The message queue provides the upper-layer user-mode programs with the read operation (receiving IPC messages) and the write operations (sending IPC messages) through LiteIPC device files.
## Development Guidelines
### Available APIs
**Table 1** APIs of the LiteIPC module (applicable to LiteOS-A only)
| Module initialization | **OsLiteIpcInit**: initializes the LiteIPC module. |
| IPC message memory pool| - **LiteIpcPoolInit**: initializes the IPC message memory pool of a process.<br>- **LiteIpcPoolReInit**: reinitializes the IPC message memory pool of a process.<br>- **LiteIpcPoolDelete**: releases the IPC message memory pool of a process. |
| Service management | **LiteIpcRemoveServiceHandle**: deletes a service. |
> **NOTE**<br>
> The APIs of the LiteIPC module are dedicated for LiteOS-A internal use only.
The OpenHarmony dynamic loading and linking mechanism includes a kernel loader and a dynamic linker. The kernel loader loads application programs and the dynamic linker. The dynamic linker loads the shared library on which the application programs depend, and performs symbol relocation for the application programs and shared libraries. Compared with static linking, dynamic linking is a mechanism for delaying the linking of applications and dynamic libraries to run time.
The OpenHarmony dynamic loading and linking mechanism includes a kernel loader and a dynamic linker. The kernel loader loads application programs and the dynamic linker. The dynamic linker loads the shared library on which the application programs depend, and performs symbol relocation for the application programs and shared libraries. Compared with static linking, dynamic linking is a mechanism for delaying the linking of applications and dynamic libraries to run time.
**Advantages of Dynamic Linking**
**Advantages of Dynamic Linking**
1. Dynamic linking allows multiple applications to share code. The minimum loading unit is page. Dynamic linking saves disk and memory space than static linking.
- Dynamic linking allows multiple applications to share code. The minimum loading unit is page. Dynamic linking saves disk and memory space than static linking.
2. When a shared library is upgraded, the new shared library overwrites the earlier version \(the APIs of the shared library are downward compatible\). You do not need to re-link the shared library.
3. The loading address can be randomized to prevent attacks and ensure security.
- When a shared library is upgraded, the new shared library overwrites the earlier version (the APIs of the shared library are downward compatible). You do not need to re-link the shared library.
- The loading address can be randomized to prevent attacks and ensure security.
## Working Principles<a name="section14140155320511"></a>
1. The kernel maps the **PT\_LOAD** section in the ELF file of the application to the process space. For files of the ET\_EXEC type, fixed address mapping is performed based on **p\_vaddr** in the **PT\_LOAD** section. For files of the ET\_DYN type \(position-independent executable programs, obtained through the compile option **-fPIE**\), the kernel selects the **base** address via **mmap** for mapping \(load\_addr = base + p\_vaddr\).
1. The kernel maps the **PT_LOAD** section in the ELF file of the application to the process space. For files of the ET_EXEC type, fixed address mapping is performed based on **p_vaddr** in the **PT_LOAD** section. For files of the ET_DYN type (position-independent executable programs, obtained through **-fPIE**), the kernel selects the **base** address via **mmap** for mapping (load_addr = base + p_vaddr).
2. If the application is statically linked \(static linking does not support the compile option **-fPIE**\), after the stack information is set, the system redirects to the address specified by **e\_entry** in the ELF file of the application and runs the application. If the program is dynamically linked, the application ELF file contains the **PT\_INTERP** section, which stores the dynamic linker path information \(ET\_DYN type\). The dynamic linker of musl is a part of the **libc-musl.so**. The entry of **libc-musl.so** is the entry of the dynamic linker. The kernel selects the **base** address for mapping via the **mmap** API, sets the stack information, redirects to the **base + e\_entry**\(entry of the dynamic linker\) address, and runs the dynamic linker.
3. The dynamic linker bootstraps and searches for all shared libraries on which the application depends, relocates the imported symbols, and finally redirects to the **e\_entry**\(or **base + e\_entry**\) of the application to run the application.
2. If the application is statically linked (static linking does not support **-fPIE**), after the stack information is set, the system redirects to the address specified by **e_entry** in the ELF file of the application and runs the application. If the program is dynamically linked, the application ELF file contains the **PT_INTERP** section, which stores the dynamic linker path information (ET_DYN type). The dynamic linker of musl is a part of the **libc-musl.so**. The entry of **libc-musl.so** is the entry of the dynamic linker. The kernel selects the **base** address for mapping via the **mmap** API, sets the stack information, redirects to the **base + e_entry** (entry of the dynamic linker) address, and runs the dynamic linker.
3. The dynamic linker bootstraps and searches for all shared libraries on which the application depends, relocates the imported symbols, and finally redirects to the **e_entry** (or **base + e_entry**) of the application to run the application.
**Figure 2** Program execution process
**Figure 2** Program execution process<aname="fig17879151310447"></a>
1. The loader and linker call **mmap** to map the **PT\_LOAD** section.
1. The loader and linker call **mmap** to map the **PT_LOAD** section.
2. The kernel calls **map\_pages** to search for and map the existing PageCache.
2. The kernel calls **map_pages** to search for and map the existing PageCache.
3. If there is no physical memory for mapping in the virtual memory region during program execution, the system triggers a page missing interrupt, which allows the ELF file to be read into the physical memory and adds the memory block to the pagecache.
3. If there is no physical memory for mapping in the virtual memory region during program execution, the system triggers a page missing interrupt, which allows the ELF file to be read into the physical memory and adds the memory block to the pagecache.
4. Map the physical memory blocks of the file read to the virtual address region.
4. Map the physical memory blocks of the file read to the virtual address region.
5. The program continues to run.
5. The program continues to run.
## Development Guidelines<a name="section133501496612"></a>
### Available APIs<a name="section874113201669"></a>
<tdclass="cellrowborder"valign="top"width="57.34573457345735%"headers="mcps1.2.4.1.3 "><pid="p48623102592"><aname="p48623102592"></a><aname="p48623102592"></a>Executes the specified user program based on the input parameters.</p>
</td>
</tr>
</tbody>
</table>
### How to Develop<a name="section196712561563"></a>
The kernel cannot directly call the **LOS\_DoExecveFile** API to start a new process. This API is generally called through the **exec\(\)** API to create a new process using the system call mechanism.
### How to Develop
The kernel cannot directly call the **LOS_DoExecveFile** API to start a new process. This API is generally called through the **exec()** API to create a new process using the system call mechanism.
Different from a common dynamic shared library, which stores its .so files in the file system, the virtual dynamic shared object \(VDSO\) has its .so files stored in the system image. The kernel determines the .so files needed and provides them to the application program. That is why the VDSO is called a virtual dynamic shared library.
## Basic Concepts
The VDSO mechanism allows OpenHarmony user-mode programs to quickly obtain kernel-related data. It can accelerate certain system calls and implement quick read of non-sensitive data \(hardware and software configuration\).
Different from a common dynamic shared library, which stores its .so files in the file system, the virtual dynamic shared object (VDSO) has its .so files stored in the system image. The kernel determines the .so files needed and provides them to the application program. That is why the VDSO is called a virtual dynamic shared library.
## Working Principles<a name="section546363114810"></a>
The VDSO mechanism allows OpenHarmony user-mode programs to quickly obtain kernel-related data. It can accelerate certain system calls and implement quick read of non-sensitive data (hardware and software configuration).
The VDSO can be regarded as a section of memory \(read-only\) maintained by the kernel and mapped to the address space of the user-mode applications. By linking **vdso.so**, the applications can directly access this mapped memory instead of invoking system calls, accelerating application execution.
## Working Principles
The VDSO can be regarded as a section of memory (read-only) maintained by the kernel and mapped to the address space of the user-mode applications. By linking **vdso.so**, the applications can directly access this mapped memory instead of invoking system calls, accelerating application execution.
VDSO can be divided into:
VDSO can be divided into:
- Data page: provides the kernel-time data mapped to the user process.
- Data page: provides the kernel-time data mapped to the user process.
- Code page: provides the logic for shielding system calls.
- Code page: provides the logic for shielding system calls.
**Figure 1** VDSO system design<aname="fig1986131094711"></a>
>- The VDSO mechanism supports the **CLOCK\_REALTIME\_COARSE** and **CLOCK\_MONOTONIC\_COARSE** functions of the **clock\_gettime** API in the LibC library. For details about how to use the **clock\_gettime** API, see the POSIX standard. You can call **clock\_gettime\(CLOCK\_REALTIME\_COARSE, &ts\)** or **clock\_gettime\(CLOCK\_MONOTONIC\_COARSE, &ts\)** of the LibC library to use the VDSO.
>
>- When VDSO is used, the time precision is the same as that of the tick interrupt of the system. The VDSO mechanism is applicable to the scenario where there is no demand for high time precision and **clock\_gettime** or **gettimeofday** is frequently triggered in a short period of time. The VDSO mechanism is not recommended for the system demanding high time precision.
> - The VDSO mechanism supports the **CLOCK_REALTIME_COARSE** and **CLOCK_MONOTONIC_COARSE** functions of the **clock_gettime** API in the LibC library. For details about how to use the **clock_gettime** API, see the POSIX standard.
>
> - You can call **clock_gettime(CLOCK_REALTIME_COARSE, &ts)** or **clock_gettime(CLOCK_MONOTONIC_COARSE, &ts)** of the Libc library to use the VDSO.
>
> - When VDSO is used, the time precision is the same as that of the tick interrupt of the system. The VDSO mechanism is applicable to the scenario where there is no demand for high time precision and **clock_gettime** or **gettimeofday** is frequently triggered in a short period of time. The VDSO mechanism is not recommended for the system demanding high time precision.
As an optional function of the kernel, memory corruption check is used to check the integrity of a dynamic memory pool. This mechanism can detect memory corruption errors in the memory pool in a timely manner and provide alerts. It helps reduce problem locating costs and increase troubleshooting efficiency.
As an optional function of the kernel, memory corruption check is used to check the integrity of a dynamic memory pool. This mechanism can detect memory corruption errors in the memory pool in a timely manner and provide alerts. It helps reduce problem locating costs and increase troubleshooting efficiency.
## Function Configuration<a name="section4696190123420"></a>
**LOSCFG\_BASE\_MEM\_NODE\_INTEGRITY\_CHECK**: specifies the setting of the memory corruption check. This function is disabled by default. To enable this function, configure it in **Debug-\> Enable integrity check or not**.
## Function Configuration
**LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK** specifies the setting of the memory corruption check. This function is disabled by default. You can enable it in **Debug -> Enable integrity check or not**.
If this macro is enabled, the memory pool integrity will be checked in real time upon each memory allocation.
If this macro is enabled, the memory pool integrity will be checked in real time upon each memory allocation.
If this macro is not enabled, you can call **LOS\_MemIntegrityCheck** to check the memory pool integrity when required. Using **LOS\_MemIntegrityCheck** does not affect the system performance. In addition, the check accuracy decreases because the node header does not contain the magic number \(which is available only when **LOSCFG\_BASE\_MEM\_NODE\_INTEGRITY\_CHECK** is enabled\).
If this macro is not enabled, you can call **LOS_MemIntegrityCheck** to check the memory pool integrity when required. Using **LOS_MemIntegrityCheck** does not affect the system performance. However, the check accuracy decreases because the node header does not contain the magic number (which is available only when **LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK** is enabled).
This check only detects the corrupted memory node and provides information about the previous node (because memory is contiguous, a node is most likely corrupted by the previous node). To further determine the location where the previous node is requested, you need to enable the memory leak check and use LRs to locate the fault.
> **CAUTION**<br/>
> If memory corruption check is enabled, a magic number is added to the node header, which increases the size of the node header. The real-time integrity check has a great impact on the performance. In performance-sensitive scenarios, you are advised to disable this function and use **LOS_MemIntegrityCheck** to check the memory pool integrity.
This check only detects the corrupted memory node and provides information about the previous node \(because memory is contiguous, a node is most likely corrupted by the previous node\). To further determine the location where the previous node is requested, you need to enable the memory leak check and use LRs to locate the fault.
>If memory corruption check is enabled, a magic number is added to the node header, which increases the size of the node header. The real-time integrity check has a great impact on the performance. In performance-sensitive scenarios, you are advised to disable this function and use **LOS\_MemIntegrityCheck** to check the memory pool integrity.
## Development Guidelines<a name="section672362973417"></a>
### How to Develop
### How to Develop<a name="section026014863416"></a>
Use **LOS_MemIntegrityCheck** to check for memory corruption. If no memory corruption occurs, **0** is returned and no log is output. If memory corruption occurs, the related log is output. For details, see the output of the following example.
Check for memory corruption by calling **LOS\_MemIntegrityCheck**. If no memory corruption occurs, **0** is returned and no log is output. If memory corruption occurs, the related log is output. For details, see the output of the following example.
### Development Example<a name="section186311302356"></a>
### Development Example
This example implements the following:
This example implements the following:
1. Requests two physically adjacent memory blocks.
1. Request two physically adjacent memory blocks.
2. Calls **memset** to construct an out-of-bounds access and overwrites the first four bytes of the next node.
3. Calls **LOS\_MemIntegrityCheck** to check whether memory corruption occurs.
2. Use **memset** to construct an out-of-bounds access and overwrites the first four bytes of the next node.
3. Call **LOS_MemIntegrityCheck** to check for memory corruption.
**Sample Code**
**Sample Code**
You can add the test function of the sample code to **TestTaskEntry** in **kernel/liteos_a/testsuites/kernel/src/osTest.c** for testing.
The sample code is as follows:
The sample code is as follows:
```
```c
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <string.h>
#include "los_memory.h"
#include "los_memory.h"
...
@@ -44,7 +54,7 @@ The sample code is as follows:
...
@@ -44,7 +54,7 @@ The sample code is as follows:
voidMemIntegrityTest(void)
voidMemIntegrityTest(void)
{
{
/* Request two physically adjacent memory blocks.*/
/* Request two physically adjacent memory blocks. */
void*ptr1=LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR,8);
void*ptr1=LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR,8);
void*ptr2=LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR,8);
void*ptr2=LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR,8);
/* Construct an out-of-bounds access to cause memory corruption. The memory block of the first node is 8 bytes. Clearing 12 bytes overwrites the header of the second memory node. */
/* Construct an out-of-bounds access to cause memory corruption. The memory block of the first node is 8 bytes. Clearing 12 bytes overwrites the header of the second memory node. */
memory used but magic num wrong, magic num = 0x00000000 /* Error information, indicating that the first four bytes, that is, the magic number, of the next node are corrupted.*/
memory used but magic num wrong, magic num = 0x00000000 /* Error information, indicating that the first four bytes, that is, the magic number, of the next node are corrupted.*/
/* Key information about the corrupted node and its previous node, including the address of the previous node, magic number of the node, and sizeAndFlag of the node. In this example, the magic number of the corrupted node is cleared. */
/* Key information about the corrupted node and its previous node, including the address of the previous node, magic number of the node, and sizeAndFlag of the node. In this example, the magic number of the corrupted node is cleared. */
broken node head LR info: /* The node LR information can be output only after the memory leak check is enabled.*/
broken node head LR info: /* The node LR information can be output only after the memory leak check is enabled. */
LR[0]:0x0800414e
LR[0]:0x0800414e
LR[1]:0x08000cc2
LR[1]:0x08000cc2
LR[2]:0x00000000
LR[2]:0x00000000
pre node head LR info: /* Based on the LR information, you can find where the previous node is requested in the assembly file and then perform further analysis.*/
pre node head LR info: /* Based on the LR information, you can find where the previous node is requested in the assembly file and then perform further analysis.*/
LR[0]:0x08004144
LR[0]:0x08004144
LR[1]:0x08000cc2
LR[1]:0x08000cc2
LR[2]:0x00000000
LR[2]:0x00000000
[ERR]Memory interity check error, cur node: 0x20003b10, pre node: 0x20003af0 /* Addresses of the corrupted node and its previous node*/
[ERR]Memory integrity check error, cur node: 0x20003b10, pre node: 0x20003af0 /* Addresses of the corrupted node and its previous node */
Memory information includes the memory pool size, memory usage, remaining memory size, maximum free memory, memory waterline, number of memory nodes, and fragmentation rate.
Memory information includes the memory pool size, memory usage, remaining memory size, maximum free memory, memory waterline, number of memory nodes, and fragmentation rate.
- Memory waterline: indicates the maximum memory used in a memory pool. The waterline value is updated upon each memory allocation and release. The memory pool size can be optimized based on this value.
- The memory waterline indicates the maximum memory used in a memory pool. The waterline value is updated each time the memory is allocated or released. The memory pool size can be optimized based on this value.
- The fragmentation rate indicates the fragmentation degree of the memory pool. If the fragmentation rate is high, there are a large number of free memory blocks in the memory pool but each block is small. You can use the following formula to calculate the fragmentation rate:<br>Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size
- Fragmentation rate: indicates the fragmentation degree of the memory pool. If the fragmentation rate is high, there are a large number of free memory blocks in the memory pool but each block is small. You can use the following formula to calculate the fragmentation rate:
-You can use **LOS_MemInfoGet()** to scan the node information in the memory pool and collect the related statistics.
Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size
## Function Configuration
- Other statistics: When **LOS\_MemInfoGet** is called, the node information in the memory pool is scanned and related statistics are collected.
**LOSCFG_MEM_WATERLINE** specifies the setting of the memory information statistics function. This function is disabled by default. If you want to obtain the memory waterline, enable it in **Debug-> Enable MEM Debug-> Enable memory pool waterline or not**.
## Function Configuration<a name="section470611682411"></a>
**LOSCFG\_MEM\_WATERLINE**: specifies the setting of the memory information statistics function. This function is disabled by default. To enable this function, configure it in **Debug-\> Enable memory pool waterline or not in the configuration item**. If you want to obtain the memory waterline, you must enable this macro.
## Development Guidelines
## Development Guidelines<a name="section9368374243"></a>
### How to Develop<a name="section679912407257"></a>
### How to Develop
Key structure:
Key structure:
```
```c
typedefstruct{
typedefstruct{
UINT32 totalUsedSize; // Memory usage of the memory pool
UINT32totalUsedSize;// Memory usage of the memory pool.
UINT32 totalFreeSize; // Remaining memory in the memory pool
UINT32totalFreeSize;// Remaining size of the memory pool.
UINT32 maxFreeNodeSize; // Maximum size of the free memory block in the memory pool
UINT32maxFreeNodeSize;// Maximum size of the free memory block in the memory pool.
UINT32 usedNodeNum; // Number of non-free memory blocks in the memory pool
UINT32usedNodeNum;// Number of non-free memory blocks in the memory pool.
UINT32 freeNodeNum; // Number of free memory blocks in the memory pool
UINT32freeNodeNum;// Number of free memory blocks in the memory pool.
#if (LOSCFG_MEM_WATERLINE == 1) // This function is disabled by default and can be enabled using the menuconfig tool.
#if (LOSCFG_MEM_WATERLINE == 1) // This function is disabled by default and can be enabled using the **menuconfig** tool.
UINT32 usageWaterLine; // Waterline of the memory pool
UINT32usageWaterLine;// Waterline of the memory pool.
#endif
#endif
}LOS_MEM_POOL_STATUS;
}LOS_MEM_POOL_STATUS;
```
```
- To obtain the memory waterline, call **LOS\_MemInfoGet**. The first parameter in the API is the start address of the memory pool, and the second parameter is the handle of the **LOS\_MEM\_POOL\_STATUS** type. The **usageWaterLine** field indicates the waterline.
To obtain the memory waterline, call **LOS_MemInfoGet(VOID *pool, LOS_MEM_POOL_STATUS *poolStatus)**. The first parameter specifies the start address of the memory pool, and the second parameter specifies the handle of the **LOS_MEM_POOL_STATUS** type. The **usageWaterLine** field indicates the waterline.
- To calculate the memory fragmentation rate, call **LOS\_MemInfoGet** to obtain the remaining memory size and the maximum free memory block size in the memory pool, and then calculate the fragmentation rate of the dynamic memory pool as follows:
To calculate the memory fragmentation rate, call **LOS_MemInfoGet** to obtain the remaining memory size and the maximum free memory block size in the memory pool, and then calculate the fragmentation rate of the dynamic memory pool as follows:
Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size
Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size
### Development Example<a name="section1025453412611"></a>
### Development Example
This example implements the following:
This example implements the following:
1. Creates a monitoring task to obtain information about the memory pool.
1. Create a monitoring task to obtain information about the memory pool.
2. Calls **LOS\_MemInfoGet** to obtain the basic information about the memory pool.
3. Calculates the memory usage and fragmentation rate.
2. Call **LOS_MemInfoGet** to obtain the basic information about the memory pool.
3. Calculate the memory usage and fragmentation rate.
**Sample Code**
**Sample Code**
You can compile and verify the sample code in **kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **MemTest()** function is called in **TestTaskEntry**.
The sample code is as follows:
The sample code is as follows:
```
```c
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <string.h>
#include "los_task.h"
#include "los_task.h"
...
@@ -66,15 +72,14 @@ void MemInfoTaskFunc(void)
...
@@ -66,15 +72,14 @@ void MemInfoTaskFunc(void)
{
{
LOS_MEM_POOL_STATUSpoolStatus={0};
LOS_MEM_POOL_STATUSpoolStatus={0};
/* pool is the memory address of the information to be collected. OS_SYS_MEM_ADDR is used as an example.*/
/* pool is the memory address of the information to be collected. OS_SYS_MEM_ADDR is used as an example.*/
void*pool=OS_SYS_MEM_ADDR;
void*pool=OS_SYS_MEM_ADDR;
LOS_MemInfoGet(pool,&poolStatus);
LOS_MemInfoGet(pool,&poolStatus);
/* Calculate the fragmentation rate of the memory pool. */
/* Calculate the fragmentation rate of the memory pool. */
As an optional function of the kernel, memory leak check is used to locate dynamic memory leak problems. After this function is enabled, the dynamic memory mechanism automatically records the link registers \(LRs\) used when memory is allocated. If a memory leak occurs, the recorded information helps locate the memory allocated for further analysis.
As an optional function of the kernel, memory leak check is used to locate dynamic memory leak problems. After this function is enabled, the dynamic memory mechanism automatically records the link registers (LRs) used when memory is allocated. If a memory leak occurs, the recorded information helps locate the memory allocated for further analysis.
## Function Configuration<a name="section13991354162914"></a>
1.**LOSCFG\_MEM\_LEAKCHECK**: specifies the setting of the memory leak check. This function is disabled by default. To enable this function, configure it in **Debug-\> Enable Function call stack of Mem operation recorded**.
## Function Configuration
2.**LOS\_RECORD\_LR\_CNT**: number of LRs recorded. The default value is **3**. Each LR consumes the memory of **sizeof\(void \*\)** bytes.
3.**LOS\_OMIT\_LR\_CNT**: number of ignored LRs. The default value is **2**, which indicates that LRs are recorded from the time when **LOS\_MemAlloc** is called. You can change the value based on actual requirements. This macro is configured because:
-**LOS\_MemAlloc** is also called internally.
-**LOS\_MemAlloc** may be encapsulated externally.
- The number of LRs configured by **LOS\_RECORD\_LR\_CNT** is limited.
**LOSCFG_MEM_LEAKCHECK** specifies the setting of the memory leak check. This function is disabled by default. You can enable it in **Debug-> Enable MEM Debug-> Enable Function call stack of Mem operation recorded**.
**LOS_RECORD_LR_CNT** specifies the number of LRs recorded. The default value is **3**. Each LR consumes the memory of **sizeof(void *)** bytes.
**LOS_OMIT_LR_CNT** specifies the number of ignored LRs. The default value is **2**, which indicates that LRs are recorded from the time when **LOS_MemAlloc** is called. You can change the value based on actual requirements. The reasons for this configuration are as follows:
-**LOS_MemAlloc** is also called internally.
-**LOS_MemAlloc** may be encapsulated externally.
- The number of LRs configured by **LOS_RECORD_LR_CNT** is limited.
Correctly setting this macro can ignore invalid LRs and reduce memory consumption.
Correctly setting this macro can ignore invalid LRs and reduce memory consumption.
## Development Guidelines<a name="section95828159308"></a>
### How to Develop<a name="section369844416304"></a>
## Development Guidelines
Memory leak check provides a method to check for memory leak in key code logic. If this function is enabled, LR information is recorded each time when memory is allocated. When **LOS\_MemUsedNodeShow** is called before and after the code snippet is checked, information about all nodes that have been used in the specified memory pool is printed. You can compare the node information. The newly added node information indicates the node where the memory leak may occur. You can locate the code based on the LR and further check whether a memory leak occurs.
### How to Develop
The node information output by calling **LOS\_MemUsedNodeShow** is in the following format:
Memory leak check provides a method to check for memory leak in key code logic. If this function is enabled, LR information is recorded each time when memory is allocated. When **LOS_MemUsedNodeShow** is called before and after the code snippet is checked, information about all nodes that have been used in the specified memory pool is printed. You can compare the node information. The newly added node information indicates the node where the memory leak may occur. You can locate the code based on the LR and further check whether a memory leak occurs.
- Each line contains information about a node.
The node information output by calling **LOS_MemUsedNodeShow** is in the following format: <br>Each line contains information about a node. The first column indicates the node address, based on which you can obtain complete node information using a tool such as a GNU Debugger (GDB). The second column indicates the node size, which is equal to the node header size plus the data field size. Columns 3 to 5 list the LR addresses. You can determine the specific memory location of the node based on the LR addresses and the assembly file.
- The first column indicates the node address, based on which you can obtain complete node information using a tool such as a GNU Debugger \(GDB\).
- The second column indicates the node size, which is equal to the node header size plus the data field size.
- Columns 3 to 5 list the LR addresses.
You can determine the specific memory location of the node based on the LR addresses and the assembly file.
>Enabling memory leak check affects memory application performance. LR addresses will be recorded for each memory node, increasing memory overhead.
>Enabling memory leak check affects memory application performance. LR addresses will be recorded for each memory node, increasing memory overhead.
### Development Example<a name="section460801313313"></a>
### Development Example
This example implements the following:
This example implements the following:
1. Call **OsMemUsedNodeShow** to print information about all nodes.
1. Call **OsMemUsedNodeShow** to print information about all nodes.
2. Simulate a memory leak by requesting memory without releasing it.
2. Simulate a memory leak by requesting memory without releasing it.
3. Call **OsMemUsedNodeShow** to print information about all nodes.
3. Call **OsMemUsedNodeShow** to print information about all nodes.
4. Compare the logs to obtain information about the node where a memory leak occurred.
4. Compare the logs to obtain information about the node where a memory leak occurred.
5. Locate the code based on the LR address.
5. Locate the code based on the LR address.
**Sample Code**
**Sample Code**
You can compile and verify the sample code in **kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **MemLeakTest()** function is called in **TestTaskEntry**.
In this example, a memory pool is created. To achieve this purpose, you need to define **LOSCFG_MEM_MUL_POOL** in **target_config.h**.
perf is a performance analysis tool. It uses the performance monitoring unit (PMU) to count sampling events and collect context information and provides hot spot distribution and hot paths.
## Working Principles
When a performance event occurs, the corresponding event counter overflows and triggers an interrupt. The interrupt handler records the event information, including the current PC, task ID, and call stack.
perf provides two working modes: counting mode and sampling mode.
In counting mode, perf collects only the number of event occurrences and duration. In sampling mode, perf also collects context data and stores the data in a circular buffer. The IDE then analyzes the data and provides information about hotspot functions and paths.
## Available APIs
The Perf module of the OpenHarmony LiteOS-A kernel provides the following APIs. For details, see the [API reference](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_perf.h).
| Configuring perf sampling events| **LOS_PerfConfig**: sets the event type and sampling period. |
| Reading sampling data| **LOS_PerfDataRead**: reads the sampling data. |
| Registering a hook for the sampling data buffer| **LOS_PerfNotifyHookReg**: registers the hook to be called when the buffer waterline is reached.<br>**LOS_PerfFlushHookReg**: registers the hook for flushing the cache in the buffer. |
**PerfConfigAttr** is the structure of the perf sampling event. For details, see [kernel\include\los_perf.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_perf.h).
The sampling data buffer is a circular buffer, and only the region that has been read in the buffer can be overwritten.
The buffer has limited space. You can register a hook to provide a buffer overflow notification or perform buffer read operation when the buffer waterline is reached. The default buffer waterline is 1/2 of the buffer size. The code snippet is as follows:
```c
VOIDExample_PerfNotifyHook(VOID)
{
CHARbuf[LOSCFG_PERF_BUFFER_SIZE]={0};
UINT32len;
PRINT_DEBUG("perf buffer reach the waterline!\n");
If the buffer sampled by perf involves caches across CPUs, you can register a hook for flushing the cache to ensure cache consistency. The code snippet is as follows:
```c
VOIDExample_PerfFlushHook(VOID*addr,UINT32size)
{
OsCacheFlush(addr,size);/* platform interface */
}
LOS_PerfNotifyHookReg(Example_PerfFlushHook);
```
The API for flushing the cache is configured based on the platform.
## Development Guidelines
### Kernel-Mode Development Process
The typical process of enabling perf is as follows:
1. Configure the macros related to the perf module.
Configure the perf control macro **LOSCFG_KERNEL_PERF**, which is disabled by default. In the **kernel/liteos_a** directory, run the **make update_config** command, choose **Kernel**, and select **Enable Perf Feature**.
| LOSCFG_PERF_CALC_TIME_BY_TICK | Time-consuming Calc Methods->By Tick | Whether to use tick as the perf timing unit.| YES/NO |
| LOSCFG_PERF_CALC_TIME_BY_CYCLE | Time-consuming Calc Methods->By Cpu Cycle | Whether to use cycle as the perf timing unit.| YES/NO |
| LOSCFG_PERF_BUFFER_SIZE | Perf Sampling Buffer Size | Size of the buffer used for perf sampling.| INT |
| LOSCFG_PERF_HW_PMU | Enable Hardware Pmu Events for Sampling | Whether to enable hardware PMU events. The target platform must support the hardware PMU.| YES/NO |
| LOSCFG_PERF_TIMED_PMU | Enable Hrtimer Period Events for Sampling | Whether to enable high-precision periodical events. The target platform must support the high precision event timer (HPET).| YES/NO |
| LOSCFG_PERF_SW_PMU | Enable Software Events for Sampling | Whether to enable software events. **LOSCFG_KERNEL_HOOK** must also be enabled.| YES/NO |
2. Call **LOS_PerfConfig** to configure the events to be sampled.
perf provides two working modes and three types of events.
- Working modes: counting mode (counts only the number of event occurrences) and sampling mode (collects context information such as task IDs, PC, and backtrace)
- Event types: CPU hardware events (such as cycle, branch, icache, and dcache), high-precision periodical events (such as CPU clock), and OS software events (such as task switch, mux pend, and IRQ)
3. Call **LOS_PerfStart(UINT32 sectionId)** at the start of the code to be sampled. The input parameter **sectionId** specifies different sampling session IDs.
4. Call **LOS_PerfStop** at the end of the code to be sampled.
5. Call **LOS_PerfDataRead** to read the sampling data and use IDE to analyze the collected data.
#### Development Example
This example implements the following:
1. Create a perf task.
2. Configure sampling events.
3. Start perf.
4. Execute algorithms for statistics.
5. Stop perf.
6. Export the result.
#### Sample Code
Prerequisites: **Enable Hook Feature** and **Enable Software Events for Sampling** are selected for the perf module in **menuconfig**.
You can compile and verify the sample code in **kernel/liteos_a/testsuites/kernel/src/osTest.c**.
The code is as follows:
```c
#include "los_perf.h"
#define TEST_MALLOC_SIZE 200
#define TEST_TIME 5
/* Add malloc() and free() in the test() function. */
You can export the data using the JTAG interface and then use the IDE offline tool to analyze the data.
You can also call **LOS_PerfDataRead** to read data to a specified address for further analysis. In the example, **OsPrintBuff** is a test API, which prints the sampled data by byte. **num** indicates the sequence number of the byte, and **hex** indicates the value in the byte.
The central processing unit percent \(CPUP\) includes the system CPUP, process CPUP, task CPUP, and interrupt CPUP. With the system CPUP, you can determine whether the current system load exceeds the designed specifications. With the CPUP of each task/process/interrupt, you can determine whether their CPU usage meets expectations of the design.
The central processing unit percent (CPUP) includes the system CPUP, process CPUP, task CPUP, and interrupt CPUP. With the system CPUP, you can determine whether the current system load exceeds the designed specifications. With the CPUP of each task/process/interrupt, you can determine whether their CPU usage meets expectations of the design.
- System CPUP
- System CPUP
System CPUP is the CPU usage of the system within a period of time. It reflects the CPU load and the system running status (idle or busy) in the given period of time. The valid range of the system CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the system runs with full load.
System CPUP is the CPU usage of the system within a period of time. It reflects the CPU load and the system running status \(idle or busy\) in the given period of time. The valid range of the system CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the system runs with full load.
- Process CPUP
- Process CPUP
Process CPUP refers to the CPU usage of a single process. It reflects the process status, busy or idle, in a period of time. The valid range of the process CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the process is being executed for a period of time.
Process CPUP refers to the CPU usage of a single process. It reflects the process status, busy or idle, in a period of time. The valid range of the process CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the process is being executed for a period of time.
- Task CPUP
- Task CPUP
Task CPUP refers to the CPU usage of a single task. It reflects the task status, busy or idle, in a period of time. The valid range of task CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the task is being executed for the given period of time.
Task CPUP refers to the CPU usage of a single task. It reflects the task status, busy or idle, in a period of time. The valid range of task CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the task is being executed for the given period of time.
- Interrupt CPUP
- Interrupt CPUP
Interrupt CPUP refers to the CPU usage of a single interrupt. It reflects the interrupt status, busy or idle, in a period of time. The valid range of the interrupt CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the interrupt is being executed for a period of time.
Interrupt CPUP refers to the CPU usage of a single interrupt. It reflects the interrupt status, busy or idle, in a period of time. The valid range of the interrupt CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the interrupt is being executed for a period of time.
## Working Principles<a name="section593718536227"></a>
## Working Principles
The OpenHarmony LiteOS-A kernel CPUP module records the CPU usage by process, task, and interrupt. When a process or task is switched, the start time of the process or task is recorded. When the process or task is switched out or exits, the system accumulates the CPU time of the entire process or task. When an interrupt is executed, the system accumulates and records the execution time of each interrupt.
The OpenHarmony LiteOS-A kernel CPUP module records the CPU usage by process, task, and interrupt. When a process or task is switched, the start time of the process or task is recorded. When the process or task is switched out or exits, the system accumulates the CPU time of the entire process or task. When an interrupt is executed, the system accumulates and records the execution time of each interrupt.
OpenHarmony provides the following types of CPUP information:
OpenHarmony provides the following types of CPUP information:
- System CPUP
- System CPUP
- Process CPUP
- Process CPUP
- Task CPUP
- Task CPUP
- Interrupt CPUP
- Interrupt CPUP
The CPUP is calculated as follows:
The CPUP is calculated as follows:
...
@@ -43,134 +42,109 @@ Task CPUP = Total running time of the task/Total running time of the system
...
@@ -43,134 +42,109 @@ Task CPUP = Total running time of the task/Total running time of the system
Interrupt CPUP = Total running time of the interrupt/Total running time of the system
Interrupt CPUP = Total running time of the interrupt/Total running time of the system
## Development Guidelines<a name="section11284210152311"></a>
## Development Guidelines
### Available APIs<a name="section3745151592312"></a>
<tdclass="cellrowborder"valign="top"width="35.12648735126487%"headers="mcps1.2.4.1.3 "><pid="p14808115353010"><aname="p14808115353010"></a><aname="p14808115353010"></a>Obtains the historical CPUP of the system.</p>
</td>
The typical CPUP development process is as follows:
2. Call **LOS_HistoryProcessCpuUsage** to obtain the historical CPUP of a specified process.
</td>
<tdclass="cellrowborder"valign="top"width="35.12648735126487%"headers="mcps1.2.4.1.3 "><pid="p1747959131016"><aname="p1747959131016"></a><aname="p1747959131016"></a>Obtains the historical CPUP of a specified process.</p>
<tdclass="cellrowborder"valign="top"headers="mcps1.2.4.1.2 "><pid="p1575419483116"><aname="p1575419483116"></a><aname="p1575419483116"></a>Obtains the historical CPUP of all processes in the system.</p>
<tdclass="cellrowborder"valign="top"width="35.12648735126487%"headers="mcps1.2.4.1.3 "><pid="p12808653183016"><aname="p12808653183016"></a><aname="p12808653183016"></a>Obtains the historical CPUP of a specified task.</p>
<tdclass="cellrowborder"valign="top"width="35.12648735126487%"headers="mcps1.2.4.1.3 "><pid="p33741531163313"><aname="p33741531163313"></a><aname="p33741531163313"></a>Obtains the historical CPUP of all interrupts in the system.</p>
</td>
</tr>
</tbody>
</table>
### How to Develop<a name="section122901429182316"></a>
The typical CPUP development process is as follows.
1. Call **LOS\_HistorySysCpuUsage** to obtain the historical CPUP of the system.
2. Call **LOS\_HistoryProcessCpuUsage** to obtain the historical CPUP of a specified process.
- If the process has been created, disable interrupt, obtain the CPUP in different modes, and then enable interrupt.
- If the process has been created, disable interrupt, obtain the CPUP in different modes, and then enable interrupt.
- If the process is not created, return an error code.
- If the process is not created, return an error code.
3. Call **LOS\_GetAllProcessCpuUsage** to obtain the CPUP of all processes.
3.Call **LOS_GetAllProcessCpuUsage** to obtain the CPUP of all processes.
- If the CPUP has been initialized, disable interrupt, obtain the CPUP in different modes, and then enable interrupt.
- If the CPUP is initialized, disable interrupt, obtain the CPUP in different modes, and then enable interrupt.
- If CPUP is not initialized or has invalid input parameters, return an error code.
- If CPUP is not initialized or has invalid input parameters, return an error code.
4. Call **LOS\_HistoryTaskCpuUsage** to obtain the historical CPUP of a specified task.
4.Call **LOS_HistoryTaskCpuUsage** to obtain the historical CPUP of a specified task.
- If the task has been created, disable interrupt, obtain the CPUP in different modes, and then enable interrupt.
- If the task has been created, disable interrupt, obtain the CPUP in different modes, and then enable interrupt.
- If the task is not created, return an error code.
- If the task is not created, return an error code.
5. Call **LOS\_GetAllIrqCpuUsage** to obtain the CPUP of all interrupts.
5.Call **LOS_GetAllIrqCpuUsage** to obtain the CPUP of all interrupts.
- If the CPUP has been initialized, disable interrupt, obtain the CPUP in different modes, and then enable interrupt.
- If the CPUP has been initialized, disable interrupt, obtain the CPUP in different modes, and then enable interrupt.
- If CPUP has not been initialized or has invalid input parameters, return an error code.
- If CPUP is not initialized or has invalid input parameters, return an error code.
### Development Example<a name="section1765785212310"></a>
### Development Example
This example implements the following:
This example implements the following:
1. Create a task for the CPUP test.
1. Create a task for the CPUP test.
2. Obtain the CPUP of the current system.
2. Obtain the CPUP of the current system.
3. Obtain the historical system CPUP in different modes.
3. Obtain the historical system CPUP in different modes.
4. Obtain the CPUP of the created test task.
4. Obtain the CPUP of the created test task.
5. Obtain the CPUP of the created test task in different modes.
5. Obtain the CPUP of the created test task in different modes.
Prerequisites
Prerequisites:
The CPUP control is enabled in the **menuconfig** configuration.
The CPUP control is enabled in the **menuconfig** configuration.
**Sample Code**
**Sample Code**
You can compile and verify the sample code in **kernel/liteos_a/testsuites /kernel/src /osTest.c**. The **CpupTest** function is called in **TestTaskEntry**.
| mode | Displays the CPUP of the system within the last 10 seconds by default.<br>- **0**: displays the CPUP within the last 10 seconds.<br>- **1**: displays the CPUP within the last 1 second.<br>- Other numbers: display the total CPUP since the system starts.| [0, 0xFFFFFFFF] |
<tdclass="cellrowborder"valign="top"width="56.99999999999999%"headers="mcps1.2.4.1.2 "><aname="ul1530071303413"></a><aname="ul1530071303413"></a><ulid="ul1530071303413"><li>Displays the CPU usage of the system within the last 10 seconds by default.</li><li><strongid="b13709113084810"><aname="b13709113084810"></a><aname="b13709113084810"></a>0</strong>: displays the CPU usage within the last 10 seconds.</li><li><strongid="b10788133319480"><aname="b10788133319480"></a><aname="b10788133319480"></a>1</strong>: displays the CPU usage within the last 1 second.</li><li>Other value: displays the total CPU usage since the system is started.</li></ul>
<tdclass="cellrowborder"valign="top"width="56.99999999999999%"headers="mcps1.2.4.1.2 "><pid="p3799mcpsimp"><aname="p3799mcpsimp"></a><aname="p3799mcpsimp"></a>Specifies the task ID.</p>
- If no parameter is specified, the system date and time in UTC format are displayed by default.
</td>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.4.1.2 "><pid="p1162201234017"><aname="p1162201234017"></a><aname="p1162201234017"></a>Displays help information.</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.4.1.2 "><pid="p26216124407"><aname="p26216124407"></a><aname="p26216124407"></a>Prints the date and time in the specified <strongid="b115041849185916"><aname="b115041849185916"></a><aname="b115041849185916"></a>Format</strong>.</p>
</td>
<tdclass="cellrowborder"valign="top"width="28.999999999999996%"headers="mcps1.2.4.1.3 "><pid="p46251220409"><aname="p46251220409"></a><aname="p46251220409"></a>Placeholders listed in <strongid="b36588246116"><aname="b36588246116"></a><aname="b36588246116"></a>--help</strong></p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.4.1.2 "><pid="p136291219403"><aname="p136291219403"></a><aname="p136291219403"></a>Displays UTC instead of the current time zone.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p3917mcpsimp"><aname="p3917mcpsimp"></a><aname="p3917mcpsimp"></a>Prints content in the buffer and clears the buffer.</p>
- This command can be used only after **LOSCFG_SHELL_DMESG** is enabled. To enable **LOSCFG_SHELL_DMESG**, run the **make menuconfig** command in **kernel/liteos_a**. In the displayed dialog box, locate the **Debug** option and set **Enable Shell dmesg** to **Yes**.
</td>
Debug ---> Enable a Debug Version ---> Enable Shell ---> Enable Shell dmesg
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p3924mcpsimp"><aname="p3924mcpsimp"></a><aname="p3924mcpsimp"></a>Clears the buffer.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p3931mcpsimp"><aname="p3931mcpsimp"></a><aname="p3931mcpsimp"></a>Disables or enables printing to the console.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p3938mcpsimp"><aname="p3938mcpsimp"></a><aname="p3938mcpsimp"></a>Disables or enables printing via the serial port.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p3945mcpsimp"><aname="p3945mcpsimp"></a><aname="p3945mcpsimp"></a>Sets the size of the buffer.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p3952mcpsimp"><aname="p3952mcpsimp"></a><aname="p3952mcpsimp"></a>Sets the buffering level.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p717417317512"><aname="p717417317512"></a><aname="p717417317512"></a>Writes the content in the buffer to the specified file.</p>
- This command depends on **LOSCFG\_SHELL\_DMESG**. Before using this command, select **Enable Shell dmesg** on **menuconfig**.
Debug ---\> Enable a Debug Version ---\> Enable Shell ---\> Enable Shell dmesg
- If no parameter is specified, all content in the buffer is printed.
- If no parameter is specified, all content in the buffer is printed.
- The parameters followed by hyphens \(-\) are mutually exclusive.
- The parameters followed by hyphens (-) are mutually exclusive.
1. Before writing content to a file, ensure that the file system has been mounted.
1. Before writing content to a file, ensure that the file system has been mounted.
2. Disabling the serial port printing will adversely affect shell. You are advised to set up a connection using Telnet before disabling the serial port.
2. Disabling the serial port printing will adversely affect shell. You are advised to set up a connection using Telnet before disabling the serial port.
## Example<a name="section13736564418"></a>
## Example
Run **dmesg\> dmesg.log**.
Run **dmesg> dmesg.log**.
## Output<a name="section194005101413"></a>
Writing the content in the buffer to the **dmesg.log** file:
## Output
Write the content in the buffer to the **dmesg.log** file.
Currently, this command supports only valid binary programs. The programs are successfully executed and then run in the background by default. However, the programs share the same device with the shell. As a result, the output of the programs and the shell may be interlaced.
Currently, this command supports only valid binary programs. The programs are successfully executed and then run in the background by default. However, the programs share the same device with the shell. As a result, the output of the programs and the shell may be interlaced.
>After the executable file is executed, the prompt **OHOS \#** is printed first. The shell **exec** command is executed in the background, causing the prompt to be printed in advance.
> After the executable file is executed, the prompt **OHOS #** is printed first. The shell **exec** command is executed in the background, causing the prompt to be printed in advance.
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p64861302212"><aname="p64861302212"></a><aname="p64861302212"></a>Displays the memory usage in bytes.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1648617012214"><aname="p1648617012214"></a><aname="p1648617012214"></a>Displays the parameters supported by the <strongid="b1247315411335"><aname="b1247315411335"></a><aname="b1247315411335"></a>free</strong> command.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p54864013214"><aname="p54864013214"></a><aname="p54864013214"></a>Displays the memory usage in bytes.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1648670192120"><aname="p1648670192120"></a><aname="p1648670192120"></a>Displays the memory usage in KiB.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p134869022114"><aname="p134869022114"></a><aname="p134869022114"></a>Displays the memory usage in MiB.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p348680122118"><aname="p348680122118"></a><aname="p348680122118"></a>Displays the memory usage in GiB.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p18486140132118"><aname="p18486140132118"></a><aname="p18486140132118"></a>Displays the memory usage in TiB.</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1737315202218"><aname="p1737315202218"></a><aname="p1737315202218"></a>Total size of the dynamic memory pool</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p197376156222"><aname="p197376156222"></a><aname="p197376156222"></a>Size of the used memory</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p97371915142218"><aname="p97371915142218"></a><aname="p97371915142218"></a>Size of the unallocated memory</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1773801514223"><aname="p1773801514223"></a><aname="p1773801514223"></a>Size of the shared memory</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p157381015192216"><aname="p157381015192216"></a><aname="p157381015192216"></a>Size of the buffer</p>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p1323011409405"><a name="p1323011409405"></a><a name="p1323011409405"></a>CPU usage within the last 10 seconds</p>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p76814443417"><a name="p76814443417"></a><a name="p76814443417"></a>CPU usage within the last 1 second</p>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p268134415419"><a name="p268134415419"></a><a name="p268134415419"></a>Interrupt type, which can be any of the following:</p>
> The value range of **signo** is [0, 64]. The recommended value range is [1, 30], and other values in the value range are reserved.
</td>
<tdclass="cellrowborder"valign="top"width="51.92%"headers="mcps1.2.4.1.2 "><pid="p3402191493310"><aname="p3402191493310"></a><aname="p3402191493310"></a>Displays the parameters supported by the <strongid="b277973411569"><aname="b277973411569"></a><aname="b277973411569"></a>kill</strong> command.</p>
<tdclass="cellrowborder"valign="top"width="51.92%"headers="mcps1.2.4.1.2 "><pid="p640281413313"><aname="p640281413313"></a><aname="p640281413313"></a>Lists the names and numbers of signals.</p>
<tdclass="cellrowborder"valign="top"width="51.92%"headers="mcps1.2.4.1.2 "><pid="p114023144336"><aname="p114023144336"></a><aname="p114023144336"></a>Specifies the signal number.</p>
<tdclass="cellrowborder"valign="top"width="51.92%"headers="mcps1.2.4.1.2 "><pid="p7402014113310"><aname="p7402014113310"></a><aname="p7402014113310"></a>Specifies the process ID.</p>
>The value range of **signo** is \[0, 64\]. The recommended value range is \[1, 30\], and other values in the value range are reserved.
## Usage<a name="section15935131220717"></a>
- The **signo** and **pid** parameters are mandatory.
- The **signo** and **pid** parameters are mandatory.
- The **pid** value range varies depending on the system configuration. For example, if the maximum **pid** value supported by the system is **256**, this value range is \[1-256\].
## Example<a name="section79281818476"></a>
- The **pid** value range varies depending on the system configuration. For example, if the maximum **pid** value supported by the system is **256**, this value range is [1, 256].
## Note
The **kill** command is not supported by the shell. mksh supports it. To switch to mksh, run **cd bin;** and **./mksh**.
## Example
- Query the process list before killing process 42.
- Query the process list before killing process 42.
- Send signal 9 \(the default action of **SIGKILL** is to immediately terminate the process\) to process 42 test\_demo \(a user-mode process\). Then, check the current process list. The commands **kill -s 9 42** and **kill -9 42** have the same effect.
-Send signal 9 (the default action of **SIGKILL** is to immediately terminate the process) to process 42 test_demo (a user-mode process). Then, check the current process list. The commands **kill -s 9 42** and **kill -9 42** have the same effect.
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p254mcpsimp"><aname="p254mcpsimp"></a><aname="p254mcpsimp"></a>Specifies the level of logs to print.</p>
This command is used to check whether the dynamically allocated memory block is complete and whether nodes in the memory pool are damaged due to out-of-bounds memory access.
This command is used to check whether the dynamically allocated memory block is complete and whether nodes in the memory pool are damaged due to out-of-bounds memory access.
## Syntax<a name="section428816435510"></a>
## Syntax
memcheck
memcheck
## Parameters<a name="section1939943304411"></a>
None
## Parameters
None.
## Usage<a name="section228914491951"></a>
## Usage Guidelines
- If all nodes in the memory pool are complete, "system memcheck over, all passed!" is displayed.
- If all nodes in the memory pool are complete, "system memcheck over, all passed!" is displayed.
- If a node in the memory pool is incomplete, information about the memory block of the corrupted node is displayed.
- If a node in the memory pool is incomplete, information about the memory block of the corrupted node is displayed.
## Example<a name="section17373205314515"></a>
## Example
Run **memcheck**.
Run **memcheck**.
## Output<a name="section13406205385413"></a>
Run **memcheck**, and memory overwriting occurs.
Example 1: All nodes in the memory pool are complete.
## Output
Example 1: No error is detected.
```
```
OHOS # memcheck
OHOS # memcheck
system memcheck over, all passed!
system memcheck over, all passed!
```
```
Example 2: Out-of-bounds memory access is detected.
| -m [mem byte] | Sets the low memory threshold (in MB). | 0 to 1<br>The value **0** means not to perform the low memory threshold check. |
</th>
| -r [mem byte] | Sets the PageCache reclaim threshold. | Low memory threshold to the maximum available memory of the system<br>Generally, the size of a PageCache is 4 KB. Sometimes, it is 16 KB to 64 KB. |
If no parameter is specified, this command displays the current OOM configuration.
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1149945111817"><aname="p1149945111817"></a><aname="p1149945111817"></a>Sets the interval (in ms) for checking the Out Of Memory (OOM) thread task.</p>
</td>
> **NOTE**<br>
<tdclass="cellrowborder"valign="top"width="27%"headers="mcps1.2.4.1.3 "><pid="p749810571812"><aname="p749810571812"></a><aname="p749810571812"></a>100 to 10000</p>
> If the system memory is insufficient, the system displays a message indicating the insufficiency.
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p2058485315912"><aname="p2058485315912"></a><aname="p2058485315912"></a>Sets the low memory threshold (in MB).</p>
</td>
<tdclass="cellrowborder"valign="top"width="27%"headers="mcps1.2.4.1.3 "><pid="p1584105318917"><aname="p1584105318917"></a><aname="p1584105318917"></a>0 (disables the low memory check) to 1</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p159263241121"><aname="p159263241121"></a><aname="p159263241121"></a>Sets the PageCache reclaim threshold.</p>
</td>
<tdclass="cellrowborder"valign="top"width="27%"headers="mcps1.2.4.1.3 "><pid="p692642412121"><aname="p692642412121"></a><aname="p692642412121"></a>Ranging from the low memory threshold to the maximum available system memory</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p9762113775517"><aname="p9762113775517"></a><aname="p9762113775517"></a>Displays help information.</p>
<tbody><trid="row502mcpsimp"><tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.1 "><pid="p583513382179"><aname="p583513382179"></a><aname="p583513382179"></a>[oom] OS is in low memory state</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p19833143819174"><aname="p19833143819174"></a><aname="p19833143819174"></a>The operating system has low memory.</p>
<pid="p83883291587"><aname="p83883291587"></a><aname="p83883291587"></a>The available physical memory in the operating system is <strongid="b15343050123397"><aname="b15343050123397"></a><aname="b15343050123397"></a>0x1bcf000</strong> bytes, <strongid="b18697901323397"><aname="b18697901323397"></a><aname="b18697901323397"></a>0x1b50000</strong> bytes have been used, and <strongid="b3252944373397"><aname="b3252944373397"></a><aname="b3252944373397"></a>0x7f000</strong> bytes are available. The current low memory threshold is <strongid="b13811086363397"><aname="b13811086363397"></a><aname="b13811086363397"></a>0x80000</strong> bytes.</p>
</td>
</tr>
<trid="row1990234224612"><tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.1 "><pid="p3902144294612"><aname="p3902144294612"></a><aname="p3902144294612"></a>[oom] candidate victim process init pid: 1, actual phy mem byte: 82602</p>
</td>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p13903144284610"><aname="p13903144284610"></a><aname="p13903144284610"></a>Memory usage of each process. The physical memory occupied by the <strongid="b143686319910"><aname="b143686319910"></a><aname="b143686319910"></a>init</strong> process is 82602 bytes.</p>
</td>
</tr>
<trid="row520212272335"><tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.1 "><pid="p172038278339"><aname="p172038278339"></a><aname="p172038278339"></a>[oom] candidate victim process UserProcess12 pid: 12, actual phy mem byte: 25951558</p>
</td>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p112034276331"><aname="p112034276331"></a><aname="p112034276331"></a>The actual memory used by the <strongid="b16405477923397"><aname="b16405477923397"></a><aname="b16405477923397"></a>UserProcess12</strong> process is <strongid="b10952024983397"><aname="b10952024983397"></a><aname="b10952024983397"></a>25951558</strong> bytes.</p>
</td>
</tr>
<trid="row3273195033416"><tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.1 "><pid="p184989213512"><aname="p184989213512"></a><aname="p184989213512"></a>[oom] max phy mem used process UserProcess12 pid: 12, actual phy mem: 25951558</p>
</td>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p112741750143417"><aname="p112741750143417"></a><aname="p112741750143417"></a>The process that uses the most memory currently is <strongid="b17770979863397"><aname="b17770979863397"></a><aname="b17770979863397"></a>UserProcess12</strong>.</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p6452818367"><aname="p6452818367"></a><aname="p6452818367"></a>The system memory is low, and the <strongid="b4088490143397"><aname="b4088490143397"></a><aname="b4088490143397"></a>UserProcess12</strong> process fails to apply for memory and exits.</p>
| [oom] OS is in low memory state<br>total physical memory: 0x1bcf000(byte), used: 0x1b50000(byte), free: 0x7f000(byte), low memory threshold: 0x80000(byte) | The OS has low memory.<br>The total physical memory is **0x1bcf000** bytes, **0x1b50000** bytes are used, and **0x7f000** bytes are left.<br/>The current lower memory threshold is **0x80000** bytes. |
| [oom] candidate victim process init pid: 1, actual phy mem byte: 82602 | The memory occupied by the **init** process is 82602 bytes. |
| [oom] candidate victim process UserProcess12 pid: 12, actual phy mem byte: 25951558 | The memory used by the **UserProcess12** process is **25951558** bytes. |
| [oom] max phy mem used process UserProcess12 pid: 12, actual phy mem: 25951558 | The process that uses the most memory currently is **UserProcess12**. |
| excFrom: User! | The system memory is low, and the **UserProcess12** process fails to apply for memory and exits. |
| inactive anon | Number of inactive anonymous pages in the page cache.|
</td>
| active file | Number of active file pages in the page cache.|
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1058062614579"><aname="p1058062614579"></a><aname="p1058062614579"></a>Address of the physical page control block</p>
| inactive file | Number of inactive file pages in the page cache.|
</td>
| pmm pages | **total** indicates the total number of physical pages. <br/>**used** indicates the number of used physical pages. <br/>**free** indicates the number of idle physical pages. |
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1858082617577"><aname="p1858082617577"></a><aname="p1858082617577"></a>First physical page address, that is, start address of the physical page memory</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p85808262572"><aname="p85808262572"></a><aname="p85808262572"></a>Size of the physical page memory</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1139715117599"><aname="p1139715117599"></a><aname="p1139715117599"></a>Number of active anonymous pages in the page cache</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1341012355019"><aname="p1341012355019"></a><aname="p1341012355019"></a>Number of inactive anonymous pages in the page cache</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1267012382019"><aname="p1267012382019"></a><aname="p1267012382019"></a>Number of active file pages in the page cache</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p17966174115018"><aname="p17966174115018"></a><aname="p17966174115018"></a>Number of inactive file pages in the page cache</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1616375952018"><aname="p1616375952018"></a><aname="p1616375952018"></a><strongid="b161631659162014"><aname="b161631659162014"></a><aname="b161631659162014"></a>total</strong>: total number of physical pages.</p>
<pid="p2029802122113"><aname="p2029802122113"></a><aname="p2029802122113"></a><strongid="b429822122113"><aname="b429822122113"></a><aname="b429822122113"></a>used</strong>: number of used physical pages.</p>
<pid="p1218312452014"><aname="p1218312452014"></a><aname="p1218312452014"></a><strongid="b132798755433826"><aname="b132798755433826"></a><aname="b132798755433826"></a>free</strong>: number of free physical pages.</p>
| fulldata | Displays information about all semaphores in use. <br/>The displayed information includes **SemID**, **Count**, **Original Count**, **Creator TaskEntry**, and **Last Access Time**. | N/A |
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p455mcpsimp"><aname="p455mcpsimp"></a><aname="p455mcpsimp"></a>Specifies the semaphore ID.</p>
</td>
<tdclass="cellrowborder"valign="top"width="27%"headers="mcps1.2.4.1.3 "><pid="p14422125918562"><aname="p14422125918562"></a><aname="p14422125918562"></a>[0, 1023] or [0x0, 0x3FF]</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p462mcpsimp"><aname="p462mcpsimp"></a><aname="p462mcpsimp"></a>Queries information about all the semaphores in use. The information includes <strongid="b189454249533849"><aname="b189454249533849"></a><aname="b189454249533849"></a>SemID</strong>, <strongid="b162724654333849"><aname="b162724654333849"></a><aname="b162724654333849"></a>Count</strong>, <strongid="b111325307233849"><aname="b111325307233849"></a><aname="b111325307233849"></a>OriginalCount</strong>, <strongid="b182850346833849"><aname="b182850346833849"></a><aname="b182850346833849"></a>Creator(TaskEntry)</strong>, and <strongid="b213750533633849"><aname="b213750533633849"></a><aname="b213750533633849"></a>LastAccessTime</strong>.</p>
- If no parameter is specified, this command displays the semaphore IDs and the number of times that each semaphore is used.
- If no parameter is specified, this command displays the semaphore IDs and the number of times that each semaphore is used.
- If **ID** is specified, the use of the specified semaphore is displayed.
- If **ID** is specified, the use of the specified semaphore is displayed.
- The **fulldata** parameter depends on **LOSCFG\_DEBUG\_SEMAPHORE**. Before using this parameter, select **Enable Semaphore Debugging** on **menuconfig**.
Debug ---\> Enable a Debug Version ---\> Enable Debug LiteOS Kernel Resource ---\> Enable Semaphore Debugging
- The **fulldata** parameter depends on **LOSCFG_DEBUG_SEMAPHORE**. Before using this parameter, set **Enable Semaphore Debugging** to **Yes** on **menuconfig**.
> When **ID** is a value within [0, 1023], semaphore information of the specified ID is displayed. If the specified semaphore is not used, a message is displayed to inform you of this case. For other values, a message is displayed indicating that the parameter is incorrect.
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p506mcpsimp"><aname="p506mcpsimp"></a><aname="p506mcpsimp"></a>Number of times that the semaphore is used</p>
>The **ID** value can be in decimal or hexadecimal format.
>When **ID** is a value within \[0, 1023\], semaphore information of the specified ID is displayed. If the specified semaphore is not used, a message is displayed to inform you of this case. For other values, a message is displayed indicating that the parameter is incorrect.
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1829104012416"><aname="p1829104012416"></a><aname="p1829104012416"></a>Number of times that the semaphore is used</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p282916401148"><aname="p282916401148"></a><aname="p282916401148"></a>Original count of the semaphore</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p168298407419"><aname="p168298407419"></a><aname="p168298407419"></a>Address of the entry function of the thread used to create the semaphore</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p198292406412"><aname="p198292406412"></a><aname="p198292406412"></a>Last time when the semaphore was accessed</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p647mcpsimp"><aname="p647mcpsimp"></a><aname="p647mcpsimp"></a>Name of the stack</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1510024539"><aname="p1510024539"></a><aname="p1510024539"></a>Size of the stack used</p>
<tdclass="cellrowborder"valign="top"width="51.93%"headers="mcps1.2.4.1.2 "><pid="p14138191243"><aname="p14138191243"></a><aname="p14138191243"></a>Specifies the ID of the target user.</p>
<tdclass="cellrowborder"valign="top"width="51.93%"headers="mcps1.2.4.1.2 "><pid="p48748461789"><aname="p48748461789"></a><aname="p48748461789"></a>Specifies the ID of the target user group.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p534mcpsimp"><aname="p534mcpsimp"></a><aname="p534mcpsimp"></a>Specifies the ID of a software timer.</p>
| State | Status of the software timer.<br>The status may be **UnUsed**, **Created**, or **Ticking**.|
</th>
| Mode | Mode of the software timer.<br>The value can be **Once**, **Period**, or **NSD** (one-shot timer that will not be automatically deleted after the timer has expired).|
</tr>
| Interval | Number of ticks for the software timer.|
</thead>
| Count | Number of times that the software timer has been used.|
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p565mcpsimp"><aname="p565mcpsimp"></a><aname="p565mcpsimp"></a>ID of the software timer</p>
</td>
> **NOTE**<br>
</tr>
> - The **ID** value can be in decimal or hexadecimal format.
> - If the **ID** value is within the range of [0, *Number of current software timers - 1*], the status of the specified software timer is returned. Otherwise, an error code is returned.
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p570mcpsimp"><aname="p570mcpsimp"></a><aname="p570mcpsimp"></a>Status of the software timer</p>
<pid="p88402543474"><aname="p88402543474"></a><aname="p88402543474"></a>The value can be <strongid="b164905263633836"><aname="b164905263633836"></a><aname="b164905263633836"></a>UnUsed</strong>, <strongid="b138979237833836"><aname="b138979237833836"></a><aname="b138979237833836"></a>Created</strong>, or <strongid="b3849463233836"><aname="b3849463233836"></a><aname="b3849463233836"></a>Ticking</strong>.</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p575mcpsimp"><aname="p575mcpsimp"></a><aname="p575mcpsimp"></a>Mode of the software timer</p>
<pid="p657320204499"><aname="p657320204499"></a><aname="p657320204499"></a>The value can be <strongid="b201632419733836"><aname="b201632419733836"></a><aname="b201632419733836"></a>Once</strong>, <strongid="b45281151733836"><aname="b45281151733836"></a><aname="b45281151733836"></a>Period</strong>, or <strongid="b73443815433836"><aname="b73443815433836"></a><aname="b73443815433836"></a>NSD</strong> (one-shot timer that will not be automatically deleted after the timer has expired).</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p580mcpsimp"><aname="p580mcpsimp"></a><aname="p580mcpsimp"></a>Number of ticks for the software timer</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p585mcpsimp"><aname="p585mcpsimp"></a><aname="p585mcpsimp"></a>Number of times that the software timer has been used</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p595mcpsimp"><aname="p595mcpsimp"></a><aname="p595mcpsimp"></a>Address of the callback</p>
>- The **ID** value can be in decimal or hexadecimal format.
>- If the **ID** value is within the range of \[0, _Number of current software timers - 1_\], the status of the specified software timer is returned. For other values, an error message is displayed.
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p662mcpsimp"><aname="p662mcpsimp"></a><aname="p662mcpsimp"></a>Whether the module is enabled</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p689mcpsimp"><aname="p689mcpsimp"></a><aname="p689mcpsimp"></a>Displays all information.</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1062611511398"><aname="p1062611511398"></a><aname="p1062611511398"></a>Parent process ID</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p2068355383916"><aname="p2068355383916"></a><aname="p2068355383916"></a>Process group ID</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p2011611331604"><aname="p2011611331604"></a><aname="p2011611331604"></a>CPU usage within last 10 seconds</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p843mcpsimp"><aname="p843mcpsimp"></a><aname="p843mcpsimp"></a>Size of the task stack</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p848mcpsimp"><aname="p848mcpsimp"></a><aname="p848mcpsimp"></a>Peak value of the stack used</p>
Currently, the shell does not support this command. mksh supports it. To switch to mksh, run **cd bin** and **./mksh**.
<tdclass="cellrowborder"valign="top"width="29.222922292229224%"headers="mcps1.2.5.1.2 "><pid="p942673885313"><aname="p942673885313"></a><aname="p942673885313"></a>Displays the parameters supported by the <strongid="b2435956125215"><aname="b2435956125215"></a><aname="b2435956125215"></a>top</strong> command.</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p19723153055519"><aname="p19723153055519"></a><aname="p19723153055519"></a>Parent process ID</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p117231630165519"><aname="p117231630165519"></a><aname="p117231630165519"></a>Process group ID</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1172323019556"><aname="p1172323019556"></a><aname="p1172323019556"></a>CPU usage within last 10 seconds</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p8724930135519"><aname="p8724930135519"></a><aname="p8724930135519"></a>Size of the task stack</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p10724103013559"><aname="p10724103013559"></a><aname="p10724103013559"></a>Peak value of the stack used</p>
<tdclass="cellrowborder"valign="top"width="66.01%"headers="mcps1.2.3.1.2 "><pid="p1664862551411"><aname="p1664862551411"></a><aname="p1664862551411"></a>Displays help information.</p>
| -m | Displays the operating system architecture name. |
</td>
| -n | Displays the network domain name of the host. |
<tdclass="cellrowborder"valign="top"width="66.01%"headers="mcps1.2.3.1.2 "><pid="p186484252141"><aname="p186484252141"></a><aname="p186484252141"></a>Displays the operating system name by default.</p>
<tdclass="cellrowborder"valign="top"width="66.01%"headers="mcps1.2.3.1.2 "><pid="p864872512145"><aname="p864872512145"></a><aname="p864872512145"></a>Displays all information.</p>
<tdclass="cellrowborder"valign="top"width="66.01%"headers="mcps1.2.3.1.2 "><pid="p1064852514149"><aname="p1064852514149"></a><aname="p1064852514149"></a>Displays the operating system name.</p>
<tdclass="cellrowborder"valign="top"width="66.01%"headers="mcps1.2.3.1.2 "><pid="p136489251143"><aname="p136489251143"></a><aname="p136489251143"></a>Displays the operating system architecture name.</p>
<tdclass="cellrowborder"valign="top"width="66.01%"headers="mcps1.2.3.1.2 "><pid="p6648132512141"><aname="p6648132512141"></a><aname="p6648132512141"></a>Displays the network domain name of the host.</p>
<tdclass="cellrowborder"valign="top"width="66.01%"headers="mcps1.2.3.1.2 "><pid="p46489250149"><aname="p46489250149"></a><aname="p46489250149"></a>Displays version information.</p>
</td>
</tr>
</tbody>
</table>
## Usage<a name="section2652124861114"></a>
- The **uname** command displays the name of the current operating system by default.
- The **uname** command displays the name of the current operating system by default.
- Except **--help** and **-a**, other parameters can be used together. **uname -a** is equivalent to **uname -srmnv**.
- Except **--help** and **-a**, other parameters can be used together. **uname -a** is equivalent to **uname -srmnv**.
## Example<a name="section0107995132"></a>
## Note
The **-r**, **-m**, and **-n** parameters are not supported currently. mksh supports these parameters. To switch to mksh, run **cd bin** and **./mksh**.
## Example
Run the following commands:
Run the following commands:
- uname -a
- uname -a
- uname -ms
- uname -ms
## Output<a name="section1215113245511"></a>
## Output
Example 1: all information of the operating system
Example 1: all information of the operating system
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p209441344121716"><aname="p209441344121716"></a><aname="p209441344121716"></a>Displays the virtual memory usage of all processes.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1494494441713"><aname="p1494494441713"></a><aname="p1494494441713"></a>Displays help information.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1594515442177"><aname="p1594515442177"></a><aname="p1594515442177"></a>Specifies the ID of the process to query.</p>
| region | Address of the control block in the virtual memory region.|
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p9137130122311"><aname="p9137130122311"></a><aname="p9137130122311"></a>Address of the virtual memory control block</p>
| name | Name of the virtual memory region.|
</td>
| base | Start address of the virtual memory region.|
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1613783082319"><aname="p1613783082319"></a><aname="p1613783082319"></a>Start address of the virtual memory</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p18137143092313"><aname="p18137143092313"></a><aname="p18137143092313"></a>Size of virtual memory</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p5137130142314"><aname="p5137130142314"></a><aname="p5137130142314"></a>Number of used physical pages</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1795344642412"><aname="p1795344642412"></a><aname="p1795344642412"></a>Address of the control block in the virtual memory region</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p19539466245"><aname="p19539466245"></a><aname="p19539466245"></a>Name of the virtual memory region</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p139536468242"><aname="p139536468242"></a><aname="p139536468242"></a>Start address of the virtual memory region</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p89531246142419"><aname="p89531246142419"></a><aname="p89531246142419"></a>Size of the virtual memory region</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p395464620242"><aname="p395464620242"></a><aname="p395464620242"></a>MMU mapping attribute of the virtual memory region</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p29541546112416"><aname="p29541546112416"></a><aname="p29541546112416"></a>Number of used physical pages, including that of the shared memory</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p10954164642419"><aname="p10954164642419"></a><aname="p10954164642419"></a>Number of used physical pages</p>
<tdclass="cellrowborder"valign="top"width="29.222922292229224%"headers="mcps1.2.5.1.2 "><pid="p986mcpsimp"><aname="p986mcpsimp"></a><aname="p986mcpsimp"></a>Specifies the number of times that the specified command is executed.</p>
<tdclass="cellrowborder"valign="top"width="29.222922292229224%"headers="mcps1.2.5.1.2 "><pid="p995mcpsimp"><aname="p995mcpsimp"></a><aname="p995mcpsimp"></a>Specifies the interval (in seconds) for periodically running the specified command.</p>
<tdclass="cellrowborder"valign="top"width="29.222922292229224%"headers="mcps1.2.5.1.2 "><pid="p1004mcpsimp"><aname="p1004mcpsimp"></a><aname="p1004mcpsimp"></a>Disables time display on the top.</p>
<tdclass="cellrowborder"valign="top"width="29.222922292229224%"headers="mcps1.2.5.1.2 "><pid="p1013mcpsimp"><aname="p1013mcpsimp"></a><aname="p1013mcpsimp"></a>Specifies the command to be monitored.</p>
<tdclass="cellrowborder"valign="top"width="29.222922292229224%"headers="mcps1.2.5.1.2 "><pid="p1022mcpsimp"><aname="p1022mcpsimp"></a><aname="p1022mcpsimp"></a>Stops the current command monitoring.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1066mcpsimp"><aname="p1066mcpsimp"></a><aname="p1066mcpsimp"></a>Specifies the file path.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1104mcpsimp"><aname="p1104mcpsimp"></a><aname="p1104mcpsimp"></a>Specifies the target file path.</p>
</td>
<tdclass="cellrowborder"valign="top"width="27%"headers="mcps1.2.4.1.3 "><pid="p1106mcpsimp"><aname="p1106mcpsimp"></a><aname="p1106mcpsimp"></a>You must have the execution (search) permission for the specified directory.</p>
</td>
</tr>
</tbody>
</table>
## Usage<a name="section3629759111317"></a>
- If **path** is not specified, this command switches to the root directory.
- If **path** is not specified, this command switches to the root directory.
- If **path** is specified, this command switches to the specified directory.
- If **path** is specified, this command switches to the specified directory.
- The **path** value starting with a slash \(/\) represents the root directory.
- The **path** value starting with a dot \(.\) represents the current directory.
- The **path** value starting with a slash (/) represents the root directory.
- The **path** value starting with two dots \(..\) represents the parent directory.
- The **path** value starting with a dot (.) represents the current directory.
- The **path** value starting with two dots (..) represents the parent directory.
- You can run **cd -** to alternate between two directories that are recently accessed.
- You can run **cd -** to alternate between two directories that are recently accessed.
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p4218826194210"><aname="p4218826194210"></a><aname="p4218826194210"></a>Specifies the file path.</p>
| mode | Specifies the permissions for a file or directory. The value is an octal number, representing the permission of **User** (owner), **Group** (group), or **Others** (other groups).| [0, 777] |
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p3911344161713"><aname="p3911344161713"></a><aname="p3911344161713"></a>Specifies the permissions for a file or directory. The value is an octal number, representing the permission of <strongid="b11602834153114"><aname="b11602834153114"></a><aname="b11602834153114"></a>User</strong> (owner), <strongid="b032113853120"><aname="b032113853120"></a><aname="b032113853120"></a>Group</strong> (group), or <strongid="b1980114418310"><aname="b1980114418310"></a><aname="b1980114418310"></a>Others</strong> (other groups).</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p149134481719"><aname="p149134481719"></a><aname="p149134481719"></a>Specifies the file name.</p>
- For the files created on the FAT file system, the file permission attributes are the same as those of the mounted nodes. Currently, the node permissions include only user read and write. The **group** and **others** permissions do not take effect. In addition, only the user read and write permissions can be modified. The read and write permissions are **rw** and **ro** only. There is no such restriction for other file systems.
- For the files created on the FAT file system, the file permission attributes are the same as those of the mounted nodes. Currently, the node permissions include only user read and write. The **group** and **others** permissions do not take effect. In addition, only the user read and write permissions can be modified. The read and write permissions are **rw** and **ro** only. There is no such restriction for other file systems.
## Example<a name="section8518195718147"></a>
## Note
Currently, the shell does not support this command.
Change the permissions on the **hello-harmony.txt** file to **644** and **777**.
## Example
## Output<a name="section127391818158"></a>
Change the permissions on the **hello-openharmony.txt** file to **644** and **777**.
Modifying the permissions on the **hello-harmony.txt** file in the **/dev** directory:
## Output
Modify the permissions on the **hello-openharmony.txt** file in the **/dev** directory.
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p14126172111"><aname="p14126172111"></a><aname="p14126172111"></a>Specifies the file owner.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p7412315218"><aname="p7412315218"></a><aname="p7412315218"></a>Specifies the file path.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p181687882317"><aname="p181687882317"></a><aname="p181687882317"></a>Displays help information.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p81686862314"><aname="p81686862314"></a><aname="p81686862314"></a>Specifies the path of the source file.</p>
</td>
<tdclass="cellrowborder"valign="top"width="27%"headers="mcps1.2.4.1.3 "><pid="p1016811862312"><aname="p1016811862312"></a><aname="p1016811862312"></a>This command does not support copy of a directory, but supports copy of multiple files at a time.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p9168789231"><aname="p9168789231"></a><aname="p9168789231"></a>Specifies the destination file path.</p>
</td>
<tdclass="cellrowborder"valign="top"width="27%"headers="mcps1.2.4.1.3 "><pid="p316810810235"><aname="p316810810235"></a><aname="p316810810235"></a>Both a directory and a file are supported.</p>
</td>
</tr>
</tbody>
</table>
## Usage<a name="section16128156162"></a>
- The name of the source file cannot be the same as that of the destination file in the same path.
- The name of the source file cannot be the same as that of the destination file in the same path.
-**SOURCEFILE** must exist and cannot be a directory.
-**SOURCEFILE** must exist and cannot be a directory.
-**SOURCEFILE** supports wildcard characters \* and ?. The asterisk \(\*\) indicates any number of characters, and the question mark \(?\) represents a single character. **DESTFILE** does not support wildcard characters. If **SOURCEFILE** specifies multiple files, **DESTFILE** must be a directory.
- If **DESTFILE** specifies a directory, this directory must exist. In this case, the destination file is named after the source file.
- The source file path supports asterisks (*) and question marks (?). The wildcard "\*" indicates any number of characters, and "?" indicates any single character. **DEST** does not support wildcard characters. If the specified **SOURCE** matches multiple files, **DEST** must be a directory.
- If **DESTFILE** specifies a file, the directory for this file must exist. In this case, the file copy is renamed.
- If **DEST** is a directory, this directory must exist. In this case, the destination file is named after the source file.
- If the destination file path is a file, the directory for this file must exist. In this case, the file copy is renamed.
- If the destination file does not exist, a new file is created. If the destination file already exists, the existing file is overwritten.
- If the destination file does not exist, a new file is created. If the destination file already exists, the existing file is overwritten.
>When important system resources are copied, unexpected results such as a system breakdown may occur. For example, when the **/dev/uartdev-1** file is copied, the system may stop responding.
> When important system resources are copied, unexpected results such as a system breakdown may occur. For example, when the **/dev/uartdev-1** file is copied, the system may stop responding.
## Example<a name="section19354171211618"></a>
## Example
Run **cp hello-OHOS.txt hello-harmony.txt ./tmp/**.
Run **cp hello-OHOS.txt hello-openharmony.txt ./tmp/**.
## Output<a name="section16754183195914"></a>
Copying **hello-OHOS.txt** and **hello-harmony.txt** to **/tmp/**:
## Output
Copy **hello-OHOS.txt** and **hello-openharmony.txt** to **/tmp/**.
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p14216153332715"><aname="p14216153332715"></a><aname="p14216153332715"></a>Displays the parameters supported by the <strongid="b22402916307"><aname="b22402916307"></a><aname="b22402916307"></a>du</strong> command.</p>
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p142161833172710"><aname="p142161833172710"></a><aname="p142161833172710"></a>Displays the occupied blocks, each of which is 1024 bytes by default.</p>
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p13216103319274"><aname="p13216103319274"></a><aname="p13216103319274"></a>Displays the occupied blocks, each of which is 512 bytes (POSIX).</p>
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p621673332720"><aname="p621673332720"></a><aname="p621673332720"></a>Displays the disk space in MB.</p>
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p2216533192717"><aname="p2216533192717"></a><aname="p2216533192717"></a>Displays the disk space in human-readable format K, M, and G, for example, <strongid="b1315823125013"><aname="b1315823125013"></a><aname="b1315823125013"></a>1K</strong>, <strongid="b385962710225"><aname="b385962710225"></a><aname="b385962710225"></a>243M</strong>, or <strongid="b1114122962214"><aname="b1114122962214"></a><aname="b1114122962214"></a>2G</strong>.</p>
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p19216103310272"><aname="p19216103310272"></a><aname="p19216103310272"></a>Specifies the target file.</p>
| sectors | Specifies the size of the allocated memory unit or sector. <br/>The value must be **0** or a power of **2**.<br/>The value **0** means to leave this parameter blank. <br/>For FAT32, the maximum value is **128**. If the parameter is set to **0**, a proper cluster size is automatically selected. The available cluster size range varies depending on the partition size. If the cluster size is incorrectly specified, the formatting may fail. |
</th>
| option | Specifies the file system type. The options are as follows:<br>- **0x01**: FMT_FAT<br>- **0x02**: FMT_FAT32<br>- **0x07**: FMT_ANY<br>- **0x08**: FMT_ERASE (USB does not support this option.)<br>If an invalid value is specified, the system automatically selects the formatting mode. If the low-level formatting bit is **1** during the formatting of a USB flash drive, an error message is printed.|
</tr>
| label | Specifies the volume label name. This parameter is optional, and the value is a string. <br/>If **null** is specified for this parameter, the previously set volume label name is cleared. |
<tdclass="cellrowborder"valign="top"width="66%"headers="mcps1.2.3.1.2 "><pid="p1197mcpsimp"><aname="p1197mcpsimp"></a><aname="p1197mcpsimp"></a>Specifies the device name.</p>
<tdclass="cellrowborder"valign="top"width="66%"headers="mcps1.2.3.1.2 "><pid="p1207mcpsimp"><aname="p1207mcpsimp"></a><aname="p1207mcpsimp"></a>Specifies the size of the allocated memory unit or sector. The value <strongid="b1574273871018"><aname="b1574273871018"></a><aname="b1574273871018"></a>0</strong> indicates null. (The value must be <strongid="b16428721113"><aname="b16428721113"></a><aname="b16428721113"></a>0</strong> or a power of <strongid="b1053419931111"><aname="b1053419931111"></a><aname="b1053419931111"></a>2</strong>. For FAT32, the maximum value is <strongid="b51473841110"><aname="b51473841110"></a><aname="b51473841110"></a>128</strong>. If the parameter is set to <strongid="b99547931214"><aname="b99547931214"></a><aname="b99547931214"></a>0</strong>, a proper cluster size is automatically selected. The available cluster size range varies depending on the partition size. If the cluster size is incorrectly specified, the formatting may fail.)</p>
<tdclass="cellrowborder"valign="top"width="66%"headers="mcps1.2.3.1.2 "><divclass="p"id="p1212mcpsimp"><aname="p1212mcpsimp"></a><aname="p1212mcpsimp"></a>Specifies the file system type. The options are as follows:<aname="ul10971366369"></a><aname="ul10971366369"></a><ulid="ul10971366369"><li><strongid="b169384514517"><aname="b169384514517"></a><aname="b169384514517"></a>0x01</strong>: FMT_FAT</li><li><strongid="b143061510125114"><aname="b143061510125114"></a><aname="b143061510125114"></a>0x02</strong>: FMT_FAT32</li><li><strongid="b3245614165116"><aname="b3245614165116"></a><aname="b3245614165116"></a>0x07</strong>: FMT_ANY</li><li><strongid="b018121813512"><aname="b018121813512"></a><aname="b018121813512"></a>0x08</strong>: FMT_ERASE (not supported by the USB flash drive)</li></ul>
</div>
<pid="p28366459374"><aname="p28366459374"></a><aname="p28366459374"></a>If an invalid value is specified, the system automatically selects the formatting mode. If the low-level formatting bit is <strongid="b4634562520"><aname="b4634562520"></a><aname="b4634562520"></a>1</strong> during the formatting of a USB flash drive, an error message is printed.</p>
<tdclass="cellrowborder"valign="top"width="66%"headers="mcps1.2.3.1.2 "><pid="p1217mcpsimp"><aname="p1217mcpsimp"></a><aname="p1217mcpsimp"></a>Specifies the volume label name. This parameter is optional, and the value is a string. If <strongid="b16648426102713"><aname="b16648426102713"></a><aname="b16648426102713"></a>null</strong> is specified for this parameter, the previously set volume label name is cleared.</p>
</td>
</tr>
</tbody>
</table>
## Usage<a name="section1510162714162"></a>
- The **format** command is used for disk formatting. You can find the device name in the **dev** directory. A storage card must be installed before the formatting.
- The **format** command is used for disk formatting. You can find the device name in the **dev** directory. A storage card must be installed before the formatting.
- The **format** command can be used to format the USB flash drive, SD card, and MMC, but not the NAND flash or NOR flash.
- The **format** command can be used to format the USB flash drive, SD card, and MMC, but not the NAND flash or NOR flash.
- An invalid **sectors** value may cause exceptions.
- An invalid **sectors** value may cause exceptions.
>During the system boot process, **ls=toybox ls --color=auto**, **ll = ls -alF**, **la=ls -A**, and **l=ls -CF** commands have been enabled using **alias** so that the initial actions of these commands are the same as those on Linux. For details, see the output description. To view help information, run **toybox ls --help**.
## Parameters<a name="section17528148171617"></a>
ls [_-ACHLSZacdfhiklmnopqrstux1_] [_--color_[_=auto_]] [_directory..._]
> **NOTE**<br>
> During the system boot process, **ls=toybox ls --color=auto**, **ll = ls -alF**, **la=ls -A**, and **l=ls -CF** commands have been enabled using **alias** so that the initial actions of these commands are the same as those on Linux. For details, see **Output**. To view help information, run **toybox ls --help**.
| -q | Displays non-printable characters, such as "?". | N/A |
</td>
| -s | Provides information about the memory occupied by the directory and its members, in 1024 bytes. | N/A |
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p161410110302"><aname="p161410110302"></a><aname="p161410110302"></a>Displays parameters supported by the <strongid="b05047195230"><aname="b05047195230"></a><aname="b05047195230"></a>ls</strong> command and their usage.</p>
| -u | Uses the last access time of the file as the timestamp. This option is used together with **-l**. | N/A |
</td>
| -A | Lists all files except implied . and .. | N/A |
| path | Specifies the path of the target directory.<br/>If **path** is left blank, the content of the current directory is displayed.<br>If **path** is an invalid directory, "ls error: No such directory." is displayed.<br><br>If **path** is a valid directory, the content of the specified directory is displayed. | Left blank<br>A valid directory|
</td>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p861431163012"><aname="p861431163012"></a><aname="p861431163012"></a>Displays all files, including .hidden files.</p>
| -x | Lists entries by line, instead of by column. |
</td>
| -ll | Lists the file time attribute as ns. |
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p6615121114307"><aname="p6615121114307"></a><aname="p6615121114307"></a>Uses ctime as the file timestamp. This parameter must be used together with <strongid="b644143217354"><aname="b644143217354"></a><aname="b644143217354"></a>-l</strong>.</p>
</td>
**Table 3** Parameters for sorting (by the initial letter by default)
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p126151511193010"><aname="p126151511193010"></a><aname="p126151511193010"></a>Displays only the directory, rather than listing the content of the directory.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p11615511193012"><aname="p11615511193012"></a><aname="p11615511193012"></a>Displays the node ID of a file.</p>
| --color | device=yellow symlink=turquoise/red dir=blue socket=purple files: exe=green suid=red suidfile=redback stickydir=greenback=auto means detect if output is a tty. |
The file node information of the FAT file system inherits from its parent node. The parent node ID is **0**. Therefore, if you run the **ls -i** command on the Hi3516D V300 development board, the file node IDs displayed are all **0**.
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p3615131103017"><aname="p3615131103017"></a><aname="p3615131103017"></a>Adds a slash (/) after the directory.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p19615511123011"><aname="p19615511123011"></a><aname="p19615511123011"></a>Displays non-printable characters, such as "?".</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p161511114303"><aname="p161511114303"></a><aname="p161511114303"></a>Provides information about the memory occupied by the directory and its members, in 1024 bytes.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p761501113306"><aname="p761501113306"></a><aname="p761501113306"></a>Uses the last access time of the file as the timestamp. This option is used together with <strongid="b83441545164512"><aname="b83441545164512"></a><aname="b83441545164512"></a>-l</strong>.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p56151511183019"><aname="p56151511183019"></a><aname="p56151511183019"></a>Lists all files except implied . and ..</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p19615151118304"><aname="p19615151118304"></a><aname="p19615151118304"></a>Follows symbolic links listed in the command line.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1761611110307"><aname="p1761611110307"></a><aname="p1761611110307"></a>If <strongid="b115515262034"><aname="b115515262034"></a><aname="b115515262034"></a>path</strong> is left blank, the content of the current directory is displayed.</p>
<pid="p10616141117308"><aname="p10616141117308"></a><aname="p10616141117308"></a>If <strongid="b9593204114312"><aname="b9593204114312"></a><aname="b9593204114312"></a>path</strong> is an invalid file name, the following failure message is displayed:</p>
<pid="p1061631112303"><aname="p1061631112303"></a><aname="p1061631112303"></a><strongid="b19604131716416"><aname="b19604131716416"></a><aname="b19604131716416"></a>ls error: No such directory</strong></p>
<pid="p206161111143018"><aname="p206161111143018"></a><aname="p206161111143018"></a>If <strongid="b615314272412"><aname="b615314272412"></a><aname="b615314272412"></a>path</strong> is a valid directory, the content of that directory is displayed.</p>
</td>
<tdclass="cellrowborder"valign="top"width="27%"headers="mcps1.2.4.1.3 "><pid="p761617115309"><aname="p761617115309"></a><aname="p761617115309"></a>Left blank or a valid directory</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1865811565309"><aname="p1865811565309"></a><aname="p1865811565309"></a>Lists one file per line.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1065865611302"><aname="p1065865611302"></a><aname="p1065865611302"></a>Lists entries by column.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p20658356183018"><aname="p20658356183018"></a><aname="p20658356183018"></a>Like <strongid="b206161282355"><aname="b206161282355"></a><aname="b206161282355"></a>-l</strong>, but do not list owner.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p16581756143014"><aname="p16581756143014"></a><aname="p16581756143014"></a>Displays the total size of files in the directory, in KiB.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1465875603018"><aname="p1465875603018"></a><aname="p1465875603018"></a>Displays detailed information about files in the directory.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p15658115620304"><aname="p15658115620304"></a><aname="p15658115620304"></a>Fills width with a list of entries separated by a comma.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1465895663016"><aname="p1465895663016"></a><aname="p1465895663016"></a>Like <strongid="b88319189351"><aname="b88319189351"></a><aname="b88319189351"></a>-l</strong>, but lists numeric user and group IDs.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p12658956193017"><aname="p12658956193017"></a><aname="p12658956193017"></a>Like <strongid="b24118395354"><aname="b24118395354"></a><aname="b24118395354"></a>-l</strong>, but do not list group information.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p13658456123014"><aname="p13658456123014"></a><aname="p13658456123014"></a>Lists entries by line, instead of by column.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p365855610302"><aname="p365855610302"></a><aname="p365855610302"></a>Lists the file time attribute as ns.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p2659756123020"><aname="p2659756123020"></a><aname="p2659756123020"></a>Colorizes the output.</p>
</td>
<tdclass="cellrowborder"valign="top"width="27%"headers="mcps1.2.4.1.3 "><pid="p2659135633011"><aname="p2659135633011"></a><aname="p2659135633011"></a>Default value: device=yellow symlink=turquoise/red dir=blue socket=purple files: exe=green suid=red suidfile=redback stickydir=greenback=auto means detect if output is a tty.</p>
</td>
</tr>
</tbody>
</table>
**Table 3** Sorting parameters \(sorted by the initial letter by default\)
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p18344132717315"><aname="p18344132717315"></a><aname="p18344132717315"></a>Do not sort.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p11344102743115"><aname="p11344102743115"></a><aname="p11344102743115"></a>Reverse order while sorting.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p10344727103114"><aname="p10344727103114"></a><aname="p10344727103114"></a>Sort by time, newest first.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1134452715312"><aname="p1134452715312"></a><aname="p1134452715312"></a>Sort by file size, largest first.</p>
>The file node information of the FAT file system inherits from its parent node. The parent node ID is **0**. Therefore, if you run the **ls -i** command on the Hi3516D V300 development board, the file node IDs displayed are all **0**.
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p2053354433413"><aname="p2053354433413"></a><aname="p2053354433413"></a>Displays the parameters supported by the <strongid="b1177313015559"><aname="b1177313015559"></a><aname="b1177313015559"></a>mkdir</strong> command.</p>
For the files created on the FAT file system, the file permission attributes are the same as those of the mounted nodes. Currently, the node permissions include only user read and write. The **group** and **others** permissions do not take effect.
In addition, only the user read and write permissions can be modified. The read and write permissions are **rw** and **ro** only. Therefore, when the **-m** option is specified in the **mkdir** command, only **777** and **555** permissions are available for the created directory, and the execute permission does not take effect.
Currently, the shell does not support this command. mksh supports it. To switch to mksh, run **cd bin** and **./mksh**.
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p9533114416343"><aname="p9533114416343"></a><aname="p9533114416343"></a>Sets the permissions on the directory to create.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p453344420349"><aname="p453344420349"></a><aname="p453344420349"></a>Prints detailed information about the directory creation process.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p653315443342"><aname="p653315443342"></a><aname="p653315443342"></a>Specifies the directory to create.</p>
>For the files created on the FAT file system, the file permission attributes are the same as those of the mounted nodes. Currently, the node permissions include only user read and write. The **group** and **others** permissions do not take effect.
>In addition, only the user read and write permissions can be modified. The read and write permissions are **rw** and **ro** only. Therefore, when the **-m** option is specified in the **mkdir** command, only **777** and **555** permissions are available for the created directory, and the execute permission does not take effect.
## Example<a name="section1113345211713"></a>
Run the following commands:
Run the following commands:
- mkdir testpath
- mkdir testpath
- mkdir -m 777 testpath
- mkdir -m 777 testpath
- mkdir -pv testpath01/testpath02/testpath03
- mkdir -pv testpath01/testpath02/testpath03
## Output<a name="section10142201012"></a>
## Output
Example 1: Create a directory named **testpath**.
```
```
OHOS:/tmp$ mkdir testpath
OHOS:/tmp$ mkdir testpath
...
@@ -83,7 +56,8 @@ total 2
...
@@ -83,7 +56,8 @@ total 2
drwxrwxrwx 1 0 0 2048 1979-12-31 00:00 testpath/
drwxrwxrwx 1 0 0 2048 1979-12-31 00:00 testpath/
```
```
Example 2: creating a directory with specified permissions
Example 2: Create a directory named **testpath** with specified permissions.
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p8804113024018"><aname="p8804113024018"></a><aname="p8804113024018"></a>Displays the parameters supported by the <strongid="b07421044122514"><aname="b07421044122514"></a><aname="b07421044122514"></a>mount</strong> command.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1980419305409"><aname="p1980419305409"></a><aname="p1980419305409"></a>Fakes mounting the file system (no mounting is actually performed).</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p680443010409"><aname="p680443010409"></a><aname="p680443010409"></a>Specifies the file system type.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p280473015402"><aname="p280473015402"></a><aname="p280473015402"></a>Specifies the mount options.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p28045303401"><aname="p28045303401"></a><aname="p28045303401"></a>Specifies the device to mount (in the format of the device directory).</p>
</td>
<tdclass="cellrowborder"valign="top"width="27%"headers="mcps1.2.4.1.3 "><pid="p8804113084010"><aname="p8804113084010"></a><aname="p8804113084010"></a>A device in the system</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1380419308409"><aname="p1380419308409"></a><aname="p1380419308409"></a>Specifies the directory.</p>
<pid="p14804153014011"><aname="p14804153014011"></a><aname="p14804153014011"></a>You must have the execution (search) permission on the specified directory.</p>
By specifying the device to mount, directory, and file system format in the **mount** command, you can successfully mount the file system to the specified directory.
By specifying the device to mount, directory, and file system format in the **mount** command, you can successfully mount the file system to the specified directory.
## Example<a name="section7424625171917"></a>
## Note
Currently, the shell does not support this command. mksh supports it. To switch to mksh, run **cd bin** and **./mksh**.
## Example
Run **mount -t nfs 192.168.1.3:/nfs nfs**.
Run **mount -t nfs 192.168.1.3:/nfs nfs**.
## Output<a name="section14757018116"></a>
Mounting the **nfs** directory on the server with IP address of **192.168.1.3** to the newly created **/nfs** directory in the current system
## Output
Mount the **nfs** directory on the server with IP address of **192.168.1.3** to the newly created **/nfs** directory in the current system.
| -i | Provides information before moving a file that would overwrite an existing file or directory. Enter **y** to overwrite the file or directory, and enter **n** to cancel the operation.| N/A |
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p1165745918447"><aname="p1165745918447"></a><aname="p1165745918447"></a>Displays help information.</p>
-**SOURCEFILE** supports wildcard characters * and ?. The asterisk (*) indicates any number of characters, and the question mark (?) represents a single character. **DEST** does not support wildcard characters. If the specified **SOURCE** matches multiple files, **DEST** must be a directory.
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p7657105917445"><aname="p7657105917445"></a><aname="p7657105917445"></a>Provides a prompt before moving a file that would overwrite an existing file. Enter <strongid="b886564463218"><aname="b886564463218"></a><aname="b886564463218"></a>y</strong> to overwrite the file or enter <strongid="b16826758113218"><aname="b16826758113218"></a><aname="b16826758113218"></a>n</strong> to cancel the operation.</p>
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p36572059164415"><aname="p36572059164415"></a><aname="p36572059164415"></a>Do not overwrite any existing file or directory.</p>
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p166571759124418"><aname="p166571759124418"></a><aname="p166571759124418"></a>This parameter does not take effect although it is supported by the latest Toybox code.</p>
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p3657205924416"><aname="p3657205924416"></a><aname="p3657205924416"></a>Specifies the path of the source file.</p>
</td>
<tdclass="cellrowborder"valign="top"width="27%"headers="mcps1.2.4.1.3 "><pid="p1365775904419"><aname="p1365775904419"></a><aname="p1365775904419"></a>This command cannot be used to move a directory. It can be used to move multiple files at a time.</p>
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p265810599448"><aname="p265810599448"></a><aname="p265810599448"></a>Specifies the destination file path.</p>
</td>
<tdclass="cellrowborder"valign="top"width="27%"headers="mcps1.2.4.1.3 "><pid="p7658105914449"><aname="p7658105914449"></a><aname="p7658105914449"></a>Both a directory and a file are supported.</p>
</td>
</tr>
</tbody>
</table>
## Usage<a name="section19190125723612"></a>
-**SOURCE** supports wildcard characters \* and ?. The asterisk \(\*\) indicates any number of characters, and the question mark \(?\) represents a single character. **DEST** does not support wildcard characters. If the specified **SOURCE** matches multiple files, **DEST** must be a directory.
- If **DEST** is a directory, this directory must exist. In this case, the destination file is named after the source file.
- If **DEST** is a directory, this directory must exist. In this case, the destination file is named after the source file.
- If **DEST** is a file, the directory for this file must exist.
- If **DEST** is a file, the directory for this file must exist.
- If the destination file already exists, it will be overwritten.
- If the destination file already exists, it will be overwritten.
## Example<a name="section10383416372"></a>
## Note
Currently, the shell does not support this command. mksh supports it. To switch to mksh, run **cd bin** and **./mksh**.
## Example
Run the following commands:
Run the following commands:
- mv -i test.txt testpath/
- mv -i test.txt testpath/
- mv test?.txt testpath/ \(Move **test3.txt**, **testA.txt**, and **test\_.txt**\)
## Output<a name="section131601649114511"></a>
- mv test?.txt testpath/ (Move **test3.txt**, **testA.txt**, and **test_.txt**)
<tdclass="cellrowborder"valign="top"width="51%"headers="mcps1.2.4.1.2 "><pid="p1407mcpsimp"><aname="p1407mcpsimp"></a><aname="p1407mcpsimp"></a>Specifies the name of the partition to be queried.</p>
The **pwd** command writes the full path (from the root directory) of the current directory to the standard output. The directories are separated by slashes (/). The directory following the first slash (/) indicates the root directory, and the last directory is the current directory.
The **pwd** command writes the full path \(from the root directory\) of the current directory to the standard output. The directories are separated by slashes \(/\). The directory following the first slash \(/\) indicates the root directory, and the last directory is the current directory.
<tdclass="cellrowborder"valign="top"width="51.519999999999996%"headers="mcps1.2.4.1.2 "><pid="p53092373308"><aname="p53092373308"></a><aname="p53092373308"></a>Deletes a file or directory forcibly without confirmation. No error will be reported when a file that does not exist is to be deleted.</p>
<tdclass="cellrowborder"valign="top"width="51.519999999999996%"headers="mcps1.2.4.1.2 "><pid="p1830913711300"><aname="p1830913711300"></a><aname="p1830913711300"></a>Displays the deletion process.</p>
<tdclass="cellrowborder"valign="top"width="51.519999999999996%"headers="mcps1.2.4.1.2 "><pid="p193091637183016"><aname="p193091637183016"></a><aname="p193091637183016"></a>Specifies the name of the file or directory to delete. The value can be a path.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p18752121015338"><aname="p18752121015338"></a><aname="p18752121015338"></a>Displays the parameters supported by the <strongid="b101038101521"><aname="b101038101521"></a><aname="b101038101521"></a>rmdir</strong> command.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1475271013319"><aname="p1475271013319"></a><aname="p1475271013319"></a>Deletes a path.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p77522010123314"><aname="p77522010123314"></a><aname="p77522010123314"></a>Suppresses the error message when a non-empty directory is to be deleted.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p3752161083313"><aname="p3752161083313"></a><aname="p3752161083313"></a>Specifies the name of the directory to delete. The directory must be empty. A path is supported.</p>
| directory | Specifies the file system directory.| The file system must exist and support the **statfs** command. The supported file systems include JFFS2, FAT, and NFS.|
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.2 "><pid="p1615mcpsimp"><aname="p1615mcpsimp"></a><aname="p1615mcpsimp"></a>Specifies the file system directory.</p>
</td>
<tdclass="cellrowborder"valign="top"width="33.33333333333333%"headers="mcps1.2.4.1.3 "><pid="p1617mcpsimp"><aname="p1617mcpsimp"></a><aname="p1617mcpsimp"></a>The file system must exist and support the <strongid="b1635148125717"><aname="b1635148125717"></a><aname="b1635148125717"></a>statfs</strong> command. The supported file systems include JFFS2, FAT, and NFS.</p>
</td>
</tr>
</tbody>
</table>
## Usage<a name="section133816772712"></a>
The printed information varies depending on the file system.
The printed information varies depending on the file system.
This command is used to synchronize cached data \(data in the file system\) to an SD card.
This command is used to synchronize cached data (data in the file system) to an SD card.
## Syntax<a name="section4731516162712"></a>
## Syntax
sync
sync
## Parameters<a name="section9352418122714"></a>
None
## Parameters
None.
## Usage<a name="section10725192142717"></a>
## Usage Guidelines
- The **sync** command is used to refresh the cache. If no SD card is inserted, no operation will be performed.
- The **sync** command is used to refresh the cache. If no SD card is inserted, no operation will be performed.
- When an SD card is inserted, the cache information is synchronized to the SD card. If the synchronization is successful, no information is displayed.
- When an SD card is inserted, the cache information is synchronized to the SD card. If the synchronization is successful, no information is displayed.
## Example<a name="section414434814354"></a>
## Example
Run **sync**. Data will be synchronized to the SD card if an SD card is available, and no operation will be performed if no SD card is available.
Run **sync**. Data will be synchronized to the SD card if an SD card is available, and no operation will be performed if no SD card is available.
<tdclass="cellrowborder"valign="top"width="52.44%"headers="mcps1.2.4.1.2 "><pid="p1122915417465"><aname="p1122915417465"></a><aname="p1122915417465"></a>Displays the parameters supported by the <strongid="b39321953125917"><aname="b39321953125917"></a><aname="b39321953125917"></a>touch</strong> command.</p>
<tdclass="cellrowborder"valign="top"width="52.44%"headers="mcps1.2.4.1.2 "><pid="p162291494614"><aname="p162291494614"></a><aname="p162291494614"></a>Specifies the name of the file to create.</p>
>If you run the **touch** command to create a file in a directory storing important system resources, unexpected results such as a system breakdown may occur. For example, if you run the **touch uartdev-0** command in the **/dev** directory, the system may stop responding.
> If you run the **touch** command to create a file in a directory storing important system resources, unexpected results such as a system breakdown may occur. For example, if you run the **touch uartdev-0** command in the **/dev** directory, the system may stop responding.
## Note
## Example<a name="section414434814354"></a>
The shell does not support **--help** or creation of multiple files at the same time. mksh supports it. To switch to mksh, run **cd bin** and **./mksh**.
## Example
Run the following commands:
Run the following commands:
- touch file.c
- touch file.c
- touch testfile1 testfile2 testfile3
- touch testfile1 testfile2 testfile3
## Output<a name="section1028419515711"></a>
Example 1: creating the **file.c** file
## Output
Example 1: Create a file named **file.c**.
```
```
OHOS:/tmp$ ls
OHOS:/tmp$ ls
...
@@ -70,7 +60,8 @@ total 0
...
@@ -70,7 +60,8 @@ total 0
-rwxrwxrwx 1 0 0 0 1979-12-31 00:00 file.c*
-rwxrwxrwx 1 0 0 0 1979-12-31 00:00 file.c*
```
```
Example 2: creating three files \(**testfile1**, **testfile2**, and **testfile3**\)
Example 2: Create three files (**testfile1**, **testfile2**, and **testfile3**) at a time.
| -t | Used together with the **-a** option to restrict the file systems specified by **-a**, allowing only the file system specified by **-t** to be unmounted.| N/A |
By specifying the **dir** parameter in the **unmount** command, you can unmount the specified file system.
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p5999201625017"><aname="p5999201625017"></a><aname="p5999201625017"></a>Displays the parameters supported by the <strongid="b15196112818310"><aname="b15196112818310"></a><aname="b15196112818310"></a>umount</strong> command.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p159991716125019"><aname="p159991716125019"></a><aname="p159991716125019"></a>Unmounts all file systems mounted.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p49997167506"><aname="p49997167506"></a><aname="p49997167506"></a>Used together with the <strongid="b19922101571717"><aname="b19922101571717"></a><aname="b19922101571717"></a>-a</strong> option to restrict the file systems specified by <strongid="b1927154112172"><aname="b1927154112172"></a><aname="b1927154112172"></a>-a</strong>, allowing only the file system specified by <strongid="b99221198185"><aname="b99221198185"></a><aname="b99221198185"></a>-t</strong> to be unmounted.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p129991162504"><aname="p129991162504"></a><aname="p129991162504"></a>Specifies the directory from which the file system is to be unmounted.</p>
</td>
<tdclass="cellrowborder"valign="top"width="27%"headers="mcps1.2.4.1.3 "><pid="p1499916164502"><aname="p1499916164502"></a><aname="p1499916164502"></a>Directory mounted with the file system</p>
</td>
</tr>
</tbody>
</table>
## Usage<a name="section92931509368"></a>
By specifying the **dir** parameter in the **unmount** command, you can unmount the specified file system from the directory.
## Example<a name="section144311323616"></a>
Run the following commands:
Run the following commands:
- umount ./nfs
- umount ./nfs
- umount -a -t nfs
- umount -a -t nfs
## Output<a name="section360525113611"></a>
**unmount** command output:
## Output
Example 1: Unmount the file system from **./nfs**.
Example 1: unmounting the file system from **./nfs**
This command is used to write data to a specified proc file system. The proc file system supports the input of string parameters. Each file needs to implement its own method.
This command is used to write data to the specified proc file system. The proc file system supports data of strings. The method for writing data needs to be implemented.
The proc file system implements its own **write()** function. Calling the **writeproc** command will pass input parameters to the **write()** function.
<tdclass="cellrowborder"valign="top"width="52.970000000000006%"headers="mcps1.2.4.1.2 "><pid="p1149945111817"><aname="p1149945111817"></a><aname="p1149945111817"></a>Specifies the string to be entered, which ends with a space. If you need to enter a space, use <strongid="b11296145424918"><aname="b11296145424918"></a><aname="b11296145424918"></a>""</strong> to enclose the space.</p>
> The procfs file system does not support multi-thread access.
<tdclass="cellrowborder"valign="top"width="52.970000000000006%"headers="mcps1.2.4.1.2 "><pid="p25985252238"><aname="p25985252238"></a><aname="p25985252238"></a>Specifies the proc file to which <strongid="b1319518261507"><aname="b1319518261507"></a><aname="b1319518261507"></a>data</strong> is to be passed.</p>
When the system does not respond, you can use the magic key function to check whether the system is suspended by an interrupt lock (the magic key also does not respond) or view the system task running status.
When the system does not respond, you can use the magic key to check whether the system is suspended by an interrupt lock or view the system task running status.
If interrupts are responded, you can use the magic key to check the task CPU usage (**cpup**) and find out the task with the highest CPU usage. Generally, the task with a higher priority preempts the CPU resources.
If interrupts are responded, you can use the magic key to check the task CPU percent (CPUP) and locate the task with the highest CPUP. Generally, the task with a higher priority preempts the CPU resources.
## How to Use
## How to Configure
The magic key depends on the macro **LOSCFG_ENABLE_MAGICKEY**.
To configure **LOSCFG_ENABLE_MAGICKEY**:
1. Configure the macro **LOSCFG_ENABLE_MAGICKEY**.
1. Run the **make menuconfig** command in **kernel/liteos_a**.
2. Locate the **Debug** option and select **Enable MAGIC KEY**.
The magic key depends on the **LOSCFG_ENABLE_MAGICKEY** macro. Before using the magic key, select **Enable MAGIC KEY** (**Debug** ---> **Enable MAGIC KEY**) on **menuconfig**. The magic key cannot be used if this option is disabled.
This option is selected by default. If it is not selected, the magic key is invalid.
> On **menuconfig**, you can move the cursor to **LOSCFG_ENABLE_MAGICKEY** and enter a question mark (?) to view help information.
> On **menuconfig**, you can move the cursor to **LOSCFG_ENABLE_MAGICKEY** and enter a question mark (?) to view help Information.
## How to Use
2. Press **Ctrl+R** to enable the magic key.
1. Press **Ctrl+R** to enable the magic key.
When the UART or USB-to-virtual serial port is connected, press **Ctrl+R**. If "Magic key on" is displayed, the magic key is enabled. To disable it, press **Ctrl+R** again. If "Magic key off" is displayed, the magic key is disabled.
When the UART or USB-to-virtual serial port is connected, press **Ctrl+R**. If "Magic key on" is displayed, the magic key is enabled. To disable it, press **Ctrl+R** again. If "Magic key off" is displayed, the magic key is disabled.
...
@@ -32,5 +38,5 @@ If interrupts are responded, you can use the magic key to check the task CPU usa
...
@@ -32,5 +38,5 @@ If interrupts are responded, you can use the magic key to check the task CPU usa
-**Ctrl+E**: Checks the integrity of the memory pool. If an error is detected, the system displays an error message. If no error is detected, the system displays "system memcheck over, all passed!".
-**Ctrl+E**: Checks the integrity of the memory pool. If an error is detected, the system displays an error message. If no error is detected, the system displays "system memcheck over, all passed!".
> If magic key is enabled, when special characters need to be entered through the UART or USB-to-virtual serial port, avoid using characters the same as the magic keys. Otherwise, the magic key may be triggered by mistake, causing errors in the original design.
> If magic key is enabled, when special characters need to be entered through the UART or USB-to-virtual serial port, avoid using characters the same as the magic keys. Otherwise, the magic key may be triggered by mistake, causing errors in design.
Hosts on an Ethernet communicate with each other using MAC addresses. IP addresses must be converted into MAC addresses to enable communication between hosts on a LAN \(Ethernet\). To achieve this purpose, the host stores a table containing the mapping between IP addresses and MAC addresses. This table is called an Address Resolution Protocol \(ARP\) cache table. Before sending an IP packet to a LAN, the host looks up the destination MAC address in the ARP cache table. The ARP cache table is maintained by the TCP/IP stack. You can run the **arp** command to view and modify the ARP cache table.
Hosts on an Ethernet communicate with each other using MAC addresses. IP addresses must be converted into MAC addresses to enable communication between hosts on a LAN (Ethernet). To achieve this purpose, the host stores a table containing the mapping between IP addresses and MAC addresses. This table is called an Address Resolution Protocol (ARP) cache table. Before sending an IP packet to a LAN, the host looks up the destination MAC address in the ARP cache table. The ARP cache table is maintained by the TCP/IP stack. You can run the **arp** command to view and modify the ARP cache table.
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p1862mcpsimp"><aname="p1862mcpsimp"></a><aname="p1862mcpsimp"></a>Queries the content of the ARP cache table.</p>
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p1869mcpsimp"><aname="p1869mcpsimp"></a><aname="p1869mcpsimp"></a>Specifies the network port. This parameter is optional.</p>
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p1877mcpsimp"><aname="p1877mcpsimp"></a><aname="p1877mcpsimp"></a>Adds an ARP entry. The second parameter is the IP address and MAC address of the other host on the LAN.</p>
<tdclass="cellrowborder"valign="top"width="52.16%"headers="mcps1.2.4.1.2 "><pid="p1884mcpsimp"><aname="p1884mcpsimp"></a><aname="p1884mcpsimp"></a>Deletes an ARP entry.</p>
- The **arp** command is used to query and modify the ARP cache table of the TCP/IP stack. If ARP entries for IP addresses on different subnets are added, the protocol stack returns a failure message.
- The **arp** command is used to query and modify the ARP cache table of the TCP/IP stack. If ARP entries for IP addresses on different subnets are added, the protocol stack returns a failure message.
- This command can be used only after the TCP/IP stack is enabled.
## Example<a name="section10383416372"></a>
- This command can be used only after the TCP/IP protocol stack is enabled.
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1915mcpsimp"><aname="p1915mcpsimp"></a><aname="p1915mcpsimp"></a>IPv4 address of a network device.</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1920mcpsimp"><aname="p1920mcpsimp"></a><aname="p1920mcpsimp"></a>MAC address of a network device.</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1925mcpsimp"><aname="p1925mcpsimp"></a><aname="p1925mcpsimp"></a>Name of the port used by the ARP entry.</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1930mcpsimp"><aname="p1930mcpsimp"></a><aname="p1930mcpsimp"></a>Indicates whether the ARP entry is dynamic or static. A dynamic ARP entry is automatically created by the protocol stack, and a static ARP entry is added by the user.</p>
</td>
</tr>
</tbody>
</table>
| Parameter| Description|
| -------- | -------- |
| Address | IPv4 address of the network device.|
| HWaddress | MAC address of the network device.|
| Iface | Name of the port used by the ARP entry.|
| Type | Whether the ARP entry is dynamic or static. A dynamic ARP entry is automatically created by the protocol stack, and a static ARP entry is added by the user. |
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p14803132214716"><aname="p14803132214716"></a><aname="p14803132214716"></a>Displays parameters supported by the <strongid="b71961312874"><aname="b71961312874"></a><aname="b71961312874"></a>dhclient</strong> command and their usage.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1180318222710"><aname="p1180318222710"></a><aname="p1180318222710"></a>Disables DHCP for a NIC.</p>
| No parameter| Displays all NIC information, which includes the IP address, network mask, gateway, MAC address, maximum transmission unit (MTUs), and running status of each NIC.| N/A |
| mtu | Specifies the MTU size, for example, **1000**.| - IPv4: [68, 1500]<br>- IPv6:[1280, 1500] |
</td>
| add | Specifies the IPv6 address, for example, **2001:a:b:c:d:e:f:d**. The NIC name and **inet6** must be specified.| N/A |
<tdclass="cellrowborder"valign="top"width="53.669999999999995%"headers="mcps1.2.4.1.2 "><pid="p1594124175315"><aname="p1594124175315"></a><aname="p1594124175315"></a>Displays all NIC information, which includes the IP address, network mask, gateway, MAC address, maximum transmission unit (MTUs), and running status of each NIC.</p>
| del | Deletes an IPv6 address. You need to specify the NIC name and add the **inet6** option. For details, see the example.| N/A |
</td>
| up | Enables the data processing function of the NIC. The NIC name must be specified.| N/A |
<tdclass="cellrowborder"valign="top"width="53.669999999999995%"headers="mcps1.2.4.1.2 "><pid="p13941445534"><aname="p13941445534"></a><aname="p13941445534"></a>Displays data sent and received by the protocol stack.</p>
- This command can be used only after the TCP/IP stack is enabled.
<tdclass="cellrowborder"valign="top"width="53.669999999999995%"headers="mcps1.2.4.1.2 "><pid="p139415485312"><aname="p139415485312"></a><aname="p139415485312"></a>Specifies the NIC name, for example, <strongid="b1368975571410"><aname="b1368975571410"></a><aname="b1368975571410"></a>eth0</strong>.</p>
<tdclass="cellrowborder"valign="top"width="53.669999999999995%"headers="mcps1.2.4.1.2 "><pid="p119454165313"><aname="p119454165313"></a><aname="p119454165313"></a>Specifies the IP address, for example, <strongid="b530715731519"><aname="b530715731519"></a><aname="b530715731519"></a>192.168.1.10</strong>. The NIC name must be specified.</p>
<tdclass="cellrowborder"valign="top"width="53.669999999999995%"headers="mcps1.2.4.1.2 "><pid="p194749536"><aname="p194749536"></a><aname="p194749536"></a>Specifies the subnet mask, for example, <strongid="b1625513191514"><aname="b1625513191514"></a><aname="b1625513191514"></a>255.255.255.0</strong>.</p>
<tdclass="cellrowborder"valign="top"width="53.669999999999995%"headers="mcps1.2.4.1.2 "><pid="p109413413534"><aname="p109413413534"></a><aname="p109413413534"></a>Specifies the gateway, for example, <strongid="b52931945195112"><aname="b52931945195112"></a><aname="b52931945195112"></a>192.168.1.1</strong>.</p>
<tdclass="cellrowborder"valign="top"width="53.669999999999995%"headers="mcps1.2.4.1.2 "><pid="p20946412532"><aname="p20946412532"></a><aname="p20946412532"></a>Specifies the MAC address, for example, <strongid="b85669109525"><aname="b85669109525"></a><aname="b85669109525"></a>00:11:22:33:44:55</strong>. Currently, only the <strongid="b534492414613"><aname="b534492414613"></a><aname="b534492414613"></a>ether</strong> hardware type is supported.</p>
<tdclass="cellrowborder"valign="top"width="53.669999999999995%"headers="mcps1.2.4.1.2 "><pid="p159418414536"><aname="p159418414536"></a><aname="p159418414536"></a>Specifies the MTU size, for example, <strongid="b2852192012261"><aname="b2852192012261"></a><aname="b2852192012261"></a>1000</strong>.</p>
<tdclass="cellrowborder"valign="top"width="53.669999999999995%"headers="mcps1.2.4.1.2 "><pid="p1952046539"><aname="p1952046539"></a><aname="p1952046539"></a>Specifies the IPv6 address, for example, <strongid="b12509153516279"><aname="b12509153516279"></a><aname="b12509153516279"></a>2001:a:b:c:d:e:f:d</strong>. The NIC name and <strongid="b912123842916"><aname="b912123842916"></a><aname="b912123842916"></a>inet6</strong> must be specified.</p>
<tdclass="cellrowborder"valign="top"width="53.669999999999995%"headers="mcps1.2.4.1.2 "><pid="p1556618562119"><aname="p1556618562119"></a><aname="p1556618562119"></a>Deletes an IPv6 address. You need to specify the NIC name and add the <strongid="b166212197409"><aname="b166212197409"></a><aname="b166212197409"></a>inet6</strong> option. For details, see the example.</p>
<tdclass="cellrowborder"valign="top"width="53.669999999999995%"headers="mcps1.2.4.1.2 "><pid="p119510455314"><aname="p119510455314"></a><aname="p119510455314"></a>Enables the data processing function of the NIC. The NIC name must be specified.</p>
<tdclass="cellrowborder"valign="top"width="53.669999999999995%"headers="mcps1.2.4.1.2 "><pid="p1795164105312"><aname="p1795164105312"></a><aname="p1795164105312"></a>Disables the data processing function of the NIC. The NIC name must be specified.</p>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p281516205410"><a name="p281516205410"></a><a name="p281516205410"></a>Indicates whether the NIC is running.</p>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p881516145415"><a name="p881516145415"></a><a name="p881516145415"></a>Indicates that the NIC is connected to the default gateway.</p>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p18201614546"><a name="p18201614546"></a><a name="p18201614546"></a>Connection status of the NIC</p>
</td>
</tr>
</tbody>
</table>
- Example 2: obtaining protocol stack statistics
```
```
OHOS # ifconfig -a
OHOS # ifconfig -a
...
@@ -213,71 +106,24 @@ option:
...
@@ -213,71 +106,24 @@ option:
TX packets(ip6):3 errors:0 overrun:0 bytes:0(0.0 B)
TX packets(ip6):3 errors:0 overrun:0 bytes:0(0.0 B)
```
```
The following table describes the output parameters.
| RX error | Number of error packets received at the IP layer. The errors include the length error, verification error, IP option error, and IP header protocol error.|
</th>
| RX dropped | Number of packets discarded at the IP layer. Packets are discarded due to packet errors, packet forwarding failures, and disabled local NICs.|
</tr>
| RX overrun | Number of packets that the MAC layer fails to deliver to the upper-layer protocol stack. The failure is caused by resource insufficiency at the protocol stack.|
</thead>
| RX bytes | Total length of normal packets received at the IP layer, excluding the length of the fragments that are not reassembled.|
| TX packets | Number of packets that have been normally sent or forwarded at the IP layer.|
</td>
| TX error | Number of packets that the IP layer fails to send. Packets may fail to be sent because the packets cannot be routed or the packets fail to be processed in the protocol stack.|
<td class="cellrowborder" valign="top" width="71%" headers="mcps1.2.3.1.2 "><p id="p1174183145516"><a name="p1174183145516"></a><a name="p1174183145516"></a>Number of normal packets received at the IP layer.</p>
| TX dropped | Number of packets that the MAC layer discards due to delivery failures, for example, the NIC driver fails to process the packets.|
</td>
| TX overrun | Not used currently.|
</tr>
| TX bytes | Total length of the packets successfully sent or forwarded at the IP layer.|
<td class="cellrowborder" valign="top" width="71%" headers="mcps1.2.3.1.2 "><p id="p1274133195513"><a name="p1274133195513"></a><a name="p1274133195513"></a>Number of error packets received at the IP layer. The errors include the length error, verification error, IP option error, and IP header protocol error.</p>
<td class="cellrowborder" valign="top" width="71%" headers="mcps1.2.3.1.2 "><p id="p13741637551"><a name="p13741637551"></a><a name="p13741637551"></a>Number of packets discarded at the IP layer. Packets are discarded due to packet errors, packet forwarding failures, and disabled local NICs.</p>
<td class="cellrowborder" valign="top" width="71%" headers="mcps1.2.3.1.2 "><p id="p17742305517"><a name="p17742305517"></a><a name="p17742305517"></a>Number of packets that the MAC layer fails to deliver to the upper-layer protocol stack. The failure is caused by resource insufficiency at the protocol stack.</p>
<td class="cellrowborder" valign="top" width="71%" headers="mcps1.2.3.1.2 "><p id="p9741385519"><a name="p9741385519"></a><a name="p9741385519"></a>Total length of normal packets received at the IP layer, excluding the length of the fragments that are not reassembled.</p>
<td class="cellrowborder" valign="top" width="71%" headers="mcps1.2.3.1.2 "><p id="p19745375513"><a name="p19745375513"></a><a name="p19745375513"></a>Number of packets that have been normally sent or forwarded at the IP layer.</p>
<td class="cellrowborder" valign="top" width="71%" headers="mcps1.2.3.1.2 "><p id="p9756312553"><a name="p9756312553"></a><a name="p9756312553"></a>Number of packets that the IP layer fails to send. Packets may fail to be sent because the packets cannot be routed or the packets fail to be processed in the protocol stack.</p>
<td class="cellrowborder" valign="top" width="71%" headers="mcps1.2.3.1.2 "><p id="p87519395520"><a name="p87519395520"></a><a name="p87519395520"></a>Number of packets that the MAC layer discards due to delivery failures, for example, the NIC driver fails to process the packets.</p>
<td class="cellrowborder" valign="top" width="71%" headers="mcps1.2.3.1.2 "><p id="p7759375512"><a name="p7759375512"></a><a name="p7759375512"></a>Total length of the packets successfully sent or forwarded at the IP layer.</p>
**ipdebug** is a console command and is used for IPv6 debugging. It can display IPv6 address prefixes, neighbor entries, destination entries, and default route entries.
**ipdebug** is a console command and is used for IPv6 debugging. It can display IPv6 address prefixes, neighbor entries, destination entries, and default route entries.
## Syntax<a name="section124061758123713"></a>
## Syntax
ipdebug
ipdebug
## Example<a name="section171837113810"></a>
## Example
Run the **ipdebug** command.
Run the **ipdebug** command.
## Output<a name="section561416467104"></a>
## Output
**ipdebug** command output:
**ipdebug** command output:
...
@@ -52,4 +55,3 @@ FE80::4639:C4FF:FE94:5D44 FE80::4639:C4FF:FE94:5D44 pmtu 1500 age 6
...
@@ -52,4 +55,3 @@ FE80::4639:C4FF:FE94:5D44 FE80::4639:C4FF:FE94:5D44 pmtu 1500 age 6
The **netstat** command is a console command and is used for monitoring the TCP/IP network. It can display the actual network connections and the status of each network interface device. This command displays statistics related to TCP and UDP and can be used to check the network connection to each port on the device \(board\).
The **netstat** command is a console command and is used for monitoring the TCP/IP network. It can display the actual network connections and the status of each network interface device. This command displays statistics related to TCP and UDP connections and can be used to check the network connection to each port on a device (board).
## Syntax<a name="section795712373812"></a>
## Syntax
netstat
netstat
## Parameters<a name="section17629431193817"></a>
None
## Parameters
## Usage<a name="section5277153519380"></a>
None.
netstat
## Example<a name="section108141437163820"></a>
## Usage Guidelines
None.
## Note
Currently, the shell does not support this command.
| Recv-Q | Amount of data that is not read by the user.<br>For Listen TCP, the value indicates the number of TCP connections that have finished the three-way handshake but are not accepted by users. |
</th>
| Send-Q | For a TCP connection, this value indicates the amount of data that has been sent but not acknowledged.<br>For a UDP connection, this value indicates the amount of data buffered before IP address resolution is complete.|
</tr>
| Local Address | Local IP address and port number. |
</thead>
| Foreign Address | Remote IP address and port number. |
> The command output like "========== total sockets 32 ====== unused sockets 22 BootTime 27 s ==========" indicates that there are 32 sockets in total, 22 sockets are not used, and it has been 27 seconds since the system starts.
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p2550mcpsimp"><aname="p2550mcpsimp"></a><aname="p2550mcpsimp"></a>Amount of data that is not read by the user.</p>
<pid="p2551mcpsimp"><aname="p2551mcpsimp"></a><aname="p2551mcpsimp"></a>For Listen TCP, the value indicates the number of TCP connections that have finished three-way handshake but are not accepted by users.</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p1250715415473"><aname="p1250715415473"></a><aname="p1250715415473"></a>For a TCP connection, this value indicates the amount of data that has been sent but not acknowledged.</p>
<pid="p1080412214470"><aname="p1080412214470"></a><aname="p1080412214470"></a>For a UDP connection, this value indicates the amount of data buffered before IP address resolution is complete.</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p2562mcpsimp"><aname="p2562mcpsimp"></a><aname="p2562mcpsimp"></a>Local IP address and port number.</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p2567mcpsimp"><aname="p2567mcpsimp"></a><aname="p2567mcpsimp"></a>Remote IP address and port number.</p>
<tdclass="cellrowborder"valign="top"width="50%"headers="mcps1.2.3.1.2 "><pid="p2572mcpsimp"><aname="p2572mcpsimp"></a><aname="p2572mcpsimp"></a>TCP connection status. This parameter is meaningless for UDP.</p>
>The command output like "========== total sockets 32 ====== unused sockets 22 BootTime 27 s ==========" indicates that there are 32 sockets in total, 22 sockets are not used, and it has been 27 seconds since the system starts.
<tdclass="cellrowborder"valign="top"width="52.480000000000004%"headers="mcps1.2.4.1.2 "><pid="p2633mcpsimp"><aname="p2633mcpsimp"></a><aname="p2633mcpsimp"></a>Specifies the IP address of the NTP server.</p>
Run the **ntpdate **\[_SERVER\_IP1_\]\[_SERVER\_IP2_\]... command. **ntpdate** obtains and displays the time of the first server with a valid IP address.
## Example<a name="section3431554203811"></a>
Run **ntpdate 192.168.1.3 **to update the system time.
Run **ntpdate 192.168.1.3 **to update the system time.
## Output<a name="section18638194610115"></a>
## Output
```
```
OHOS # ntpdate 192.168.1.3
OHOS # ntpdate 192.168.1.3
time server 192.168.1.3: Mon Jun 13 09:24:25 2016
time server 192.168.1.3: Mon Jun 13 09:24:25 2016
```
```
If the time zone of the board is different from that of the server, the displayed time may be several hours different from the obtained server time.
If the time zone of the board is different from that of the server, the displayed time may be several hours different from the server time obtained.
| IP | Specifies the IPv4 address of the network to test.| N/A |
</td>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p122810445818"><aname="p122810445818"></a><aname="p122810445818"></a>Displays the parameters supported by the <strongid="b1796144112279"><aname="b1796144112279"></a><aname="b1796144112279"></a>ping</strong> command.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p16281846585"><aname="p16281846585"></a><aname="p16281846585"></a>Forcibly pings the destination address using the IPv4 protocol.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p1281248583"><aname="p1281248583"></a><aname="p1281248583"></a>Specifies the number of execution times. The default value is <strongid="b209506262288"><aname="b209506262288"></a><aname="b209506262288"></a>3</strong>.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p22811642583"><aname="p22811642583"></a><aname="p22811642583"></a>Pings an IPv4 address in implicit mode. The default parameter configuration is equivalent to <strongid="b12261222102915"><aname="b12261222102915"></a><aname="b12261222102915"></a>-c 15 -i 0.2</strong>.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p15281184125813"><aname="p15281184125813"></a><aname="p15281184125813"></a>Specifies the interval (in ms) for sending a ping packet.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p13281124155815"><aname="p13281124155815"></a><aname="p13281124155815"></a>Implicitly pings an IPv4 address. If the host is active, the ping stops after <strongid="b3813112783011"><aname="b3813112783011"></a><aname="b3813112783011"></a>true</strong> is received.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p12281154165819"><aname="p12281154165819"></a><aname="p12281154165819"></a>Specifies the size of a ping packet, in bytes. The default size is <strongid="b145002224316"><aname="b145002224316"></a><aname="b145002224316"></a>56</strong> bytes.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p4282545588"><aname="p4282545588"></a><aname="p4282545588"></a>Specifies the IPv4 address to test.</p>
- If the destination IPv6 address is unreachable, "Request Timed Out" will be displayed.
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p2759mcpsimp"><aname="p2759mcpsimp"></a><aname="p2759mcpsimp"></a>Specifies the number of execution times. If this parameter is not specified, the default value is <strongid="b1769545815488"><aname="b1769545815488"></a><aname="b1769545815488"></a>4</strong>.</p>
</td>
- If no route is available to the destination IPv6 address, "Destinatin Host Unreachable" will be displayed.
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p2766mcpsimp"><aname="p2766mcpsimp"></a><aname="p2766mcpsimp"></a>Performs an IPv6 ping operation for a specified NIC.</p>
Currently, the shell does not support this command.
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p134111362417"><aname="p134111362417"></a><aname="p134111362417"></a>Specifies the IP address of the destination host.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p2861mcpsimp"><aname="p2861mcpsimp"></a><aname="p2861mcpsimp"></a>Enables the Telnet server service.</p>
<tdclass="cellrowborder"valign="top"width="52%"headers="mcps1.2.4.1.2 "><pid="p2868mcpsimp"><aname="p2868mcpsimp"></a><aname="p2868mcpsimp"></a>Disables the Telnet server service.</p>
- Before enabling Telnet, ensure that the network driver and network protocol stack have been initialized and the NIC of the board is in the **link up** state.
- Before enabling Telnet, ensure that the network driver and network protocol stack have been initialized and the NIC of the board is in the **link up** state.
- Currently, multiple clients \(Telnet + IP\) cannot connect to the development board at the same time.
Trivial File Transfer Protocol \(TFTP\) is a protocol in the TCP/IP protocol suite for transferring files between clients and servers. TFTP provides simple and low-overhead file transfer services. The port number is 69.
Trivial File Transfer Protocol (TFTP) is a protocol in the TCP/IP protocol suite for transferring files between clients and servers. TFTP provides simple and low-overhead file transfer services. The port number is 69.
The **tftp** command is used to transfer files with a TFTP server.
The **tftp** command is used to transfer files with a TFTP server.
| -g/-p | Specifies the file transfer direction.<br>- **-g**: obtains a file from the TFTP server.<br>- **-p**: uploads a file to the TFTP server.| N/A |
<tdclass="cellrowborder"valign="top"width="52.480000000000004%"headers="mcps1.2.4.1.2 "><pid="p2911mcpsimp"><aname="p2911mcpsimp"></a><aname="p2911mcpsimp"></a>Specifies the file transfer direction.</p>
<aname="ul73571240131312"></a><aname="ul73571240131312"></a><ulid="ul73571240131312"><li><strongid="b0778214125818"><aname="b0778214125818"></a><aname="b0778214125818"></a>-g</strong>: downloads files from the TFTP server.</li><li><strongid="b7168132555814"><aname="b7168132555814"></a><aname="b7168132555814"></a>-p</strong>: uploads files to the TFTP server.</li></ul>
<tdclass="cellrowborder"valign="top"width="52.480000000000004%"headers="mcps1.2.4.1.2 "><pid="p2925mcpsimp"><aname="p2925mcpsimp"></a><aname="p2925mcpsimp"></a>Specifies the complete path of a local file.</p>
<tdclass="cellrowborder"valign="top"width="52.480000000000004%"headers="mcps1.2.4.1.2 "><pid="p2931mcpsimp"><aname="p2931mcpsimp"></a><aname="p2931mcpsimp"></a>Specifies the file name on the server.</p>
<tdclass="cellrowborder"valign="top"width="52.480000000000004%"headers="mcps1.2.4.1.2 "><pid="p2937mcpsimp"><aname="p2937mcpsimp"></a><aname="p2937mcpsimp"></a>Specifies the server IP address.</p>
2. Use the **tftp** command to upload files from or download files to an OpenHarmony board.
>TFTP is used for debugging and disabled by default. Do not use it in formal products.
3. The size of the file to be transferred cannot exceed 32 MB.
> **NOTICE**<br>
> TFTP is used for debugging and disabled by default. Do not use it in formal products.
## Example<a name="section148921918114015"></a>
## Example
Download the **out** file from the server.
Download the **out** file from the server.
## Output<a name="section7872155631313"></a>
## Output
```
```
OHOS # ./bin/tftp -g -l /nfs/out -r out 192.168.1.2
OHOS # ./bin/tftp -g -l /nfs/out -r out 192.168.1.2
...
@@ -78,4 +50,3 @@ TFTP transfer finish
...
@@ -78,4 +50,3 @@ TFTP transfer finish
```
```
After the **tftp** command is executed, **TFTP transfer finish** is displayed if the file transfer is complete. If the file transfer fails, other information is displayed to help locate the fault.
After the **tftp** command is executed, **TFTP transfer finish** is displayed if the file transfer is complete. If the file transfer fails, other information is displayed to help locate the fault.
@@ -28,20 +28,18 @@ The online mode must be used with the integrated development environment (IDE).
...
@@ -28,20 +28,18 @@ The online mode must be used with the integrated development environment (IDE).
The trace module of the OpenHarmony LiteOS-A kernel provides the following APIs. For more details, see [API reference](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h).
The trace module of the OpenHarmony LiteOS-A kernel provides the following APIs. For more details, see [API reference](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h).
| Managing trace records| **LOS_TraceRecordDump**: dumps data from the trace buffer.<br>**LOS_TraceRecordGet**: obtains the start address of the trace buffer.<br>**LOS_TraceReset**: clears events in the trace buffer.|
| Managing trace records| **LOS_TraceRecordDump**: dumps data from the trace buffer.<br>**LOS_TraceRecordGet**: obtains the start address of the trace buffer.<br>**LOS_TraceReset**: clears events in the trace buffer.|
| Filtering trace records| **LOS_TraceEventMaskSet**: sets the event mask to trace only events of the specified modules.|
| Filtering trace records| **LOS_TraceEventMaskSet**: sets the event mask to trace only events of the specified modules.|
| Masking events of specified interrupt IDs| **LOS_TraceHwiFilterHookReg**: registers a hook to filter out events of specified interrupt IDs.|
| Masking events of specified interrupt IDs| **LOS_TraceHwiFilterHookReg**: registers a hook to filter out events of specified interrupt IDs.|
| Performing function instrumentation| **LOS_TRACE_EASY**: performs simple instrumentation.<br>**LOS_TRACE**: performs standard instrumentation. |
| Performing function instrumentation| **LOS_TRACE_EASY**: performs simple instrumentation.<br>**LOS_TRACE**: performs standard instrumentation.|
You can perform function instrumentation in the source code to trace specific events. The system provides the following APIs for instrumentation:
-**LOS_TRACE_EASY(TYPE, IDENTITY, params...)** for simple instrumentation
- You can perform function instrumentation in the source code to trace specific events. The system provides the following APIs for instrumentation:
-**LOS_TRACE_EASY(TYPE, IDENTITY, params...)** for simple instrumentation
- You only need to insert this API into the source code.
- You only need to insert this API into the source code.
-**TYPE** specifies the event type. The value range is 0 to 0xF. The meaning of each value is user-defined.
-**TYPE** specifies the event type. The value range is 0 to 0xF. The meaning of each value is user-defined.
-**IDENTITY** specifies the object of the event operation. The value is of the **UIntPtr** type.
-**IDENTITY** specifies the object of the event operation. The value is of the **UIntPtr** type.
...
@@ -60,7 +58,7 @@ You can perform function instrumentation in the source code to trace specific ev
...
@@ -60,7 +58,7 @@ You can perform function instrumentation in the source code to trace specific ev
Insert the following in the position where the fd2 file is written:
Insert the following in the position where the fd2 file is written:
LOS_TRACE_EASY(2, fd2, flag, size);
LOS_TRACE_EASY(2, fd2, flag, size);
```
```
-**LOS_TRACE(TYPE, IDENTITY, params...)** for standard instrumentation.
-**LOS_TRACE(TYPE, IDENTITY, params...)** for standard instrumentation.
- Compared with simple instrumentation, standard instrumentation supports dynamic event filtering and parameter tailoring. However, you need to extend the functions based on rules.
- Compared with simple instrumentation, standard instrumentation supports dynamic event filtering and parameter tailoring. However, you need to extend the functions based on rules.
-**TYPE** specifies the event type. You can define the event type in **enum LOS_TRACE_TYPE** in the header file **los_trace.h**. For details about methods and rules for defining events, see other event types.
-**TYPE** specifies the event type. You can define the event type in **enum LOS_TRACE_TYPE** in the header file **los_trace.h**. For details about methods and rules for defining events, see other event types.
- The **IDENTITY** and **Params** are the same as those of simple instrumentation.
- The **IDENTITY** and **Params** are the same as those of simple instrumentation.
...
@@ -86,34 +84,33 @@ You can perform function instrumentation in the source code to trace specific ev
...
@@ -86,34 +84,33 @@ You can perform function instrumentation in the source code to trace specific ev
> The trace event types and parameters can be modified as required. For details about the parameters, see **kernel\include\los_trace.h**.
> The preset trace events and parameters can be tailored in the same way. For details about the parameters, see [kernel\include\los_trace.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h).
For **LOS_TraceEventMaskSet(UINT32 mask)**, only the most significant 28 bits (corresponding to the enable bit of the module in **LOS_TRACE_MASK**) of the mask take effect and are used only for module-based tracing. Currently, fine-grained event-based tracing is not supported. For example, in **LOS_TraceEventMaskSet(0x202)**, the effective mask is **0x200 (TRACE_QUE_FLAG)** and all events of the QUE module are collected. The recommended method is **LOS_TraceEventMaskSet(TRACE_EVENT_FLAG | TRACE_MUX_FLAG | TRACE_SEM_FLAG | TRACE_QUE_FLAG);**.
To enable trace of only simple instrumentation events, set **Trace Mask** to **TRACE_MAX_FLAG**.
- For **LOS_TraceEventMaskSet(UINT32 mask)**, only the most significant 28 bits (corresponding to the enable bit of the module in **LOS_TRACE_MASK**) of the mask take effect and are used only for module-based tracing. Currently, fine-grained event-based tracing is not supported. For example, in **LOS_TraceEventMaskSet(0x202)**, the effective mask is **0x200 (TRACE_QUE_FLAG)** and all events of the QUE module are collected. The recommended method is **LOS_TraceEventMaskSet(TRACE_EVENT_FLAG | TRACE_MUX_FLAG | TRACE_SEM_FLAG | TRACE_QUE_FLAG);**.
The trace buffer has limited capacity. When the trace buffer is full, events will be overwritten. You can use **LOS_TraceRecordDump** to export data from the trace buffer and locate the latest records by **CurEvtIndex**.
- To enable trace of only simple instrumentation events, set **Trace Mask** to **TRACE_MAX_FLAG**.
The typical trace operation process includes **LOS_TraceStart**, **LOS_TraceStop**, and **LOS_TraceRecordDump**.
- The trace buffer has limited capacity. When the trace buffer is full, events will be overwritten. You can use **LOS_TraceRecordDump** to export data from the trace buffer and locate the latest records by **CurEvtIndex**.
You can filter out interrupt events by interrupt ID to prevent other events from being overwritten due to frequent triggering of a specific interrupt in some scenarios. You can customize interrupt filtering rules.
- The typical trace operation process includes **LOS_TraceStart**, **LOS_TraceStop**, and **LOS_TraceRecordDump**.
Example:
- You can filter out interrupt events by interrupt ID to prevent other events from being overwritten due to frequent triggering of a specific interrupt in some scenarios. You can customize interrupt filtering rules.
Example:
```
```c
BOOL Example_HwiNumFilter(UINT32 hwiNum)
BOOLExample_HwiNumFilter(UINT32hwiNum)
{
{
if((hwiNum==TIMER_INT)||(hwiNum==DMA_INT)){
if((hwiNum==TIMER_INT)||(hwiNum==DMA_INT)){
returnTRUE;
returnTRUE;
}
}
returnFALSE;
returnFALSE;
}
}
LOS_TraceHwiFilterHookReg(Example_HwiNumFilter);
LOS_TraceHwiFilterHookReg(Example_HwiNumFilter);
```
```
The interrupt events with interrupt ID of **TIMER_INT** or **DMA_INT** are not traced.
The interrupt events with interrupt ID of **TIMER_INT** or **DMA_INT** are not traced.
...
@@ -129,7 +126,7 @@ The trace character device is added in **/dev/trace**. You can use **read()**, *
...
@@ -129,7 +126,7 @@ The trace character device is added in **/dev/trace**. You can use **read()**, *
@@ -151,25 +148,24 @@ For details, see [User-Mode Development Example](kernel-small-debug-trace.md#use
...
@@ -151,25 +148,24 @@ For details, see [User-Mode Development Example](kernel-small-debug-trace.md#use
The typical trace process is as follows:
The typical trace process is as follows:
1. Configure the macro related to the trace module.
1. Configure the macro related to the trace module.
Configure the macro **LOSCFG_KERNEL_TRACE**, which is disabled by default. Run the **make update_config** command in the **kernel/liteos_a** directory, choose **Kernel** > **Enable Hook Feature**, and set **Enable Trace Feature** to **YES**.
Configure the macro **LOSCFG_KERNEL_TRACE**, which is disabled by default. Run the **make update_config** command in the **kernel/liteos_a** directory, choose **Kernel** > **Enable Hook Feature**, and set **Enable Trace Feature** to **YES**.
| LOSCFG_KERNEL_TRACE | Enable Trace Feature | Specifies whether to enable the trace feature.| YES/NO |
| LOSCFG_KERNEL_TRACE | Enable Trace Feature | Specifies whether to enable the trace feature.| YES/NO |
| LOSCFG_RECORDER_MODE_OFFLINE | Trace work mode ->Offline mode | Specifies whether to enable the online trace mode.| YES/NO |
| LOSCFG_RECORDER_MODE_OFFLINE | Trace work mode -> Offline mode | Specifies whether to enable the online trace mode.| YES/NO |
| LOSCFG_RECORDER_MODE_ONLINE | Trace work mode ->Online mode | Specifies whether to enable the offline trace mode.| YES/NO |
| LOSCFG_RECORDER_MODE_ONLINE | Trace work mode -> Online mode | Specifies whether to enable the offline trace mode.| YES/NO |
| LOSCFG_TRACE_CLIENT_INTERACT | Enable Trace Client Visualization and Control | Enables interaction with Trace IDE (dev tools), including data visualization and process control.| YES/NO |
| LOSCFG_TRACE_CLIENT_INTERACT | Enable Trace Client Visualization and Control | Enables interaction with Trace IDE (dev tools), including data visualization and process control.| YES/NO |
| LOSCFG_TRACE_FRAME_CORE_MSG | Enable Record more extended content -<br>>Record cpuid, hardware interrupt<br> status, task lock status | Specifies whether to enable recording of the CPU ID, interruption state, and lock task state.| YES/NO |
| LOSCFG_TRACE_FRAME_CORE_MSG | Enable Record more extended content -> Record cpuid, hardware interrupt status, task lock status | Specifies whether to enable recording of the CPU ID, interruption state, and lock task state.| YES/NO |
| LOSCFG_TRACE_FRAME_EVENT_COUNT | Enable Record more extended content<br> ->Record event count,<br> which indicate the sequence of happend events | Specifies whether to enables recording of the event sequence number.| YES/NO |
| LOSCFG_TRACE_FRAME_EVENT_COUNT | Enable Record more extended content -> Record event count, which indicate the sequence of happend events | Specifies whether to enables recording of the event sequence number.| YES/NO |
| LOSCFG_TRACE_FRAME_MAX_PARAMS | Record max params | Specifies the maximum number of parameters for event recording.| INT |
| LOSCFG_TRACE_FRAME_MAX_PARAMS | Record max params | Specifies the maximum number of parameters for event recording.| INT |
| LOSCFG_TRACE_BUFFER_SIZE | Trace record buffer size | Specifies the trace buffer size.| INT |
| LOSCFG_TRACE_BUFFER_SIZE | Trace record buffer size | Specifies the trace buffer size.| INT |
2. (Optional) Preset event parameters and stubs (or use the default event parameter settings and event stubs).
2. (Optional) Preset event parameters and stubs (or use the default event parameter settings and event stubs).
3. (Optional) Call **LOS_TraceStop** to stop trace and call **LOS_TraceReset** to clear the trace buffer. (Trace is started by default.)
3. (Optional) Call **LOS_TraceStop** to stop trace and call **LOS_TraceReset** to clear the trace buffer. (Trace is started by default.)
4. (Optional) Call **LOS_TraceEventMaskSet** to set the event mask for trace (only the interrupts and task events are enabled by default). For details about the event mask, see **LOS_TRACE_MASK** in **los_trace.h**.
4. (Optional) Call **LOS_TraceEventMaskSet** to set the mask of the events to be traced. The default event mask enables only trace of interrupts and task events. For details about the event masks, see **LOS_TRACE_MASK** in [los_trace.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h).
5. Call **LOS_TraceStart** at the start of the code where the event needs to be traced.
5. Call **LOS_TraceStart** at the start of the code where the event needs to be traced.
...
@@ -177,7 +173,7 @@ The typical trace process is as follows:
...
@@ -177,7 +173,7 @@ The typical trace process is as follows:
7. Call **LOS_TraceRecordDump** to output the data in the buffer. (The input parameter of the function is of the Boolean type. The value **FALSE** means to output data in the specified format, and the value **TRUE** means to output data to Trace IDE.)
7. Call **LOS_TraceRecordDump** to output the data in the buffer. (The input parameter of the function is of the Boolean type. The value **FALSE** means to output data in the specified format, and the value **TRUE** means to output data to Trace IDE.)
The methods in steps 3 to 7 are encapsulated with shell commands. You can run these commands on shell. The mappings between the functions and commands are as follows:
The methods in steps 3 to 7 are encapsulated with shell commands. You can run these commands on shell. The mappings between the methods and commands are as follows:
- LOS_TraceReset —— trace_reset
- LOS_TraceReset —— trace_reset
...
@@ -207,10 +203,12 @@ This example implements the following:
...
@@ -207,10 +203,12 @@ This example implements the following:
### Kernel-Mode Sample Code
### Kernel-Mode Sample Code
You can add the test function of the sample code to **TestTaskEntry** in **kernel/liteos_a/testsuites /kernel /src/osTest.c** for testing.
@@ -280,13 +279,13 @@ Index Time(cycles) EventType CurTask Identity params
...
@@ -280,13 +279,13 @@ Index Time(cycles) EventType CurTask Identity params
The output event information includes the occurrence time, event type, task in which the event occurs, object of the event operation, and other parameters of the event.
The output event information includes the occurrence time, event type, task in which the event occurs, object of the event operation, and other parameters of the event.
-**EventType**: event type. For details, see **enum LOS_TRACE_TYPE** in the header file **los_trace.h**.
-**EventType**: type of the event. For details, see **enum LOS_TRACE_TYPE** in [los_trace.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h).
-**CurrentTask**: ID of the running task.
-**CurrentTask**: ID of the running task.
-**Identity**: object of the event operation. For details, see **#TYPE#_PARAMS** in the header file **los_trace.h**.
-**Identity**: object of the event operation. For details, see **\#TYPE\#_PARAMS** in [los_trace.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h).
-**params**: event parameters. For details, see **#TYPE#_PARAMS** in the header file **los_trace.h**.
-**params**: event parameters. For details, see **\#TYPE\#_PARAMS** in [los_trace.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h).
The following uses output No. 0 as an example.
The following uses output No. 0 as an example.
...
@@ -302,14 +301,15 @@ Index Time(cycles) EventType CurTask Identity params
...
@@ -302,14 +301,15 @@ Index Time(cycles) EventType CurTask Identity params
- For details about the meanings of **Identity** and **params**, see the **TASK_SWITCH_PARAMS** macro.
- For details about the meanings of **Identity** and **params**, see the **TASK_SWITCH_PARAMS** macro.
> The number of parameters in **params** is specified by **LOSCFG_TRACE_FRAME_MAX_PARAMS**. The default value is **3**. Excess parameters are not recorded. You need to set **LOSCFG_TRACE_FRAME_MAX_PARAMS** based on service requirements.
> The number of parameters in **params** is specified by **LOSCFG_TRACE_FRAME_MAX_PARAMS**. The default value is **3**. Excess parameters are not recorded. You need to set **LOSCFG_TRACE_FRAME_MAX_PARAMS** based on service requirements.
Task 0x1 is switched to Task 0x0. The priority of task 0x1 is **0x1f**, and the state is **0x4**. The priority of the task 0x0 is **0x0**.
Task 0x1 is switched to Task 0x0. The priority of task 0x1 is **0x1f**, and the state is **0x4**. The priority of the task 0x0 is **0x0**.
The musl libc library of the debug version provides mechanisms, such as memory leak check, heap memory statistics, memory corruption check, and backtrace, to improve the efficiency in locating memory problems in user space.
The musl libc library of the debug version provides maintenance and test methods, such as memory leak check, heap memory statistics, memory corruption check, and backtrace, to improve the efficiency of locating memory problems in user space.
Instrumentation is performed in the **malloc** and **free** APIs to log key node information. The memory node integrity is checked when memory is requested and released by an application. When the application ends, memory statistics are provided to help identifying memory leaks.
Instrumentation is performed on the **malloc** and **free** APIs to log key node information. When memory is requested and released by a program, the memory node integrity is checked. When the program ends, memory statistics are provided for identifying memory leaks.
## Working Principles
## Working Principles
...
@@ -18,15 +17,15 @@ When memory is requested, key information is saved to the memory node control bl
...
@@ -18,15 +17,15 @@ When memory is requested, key information is saved to the memory node control bl
When memory is released, the system matches the memory node control block based on the memory address to be released and deletes the control block.
When memory is released, the system matches the memory node control block based on the memory address to be released and deletes the control block.
When memory is allocated, the returned address is saved in a link register (LR). During the process running, the system adds information, such as the LR corresponding to the suspected leak, to the memory node control block. <xrefhref="#fig716011269106"idp:producemode_text="auto"class="- topic/xref "id="xref106398301961"></xref> shows the heap memory node information.
When memory is allocated, the returned address is saved in a link register (LR). During the process running, the system adds information, such as the LR corresponding to the suspected leak, to the memory node control block. The following figure shows the heap memory node information.
**TID** indicates the thread ID; **PID** indicates the process ID; **ptr** indicates the address of the memory requested; **size** indicates the size of the requested memory; **lr[*n*]** indicates the address of the call stack, and *n* is configurable.
**TID** indicates the thread ID; **PID** indicates the process ID; **ptr** indicates the address of the memory requested; **size** indicates the size of the requested memory; **lr[*n*]** indicates the address of the call stack, and *n* is configurable.
...
@@ -34,9 +33,9 @@ When memory is released, the input parameter pointer in the **free** API is used
...
@@ -34,9 +33,9 @@ When memory is released, the input parameter pointer in the **free** API is used
You can export the memory debugging information of each process through the serial port or file, and use the addr2line tool to convert the exported information into the code lines that cause memory leaks. In this way, the memory leakage problem can be solved.
You can export the memory debugging information of each process through the serial port or file, and use the addr2line tool to convert the exported information into the code lines that cause memory leaks. In this way, the memory leakage problem can be solved.
**Figure 3** Process of locating the code line for a memory leak
**Figure 3** Process of locating the code line for a memory leak
@@ -46,21 +45,29 @@ You can collect statistics on the percentage of heap memory requested by each th
...
@@ -46,21 +45,29 @@ You can collect statistics on the percentage of heap memory requested by each th
### Memory Integrity Check
### Memory Integrity Check
- If the memory requested by using **malloc** is less than or equal to 0x1c000 bytes, the heap allocation algorithm is used to allocate memory.
- Requested memory less than or equal to 0x1c000 bytes
When the requested memory is less than or equal to 0x1c000 bytes, **malloc** uses the heap allocation algorithm to allocate memory.
When a user program requests heap memory, information such as the check value is added to the heap memory node. If the check value is abnormal, it is probably that the previous heap memory block is overwritten. Currently, the scenario where the check value is damaged by a wild pointer cannot be identified. When memory is allocated or released, the memory node check value is verified. If the memory node is corrupted and the verification fails, the following information is output: TID, PID, and call stack information saved when the previous heap memory block of the corrupted node is allocated. You can use the addr2line tool to obtain the specific code line and rectify the fault.
When a user program requests heap memory, information such as the check value is added to the heap memory node. If the check value is abnormal, it is probably that the previous heap memory block is overwritten. Currently, the scenario where the check value is damaged by a wild pointer cannot be identified. When memory is allocated or released, the memory node check value is verified. If the memory node is corrupted and the verification fails, the following information is output: TID, PID, and call stack information saved when the previous heap memory block of the corrupted node is allocated. You can use the addr2line tool to obtain the specific code line and rectify the fault.
**Figure 4** Adding a check value to the node header information
**Figure 4** Adding a check value to the node header information
When heap memory is released by using **free**, the memory block is not released immediately. Instead, the magic number 0xFE is written into the memory block, which is then placed in the free queue to prevent the memory block from being allocated by **malloc** within a certain period of time. When a wild pointer or **use-after-free** operation is performed to read the memory, an exception can be detected. However, this mechanism does not apply to write operations.
When heap memory is released by **free**, the memory block is not released immediately. Instead, the magic number 0xFE is written into the memory block, which is then placed in the free queue to prevent the memory block from being allocated by **malloc** within a certain period of time. When a wild pointer or **use-after-free** operation is performed to read the memory, an exception can be detected. However, this mechanism does not apply to write operations.
- If the memory requested by using **malloc** is greater than 0x1c000 bytes, **mmap** is used to allocate memory.
When **mmap** is used to request a large memory block, one more page is allocated at the start and end of the memory region. The current **PAGE_SIZE** of each page is **0x1000**. The permissions of the two pages are set to **PROT_NONE** (no read or write permission) by using the **mprotect** API to prevent out-of-bounds read and write of memory. If out-of-bounds read and write of memory occurs, the user program becomes abnormal because the user does not have the read or write permission. The code logic can be identified based on the abnormal call stack information.
- Requested memory greater than 0x1c000 bytes
When the requested memory is greater than 0x1c000 bytes, **malloc** uses **mmap** to allocate memory.
When **mmap** is used to allocate a large memory block, one more page is allocated at the start and end of the memory region. The current **PAGE_SIZE** of each page is **0x1000**. The permissions of the two pages are set to **PROT_NONE** (no read or write permission) by using the **mprotect** API to prevent out-of-bounds read and write of memory. If out-of-bounds read and write of memory occurs, the user program becomes abnormal because the user does not have the read or write permission. The code logic can be identified based on the abnormal call stack information.
**Figure 6** Layout of the memory allocated by using the **mmap** mechanism of **malloc**
**Figure 6** Layout of the memory allocated by using the **mmap** mechanism of **malloc**
...
@@ -105,7 +112,7 @@ You can perform heap memory debugging by using either of the following:
...
@@ -105,7 +112,7 @@ You can perform heap memory debugging by using either of the following:
- CLI: By using the CLI, you do not need to modify user code. However, you cannot accurately check the heap memory information of a specific logic segment.
- CLI: By using the CLI, you do not need to modify user code. However, you cannot accurately check the heap memory information of a specific logic segment.
> After memory debugging is enabled, a heap memory leak check and a heap memory integrity check will be performed by default when a process exits. If memory debugging is disabled, the heap memory statistics, heap memory leak check, and heap memory integrity check cannot be enabled, and there is no response to the calling of any debug API.
> After memory debugging is enabled, a heap memory leak check and a heap memory integrity check will be performed by default when a process exits. If memory debugging is disabled, the heap memory statistics, heap memory leak check, and heap memory integrity check cannot be enabled, and there is no response to the calling of any debug API.
...
@@ -119,7 +126,7 @@ You can perform heap memory debugging by using either of the following:
...
@@ -119,7 +126,7 @@ You can perform heap memory debugging by using either of the following:
The sample code explicitly calls the related APIs of the memory debugging module to check the memory.
The sample code explicitly calls the related APIs of the memory debugging module to check the memory.
```
```c
#include <pthread.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
...
@@ -127,7 +134,8 @@ The sample code explicitly calls the related APIs of the memory debugging module
...
@@ -127,7 +134,8 @@ The sample code explicitly calls the related APIs of the memory debugging module
> The preceding information recorded gradually is added to the file specified during initialization. Therefore, running the **cat** command can also display the historical information in the file.
> The preceding information recorded gradually is added to the file specified during initialization. Therefore, running the **cat** command can also display the historical information in the file.
## Common Problems
## Common Problems
### Use After Free (UAF)
### Use After Free (UAF)
- Requested memory block less than or equal to 0x1c000 bytes:
- Requested memory less than or equal to 0x1c000 bytes:
After the memory is released:
Read operation: If the magic number (0xFEFEFEFE) is read from the memory block released, UAF occurs.
Read operation: If the magic number (0xFEFEFEFE) is read from the memory block released, UAF occurs.
> After **free** is called, the heap memory will not be released to the heap memory pool immediately. Instead, the heap memory is placed in a queue with a fixed length and filled with the magic number 0xFE. When the queue is full, the memory block first placed in the queue is released to the heap memory pool first.
> After **free** is called, the heap memory will not be released to the heap memory pool immediately. Instead, the heap memory is placed in a queue with a fixed length and filled with the magic number 0xFE. When the queue is full, the memory block first placed in the queue is released to the heap memory pool first.
Write operation: The memory debugging module cannot detect UAF errors from write operations.
Write operation: The memory debugging module cannot detect UAF errors from write operations.
- Requested memory block greater than 0x1c000 bytes:
- Requested memory block greater than 0x1c000 bytes:
The heap memory greater than 0x1c000 bytes must be requested by calling the **mmap** API via **malloc**. If the heap memory is accessed after being released, the user program will become abnormal (because the memory region has been unmapped).
The heap memory greater than 0x1c000 bytes must be requested by calling the **mmap** API via **malloc**. If the heap memory is accessed after being released, the user program will become abnormal (because the memory region has been unmapped).
...
@@ -527,6 +538,7 @@ Double free errors occur when **free()** is called more than once with the same
...
@@ -527,6 +538,7 @@ Double free errors occur when **free()** is called more than once with the same
### Heap Memory Node Corrupted
### Heap Memory Node Corrupted
- Requested memory block less than or equal to 0x1c000 bytes:
- Requested memory block less than or equal to 0x1c000 bytes:
When a heap memory node is corrupted, the user program exits unexpectedly, and the call stack that requests the heap memory of the node corrupted is output. The memory debugging module, however, cannot debug the memory corrupted by a wild pointer. For example, if the user program mem_check has heap memory overwriting, you can use the command line to obtain the possible location of the memory corruption.
When a heap memory node is corrupted, the user program exits unexpectedly, and the call stack that requests the heap memory of the node corrupted is output. The memory debugging module, however, cannot debug the memory corrupted by a wild pointer. For example, if the user program mem_check has heap memory overwriting, you can use the command line to obtain the possible location of the memory corruption.
@@ -59,10 +59,9 @@ The user mode provides only the LMS check library. It does not provide external
...
@@ -59,10 +59,9 @@ The user mode provides only the LMS check library. It does not provide external
The typical process for enabling LMS is as follows:
The typical process for enabling LMS is as follows:
1. Configure the macros related to the LMS module.
1. Configure the macros related to the LMS module.
Configure the LMS macro **LOSCFG_KERNEL_LMS**, which is disabled by default. Run the **make update_config** command in the **kernel/liteos_a** directory, choose **Kernel**, and select **Enable Lite Memory Sanitizer**.
Configure the LMS macro **LOSCFG_KERNEL_LMS**, which is disabled by default. Run the **make update_config** command in the **kernel/liteos_a** directory, choose **Kernel**, and select **Enable Lite Memory Sanitizer**.
@@ -260,7 +259,7 @@ The key output information is as follows:
...
@@ -260,7 +259,7 @@ The key output information is as follows:
### User-Mode Development Process
### User-Mode Development Process
Add the following to the build script of the app to be checked. For details about the complete code, see **/kernel/liteos_a/apps/lms/BUILD.gn**.
Add the following to the app build script to be checked. For details about the sample code, see [/kernel/liteos_a/apps/lms/BUILD.gn](https://gitee.com/openharmony/kernel_liteos_a/blob/master/apps/lms/BUILD.gn).
```
```
...
@@ -318,7 +317,7 @@ This example implements the following:
...
@@ -318,7 +317,7 @@ This example implements the following:
The code is as follows:
The code is as follows:
```
```c
staticvoidBufWriteTest(void*buf,intstart,intend)
staticvoidBufWriteTest(void*buf,intstart,intend)
{
{
for(inti=start;i<=end;i++){
for(inti=start;i<=end;i++){
...
@@ -335,7 +334,7 @@ static void BufReadTest(void *buf, int start, int end)
...
@@ -335,7 +334,7 @@ static void BufReadTest(void *buf, int start, int end)
The kernel startup process consists of the assembly startup and C language startup, as shown in the following figure.
The kernel startup process consists of the assembly startup and C language startup, as shown in **Figure 1**.
The assembly startup involves the following operations: initializing CPU settings, disabling dCache/iCache, enabling the FPU and NEON, setting the MMU to establish the virtual-physical address mapping, setting the system stack, clearing the BSS segment, and calling the main function of the C language.
The assembly startup involves the following operations: initializing CPU settings, disabling dCache/iCache, enabling the FPU and NEON, setting the MMU to establish the virtual-physical address mapping, setting the system stack, clearing the BSS segment, and calling the main function of the C language.
The C language startup involves the following operations: starting the **OsMain** function and starting scheduling. As shown in the following figure, the **OsMain** function is used for basic kernel initialization and architecture- and board-level initialization. The kernel startup framework leads the initialization process. The right part of the figure shows the phase in which external modules can register with the kernel startup framework and starts. The table below describes each phase.
The C language startup involves the following operations: starting the **OsMain** function and starting scheduling.
**OsMain()** is used for basic kernel initialization and architecture- and board-level initialization. The kernel startup framework leads the initialization process. The right part of the figure shows the phase in which external modules can register with the kernel startup framework and starts. **Table 1** describes each phase.
| LOS_INIT_LEVEL_EARLIEST | Earliest initialization.<br>The initialization is architecture-independent. The board and subsequent modules initialize the pure software modules on which they depend.<br>Example: trace module|
| LOS_INIT_LEVEL_EARLIEST | Earliest initialization.<br>The initialization is architecture-independent. The board and subsequent modules initialize the pure software modules on which they depend.<br>Example: trace module|
| LOS_INIT_LEVEL_ARCH_EARLY | Early initialization of the architecture.<br>The initialization is architecture-dependent. Subsequent modules initialize the modules on which they depend. It is recommended that functions not required for startup be placed at **LOS_INIT_LEVEL_ARCH**.|
| LOS_INIT_LEVEL_ARCH_EARLY | Early initialization of the architecture.<br>The initialization is architecture-dependent. Subsequent modules initialize the modules on which they depend. It is recommended that functions not required for startup be placed at **LOS_INIT_LEVEL_ARCH**.|
...
@@ -28,54 +30,52 @@ The C language startup involves the following operations: starting the **OsMain*
...
@@ -28,54 +30,52 @@ The C language startup involves the following operations: starting the **OsMain*
| LOS_INIT_LEVEL_KMOD_BASIC | Initialization of the kernel basic modules.<br>Initialize the basic modules that can be detached from the kernel.<br>Example: VFS initialization|
| LOS_INIT_LEVEL_KMOD_BASIC | Initialization of the kernel basic modules.<br>Initialize the basic modules that can be detached from the kernel.<br>Example: VFS initialization|
| LOS_INIT_LEVEL_KMOD_EXTENDED | Initialization of the kernel extended modules.<br>Initialize the extended modules that can be detached from the kernel.<br>Example: initialization of system call, ProcFS, Futex, HiLog, HiEvent, and LiteIPC|
| LOS_INIT_LEVEL_KMOD_EXTENDED | Initialization of the kernel extended modules.<br>Initialize the extended modules that can be detached from the kernel.<br>Example: initialization of system call, ProcFS, Futex, HiLog, HiEvent, and LiteIPC|
| LOS_INIT_LEVEL_KMOD_TASK | Kernel task creation.<br>Create kernel tasks (kernel tasks and software timer tasks).<br>Example: creation of the resident resource reclaiming task, SystemInit task, and CPU usage statistics task|
| LOS_INIT_LEVEL_KMOD_TASK | Kernel task creation.<br>Create kernel tasks (kernel tasks and software timer tasks).<br>Example: creation of the resident resource reclaiming task, SystemInit task, and CPU usage statistics task|
| LOS_INIT_LEVEL_FINISH | Complete of the kernel initialization.|
## Programming Example
## Development Example
**Example Description**
**Example Description**
Add a kernel module and register the initialization function of the module to the kernel startup process through the kernel startup framework, so as to complete the module initialization during the kernel initialization process.
Add a kernel module and register the initialization function of the module to the kernel startup process through the kernel startup framework, so as to complete the module initialization during the kernel initialization process.
You can compile and verify the sample code in **kernel/liteos_a/testsuites/kernel/src/osTest.c**.
**Sample Code**
**Sample Code**
```c
```
/* Header file of the kernel startup framework */
/* Header file of the kernel startup framework */
#include "los_init.h"
#include "los_init.h"
...
/* Initialization function of the new module */
/* Initialization function of the new module */
unsignedintOsSampleModInit(void)
unsignedintOsSampleModInit(void)
{
{
PRINTK("OsSampleModInit SUCCESS!\n");
PRINTK("OsSampleModInit SUCCESS!\n");
......
}
}
...
/* Register the new module at the target level of the kernel startup framework. */
/* Register the new module at the target level of the kernel startup framework. */
/* The print information may vary depending on the running environment. */
...
/* Print the initialization function of the new module in the test code. */
OsSampleModInit SUCCESS!
OsSampleModInit SUCCESS!
releasing 1 secondary cores
cpu 1 entering scheduler
cpu 0 entering scheduler
```
```
According to the information displayed during the system startup, the kernel has called the initialization function of the registered module during the startup to initialize the module.
According to the information displayed during the system startup, the kernel calls the initialization function of the registered module during the startup to initialize the module.
> Modules at the same level cannot depend on each other. It is recommended that a new module be split based on the preceding startup phase and be registered and started as required.
> Modules of the same level cannot depend on each other. It is recommended that a new module be split based on the preceding startup phase and be registered and started as required.
>
>
> You can view the symbol table in the **.rodata.init.kernel.*** segment of the **OHOS_Image.map** file generated after the build is complete, so as to learn about the initialization entry of each module that has been registered with the kernel startup framework and check whether the newly registered initialization entry has taken effect.
> You can view the symbol table in the **.rodata.init.kernel.*** segment of the **OHOS_Image.map** file generated after the build is complete, so as to learn about the initialization entry of each module that has been registered with the kernel startup framework and check whether the newly registered initialization entry has taken effect.
During system startup, **OsUserInitProcess** is called to start the **init** process. The procedure is as follows:
> **NOTE**
>
> The preceeding code is in **kernel/liteos_a/kernel/user/src/los_user_init.c**. The value of **g_initPath** can be **/dev/shm/init** or **/bin/init**, depending on the startup settings.
1. The kernel calls **OsLoadUserInit** to load the code.
Use **OsUserInitProcess** to start the **init** process. The procedure is as follows:
2. A process space is created to start the **/bin/init** process.
### Responsibilities of the Root Process<a name="section1590220321759"></a>
1. The kernel calls **OsLoadUserInit** to load the code for startup.
2. A process space is created to start the **/bin/init** process.
- Starts key system programs or services, such as shell.
>In OpenHarmony, the **init** process reads the **/etc/init.cfg** file and runs specified commands or starts specified processes based on configurations. For details, see [init Module](../subsystems/subsys-boot-init-cfg.md).
- The root process starts key system programs or services, such as shell.
> **NOTE**
> In OpenHarmony, the **init** process reads **/etc/init.cfg** and runs commands or starts processes based on the configuration. For details, see [init Configuration File](../subsystems/subsys-boot-init-cfg.md).
- Monitors the process for reclaiming the orphan process and clears the zombie processes in child processes.
-The root process monitors the process for reclaiming the orphan process and clears the zombie processes in child processes.
## Running Programs in User Mode<a name="section194576310611"></a>
## Running Programs in User Mode
A user-mode program can be started in either of the following ways:
A user-mode program can be started in either of the following ways:
- Run the shell command to start the process.
-Using shell commands
```
```
OHOS $ exec helloworld
OHOS $ exec helloworld
...
@@ -52,9 +59,6 @@ A user-mode program can be started in either of the following ways:
...
@@ -52,9 +59,6 @@ A user-mode program can be started in either of the following ways:
OHOS $ /bin/helloworld
OHOS $ /bin/helloworld
```
```
- Using POSIX APIs
- Start a new process by calling the POSIX API.
Use **Fork()** to create a process, and call **exec()** to execute a process.
Use the **Fork\(\)** method to create a process, and call the **exec\(\)** method to execute a new process.