未验证 提交 9f59be25 编写于 作者: O openharmony_ci 提交者: Gitee

!14334 [翻译完成】#I6868S

Merge pull request !14334 from Annie_wang/PR12967C
......@@ -26,6 +26,7 @@
- [Exception Debugging](kernel-mini-memory-exception.md)
- [Trace](kernel-mini-memory-trace.md)
- [LMS](kernel-mini-memory-lms.md)
- [Shell](kernel-mini-debug-shell.md)
- Appendix
- [Kernel Coding Specification](kernel-mini-appx-code.md)
- [Standard Libraries](kernel-mini-appx-lib.md)
......
......@@ -177,7 +177,7 @@ int main (void) {
// ...
osKernelInitialize(); // Initialize CMSIS-RTOS.
osThreadNew(app_main, NULL, NULL); // Create the main thread of the application.
osThreadNew(app_main, NULL, NULL); // Create the main thread of the application.
osKernelStart(); // Start to execute the thread.
for (;;) {}
}
......@@ -196,14 +196,14 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
#### Available APIs
**Table 1** APIs for process management
**Table 11** APIs for process management
| Header File| API| Description|
| -------- | -------- | -------- |
| \#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 <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_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_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_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
| \#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_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_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_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_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_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.|
......@@ -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_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_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|
| -------- | -------- | -------- |
......@@ -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/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|
| -------- | -------- | -------- |
......@@ -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 <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 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_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> | 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|
| -------- | -------- | -------- |
| \#include <stdlib.h> | int atoi(const char \*nptr); | Converts the string pointed to by **nptr** 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 long atoll(const char \*nptr); | Converts the string pointed to by **nptr** into a long long Integer (long long 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 into a long Integer (**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 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.|
......@@ -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 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> | 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 <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 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 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 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 regexec(const regex_t \*preg, const char \*string, size_t nmatch, regmatch_t pmatch[], int eflags); | Executes the compiled regular expression.|
| \#include <regex.h> | void regfree(regex_t \*preg); | Releases the regular expression.|
| \#include <string.h> | char \*strerror(int errnum); | Obtains an error message string of the specified error code.|
**Table 5** APIs for math operations
**Table 15** APIs for math operations
| Header File| API| Description|
| -------- | -------- | -------- |
......@@ -322,7 +322,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include <math.h> | double round(double x); | Rounds off the value from zero to the nearest integer.|
| \#include <math.h> | double sqrt(double x); | Obtains the square root of **x**.|
**Table 6** APIs for I/O operations
**Table 16** APIs for I/O operations
| Header File| API| Description|
| -------- | -------- | -------- |
......@@ -335,16 +335,16 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include <stdio.h> | int fileno(FILE \*stream); | Obtains the file descriptor for a stream.|
| \#include <stdio.h> | FILE \*fopen(const char \*path, const char \*mode); | Opens a stream.|
| \#include <stdio.h> | int fputs(const char \*s, FILE \*stream); | Writes a line to the specified stream.|
| \#include <stdio.h> | size_t fread(void \*ptr, size_t size, size_t nmemb,FILE \*stream); | Reads a stream.|
| \#include <stdio.h> | size_t fread(void \*ptr, size_t size, size_t nmemb, FILE \*stream); | Reads a stream.|
| \#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> | 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 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 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|
| -------- | -------- | -------- |
......@@ -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> | 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|
| -------- | -------- | -------- |
......@@ -374,7 +374,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include <stdlib.h> | void \*malloc(size_t size); | Dynamically allocates memory blocks.|
| \#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|
| -------- | -------- | -------- |
......@@ -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> | 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_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> | 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> | 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> | 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> | int libc_get_version(void); | Obtains the libc version.|
......@@ -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.
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **DemoForTest** function is called in **TestTaskEntry**.
```
#include <stdio.h>
......
# Shell
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.
#### Format
cp [SOURCEFILE] [DESTFILE]
#### Parameters
| Parameter | Description | Value Range |
| ---------- | -------------- | ----------------------------------------- |
| 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.
#### Format
ls [DIRECTORY]
#### Parameters
| Parameter | Description | Value Range |
| --------- | ---------- | ------------------------------------------------------------ |
| 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.
#### Format
mkdir [DIRECTORY]
#### Parameters
| Parameter | Description | Value Range |
| --------- | ---------- | ------------------------------------- |
| DIRECTORY | Path of the directory.| The value of **DIRECTORY** can be an absolute path or a relative path.|
### ping
Checks whether the network is connected. This command can be used only after **LWIP_SHELLCMD_ENABLE** is enabled.
#### Format
ping [ip]
#### Parameters
| Parameter| Description | Value Range|
| ---- | ------------------------------ | -------- |
| ip | IPv4 address of the network to test.| N/A |
### pwd
Displays the current path. This command can be used only after **LOSCFG_FS_VFS** is enabled.
#### Format
pwd
### rm
Deletes a file or folder. This command can be used only after **LOSCFG_FS_VFS** is enabled.
#### Format
rm [FILE] or rm [-r/-R] [FILE]
#### Parameters
| Parameter | Description | Value Range |
| ----- | ------------------------------- | -------------------------------- |
| FILE | File or folder name.| The value of **FILE** can be an absolute path or a relative path.|
| -r/-R | If **FILE** is a folder, -r/-R needs to be set. | N/A |
### rmdir
Deletes a folder. This command can be used only after **LOSCFG_FS_VFS** is enabled.
#### Format
rmdir [DIRECTORY]
#### Parameters
| Parameter | Description | Value Range |
| --------- | ---------- | ------------------------------------- |
| DIRECTORY | Path of the directory.| The value of **DIRECTORY** can be an absolute path or a relative path.|
### task
Displays the status of each task.
#### Format
task
The displayed information includes the task No., priority, status, stack information, signal, event, CPU usage, and task name.
### touch
Creates a file. This command can be used only after **LOSCFG_FS_VFS** is enabled.
#### Format
touch [FILE]
#### Parameters
| Parameter| Description| Value Range |
| ---- | -------- | -------------------------------- |
| 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 |
| -e | Stop recording and print scheduling information.| N/A |
# CPUP
## Basic Concepts
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.
**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.
**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
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:
- System CPUP
- Task CPUP
- System 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:
......@@ -29,156 +43,148 @@ System CPUP = Total running time of all tasks except idle tasks/Total running ti
Task CPUP = Total running time of the task/Total running time of the system
## Available APIs<a name="section158501652121514"></a>
**Table 1** Functions
<a name="table18293928155615"></a>
<table><thead align="left"><tr id="row129362875613"><th class="cellrowborder" valign="top" width="33.33333333333333%" id="mcps1.2.4.1.1"><p id="p19444103765618"><a name="p19444103765618"></a><a name="p19444103765618"></a>Function</p>
</th>
<th class="cellrowborder" valign="top" width="33.33333333333333%" id="mcps1.2.4.1.2"><p id="p944473716569"><a name="p944473716569"></a><a name="p944473716569"></a>API</p>
</th>
<th class="cellrowborder" valign="top" width="33.33333333333333%" id="mcps1.2.4.1.3"><p id="p144445378565"><a name="p144445378565"></a><a name="p144445378565"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row1143613475615"><td class="cellrowborder" rowspan="2" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.1 "><p id="p942993405610"><a name="p942993405610"></a><a name="p942993405610"></a>Obtaining the system CPU usage</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.2 "><p id="p242973419563"><a name="p242973419563"></a><a name="p242973419563"></a>LOS_SysCpuUsage</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.3 "><p id="p7429163416565"><a name="p7429163416565"></a><a name="p7429163416565"></a>Obtains the current system CPUP.</p>
</td>
</tr>
<tr id="row15436163435611"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p20429183410563"><a name="p20429183410563"></a><a name="p20429183410563"></a>LOS_HistorySysCpuUsage</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p542953465617"><a name="p542953465617"></a><a name="p542953465617"></a>Obtains the historical CPUP of the system.</p>
</td>
</tr>
<tr id="row143610342562"><td class="cellrowborder" rowspan="3" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.1 "><p id="p174295347568"><a name="p174295347568"></a><a name="p174295347568"></a>Obtaining the task CPUP</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.2 "><p id="p124291734155614"><a name="p124291734155614"></a><a name="p124291734155614"></a>LOS_TaskCpuUsage</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.3 "><p id="p1042963410568"><a name="p1042963410568"></a><a name="p1042963410568"></a>Obtains the CPUP of a specified task.</p>
</td>
</tr>
<tr id="row12436143414561"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p6429834185613"><a name="p6429834185613"></a><a name="p6429834185613"></a>LOS_HistoryTaskCpuUsage</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p74302034175614"><a name="p74302034175614"></a><a name="p74302034175614"></a>Obtains the historical CPUP of a specified task.</p>
</td>
</tr>
<tr id="row2435834135618"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p843073420563"><a name="p843073420563"></a><a name="p843073420563"></a>LOS_AllCpuUsage</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p4430134185614"><a name="p4430134185614"></a><a name="p4430134185614"></a>Obtains the CPUP of all tasks.</p>
</td>
</tr>
<tr id="row15435934155618"><td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.1 "><p id="p1543033435615"><a name="p1543033435615"></a><a name="p1543033435615"></a>Outputting the task CPUP</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.2 "><p id="p1643016342562"><a name="p1643016342562"></a><a name="p1643016342562"></a>LOS_CpupUsageMonitor</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.3 "><p id="p84301234115617"><a name="p84301234115617"></a><a name="p84301234115617"></a>Outputs the historical CPUP of a task.</p>
</td>
</tr>
</tbody>
</table>
Interrupt CPUP = Running time of a single interrupt/Total running time of all interrupts
## Available APIs
**Table 1** APIs for CPUP
| Category| Description|
| -------- | -------- |
| Obtaining the system CPUP| **LOS_SysCpuUsage**: obtains the current system CPUP.<br>**LOS_HistorySysCpuUsage**: obtains the historical CPUP of the system.|
| 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.|
| Outputting the task CPUP| **LOS_CpupUsageMonitor**: outputs the historical CPUP of a task.|
| Obtaining the interrupt CPUP| **LOS_GetAllIrqCpuUsage**: obtains the CPUP of all interrupts.|
## 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:
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.
- 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.
1. Call **LOS_SysCpuUsage** to obtain the system CPUP.
2. Call **LOS_HistorySysCpuUsage** to obtain the historical CPUP of the system.
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 is not created, return an error code.
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 is not created, return an error code.
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 is not initialized or has invalid input parameters, return an error code.
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 is not created, return an error code.
5. Call **LOS_AllCpuUsage** to obtain the CPUP of all tasks.
- 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.
## Development Example
### Example Description
This example implements the following:
1. Create a task for the CPUP test.
2. Obtain the CPUP of the current system.
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.
1. Create a task for the CPUP test.
2. Obtain the CPUP of the current system.
3. Obtain the historical system CPUP in different modes.
4. Obtain the CPUP of the created task.
5. Obtain the CPUP of the created task in different modes.
### 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 can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleCpup** function is called in **TestTaskEntry**.
```
#include "los_task.h"
#include "los_cpup.h"
#define MODE 4
UINT32 g_cpuTestTaskID;
VOID ExampleCpup(VOID)
{
#include "los_cpup.h"
#define TEST_TASK_PRIO 5
#define TASK_DELAY_TIME 100
VOID CpupTask(VOID)
{
printf("entry cpup test example\n");
while(1) {
usleep(100);
}
usleep(TASK_DELAY_TIME);
usleep(TASK_DELAY_TIME);
printf("exit cpup test example\n");
}
UINT32 ItCpupTest(VOID)
{
UINT32 ExampleCpup(VOID)
{
UINT32 ret;
UINT32 cpupUse;
UINT32 taskID;
TSK_INIT_PARAM_S cpupTestTask = { 0 };
memset(&cpupTestTask, 0, sizeof(TSK_INIT_PARAM_S));
cpupTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleCpup;
cpupTestTask.pcName = "TestCpupTsk";
cpupTestTask.uwStackSize = 0x800;
cpupTestTask.usTaskPrio = 5;
ret = LOS_TaskCreate(&g_cpuTestTaskID, &cpupTestTask);
cpupTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)CpupTask;
cpupTestTask.pcName = "TestCpupTsk";
cpupTestTask.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
cpupTestTask.usTaskPrio = TEST_TASK_PRIO;
ret = LOS_TaskCreate(&taskID, &cpupTestTask);
if(ret != LOS_OK) {
printf("cpupTestTask create failed .\n");
return LOS_NOK;
}
usleep(100);
usleep(TASK_DELAY_TIME);
/* Obtain the current CPUP of the system. */
/* Obtain the current system CPUP. */
cpupUse = LOS_SysCpuUsage();
printf("the current system cpu usage is: %u.%u\n",
cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT);
cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT);
cpupUse = LOS_HistorySysCpuUsage(CPU_LESS_THAN_1S);
/* Obtain the CPUP of the specified task (cpupTestTask in this example).*/
printf("the history system CPUP in all time: %u.%u\n",
/* Obtain the historical CPUP of the system. */
cpupUse = LOS_HistorySysCpuUsage(CPUP_LESS_THAN_1S);
printf("the history system cpu usage in all time: %u.%u\n",
cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT);
cpupUse = LOS_TaskCpuUsage(g_cpuTestTaskID);
/* Obtain the CPUP of the specified historical task (cpupTestTask in this example) since the system startup. */
/* Obtain the CPUP of a specified task. */
cpupUse = LOS_TaskCpuUsage(taskID);
printf("cpu usage of the cpupTestTask:\n TaskID: %d\n usage: %u.%u\n",
g_cpuTestTaskID, cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT);
cpupUse = LOS_HistoryTaskCpuUsage(g_cpuTestTaskID, CPU_LESS_THAN_1S);
taskID, cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT);
/* Obtain the CPUP of a specified task since the system starts. */
cpupUse = LOS_HistoryTaskCpuUsage(taskID, CPUP_LESS_THAN_1S);
printf("cpu usage of the cpupTestTask in all time:\n TaskID: %d\n usage: %u.%u\n",
g_cpuTestTaskID, cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT);
return LOS_OK;
taskID, cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT);
return LOS_OK;
}
```
### Verification
The development is successful if the return result is as follows:
The development is successful if the return result is as follows:
```
entry cpup test example
the current system cpu usage is : 1.5
the history system cpu usage in all time: 3.0
cpu usage of the cpupTestTask: TaskID:10 usage: 0.0
cpu usage of the cpupTestTask&nbsp;in all time: TaskID:10 usage: 0.0
entry cpup test example
the current system cpu usage is: 8.2
the history system cpu usage in all time: 8.9
cpu usage of the cpupTestTask:
TaskID: 5
usage: 0.5
cpu usage of the cpupTestTask in all time:
TaskID: 5
usage: 0.5
exit cpup test example
The preceding data may vary depending on the running environment.
```
......@@ -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 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
**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
......@@ -33,20 +33,20 @@ Key structure:
```
typedef struct {
UINT32 totalUsedSize; // Memory usage of the memory pool.
UINT32 totalFreeSize; // Remaining size of 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 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.
UINT32 usageWaterLine; // Waterline of the memory pool.
UINT32 totalUsedSize; // Memory usage of the memory pool.
UINT32 totalFreeSize; // Remaining size of 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 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.
UINT32 usageWaterLine; // Waterline of the memory pool.
#endif
} 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
......@@ -62,7 +62,9 @@ This example implements the following:
#### 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>
......@@ -71,20 +73,20 @@ This example implements the following:
#include "los_memory.h"
#include "los_config.h"
#define TEST_TASK_PRIO 5
void MemInfoTaskFunc(void)
{
LOS_MEM_POOL_STATUS poolStatus = {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;
LOS_MemInfoGet(pool, &poolStatus);
/* Calculate the fragmentation rate of the memory pool. */
unsigned char fragment = 100 - poolStatus.maxFreeNodeSize * 100 / poolStatus.totalFreeSize;
float fragment = 100 - poolStatus.maxFreeNodeSize * 100.0 / poolStatus.totalFreeSize;
/* Calculate the memory usage of the memory pool. */
unsigned char usage = LOS_MemTotalUsedGet(pool) * 100 / LOS_MemPoolSizeGet(pool);
printf("usage = %d, fragment = %d, maxFreeSize = %d, totalFreeSize = %d, waterLine = %d\n", usage, fragment, poolStatus.maxFreeNodeSize,
poolStatus.totalFreeSize, poolStatus.usageWaterLine);
float usage = LOS_MemTotalUsedGet(pool) * 100.0 / LOS_MemPoolSizeGet(pool);
printf("usage = %f, fragment = %f, maxFreeSize = %d, totalFreeSize = %d, waterLine = %d\n", usage, fragment,
poolStatus.maxFreeNodeSize, poolStatus.totalFreeSize, poolStatus.usageWaterLine);
}
int MemTest(void)
......@@ -93,9 +95,9 @@ int MemTest(void)
unsigned int taskID;
TSK_INIT_PARAM_S taskStatus = {0};
taskStatus.pfnTaskEntry = (TSK_ENTRY_FUNC)MemInfoTaskFunc;
taskStatus.uwStackSize = 0x1000;
taskStatus.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
taskStatus.pcName = "memInfo";
taskStatus.usTaskPrio = 10;
taskStatus.usTaskPrio = TEST_TASK_PRIO;
ret = LOS_TaskCreate(&taskID, &taskStatus);
if (ret != LOS_OK) {
printf("task create failed\n");
......@@ -112,7 +114,9 @@ The result is as follows:
```
usage = 22, fragment = 3, maxFreeSize = 49056, totalFreeSize = 50132, waterLine = 1414
usage = 0.458344, fragment = 0.000000, maxFreeSize = 16474928, totalFreeSize = 16474928, waterLine = 76816
The preceding data may vary depending on the running environment.
```
## Memory Leak Check
......@@ -124,14 +128,15 @@ As an optional function of the kernel, memory leak check is used to locate dynam
### 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**.
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_RECORD_LR_CNT** specifies the number of LRs recorded. The default value is **3**. Each LR consumes the memory of **sizeof(void \*)** bytes.
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** may be encapsulated externally.
- The number of LRs configured by **LOSCFG_MEM_RECORD_LR_CNT** is limited.
**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** may be encapsulated externally.
- 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.
......@@ -156,7 +161,8 @@ node size LR[0] LR[1] LR[2]
0x100179cc: 0x5c 0x9b02c24e 0x9b02c246 0x9b008ef0
```
> ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **CAUTION**<br/>
> **CAUTION**
>
> 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:
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>
......@@ -216,7 +228,9 @@ node size LR[0] LR[1] LR[2]
0x20002594: 0x120 0x08000e0c 0x08000e56 0x08000c8a
0x20002aac: 0x56 0x08000e0c 0x08000e56 0x08004220
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.
......@@ -224,7 +238,9 @@ The difference between the two logs is as follows. The following memory nodes ar
```
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:
......@@ -246,6 +262,8 @@ The following is part of the assembly file:
0x80041f0: 0xf7fd 0xf933 BL LOS_MemUsedNodeShow ; 0x800145a
0x80041f4: 0xbd10 POP {R4, PC}
0x80041f6: 0x0000 MOVS R0, R0
The preceding data may vary depending on the running environment.
```
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
### 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.
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.
> ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **CAUTION**<br/>
> **CAUTION**
>
> 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:
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**.
```
#include <stdio.h>
......@@ -320,20 +345,28 @@ The log is as follows:
```
[ERR][OsMemMagicCheckPrint], 2028, memory check error!
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. */
broken node head: 0x20003af0 0x00000000 0x80000020, prev node head: 0x20002ad4 0xabcddcba 0x80000020
/* 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. */
LR[0]:0x0800414e
LR[1]:0x08000cc2
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. */
LR[0]:0x08004144
LR[1]:0x08000cc2
LR[2]:0x00000000
[ERR]Memory integrity check error, cur node: 0x20003b10, pre node: 0x20003af0 /* Addresses of the corrupted node and its previous node */
/* 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. */
[ERR][IT_TST_INI][OsMemMagicCheckPrint], 1664, memory check error!
memory used but magic num wrong, magic num = 0x0
/* 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: 0x2103d7e8 0x0 0x80000020, prev node head: 0x2103c7cc 0xabcddcba 0x80000020
/*The node LR information can be output only after the memory leak check is enabled. */
broken node head LR info:
LR[0]:0x2101906c
LR[1]:0x0
LR[2]:0x0
/* 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. */
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.
```
# perf
## Basic Concepts
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
### Kernel Mode
The Perf module of the OpenHarmony LiteOS-A kernel provides the following functions. For details about the interfaces, see the [API reference](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_perf.h).
**Table 1** APIs of the perf module
| API| Description|
| -------- | -------- |
| LOS_PerfStart| Starts sampling.|
| LOS_PerfStop| Stops sampling.|
| LOS_PerfConfig| Sets the event type and sampling interval.|
| LOS_PerfDataRead| Reads the sampling data.|
| LOS_PerfNotifyHookReg| Registers the hook to be called when the buffer waterline is reached.|
| LOS_PerfFlushHookReg| Registers the hook for flushing the cache in the buffer.|
- The structure of the perf sampling event is **PerfConfigAttr**. For details, see **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.
Example:
```
VOID Example_PerfNotifyHook(VOID)
{
CHAR buf[LOSCFG_PERF_BUFFER_SIZE] = {0};
UINT32 len;
PRINT_DEBUG("perf buffer reach the waterline!\n");
len = LOS_PerfDataRead(buf, LOSCFG_PERF_BUFFER_SIZE);
OsPrintBuff(buf, len); /* print data */
}
LOS_PerfNotifyHookReg(Example_PerfNotifyHook);
```
- If the buffer sampled by perf involves caches across CPUs, you can register a hook for flushing the cache to ensure cache consistency.
Example:
```
VOID Example_PerfFlushHook(VOID *addr, UINT32 size)
{
OsCacheFlush(addr, size); /* platform interface */
}
LOS_PerfNotifyHookReg(Example_PerfFlushHook);
```
The API for flushing the cache is configured based on the platform.
### User Mode
The perf character device is located in **/dev/perf**. You can read, write, and control the user-mode perf by running the following commands on the device node:
- **read**: reads perf data in user mode.
- **write**: writes user-mode sampling events.
- **ioctl**: controls the user-mode perf, which includes the following:
```
#define PERF_IOC_MAGIC 'T'
#define PERF_START _IO(PERF_IOC_MAGIC, 1)
#define PERF_STOP _IO(PERF_IOC_MAGIC, 2)
```
The operations correspond to **LOS_PerfStart** and **LOS_PerfStop**.
For details, see [User-Mode Development Example](#user-mode-development-example).
## How to Develop
### 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**.
| Item| menuconfig Option| Description| Value|
| -------- | -------- | -------- | -------- |
| LOSCFG_KERNEL_PERF | Enable Perf Feature | Whether to enable perf.| YES/NO |
| LOSCFG_PERF_CALC_TIME_BY_TICK | Time-consuming Calc Methods-&gt;By Tick | Whether to use tick as the perf timing unit.| YES/NO |
| LOSCFG_PERF_CALC_TIME_BY_CYCLE | Time-consuming Calc Methods-&gt;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)
Events: 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.
#### Kernel-Mode 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.
#### Kernel-Mode Sample Code
Prerequisites: The perf module configuration is complete in **menuconfig**.
The sample code is as follows:
```
#include "los_perf.h"
STATIC VOID OsPrintBuff(const CHAR *buf, UINT32 num)
{
UINT32 i = 0;
PRINTK("num: ");
for (i = 0; i < num; i++) {
PRINTK(" %02d", i);
}
PRINTK("\n");
PRINTK("hex: ");
for (i = 0; i < num; i++) {
PRINTK(" %02x", buf[i]);
}
PRINTK("\n");
}
STATIC VOID perfTestHwEvent(VOID)
{
UINT32 ret;
CHAR *buf = NULL;
UINT32 len;
PerfConfigAttr attr = {
.eventsCfg = {
.type = PERF_EVENT_TYPE_HW,
.events = {
[0] = {PERF_COUNT_HW_CPU_CYCLES, 0xFFFF},
[1] = {PERF_COUNT_HW_BRANCH_INSTRUCTIONS, 0xFFFFFF00},
},
.eventsNr = 2,
.predivided = 1, /* cycle counter increase every 64 cycles */
},
.taskIds = {0},
.taskIdsNr = 0,
.needSample = 0,
.sampleType = PERF_RECORD_IP | PERF_RECORD_CALLCHAIN,
};
ret = LOS_PerfConfig(&attr);
if (ret != LOS_OK) {
PRINT_ERR("perf config error %u\n", ret);
return;
}
PRINTK("------count mode------\n");
LOS_PerfStart(0);
test(); /* this is any test function*/
LOS_PerfStop();
PRINTK("--------sample mode------ \n");
attr.needSample = 1;
LOS_PerfConfig(&attr);
LOS_PerfStart(2);
test(); /* this is any test function*/
LOS_PerfStop();
buf = LOS_MemAlloc(m_aucSysMem1, LOSCFG_PERF_BUFFER_SIZE);
if (buf == NULL) {
PRINT_ERR("buffer alloc failed\n");
return;
}
/* get sample data */
len = LOS_PerfDataRead(buf, LOSCFG_PERF_BUFFER_SIZE);
OsPrintBuff(buf, len); /* print data */
(VOID)LOS_MemFree(m_aucSysMem1, buf);
}
UINT32 Example_Perf_test(VOID){
UINT32 ret;
TSK_INIT_PARAM_S perfTestTask;
/* Create a perf task. */
memset(&perfTestTask, 0, sizeof(TSK_INIT_PARAM_S));
perfTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)perfTestHwEvent;
perfTestTask.pcName = "TestPerfTsk"; /* Test task name. */
perfTestTask.uwStackSize = 0x800;
perfTestTask.usTaskPrio = 5;
perfTestTask.uwResved = LOS_TASK_STATUS_DETACHED;
ret = LOS_TaskCreate(&g_perfTestTaskId, &perfTestTask);
if(ret != LOS_OK){
PRINT_ERR("PerfTestTask create failed.\n");
return LOS_NOK;
}
return LOS_OK;
}
LOS_MODULE_INIT(perfTestHwEvent, LOS_INIT_LEVEL_KMOD_EXTENDED);
```
#### Kernel-Mode Verification
The output is as follows:
```
--------count mode----------
[EMG] [cycles] eventType: 0xff: 5466989440
[EMG] [branches] eventType: 0xc: 602166445
------- sample mode----------
[EMG] dump section data, addr: 0x8000000 length: 0x800000
num: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 ...
hex: 00 ef ef ef 00 00 00 00 14 00 00 00 60 00 00 00 00 00 00 00 70 88 36 40 08 00 00 00 6b 65 72 6e 65 6c 00 00 01 00 00 00 cc 55 30 40 08 00 00 00 6b 65 72 6e 65 6c 00 00
```
- For the counting mode, the following information is displayed after perf is stopped:
Event name (cycles), event type (0xff), and number of event occurrences (5466989440)
For hardware PMU events, the displayed event type is the hardware event ID, not the abstract type defined in **enum PmuHWId**.
- For the sampling mode, the address and length of the sampled data will be displayed after perf is stopped:
dump section data, addr: (0x8000000) length: (0x5000)
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.
### User-Mode Development Process
Choose **Driver** > **Enable PERF DRIVER** in **menuconfig** to enable the perf driver. This option is available in **Driver** only after **Enable Perf Feature** is selected in the kernel.
1. Open the **/dev/perf** file and perform read, write, and ioctl operations.
2. Run the **perf** commands in user mode in the **/bin** directory.
After running **cd bin**, you can use the following commands:
- **./perf start [*id*]**: starts perf sampling. *id* is optional and is **0** by default.
- **./perf stop**: stops perf sampling.
- **./perf read <*nBytes*>**: reads n-byte data from the sampling buffer and displays the data.
- **./perf list**: lists the events supported by **-e**.
- **./perf stat/record [*option*] <*command*>**: sets counting or sampling parameters.
- The [*option*] can be any of the following:
- -**-e**: sets sampling events. Events of the same type listed in **./perf list** can be used.
- -**-p**: sets the event sampling interval.
- -**-o**: specifies the path of the file for saving the perf sampling data.
- -**-t**: specifies the task IDs for data collection. Only the contexts of the specified tasks are collected. If this parameter is not specified, all tasks are collected by default.
- -**-s**: specifies the context type for sampling. For details, see **PerfSampleType** defined in **los_perf.h**.
- -**-P**: specifies the process IDs for data collection. Only the contexts of the specified processes are collected. If this parameter is not specified, all processes are collected by default.
- -**-d**: specifies whether to divide the frequency (the value is incremented by 1 each time an event occurs 64 times). This option is valid only for hardware cycle events.
- *command* specifies the program to be checked by perf.
Examples:
Run the **./perf list** command to display available events.
The output is as follows:
```
cycles [Hardware event]
instruction [Hardware event]
dcache [Hardware event]
dcache-miss [Hardware event]
icache [Hardware event]
icache-miss [Hardware event]
branch [Hardware event]
branch-miss [Hardware event]
clock [Timed event]
task-switch [Software event]
irq-in [Software event]
mem-alloc [Software event]
mux-pend [Software event]
```
Run **./perf stat -e cycles os_dump**.
The output is as follows:
```
type: 0
events[0]: 255, 0xffff
predivided: 0
sampleType: 0x0
needSample: 0
usage os_dump [--help | -l | SERVICE]
--help: shows this help
-l: only list services, do not dump them
SERVICE: dumps only service SERVICE
time used: 0.058000(s)
[cycles] eventType: 0xff [core 0]: 21720647
[cycles] eventType: 0xff [core 1]: 13583830
```
Run **./perf record -e cycles os_dump**.
The output is as follows:
```
type: 0
events[0]: 255, 0xffff
predivided: 0
sampleType: 0x60
needSample: 1
usage os_dump [--help | -l | SERVICE]
--help: shows this help
-l: only list services, do not dump them
SERVICE: dumps only service SERVICE
dump perf data, addr: 0x408643d8 length: 0x5000
time used: 0.059000(s)
save perf data success at /storage/data/perf.data
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> After running the **./perf stat/record** command, you can run the **./perf start** and **./perf stop** commands multiple times. The sampling event configuration is as per the parameters set in the latest **./perfstat/record** command.
#### User-Mode Development Example
This example implements the following:
1. Open the perf character device.
2. Write the perf events.
3. Start perf.
4. Stop perf.
5. Read the perf sampling data.
#### User-Mode Sample Code
The code is as follows:
```
#include "fcntl.h"
#include "user_copy.h"
#include "sys/ioctl.h"
#include "fs/driver.h"
#include "los_dev_perf.h"
#include "los_perf.h"
#include "los_init.h"
/* perf ioctl */
#define PERF_IOC_MAGIC 'T'
#define PERF_START _IO(PERF_IOC_MAGIC, 1)
#define PERF_STOP _IO(PERF_IOC_MAGIC, 2)
int main(int argc, char **argv)
{
char *buf = NULL;
ssize_t len;
int fd = open("/dev/perf", O_RDWR);
if (fd == -1) {
printf("Perf open failed.\n");
exit(EXIT_FAILURE);
}
PerfConfigAttr attr = {
.eventsCfg = {
#ifdef LOSCFG_PERF_HW_PMU
.type = PERF_EVENT_TYPE_HW,
.events = {
[0] = {PERF_COUNT_HW_CPU_CYCLES, 0xFFFF},
},
#elif defined LOSCFG_PERF_TIMED_PMU
.type = PERF_EVENT_TYPE_TIMED,
.events = {
[0] = {PERF_COUNT_CPU_CLOCK, 100},
},
#elif defined LOSCFG_PERF_SW_PMU
.type = PERF_EVENT_TYPE_SW,
.events = {
[0] = {PERF_COUNT_SW_TASK_SWITCH, 1},
},
#endif
.eventsNr = 1, /* 1 event */
.predivided = 0,
},
.taskIds = {0},
.taskIdsNr = 0,
.processIds = {0},
.processIdsNr = 0,
.needSample = 1,
.sampleType = PERF_RECORD_IP | PERF_RECORD_CALLCHAIN,
};
(void)write(fd, &attr, sizeof(PerfConfigAttr)); /* perf config */
ioctl(fd, PERF_START, NULL); /* perf start */
test();
ioctl(fd, PERF_STOP, NULL); /* perf stop */
buf = (char *)malloc(LOSCFG_PERF_BUFFER_SIZE);
if (buf == NULL) {
printf("no memory for read perf 0x%x\n", LOSCFG_PERF_BUFFER_SIZE);
return -1;
}
len = read(fd, buf, LOSCFG_PERF_BUFFER_SIZE);
OsPrintBuff(buf, len); /* print data */
free(buf);
close(fd);
return 0;
}
```
#### User-Mode Verification
The output is as follows:
```
[EMG] dump section data, addr: 0x8000000 length: 0x800000
num: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 ...
hex: 00 ef ef ef 00 00 00 00 14 00 00 00 60 00 00 00 00 00 00 00 70 88 36 40 08 00 00 00 6b 65 72 6e 65 6c 00 00 01 00 00 00 cc 55 30 40 08 00 00 00 6b 65 72 6e 65 6c 00 00
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册