diff --git a/en/device-dev/kernel/Readme-EN.md b/en/device-dev/kernel/Readme-EN.md index 243ae9fb87332aa7ba04b381fecc814f610ffb93..47a8e490fe57fad8be004c3cfeba2dec9d729b5f 100644 --- a/en/device-dev/kernel/Readme-EN.md +++ b/en/device-dev/kernel/Readme-EN.md @@ -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) @@ -43,19 +44,19 @@ - Memory Management - [Heap Memory Management](kernel-small-basic-memory-heap.md) - [Physical Memory Management](kernel-small-basic-memory-physical.md) - - [Virtual Memory Management](kernel-small-basic-memory-virtual.md) - - [Virtual-to-Physical Mapping](kernel-small-basic-inner-reflect.md) + - [Virtual Memory Management](kernel-small-basic-memory-virtual.md) + - [Virtual-to-Physical Mapping](kernel-small-basic-inner-reflect.md) - Kernel Communication Mechanisms - [Event](kernel-small-basic-trans-event.md) - - [Semaphore](kernel-small-basic-trans-semaphore.md) - - [Mutex](kernel-small-basic-trans-mutex.md) + - [Semaphore](kernel-small-basic-trans-semaphore.md) + - [Mutex](kernel-small-basic-trans-mutex.md) - [Queue](kernel-small-basic-trans-queue.md) - [RW Lock](kernel-small-basic-trans-rwlock.md) - [Futex](kernel-small-basic-trans-user-mutex.md) - [Signal](kernel-small-basic-trans-user-signal.md) - [Time Management](kernel-small-basic-time.md) - - [Software Timer](kernel-small-basic-softtimer.md) - - [Atomic Operation](kernel-small-basic-atomic.md) + - [Software Timer](kernel-small-basic-softtimer.md) + - [Atomic Operation](kernel-small-basic-atomic.md) - Extension Components - [System Call](kernel-small-bundles-system.md) - [Dynamic Loading and Linking](kernel-small-bundles-linking.md) @@ -135,7 +136,7 @@ - [Magic Key](kernel-small-debug-shell-magickey.md) - [User-Space Exception Information](kernel-small-debug-shell-error.md) - [Trace](kernel-small-debug-trace.md) - - [Perf](kernel-mini-memory-perf.md) + - [Perf](kernel-small-debug-perf.md) - [LMS](kernel-small-memory-lms.md) - [Process Debugging](kernel-small-debug-process-cpu.md) - Kernel-Mode Memory Debugging diff --git a/en/device-dev/kernel/figures/futex-design.jpg b/en/device-dev/kernel/figures/futex-design.jpg index f6c83d6434f3c68d1baecbf42db9a3df21568b49..a7ab34d091c5d6bd1a983d1aedbf9ea7a5617feb 100644 Binary files a/en/device-dev/kernel/figures/futex-design.jpg and b/en/device-dev/kernel/figures/futex-design.jpg differ diff --git a/en/device-dev/kernel/kernel-mini-appx-lib.md b/en/device-dev/kernel/kernel-mini-appx-lib.md index 9f1021017b7ae99e88bee3430cf365076226b739..17a997d2411dc5ec5b9f9b4231c99dc526d77d2b 100644 --- a/en/device-dev/kernel/kernel-mini-appx-lib.md +++ b/en/device-dev/kernel/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 diff --git a/en/device-dev/kernel/kernel-mini-basic-ipc-event.md b/en/device-dev/kernel/kernel-mini-basic-ipc-event.md index a39a68606f1a780ea75b05fe788f4d577ac554a5..3339899d1e1b04c94513c64692c93aeb1bea8b0a 100644 --- a/en/device-dev/kernel/kernel-mini-basic-ipc-event.md +++ b/en/device-dev/kernel/kernel-mini-basic-ipc-event.md @@ -1,15 +1,15 @@ -# Events +# Event ## Basic Concepts -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. - 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. @@ -18,7 +18,7 @@ APIs are provided to initialize, read/write, clear, and destroy events. ### 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 { ### 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. -**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 @@ -58,12 +68,12 @@ The input parameters **eventMask** and **mode** determine whether the condition | Category| API| Description| | -------- | -------- | -------- | -| Event check| LOS_EventPoll | Checks whether the expected event occurs based on **eventID**, **eventMask**, and **mode**.
**NOTICE**

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.| -| Event read| LOS_EventRead | Reads an event (wait event). The task will be blocked to wait based on the timeout period (in ticks).
If no event is read, **0** is returned.
If an event is successfully read, a positive value (event set) is returned.
In other cases, an error code is returned.| -| Event write| 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.| -| Event destruction| LOS_EventDestroy | Destroys an event control block.| +| Checking an event | LOS_EventPoll | Checks whether the expected event occurs based on **eventID**, **eventMask**, and **mode**.
**NOTE**
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. | +| Initializing an event control block | LOS_EventInit | Initializes an event control block.| +| Reading an event | LOS_EventRead | Reads an event (wait event). The task will be blocked to wait based on the timeout period (in ticks).
If no event is read, **0** is returned.
If an event is successfully read, a positive value (event set) is returned.
In other cases, an error code is returned.| +| Writing an event | LOS_EventWrite | Writes an event to the event control block.| +| Clearing events | LOS_EventClear | Clears events in the event control block based on the event mask. | +| Destroying events | LOS_EventDestroy | Destroys an event control block.| ## How to Develop @@ -72,11 +82,11 @@ The typical event development process is as follows: 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. @@ -84,7 +94,7 @@ The typical event development process is as follows: > **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. @@ -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 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**. ``` diff --git a/en/device-dev/kernel/kernel-mini-basic-ipc-queue.md b/en/device-dev/kernel/kernel-mini-basic-ipc-queue.md index 3f874e55624965233b940bf1a33d378120a47762..b0677e6d8074ee0d0fbed29d74074cbc582fe543 100644 --- a/en/device-dev/kernel/kernel-mini-basic-ipc-queue.md +++ b/en/device-dev/kernel/kernel-mini-basic-ipc-queue.md @@ -77,7 +77,7 @@ The preceding figure illustrates how to write data to the tail node only. Writin ## 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.
**LOS_QueueCreateStatic**: creates a static message queue. You need to pass in the queue space.
**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.
**LOS_QueueWrite**: writes the **bufferAddr** (buffer address) to the tail node of the specified queue.
**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 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**. ``` diff --git a/en/device-dev/kernel/kernel-mini-debug-shell.md b/en/device-dev/kernel/kernel-mini-debug-shell.md new file mode 100644 index 0000000000000000000000000000000000000000..142bf85cec273294fd71c69fc420ccdf77788406 --- /dev/null +++ b/en/device-dev/kernel/kernel-mini-debug-shell.md @@ -0,0 +1,258 @@ +# 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.
If **DIRECTORY** is a valid directory, the content of the specified directory is displayed.
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 | diff --git a/en/device-dev/kernel/kernel-mini-extend-cpup.md b/en/device-dev/kernel/kernel-mini-extend-cpup.md index a5d10352b390a3610804eaf10e70b3d021193322..f6c1e97c7bf8b46ddfcb1b318b220dcc8c5315a7 100644 --- a/en/device-dev/kernel/kernel-mini-extend-cpup.md +++ b/en/device-dev/kernel/kernel-mini-extend-cpup.md @@ -1,27 +1,41 @@ # 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 - -**Table 1** Functions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Obtaining the system CPU usage

-

LOS_SysCpuUsage

-

Obtains the current system CPUP.

-

LOS_HistorySysCpuUsage

-

Obtains the historical CPUP of the system.

-

Obtaining the task CPUP

-

LOS_TaskCpuUsage

-

Obtains the CPUP of a specified task.

-

LOS_HistoryTaskCpuUsage

-

Obtains the historical CPUP of a specified task.

-

LOS_AllCpuUsage

-

Obtains the CPUP of all tasks.

-

Outputting the task CPUP

-

LOS_CpupUsageMonitor

-

Outputs the historical CPUP of a task.

-
+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.
**LOS_HistorySysCpuUsage**: obtains the historical CPUP of the system.| +| Obtaining the task CPUP| **LOS_TaskCpuUsage**: obtains the CPUP of a task.
**LOS_HistoryTaskCpuUsage**: obtains the historical CPUP of a task.
**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.
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 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. ``` - diff --git a/en/device-dev/kernel/kernel-mini-extend-file.md b/en/device-dev/kernel/kernel-mini-extend-file.md index 5d0656dd59a90ea3fd9b6aade4acae18a932d4b9..ff10e418ada3317e8ff5c5e4eefc6e2e892ea31f 100644 --- a/en/device-dev/kernel/kernel-mini-extend-file.md +++ b/en/device-dev/kernel/kernel-mini-extend-file.md @@ -1,27 +1,32 @@ -# File System +# File Systems -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| | close | Closes a file.| Supported| Supported| -| read | Reads the file content.| Supported| Supported| -| write | Writes data to a file.| Supported| Supported| -| lseek | Sets the file offset.| Supported| Supported| +| read | Reads the file content. | Supported | Supported | +| write | Writes data to a file. | Supported | Supported | +| lseek | Sets the file offset. | Supported | Supported | +| stat | Obtains file information based on the file path name.| Supported | Supported | | unlink | Deletes a file.| Supported| Supported| | rename | Renames the file.| 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 file updates to a storage device.| Supported| Supported| - +| fstat | Obtains file information based on the file handle. | Supported | Supported | +| fsync | Saves a file to a storage device. | Supported | Supported | - **Table 2** Directory management operations +**Table 2** APIs for directory operations | API| Description| FATFS | LITTLEFS | | -------- | -------- | -------- | -------- | @@ -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| | rmdir | Deletes a directory.| Supported| Supported| - - **Table 3** Partition operations +**Table 3** APIs for partition operations | API| Description| FATFS | LITTLEFS | | -------- | -------- | -------- | -------- | @@ -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| | 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 ### 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 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 partition and logical partition. +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 @@ -56,11 +64,13 @@ The OpenHarmony kernel supports FAT12, FAT16, and FAT32 file systems. These file #### 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 #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. +- **partNum**: number of partitions. + +API for formatting a partition: + +**int LOS_PartitionFormat(const char \*partName, char \*fsType, void \*data);** + +- **partName**: pointer to the partition name, in the *Device_name*+**p**+*Partition_ number* format. For example, **spinorblk0p0**. +- **fsType**: pointer to the file system type, which is **vfat** for the FAT file system. +- **data**: pointer to the private data that passes in **(VOID \*) formatType**, for example, **FMT_FAT** or **FMT_FAT32**. + +API for mounting a partition: + +**int mount(const char \*source, const char \*target, const char \*filesystemtype, unsigned long mountflags, const void \*data);** + +- **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. + + #include "fatfs_conf.h" + #include "fs_config.h" + #include "los_config.h" + #include "ram_virt_flash.h" + #include "los_fs.h" + + struct fs_cfg { + CHAR *mount_point; + struct PartitionCfg partCfg; + }; + + INT32 FatfsLowLevelInit() + { + INT32 ret; + INT32 i; + UINT32 addr; + int data = FMT_FAT32; + + const char * const pathName[FF_VOLUMES] = {FF_VOLUME_STRS}; + 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); + printf("%s: DiskPartition %s\n", __func__, (ret == 0) ? "succeed" : "failed"); + if (ret != 0) { + return -1; + } + + ret = LOS_PartitionFormat("spinorblk0p0", "vfat", &data); + printf("%s: PartitionFormat %s\n", __func__, (ret == 0) ? "succeed" : "failed"); + if (ret != 0) { + return -1; + } + + 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 -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. - - **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. -- 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. +- 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 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. - 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. -Note the following when mounting and unmounting FatFS partitions: -- 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. +Observe the following when managing files and directories in a FAT file system: + +- 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. -- 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**. + +You can use **fatfs_fdisk()** and **fatfs_format()** to re-partition the device storage and format the partitions. Observe the following: -The FAT file system supports re-partitioning and formatting of storage devices using **fatfs_fdisk** and **fatfs_format**. -- 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. @@ -102,9 +198,9 @@ The FAT file system supports re-partitioning and formatting of storage devices u 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. @@ -123,99 +219,103 @@ This example implements the following: #### Sample Code - **Prerequisites** +**Prerequisites** - The MMC device partition is mounted to the **user** directory. +- 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. - The sample code is as follows: - - ``` - #include - #include - #include "sys/stat.h" - #include "fcntl.h" - #include "unistd.h" +**Implementation** - #define LOS_OK 0 - #define LOS_NOK -1 +The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleFatfs** function is called in **TestTaskEntry**. - int FatfsTest(void) - { + ``` +#include +#include +#include "sys/stat.h" +#include "fcntl.h" +#include "unistd.h" + +#define BUF_SIZE 20 +#define TEST_ROOT "system" /* Set the test root directory. */ +VOID ExampleFatfs(VOID) +{ int ret; - int fd = -1; + int fd; ssize_t len; off_t off; - char dirName[20] = "user/test"; - char fileName[20] = "user/test/file.txt"; - char writeBuf[20] = "Hello OpenHarmony!"; - char readBuf[20] = {0}; + char dirName[BUF_SIZE] = TEST_ROOT"/test"; + char fileName[BUF_SIZE] = TEST_ROOT"/test/file.txt"; + char writeBuf[BUF_SIZE] = "Hello OpenHarmony!"; + char readBuf[BUF_SIZE] = {0}; - /* Create the user/test directory. */ + /* Create a test directory. */ ret = mkdir(dirName, 0777); if (ret != LOS_OK) { printf("mkdir failed.\n"); - return LOS_NOK; + return; } - /* 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); if (fd < 0) { printf("open file failed.\n"); - return LOS_NOK; + return; } /* Write the content from writeBuf to the file. */ len = write(fd, writeBuf, strlen(writeBuf)); if (len != strlen(writeBuf)) { printf("write file failed.\n"); - return LOS_NOK; + return; } /* Save the file to a storage device. */ ret = fsync(fd); if (ret != LOS_OK) { printf("fsync failed.\n"); - return LOS_NOK; + return; } /* Move the read/write pointer to the beginning of the file. */ off = lseek(fd, 0, SEEK_SET); if (off != 0) { printf("lseek failed.\n"); - return LOS_NOK; + return; } /* Read the file content with the length of readBuf to readBuf. */ len = read(fd, readBuf, sizeof(readBuf)); if (len != strlen(writeBuf)) { printf("read file failed.\n"); - return LOS_NOK; + return; } printf("%s\n", readBuf); - /* Close the file. */ + /* Close the test file. */ ret = close(fd); if (ret != LOS_OK) { printf("close failed.\n"); - return LOS_NOK; + return; } - /* Delete file.txt from the user/test directory. */ + /* Delete the test file. */ ret = unlink(fileName); if (ret != LOS_OK) { printf("unlink failed.\n"); - return LOS_NOK; + return; } - /* Delete the user/test directory. */ + /* Delete the test directory. */ ret = rmdir(dirName); if (ret != LOS_OK) { printf("rmdir failed.\n"); - return LOS_NOK; + return; } - return LOS_OK; - } + return; +} ``` @@ -232,102 +332,219 @@ Hello OpenHarmony! ### 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. ### 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. +- **partNum**: number of partitions. + +API for formatting a partition: + +**int LOS_PartitionFormat(const char \*partName, char \*fsType, void \*data);** + +- **partName**: pointer to the partition name. +- **fsType**: pointer to the file system type, which is **littlefs** for LittleFS. +- **data**: pointer to the private data that passes in **void pass (VOID \*) struct fs_cfg**. + +API for mounting a partition: + +**int mount(const char \*source, const char \*target, const char \*filesystemtype, unsigned long mountflags, const void \*data);** + +- **source**: pointer to the partition name. +- **target**: pointer to the target path to mount. +- **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. ``` -const struct lfs_config cfg = { - // block device operations - .read = user_provided_block_device_read, - .prog = user_provided_block_device_prog, - .erase = user_provided_block_device_erase, - .sync = user_provided_block_device_sync, - - // block device configuration - .read_size = 16, - .prog_size = 16, - .block_size = 4096, - .block_count = 128, - .cache_size = 16, - .lookahead_size = 16, - .block_cycles = 500, +#include "los_config.h" +#include "ram_virt_flash.h" +#include "los_fs.h" + +struct fs_cfg { + CHAR *mount_point; + struct PartitionCfg partCfg; }; + +INT32 LfsLowLevelInit() +{ + INT32 ret; + struct fs_cfg fs[LOSCFG_LFS_MAX_MOUNT_SIZE] = {0}; + HalLogicPartition *halPartitionsInfo = getPartitionInfo(); /* Function for obtaining the partition lengths and start addresses. You can modify the function to match your development. */ + + INT32 lengthArray[2]; + lengthArray[0]= halPartitionsInfo[FLASH_PARTITION_DATA0].partitionLength; + + INT32 addrArray[2]; + addrArray[0] = halPartitionsInfo[FLASH_PARTITION_DATA0].partitionStartAddr; + + ret = LOS_DiskPartition("flash0", "littlefs", lengthArray, addrArray, 2); + printf("%s: DiskPartition %s\n", __func__, (ret == 0) ? "succeed" : "failed"); + if (ret != 0) { + return -1; + } + fs[0].mount_point = "/littlefs"; + fs[0].partCfg.partNo = 0; + fs[0].partCfg.blockSize = 4096; /* 4096, lfs block size */ + fs[0].partCfg.blockCount = 1024; /* 2048, lfs block count */ + fs[0].partCfg.readFunc = virt_flash_read; /* Function for reading data from the flash drive. You can modify it to match your development. */ + fs[0].partCfg.writeFunc = virt_flash_write; /* Function for writing data to the flash drive. You can modify it to match your development. */ + fs[0].partCfg.eraseFunc = virt_flash_erase; /* Function for erasing the flash driver. You can modify it to match your development. */ + + fs[0].partCfg.readSize = 256; /* 256, lfs read size */ + fs[0].partCfg.writeSize = 256; /* 256, lfs prog size */ + fs[0].partCfg.cacheSize = 256; /* 256, lfs cache size */ + fs[0].partCfg.lookaheadSize = 16; /* 16, lfs lookahead size */ + fs[0].partCfg.blockCycles = 1000; /* 1000, lfs block cycles */ + + ret = LOS_PartitionFormat("flash0", "littlefs", &fs[0].partCfg); + printf("%s: PartitionFormat %s\n", __func__, (ret == 0) ? "succeed" : "failed"); + if (ret != 0) { + return -1; + } + 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 - 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" -lfs_t lfs; -lfs_file_t file; -const struct lfs_config cfg = { - // block device operations - .read = user_provided_block_device_read, - .prog = user_provided_block_device_prog, - .erase = user_provided_block_device_erase, - .sync = user_provided_block_device_sync, - // block device configuration - .read_size = 16, - .prog_size = 16, - .block_size = 4096, - .block_count = 128, - .cache_size = 16, - .lookahead_size = 16, - .block_cycles = 500, -}; -int main(void) { - // mount the filesystem - int err = lfs_mount(&lfs, &cfg); - // reformat if we can't mount the filesystem - // this should only happen on the first boot - if (err) { - lfs_format(&lfs, &cfg); - lfs_mount(&lfs, &cfg); +#include +#include +#include "sys/stat.h" +#include "fcntl.h" +#include "unistd.h" + +#define BUF_SIZE 20 +#define TEST_ROOT "/littlefs" /* Set the test root directory. */ +VOID ExampleLittlefs(VOID) +{ + int ret; + int fd; + ssize_t len; + off_t off; + char dirName[BUF_SIZE] = TEST_ROOT"/test"; + char fileName[BUF_SIZE] = TEST_ROOT"/test/file.txt"; + char writeBuf[BUF_SIZE] = "Hello OpenHarmony!"; + char readBuf[BUF_SIZE] = {0}; + + /* Create a test directory. */ + ret = mkdir(dirName, 0777); + if (ret != LOS_OK) { + printf("mkdir failed.\n"); + return; } - // read current count - uint32_t boot_count = 0; - lfs_file_open(&lfs, &file, "boot_count", LFS_O_RDWR | LFS_O_CREAT); - lfs_file_read(&lfs, &file, &boot_count, sizeof(boot_count)); - // update boot count - boot_count += 1; - lfs_file_rewind(&lfs, &file); - lfs_file_write(&lfs, &file, &boot_count, sizeof(boot_count)); - // remember the storage is not updated until the file is closed successfully - lfs_file_close(&lfs, &file); - // release any resources we were using - lfs_unmount(&lfs); - // print the boot count - printf("boot_count: %d\n", boot_count); + + /* Create a file that is readable and writable. */ + fd = open(fileName, O_RDWR | O_CREAT, 0777); + if (fd < 0) { + printf("open file failed.\n"); + return; + } + + /* Write the content from writeBuf to the file. */ + len = write(fd, writeBuf, strlen(writeBuf)); + if (len != strlen(writeBuf)) { + printf("write file failed.\n"); + return; + } + + /* Save the file to a storage device. */ + ret = fsync(fd); + if (ret != LOS_OK) { + printf("fsync failed.\n"); + return; + } + + /* Move the read/write pointer to the beginning of the file. */ + off = lseek(fd, 0, SEEK_SET); + if (off != 0) { + printf("lseek failed.\n"); + return; + } + + /* Read the file content with the length of readBuf to readBuf. */ + len = read(fd, readBuf, sizeof(readBuf)); + if (len != strlen(writeBuf)) { + printf("read file failed.\n"); + return; + } + printf("%s\n", readBuf); + + /* Close the test file. */ + ret = close(fd); + if (ret != LOS_OK) { + printf("close failed.\n"); + return; + } + + /* Delete the test file. */ + ret = unlink(fileName); + if (ret != LOS_OK) { + printf("unlink failed.\n"); + return; + } + + /* Delete the directory. */ + ret = rmdir(dirName); + if (ret != LOS_OK) { + printf("rmdir failed.\n"); + return; + } + + return LOS_OK; } ``` - - **Verification** +**Verification** The development is successful if the return result is as follows: ``` -Say hello 1 times. +Hello OpenHarmony! ``` + diff --git a/en/device-dev/kernel/kernel-mini-memory-debug.md b/en/device-dev/kernel/kernel-mini-memory-debug.md index 4cb0f39bba4e3a86a09238de86431d4541f8d051..c23372f9f0ffdd1b55e3eb818cb0f5acb78c942f 100644 --- a/en/device-dev/kernel/kernel-mini-memory-debug.md +++ b/en/device-dev/kernel/kernel-mini-memory-debug.md @@ -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:
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:
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:
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:
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 @@ -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**
+> **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 @@ -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**
+> **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 @@ -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. ``` diff --git a/en/device-dev/kernel/kernel-mini-memory-exception.md b/en/device-dev/kernel/kernel-mini-memory-exception.md index a5fa385993177947d5884643fd3186cb65d2bfa8..599623cbb364b7fc93cd1b6a9cd6d11cc338053d 100644 --- a/en/device-dev/kernel/kernel-mini-memory-exception.md +++ b/en/device-dev/kernel/kernel-mini-memory-exception.md @@ -1,321 +1,277 @@ # Exception Debugging + ## Basic Concepts 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 -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. The following figure illustrates the stack analysis mechanism for your reference. The actual stack information varies depending on the CPU architecture. -**Figure 1** Stack analysis mechanism +**Figure 1** Stack analysis mechanism + ![](figures/stack-analysis-mechanism.png "stack-analysis-mechanism") 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 The following table describes APIs available for the OpenHarmony LiteOS-M stack trace module. For more details about the APIs, see the API reference. -**Table 1** APIs of the stack trace module - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Stack trace

-

LOS_BackTrace

-

Prints the call stack relationship at the function calling point.

-

LOS_RecordLR

-

Obtains the call stack relationship at the function calling point when print is unavailable.

-
- -## Usage Guidelines + **Table 1** APIs of the stack trace module + +| Category| API| +| -------- | -------- | +| Stack tracing| **LOS_BackTrace**: prints the call stack relationship at the calling point.
**LOS_RecordLR**: obtains the call stack relationship at the calling point when print is unavailable.| + + +## Development Guidelines + ### How to Develop The typical process for enabling exception debugging is as follows: -1. Configure the macros related to exception handling. - - Modify the configuration in the **target\_config.h** file. - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value

-

LOSCFG_BACKTRACE_DEPTH

-

Depth of the function call stack. The default value is 15.

-

15

-

LOSCFG_BACKTRACE_TYPE

-

Type of the stack trace.

-

0: disabled

-

1: supports function call stack analysis of the Cortex-m series hardware.

-

2: supports function call stack analysis of the RISC-V series hardware.

-

Set this parameter to 1 or 2 based on the toolchain type.

-
- - -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: - - ``` - #include - #include "los_config.h" - #include "los_interrupt.h" - #include "los_task.h" - - UINT32 g_taskExcId; - #define TSK_PRIOR 4 - - /* Simulate an abnormal function. */ - - UINT32 Get_Result_Exception_0(UINT16 dividend){ - UINT32 divisor = 0; - UINT32 result = dividend / divisor; - return result; - } - - UINT32 Get_Result_Exception_1(UINT16 dividend){ - return Get_Result_Exception_0(dividend); - } - - UINT32 Get_Result_Exception_2(UINT16 dividend){ - return Get_Result_Exception_1(dividend); - } - - UINT32 Example_Exc(VOID) - { - UINT32 ret; - - printf("Enter Example_Exc Handler.\r\n"); - - /* Simulate the function calling. */ - ret = Get_Result_Exception_2(TSK_PRIOR); - printf("Divided result =%u.\r\n", ret); - - printf("Exit Example_Exc Handler.\r\n"); - return ret; - } - - - /* Task entry function used to create a task with an exception. */ - UINT32 Example_Exc_Entry(VOID) - { - UINT32 ret; - TSK_INIT_PARAM_S initParam; - - /* Lock task scheduling to prevent newly created tasks from being scheduled prior to this task due to higher priority.*/ - LOS_TaskLock(); - - printf("LOS_TaskLock() Success!\r\n"); - - initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Exc; - initParam.usTaskPrio = TSK_PRIOR; - initParam.pcName = "Example_Exc"; - initParam.uwStackSize = LOSCFG_SECURE_STACK_DEFAULT_SIZE; - /* Create a task with higher priority. The task will not be executed immediately after being created, because task scheduling is locked.*/ - ret = LOS_TaskCreate(&g_taskExcId, &initParam); - if (ret != LOS_OK) { - LOS_TaskUnlock(); - - printf("Example_Exc create Failed!\r\n"); - return LOS_NOK; - } - - printf("Example_Exc create Success!\r\n"); - - /* Unlock task scheduling. The task with the highest priority in the Ready queue will be executed.*/ - LOS_TaskUnlock(); - - return LOS_OK; - } - ``` - - -1. The error information displayed on the serial port terminal is as follows: - - ``` - entering kernel init... - LOS_TaskLock() Success! - Example_Exc create Success! - Entering scheduler - Enter Example_Exc Handler. - *************Exception Information************** - Type = 10 - ThrdPid = 4 - Phase = exc in task - FaultAddr = 0xabababab - Current task info: - Task name = Example_Exc - Task ID = 4 - Task SP = 0x200051ac - Task ST = 0x20004ff0 - Task SS = 0x200 - Exception reg dump: - PC = 0x80037da - LR = 0x80037fe - SP = 0x20005190 - R0 = 0x4 - R1 = 0x40 - R2 = 0x4 - R3 = 0x0 - R4 = 0x4040404 - R5 = 0x5050505 - R6 = 0x6060606 - R7 = 0x20005190 - R8 = 0x8080808 - R9 = 0x9090909 - R10 = 0x10101010 - R11 = 0x11111111 - R12 = 0x12121212 - PriMask = 0x0 - xPSR = 0x41000000 - ----- backtrace start ----- - backtrace 0 -- lr = 0x800381a - backtrace 1 -- lr = 0x8003836 - backtrace 2 -- lr = 0x8005a4e - backtrace 3 -- lr = 0x8000494 - backtrace 4 -- lr = 0x8008620 - backtrace 5 -- lr = 0x800282c - backtrace 6 -- lr = 0x80008a0 - backtrace 7 -- lr = 0x80099f8 - backtrace 8 -- lr = 0x800a01a - backtrace 9 -- lr = 0x800282c - backtrace 10 -- lr = 0x80008a0 - backtrace 11 -- lr = 0x80099f8 - backtrace 12 -- lr = 0x8009bf0 - backtrace 13 -- lr = 0x8009c52 - backtrace 14 -- lr = 0x80099aa - ----- backtrace end ----- - - TID Priority Status StackSize WaterLine StackPoint TopOfStack EventMask SemID name - --- -------- -------- --------- ---------- ---------- ---------- --------- ----- ---- - 0 0 Pend 0x2d0 0x104 0x200029bc 0x200027f0 0x0 0xffff Swt_Task - 1 31 Ready 0x500 0x44 0x20002f84 0x20002ac8 0x0 0xffff IdleCore000 - 2 6 Ready 0x1000 0x44 0x20003f94 0x20002fd8 0x0 0xffff TaskSampleEntry1 - 3 7 Ready 0x1000 0x44 0x20004f9c 0x20003fe0 0x0 0xffff TaskSampleEntry2 - 4 4 Running 0x200 0xec 0x200051ac 0x20004ff0 0x0 0xffff Example_Exc - - OS exception NVIC dump: - interrupt enable register, base address: 0xe000e100, size: 0x20 - 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 - interrupt pending register, base address: 0xe000e200, size: 0x20 - 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 - interrupt active register, base address: 0xe000e300, size: 0x20 - 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 - interrupt priority register, base address: 0xe000e400, size: 0xf0 - 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 - 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 - 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 - 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 - interrupt exception register, base address: 0xe000ed18, size: 0xc - 0x0 0x0 0xf0f00000 - interrupt shcsr register, base address: 0xe000ed24, size: 0x4 - 0x70008 - interrupt control register, base address: 0xe000ed04, size: 0x4 - 0x400f806 - - memory pools check: - system heap memcheck over, all passed! - memory pool check end! - ``` +1. Configure the macros related to exception handling + in the **target_config.h** file. + | Configuration Item| Description| Value| + | -------- | -------- | -------- | + | LOSCFG_BACKTRACE_DEPTH | Depth of the function call stack. The default value is **15**.| 15 | + | LOSCFG_BACKTRACE_TYPE | Type of the stack tracing.
**0**: The stack tracing is disabled.
**1**: supports call stack analysis of the Cortex-M series hardware.
**2**: supports call stack analysis of the RISC-V series hardware.| Set this parameter to **1** or **2** based on the toolchain type.| + +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 sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleExcEntry** function is called in **TestTaskEntry**. + + ``` + #include + #include "los_config.h" + #include "los_interrupt.h" + #include "los_task.h" + + UINT32 g_taskExcId; + #define TSK_PRIOR 4 + + /* Simulate an exception. */ + UINT32 GetResultException0(UINT16 dividend){ + UINT32 result = *(UINT32 *)(0xffffffff); + printf("Enter GetResultException0. %u\r\n", result); + return result; + } + + UINT32 GetResultException1(UINT16 dividend){ + printf("Enter GetResultException1.\r\n"); + return GetResultException0(dividend); + } + + UINT32 GetResultException2(UINT16 dividend){ + printf("Enter GetResultException2.\r\n"); + return GetResultException1(dividend); + } + + UINT32 ExampleExc(VOID) + { + UINT32 ret; + + printf("Enter Example_Exc Handler.\r\n"); + + /* Simulate the triggering of the exception. */ + ret = GetResultException2(TSK_PRIOR); + printf("Divided result =%u.\r\n", ret); + + printf("Exit Example_Exc Handler.\r\n"); + return ret; + } + + + /* Create a task with an exception in the task entry function. */ + UINT32 ExampleExcEntry(VOID) + { + UINT32 ret; + TSK_INIT_PARAM_S initParam = { 0 }; + + /* Lock task scheduling to prevent newly created tasks from being scheduled prior to this task due to higher priority. */ + LOS_TaskLock(); + + printf("LOS_TaskLock() Success!\r\n"); + + initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleExc; + initParam.usTaskPrio = TSK_PRIOR; + initParam.pcName = "Example_Exc"; + initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + /* Create a task with a higher priority. The task will not be executed because task scheduling is locked. */ + ret = LOS_TaskCreate(&g_taskExcId, &initParam); + if (ret != LOS_OK) { + LOS_TaskUnlock(); + + printf("Example_Exc create Failed!\r\n"); + return LOS_NOK; + } + + printf("Example_Exc create Success!\r\n"); + + /* Unlock task scheduling. The task with the highest priority in the Ready queue will be executed. */ + LOS_TaskUnlock(); + + return LOS_OK; + } + ``` + + The error information output by the serial port terminal is as follows: + + ``` + LOS_TaskLock() Success! + Example_Exc create Success! + Enter Example_Exc Handler. + Enter GetResultException2. + Enter GetResultException1. + *************Exception Information************** + Type = 4 + ThrdPid = 5 + Phase = exc in task + FaultAddr = 0xfffffffc + Current task info: + Task name = Example_Exc + Task ID = 5 + Task SP = 0x210549bc + Task ST = 0x21053a00 + Task SS = 0x1000 + Exception reg dump: + PC = 0x2101c61a + LR = 0x2101c64d + SP = 0x210549a8 + R0 = 0x4 + R1 = 0xa + R2 = 0x0 + R3 = 0xffffffff + R4 = 0x2103fb20 + R5 = 0x5050505 + R6 = 0x6060606 + R7 = 0x210549a8 + R8 = 0x8080808 + R9 = 0x9090909 + R10 = 0x10101010 + R11 = 0x11111111 + R12 = 0x0 + PriMask = 0x0 + xPSR = 0x41000000 + ----- backtrace start ----- + backtrace 0 -- lr = 0x2101c64c + backtrace 1 -- lr = 0x2101c674 + backtrace 2 -- lr = 0x2101c696 + backtrace 3 -- lr = 0x2101b1ec + ----- backtrace end ----- + + TID Priority Status StackSize WaterLine StackPoint TopOfStack EventMask SemID CPUUSE CPUUSE10s CPUUSE1s TaskEntry name + --- -------- -------- --------- --------- ---------- ---------- --------- ------ ------- --------- -------- ---------- ---- + 0 0 Pend 0x1000 0xdc 0x2104730c 0x210463e8 0 0xffff 0.0 0.0 0.0 0x2101a199 Swt_Task + 1 31 Ready 0x500 0x44 0x210478e4 0x21047428 0 0xffff 0.0 0.0 0.0 0x2101a9c9 IdleCore000 + 2 5 PendTime 0x6000 0xd4 0x2104e8f4 0x210489c8 0 0xffff 5.7 5.7 0.0 0x21016149 tcpip_thread + 3 3 Pend 0x1000 0x488 0x2104f90c 0x2104e9e8 0x1 0xffff 8.6 8.6 0.0 0x21016db5 ShellTaskEntry + 4 25 Ready 0x4000 0x460 0x21053964 0x2104f9f0 0 0xffff 9.0 8.9 0.0 0x2101c765 IT_TST_INI + 5 4 Running 0x1000 0x458 0x210549bc 0x21053a00 0 0xffff 76.5 76.6 0.0 0x2101c685 Example_Exc + + OS exception NVIC dump: + interrupt enable register, base address: 0xe000e100, size: 0x20 + 0x2001 0x0 0x0 0x0 0x0 0x0 0x0 0x0 + interrupt pending register, base address: 0xe000e200, size: 0x20 + 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 + interrupt active register, base address: 0xe000e300, size: 0x20 + 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 + interrupt priority register, base address: 0xe000e400, size: 0xf0 + 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 + 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 + 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 + 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 + interrupt exception register, base address: 0xe000ed18, size: 0xc + 0x0 0x0 0xf0f00000 + interrupt shcsr register, base address: 0xe000ed24, size: 0x4 + 0x70002 + interrupt control register, base address: 0xe000ed04, size: 0x4 + 0x1000e805 + + memory pools check: + system heap memcheck over, all passed! + memory pool check end! + + The preceding data may vary depending on the running environment. + ``` ### How to Locate Exceptions 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: - - ``` - arm-none-eabi-objdump -S -l XXX.elf - ``` - - -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 **0x80037da** and locate the instruction being executed by the CPU. Disassemble the code as follows: - - ``` - UINT32 Get_Result_Exception_0(UINT16 dividend){ - 80037c8: b480 push {r7} - 80037ca: b085 sub sp, #20 - 80037cc: af00 add r7, sp, #0 - 80037ce: 4603 mov r3, r0 - 80037d0: 80fb strh r3, [r7, #6] - kernel_liteos_m\targets\cortex-m7_nucleo_f767zi_gcc/Core/Src/exc_example.c:10 - UINT32 divisor = 0; - 80037d2: 2300 movs r3, #0 - 80037d4: 60fb str r3, [r7, #12] - kernel_liteos_m\targets\cortex-m7_nucleo_f767zi_gcc/Core/Src/exc_example.c:11 - UINT32 result = dividend / divisor; - 80037d6: 88fa ldrh r2, [r7, #6] - 80037d8: 68fb ldr r3, [r7, #12] - 80037da: fbb2 f3f3 udiv r3, r2, r3 - 80037de: 60bb str r3, [r7, #8] - ``` - - -1. As indicated by the code: - 1. When the exception occurs, the CPU is executing **udiv r3, r2, r3**. The value of **r3** is **0**, which causes the divide-by-zero error. - 2. The exception occurs in the **Get\_Result\_Exception\_0** function. - -2. Locate the parent function of the abnormal function based on the LR value. - - The code disassembly of the LR value **0x80037fe** is as follows: - - ``` - 080037ec : - Get_Result_Exception_1(): - kernel_liteos_m\targets\cortex-m7_nucleo_f767zi_gcc/Core/Src/exc_example.c:15 - UINT32 Get_Result_Exception_1(UINT16 dividend){ - 80037ec: b580 push {r7, lr} - 80037ee: b082 sub sp, #8 - 80037f0: af00 add r7, sp, #0 - 80037f2: 4603 mov r3, r0 - 80037f4: 80fb strh r3, [r7, #6] - kernel_liteos_m\targets\cortex-m7_nucleo_f767zi_gcc/Core/Src/exc_example.c:16 - return Get_Result_Exception_0(dividend); - 80037f6: 88fb ldrh r3, [r7, #6] - 80037f8: 4618 mov r0, r3 - 80037fa: f7ff ffe5 bl 80037c8 - 80037fe: 4603 mov r3, r0 - ``` - - -1. The previous line of LR **80037fe** is **bl 80037c8 **, which calls the abnormal function. The parent function that calls the abnormal function is **Get\_Result\_Exception\_1\(\)**. -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. - +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 + ``` + +3. 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: + + ``` + 2101c60c : + 2101c60c: b580 push {r7, lr} + 2101c60e: b084 sub sp, #16 + 2101c610: af00 add r7, sp, #0 + 2101c612: 4603 mov r3, r0 + 2101c614: 80fb strh r3, [r7, #6] + 2101c616: f04f 33ff mov.w r3, #4294967295 ; 0xffffffff + 2101c61a: 681b ldr r3, [r3, #0] + 2101c61c: 60fb str r3, [r7, #12] + 2101c61e: 68f9 ldr r1, [r7, #12] + 2101c620: 4803 ldr r0, [pc, #12] ; (2101c630 ) + 2101c622: f001 f92b bl 2101d87c + 2101c626: 68fb ldr r3, [r7, #12] + 2101c628: 4618 mov r0, r3 + 2101c62a: 3710 adds r7, #16 + 2101c62c: 46bd mov sp, r7 + 2101c62e: bd80 pop {r7, pc} + 2101c630: 21025f90 .word 0x21025f90 + ``` + + As indicated by the information displayed: + + - The CPU is executing **ldr r3, [r3, #0]** when an exception occurs. The value of **r3** is **0xffffffff**, which causes an invalid address. + - The exception occurs in the **GetResultException0** function. + +4. Search for the parent function of the abnormal function based on the LR value. + The code disassembly of the LR value **0x2101c64d** is as follows: + + ``` + 2101c634 : + 2101c634: b580 push {r7, lr} + 2101c636: b082 sub sp, #8 + 2101c638: af00 add r7, sp, #0 + 2101c63a: 4603 mov r3, r0 + 2101c63c: 80fb strh r3, [r7, #6] + 2101c63e: 4806 ldr r0, [pc, #24] ; (2101c658 ) + 2101c640: f001 f91c bl 2101d87c + 2101c644: 88fb ldrh r3, [r7, #6] + 2101c646: 4618 mov r0, r3 + 2101c648: f7ff ffe0 bl 2101c60c + 2101c64c: 4603 mov r3, r0 + 2101c64e: 4618 mov r0, r3 + 2101c650: 3708 adds r7, #8 + 2101c652: 46bd mov sp, r7 + 2101c654: bd80 pop {r7, pc} + 2101c656: bf00 nop + 2101c658: 21025fb0 .word 0x21025fb0 + ``` + + The previous line of LR **2101c648** is **bl2101c60c **, which calls the abnormal function. The parent function is **GetResultException1**. + +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. \ No newline at end of file diff --git a/en/device-dev/kernel/kernel-mini-memory-lms.md b/en/device-dev/kernel/kernel-mini-memory-lms.md index afce67ceeabce8acadfd993eebd32f7e968280b9..eb6f913d03dd05d67d02f852c9975c53918a8a24 100644 --- a/en/device-dev/kernel/kernel-mini-memory-lms.md +++ b/en/device-dev/kernel/kernel-mini-memory-lms.md @@ -1,180 +1,117 @@ # LMS + ## Basic Concepts -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: -- 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 when libc frequently accessed functions, including **memset**, **memcpy**, **memmove**, **strcat**, **strcpy**, **strncat** and **strncpy**, are called. +- 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 when libc frequently accessed functions, including **memset**, **memcpy**, **memmove**, **strcat**, **strcpy**, **strncat** and **strncpy**, are called. + ## 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. + +- 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. + +- 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. -- 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. -- 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. ## 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. - -**Table 1** LMS module APIs - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

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.

-

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.

-
+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). + +**Table 1** APIs of the LMS module + +| Category| API | Description| +| -------- | -------- | -------- | +| 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.| +| 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.| + ## Development Guidelines + ### How to Develop The typical process for enabling LMS is as follows: -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\_m** directory, choose **Kernel**, and set **Enable Lite Memory Sanitizer** to **Yes**. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Macro

-

menuconfig Option

-

Description

-

Value

-

LOSCFG_KERNEL_LMS

-

Enable Lms Feature

-

Whether to enable LMS.

-

YES/NO

-

LOSCFG_LMS_MAX_RECORD_POOL_NUM

-

Lms check pool max num

-

Maximum number of memory pools that can be checked by LMS.

-

INT

-

LOSCFG_LMS_LOAD_CHECK

-

Enable lms read check

-

Whether to enable LMS read check.

-

YES/NO

-

LOSCFG_LMS_STORE_CHECK

-

Enable lms write check

-

Whether to enable LMS write check.

-

YES/NO

-

LOSCFG_LMS_CHECK_STRICT

-

Enable lms strict check, byte-by-byte

-

Whether to enable LMS byte-by-byte check.

-

YES/NO

-
- -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") { - cflags_c = [ - "-O0", - "-fsanitize=kernel-address", - ] - } else { - cflags_c = [ - "-O0", - "-fsanitize=kernel-address", - "-mllvm", - "-asan-instrumentation-with-call-threshold=0", - "-mllvm", - "-asan-stack=0", - "-mllvm", - "-asan-globals=0", - ] - } - ``` +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**. + + | Macro| menuconfig Option| Description| Value| + | -------- | -------- | -------- | -------- | + | LOSCFG_KERNEL_LMS | Enable Lms Feature | Whether to enable LMS.| YES/NO | + | LOSCFG_LMS_MAX_RECORD_POOL_NUM | Lms check pool max num | Maximum number of memory pools that can be checked by LMS.| INT | + | LOSCFG_LMS_LOAD_CHECK | Enable lms read check | Whether to enable LMS read check.| YES/NO | + | LOSCFG_LMS_STORE_CHECK | Enable lms write check | Whether to enable LMS write check.| YES/NO | + | LOSCFG_LMS_CHECK_STRICT | Enable lms strict check, byte-by-byte | Whether to enable LMS byte-by-byte check.| YES/NO | + +2. Modify the build script of the target module. + Add **-fsanitize=kernel-address** to insert memory access checks, and add **-O0** 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") { + cflags_c = [ + "-O0", + "-fsanitize=kernel-address", + ] + } else { + cflags_c = [ + "-O0", + "-fsanitize=kernel-address", + "-mllvm", + "-asan-instrumentation-with-call-threshold=0", + "-mllvm", + "-asan-stack=0", + "-mllvm", + "-asan-globals=0", + ] + } + ``` + +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 This example implements the following: -1. Create a task for LMS. -2. Construct a buffer overflow error and a UAF error. -3. Add "-fsanitize=kernel-address", execute the compilation, and check the output. +1. Create a task for LMS. + +2. Construct a buffer overflow error and a UAF error. + +3. Add "-fsanitize=kernel-address", execute the compilation, and check the output. + ### Sample Code 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**. + ``` #define PAGE_SIZE (0x1000U) #define INDEX_MAX 20 @@ -214,10 +151,10 @@ VOID LmsTestCaseTask(VOID) UINT32 Example_Lms_test(VOID){ UINT32 ret; TSK_INIT_PARAM_S lmsTestTask; - /* Create a task for LMS. */ + /* Create a task for LMS. */ memset(&lmsTestTask, 0, sizeof(TSK_INIT_PARAM_S)); lmsTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)LmsTestCaseTask; - lmsTestTask.pcName = "TestLmsTsk"; /* Task name. */ + lmsTestTask.pcName = "TestLmsTsk"; /* Test task name. */ lmsTestTask.uwStackSize = 0x800; lmsTestTask.usTaskPrio = 5; lmsTestTask.uwResved = LOS_TASK_STATUS_DETACHED; @@ -230,89 +167,137 @@ UINT32 Example_Lms_test(VOID){ } ``` + ### Verification -The output is as follows: + The following is an example of the command output. The data may vary depending on the running environment. ``` ######LmsTestOsmallocOverflow start ###### -[ERR]***** Kernel Address Sanitizer Error Detected Start ***** -[ERR]Heap buffer overflow error detected -[ERR]Illegal READ address at: [0x4157a3c8] -[ERR]Shadow memory address: [0x4157be3c : 4] Shadow memory value: [2] -OsBackTrace fp = 0x402c0f88 -runTask->taskName = LmsTestCaseTask -runTask->taskID = 2 -*******backtrace begin******* -traceback fp fixed, trace using fp = 0x402c0fd0 -traceback 0 -- lr = 0x400655a4 fp = 0x402c0ff8 -traceback 1 -- lr = 0x40065754 fp = 0x402c1010 -traceback 2 -- lr = 0x40044bd0 fp = 0x402c1038 -traceback 3 -- lr = 0x40004e14 fp = 0xcacacaca -[LMS] Dump info around address [0x4157a3c8]: - [0x4157a3a0]: 00 00 00 00 00 00 00 00 | [0x4157be3a | 0]: 1 1 - [0x4157a3a8]: ba dc cd ab 00 00 00 00 | [0x4157be3a | 4]: 2 2 - [0x4157a3b0]: 20 00 00 80 00 00 00 00 | [0x4157be3b | 0]: 2 0 - [0x4157a3b8]: 00 00 00 00 00 00 00 00 | [0x4157be3b | 4]: 0 0 - [0x4157a3c0]: 00 00 00 00 00 00 00 00 | [0x4157be3c | 0]: 0 0 - [0x4157a3c8]: [ba] dc cd ab a8 a3 57 41 | [0x4157be3c | 4]: [2] 2 - [0x4157a3d0]: 2c 1a 00 00 00 00 00 00 | [0x4157be3d | 0]: 2 3 - [0x4157a3d8]: 00 00 00 00 00 00 00 00 | [0x4157be3d | 4]: 3 3 - [0x4157a3e0]: 00 00 00 00 00 00 00 00 | [0x4157be3e | 0]: 3 3 - [0x4157a3e8]: 00 00 00 00 00 00 00 00 | [0x4157be3e | 4]: 3 3 - [0x4157a3f0]: 00 00 00 00 00 00 00 00 | [0x4157be3f | 0]: 3 3 -[ERR]***** Kernel Address Sanitizer Error Detected End ***** -str[20]=0xffffffba +[ERR][TestLmsTsk]***** Kernel Address Sanitizer Error Detected Start ***** +[ERR][TestLmsTsk]Heap buffer overflow error detected +[ERR][TestLmsTsk]Illegal READ address at: [0x21040414] +[ERR][TestLmsTsk]Shadow memory address: [0x21041e84 : 6] Shadow memory value: [2] +psp, start = 21057d88, end = 21057e80 +taskName = TestLmsTsk +taskID = 5 +----- traceback start ----- +traceback 0 -- lr = 0x210099f4 +traceback 1 -- lr = 0x2101da6e +traceback 2 -- lr = 0x2101db38 +traceback 3 -- lr = 0x2101c494 +----- traceback end ----- + +[LMS] Dump info around address [0x21040414]: + + [0x21040390]: 00 00 00 00 00 00 00 00 | [0x21041e7c | 4]: 1 1 + [0x21040398]: 00 00 00 00 00 00 00 00 | [0x21041e7d | 0]: 1 1 + [0x210403a0]: 00 00 00 00 00 00 00 00 | [0x21041e7d | 4]: 1 1 + [0x210403a8]: 00 00 00 00 00 00 00 00 | [0x21041e7e | 0]: 1 1 + [0x210403b0]: 00 00 00 00 00 00 00 00 | [0x21041e7e | 4]: 1 1 + [0x210403b8]: 00 00 00 00 00 00 00 00 | [0x21041e7f | 0]: 1 1 + [0x210403c0]: 00 00 00 00 00 00 00 00 | [0x21041e7f | 4]: 1 1 + [0x210403c8]: 00 00 00 00 00 00 00 00 | [0x21041e80 | 0]: 1 1 + [0x210403d0]: 00 00 00 00 00 00 00 00 | [0x21041e80 | 4]: 1 1 + [0x210403d8]: 00 00 00 00 00 00 00 00 | [0x21041e81 | 0]: 1 1 + [0x210403e0]: 00 00 00 00 00 00 00 00 | [0x21041e81 | 4]: 1 1 + [0x210403e8]: 00 00 00 00 00 00 00 00 | [0x21041e82 | 0]: 1 1 + [0x210403f0]: 00 00 00 00 00 00 00 00 | [0x21041e82 | 4]: 1 1 + [0x210403f8]: 40 1e 04 21 05 07 00 80 | [0x21041e83 | 0]: 2 2 + [0x21040400]: 00 00 00 00 00 00 00 00 | [0x21041e83 | 4]: 0 0 + [0x21040408]: 00 00 00 00 00 00 00 00 | [0x21041e84 | 0]: 0 0 + [0x21040410]: 00 00 00 00 [f8] 03 04 21 | [0x21041e84 | 4]: 0 [2] + [0x21040418]: 00 8b 06 00 00 00 00 00 | [0x21041e85 | 0]: 2 3 + [0x21040420]: 00 00 00 00 00 00 00 00 | [0x21041e85 | 4]: 3 3 + [0x21040428]: 00 00 00 00 00 00 00 00 | [0x21041e86 | 0]: 3 3 + [0x21040430]: 00 00 00 00 00 00 00 00 | [0x21041e86 | 4]: 3 3 + [0x21040438]: 00 00 00 00 00 00 00 00 | [0x21041e87 | 0]: 3 3 + [0x21040440]: 00 00 00 00 00 00 00 00 | [0x21041e87 | 4]: 3 3 + [0x21040448]: 00 00 00 00 00 00 00 00 | [0x21041e88 | 0]: 3 3 + [0x21040450]: 00 00 00 00 00 00 00 00 | [0x21041e88 | 4]: 3 3 + [0x21040458]: 00 00 00 00 00 00 00 00 | [0x21041e89 | 0]: 3 3 + [0x21040460]: 00 00 00 00 00 00 00 00 | [0x21041e89 | 4]: 3 3 + [0x21040468]: 00 00 00 00 00 00 00 00 | [0x21041e8a | 0]: 3 3 + [0x21040470]: 00 00 00 00 00 00 00 00 | [0x21041e8a | 4]: 3 3 + [0x21040478]: 00 00 00 00 00 00 00 00 | [0x21041e8b | 0]: 3 3 + [0x21040480]: 00 00 00 00 00 00 00 00 | [0x21041e8b | 4]: 3 3 + [0x21040488]: 00 00 00 00 00 00 00 00 | [0x21041e8c | 0]: 3 3 + [0x21040490]: 00 00 00 00 00 00 00 00 | [0x21041e8c | 4]: 3 3 +[ERR][TestLmsTsk]***** Kernel Address Sanitizer Error Detected End ***** +str[20]=0xfffffff8 ######LmsTestOsmallocOverflow stop ###### -###### LmsTestUseAfterFree start ###### -[ERR]***** Kernel Address Sanitizer Error Detected Start ***** -[ERR]Use after free error detected -[ERR]Illegal READ address at: [0x4157a3d4] -[ERR]Shadow memory address: [0x4157be3d : 2] Shadow memory value: [3] -OsBackTrace fp = 0x402c0f90 -runTask->taskName = LmsTestCaseTask -runTask->taskID = 2 -*******backtrace begin******* -traceback fp fixed, trace using fp = 0x402c0fd8 -traceback 0 -- lr = 0x40065680 fp = 0x402c0ff8 -traceback 1 -- lr = 0x40065758 fp = 0x402c1010 -traceback 2 -- lr = 0x40044bd0 fp = 0x402c1038 -traceback 3 -- lr = 0x40004e14 fp = 0xcacacaca -[LMS] Dump info around address [0x4157a3d4]: - [0x4157a3a8]: ba dc cd ab 00 00 00 00 | [0x4157be3a | 4]: 2 2 - [0x4157a3b0]: 20 00 00 80 00 00 00 00 | [0x4157be3b | 0]: 2 0 - [0x4157a3b8]: 00 00 00 00 00 00 00 00 | [0x4157be3b | 4]: 0 0 - [0x4157a3c0]: 00 00 00 00 00 00 00 00 | [0x4157be3c | 0]: 0 0 - [0x4157a3c8]: ba dc cd ab a8 a3 57 41 | [0x4157be3c | 4]: 2 2 - [0x4157a3d0]: 2c 1a 00 00 [00] 00 00 00 | [0x4157be3d | 0]: 2 [3] - [0x4157a3d8]: 00 00 00 00 00 00 00 00 | [0x4157be3d | 4]: 3 3 - [0x4157a3e0]: 00 00 00 00 00 00 00 00 | [0x4157be3e | 0]: 3 3 - [0x4157a3e8]: ba dc cd ab c8 a3 57 41 | [0x4157be3e | 4]: 2 2 - [0x4157a3f0]: 0c 1a 00 00 00 00 00 00 | [0x4157be3f | 0]: 2 3 - [0x4157a3f8]: 00 00 00 00 00 00 00 00 | [0x4157be3f | 4]: 3 3 -[ERR]***** Kernel Address Sanitizer Error Detected End ***** + +######LmsTestUseAfterFree start ###### +[ERR][TestLmsTsk]***** Kernel Address Sanitizer Error Detected Start ***** +[ERR][TestLmsTsk]Use after free error detected +[ERR][TestLmsTsk]Illegal READ address at: [0x2104041c] +[ERR][TestLmsTsk]Shadow memory address: [0x21041e85 : 2] Shadow memory value: [3] +psp, start = 21057d90, end = 21057e80 +taskName = TestLmsTsk +taskID = 5 +----- traceback start ----- +traceback 0 -- lr = 0x210099f4 +traceback 1 -- lr = 0x2101daec +traceback 2 -- lr = 0x2101db3c +traceback 3 -- lr = 0x2101c494 +----- traceback end ----- + +[LMS] Dump info around address [0x2104041c]: + + [0x21040398]: 00 00 00 00 00 00 00 00 | [0x21041e7d | 0]: 1 1 + [0x210403a0]: 00 00 00 00 00 00 00 00 | [0x21041e7d | 4]: 1 1 + [0x210403a8]: 00 00 00 00 00 00 00 00 | [0x21041e7e | 0]: 1 1 + [0x210403b0]: 00 00 00 00 00 00 00 00 | [0x21041e7e | 4]: 1 1 + [0x210403b8]: 00 00 00 00 00 00 00 00 | [0x21041e7f | 0]: 1 1 + [0x210403c0]: 00 00 00 00 00 00 00 00 | [0x21041e7f | 4]: 1 1 + [0x210403c8]: 00 00 00 00 00 00 00 00 | [0x21041e80 | 0]: 1 1 + [0x210403d0]: 00 00 00 00 00 00 00 00 | [0x21041e80 | 4]: 1 1 + [0x210403d8]: 00 00 00 00 00 00 00 00 | [0x21041e81 | 0]: 1 1 + [0x210403e0]: 00 00 00 00 00 00 00 00 | [0x21041e81 | 4]: 1 1 + [0x210403e8]: 00 00 00 00 00 00 00 00 | [0x21041e82 | 0]: 1 1 + [0x210403f0]: 00 00 00 00 00 00 00 00 | [0x21041e82 | 4]: 1 1 + [0x210403f8]: 40 1e 04 21 05 07 00 80 | [0x21041e83 | 0]: 2 2 + [0x21040400]: 00 00 00 00 00 00 00 00 | [0x21041e83 | 4]: 0 0 + [0x21040408]: 00 00 00 00 00 00 00 00 | [0x21041e84 | 0]: 0 0 + [0x21040410]: 00 00 00 00 f8 03 04 21 | [0x21041e84 | 4]: 0 2 + [0x21040418]: 05 8b 06 00 [00] 00 00 00 | [0x21041e85 | 0]: 2 [3] + [0x21040420]: 00 00 00 00 00 00 00 00 | [0x21041e85 | 4]: 3 3 + [0x21040428]: 00 00 00 00 00 00 00 00 | [0x21041e86 | 0]: 3 3 + [0x21040430]: 14 04 04 21 00 84 06 00 | [0x21041e86 | 4]: 2 2 + [0x21040438]: 00 00 00 00 00 00 00 00 | [0x21041e87 | 0]: 3 3 + [0x21040440]: 00 00 00 00 00 00 00 00 | [0x21041e87 | 4]: 3 3 + [0x21040448]: 00 00 00 00 00 00 00 00 | [0x21041e88 | 0]: 3 3 + [0x21040450]: 00 00 00 00 00 00 00 00 | [0x21041e88 | 4]: 3 3 + [0x21040458]: 00 00 00 00 00 00 00 00 | [0x21041e89 | 0]: 3 3 + [0x21040460]: 00 00 00 00 00 00 00 00 | [0x21041e89 | 4]: 3 3 + [0x21040468]: 00 00 00 00 00 00 00 00 | [0x21041e8a | 0]: 3 3 + [0x21040470]: 00 00 00 00 00 00 00 00 | [0x21041e8a | 4]: 3 3 + [0x21040478]: 00 00 00 00 00 00 00 00 | [0x21041e8b | 0]: 3 3 + [0x21040480]: 00 00 00 00 00 00 00 00 | [0x21041e8b | 4]: 3 3 + [0x21040488]: 00 00 00 00 00 00 00 00 | [0x21041e8c | 0]: 3 3 + [0x21040490]: 00 00 00 00 00 00 00 00 | [0x21041e8c | 4]: 3 3 + [0x21040498]: 00 00 00 00 00 00 00 00 | [0x21041e8d | 0]: 3 3 +[ERR][TestLmsTsk]***** Kernel Address Sanitizer Error Detected End ***** str[ 0]=0x 0 ######LmsTestUseAfterFree stop ###### ``` The key output information is as follows: -- Error type: - - Heap buffer overflow - - UAF - -- Incorrect operations: - - Illegal read - - Illegal write - - Illegal double free - -- Context: - - Task information \(**taskName** and **taskId**\) - - Backtrace +- Error type: + - Heap buffer overflow + - UAF -- Memory information of the error addresses: - - Memory value and the value of the corresponding shadow memory - - Memory address: memory value|\[shadow memory address|shadow memory byte offset\]: shadow memory value - - Shadow memory value. **0** \(Accessible\), **3** \(Freed\), **2** \(RedZone\), and **1** \(filled value\) +- Incorrect operations: + - Illegal read + - Illegal write + - Illegal double free +- Context: + - Task information (**taskName** and **taskId**) + - Backtrace +- Memory information of the error addresses: + - Memory value and the value of the corresponding shadow memory + - Memory address: memory value|[shadow memory address|shadow memory byte offset]: shadow memory value + - Shadow memory value. **0** (Accessible), **3** (Freed), **2** (RedZone), and **1** (filled value) diff --git a/en/device-dev/kernel/kernel-mini-memory-trace.md b/en/device-dev/kernel/kernel-mini-memory-trace.md index 1417442602eee705b8541acd9547f3dd55267d23..a60e3656c477f26c58cc135304fb343bb4c34730 100644 --- a/en/device-dev/kernel/kernel-mini-memory-trace.md +++ b/en/device-dev/kernel/kernel-mini-memory-trace.md @@ -1,8 +1,10 @@ # Trace + ## Basic Concepts -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 @@ -16,265 +18,168 @@ In offline mode, trace frames are stored in a circular buffer. If too many frame ![](figures/kernel-small-mode-process.png) -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 -The trace module of the OpenHarmony LiteOS-M kernel provides the following functions. For more details about the APIs, see the API reference. - -**Table 1** Trace module APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Starting and stopping trace

-

LOS_TraceStart

-

Starts trace.

-

LOS_TraceStop

-

Stops trace.

-

Managing trace records

-

LOS_TraceRecordDump

-

Exports data in the trace buffer.

-

LOS_TraceRecordGet

-

Obtains the start address of the trace buffer.

-

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.

-

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.

-

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 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. - - **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. - - Example: - - ``` - Perform simple instrumentation for reading and writing files fd1 and fd2. - Set TYPE to 1 for read operations and 2 for write operations. - Insert the following to the position where the fd1 file is read: - 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. - - 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. - - The **IDENTITY** and **Params** are the same as those of simple instrumentation. - - Example: - - ``` - 1. Set the event mask (module-level event type) in enum LOS_TRACE_MASK. - Format: TRACE_#MOD#_FLAG (MOD indicates the module name) - Example: - 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. - #TYPE# is the #TYPE# defined in step 2. - Example: - #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 modify the parameters as required. - If no parameter is specified, events of this type are not traced. - #define FS_READ_PARAMS(fp, fd, flag, size) // File reading events are not traced. - 4. Insert a code stub in a proper position. - Format: LOS_TRACE(#TYPE#, #TYPE#_PARAMS(IDENTITY, parma1...)) - LOS_TRACE(FS_READ, fp, fd, flag, size); // Code stub for reading files - The parameters following #TYPE# are the input parameter of the FS_READ_PARAMS function in step 3. - ``` - - >![](../public_sys-resources/icon-note.gif) **NOTE:** - >The trace event types and parameters can be modified 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**. -- 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. +## Available APIs +The trace module of the OpenHarmony LiteOS-M kernel provides the following APIs. For more details about the APIs, see the API reference. + + **Table 1** APIs of the trace module + +| Category| API| +| -------- | -------- | +| Starting/Stopping trace| - **LOS_TraceStart**: starts a trace.
- **LOS_TraceStop**: stops the trace.| +| Managing trace records| - **LOS_TraceRecordDump**: dumps data from the trace buffer.
- **LOS_TraceRecordGet**: obtains the start address of the trace buffer.
- **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.| +| 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.
- **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 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. + - **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. + - Example of simple instrumentation for reading and writing data based on the file FDs: + + ``` + /* Set TYPE to 1 for read operation and 2 for write operations. */ + LOS_TRACE_EASY(1, fd, flag, size); /* Add it to a proper position. */ + LOS_TRACE_EASY(2, fd, flag, size); /* Add it to a proper position. */ + ``` + - **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. + - **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. + - Example: + 1. Define the type of the FS module (event mask of the FS module) in **enum LOS_TRACE_MASK**. + + ``` + /* Define the event mask in the format of TRACE_#MOD#_FLAG, where #MOD# indicates the module name. */ + TRACE_FS_FLAG = 0x4000 + ``` + + 2. Define the event types of the FS module. + + + ``` + /* 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. */ + ``` + + 4. Add the code stubs in the code. + + + ``` + /* Format: LOS_TRACE(#TYPE#, #TYPE#_PARAMS(IDENTITY, parma1...)) */ + LOS_TRACE(FS_READ, fp, fd, flag, size); /* Code stub for reading data. */ + ``` + + > **NOTE**
+ > 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**. + +- 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.
The sample code is as follows: + + ``` + BOOL Example_HwiNumFilter(UINT32 hwiNum) + { + if ((hwiNum == TIMER_INT) || (hwiNum == DMA_INT)) { + return TRUE; + } + return FALSE; + } + LOS_TraceHwiFilterHookReg(Example_HwiNumFilter); + ``` - ``` - BOOL Example_HwiNumFilter(UINT32 hwiNum) - { - if ((hwiNum == TIMER_INT) || (hwiNum == DMA_INT)) { - return TRUE; - } - return FALSE; - } - 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 + ### How to Develop -The typical trace process is as follows: - -1. Configure the macro related to the trace module. - - Modify the configuration in the **target\_config.h** file. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Configuration

-

Description

-

Value

-

LOSCFG_KERNEL_TRACE

-

Specifies whether to enable the trace feature.

-

YES/NO

-

LOSCFG_RECORDER_MODE_OFFLINE

-

Specifies whether to enable the online trace mode.

-

YES/NO

-

LOSCFG_RECORDER_MODE_ONLINE

-

Specifies whether to enable the offline trace mode.

-

YES/NO

-

LOSCFG_TRACE_CLIENT_INTERACT

-

Specifies whether to enable interaction with Trace IDE (dev tools), including data visualization and process control.

-

YES/NO

-

LOSCFG_TRACE_FRAME_CORE_MSG

-

Specifies whether to enable recording of the CPU ID, interruption state, and lock task state.

-

YES/NO

-

LOSCFG_TRACE_FRAME_EVENT_COUNT

-

Specifies whether to enables recording of the event sequence number.

-

YES/NO

-

LOSCFG_TRACE_FRAME_MAX_PARAMS

-

Specifies the maximum number of parameters for event recording.

-

INT

-

LOSCFG_TRACE_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\). -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 typical development process is as follows: + +1. Configure the macros related to the trace module in the **target_config.h** file. + | Configuration Item| Description| Value| + | -------- | -------- | -------- | + | LOSCFG_KERNEL_TRACE | Whether to enable the trace feature. | YES/NO | + | 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 | + | LOSCFG_TRACE_CLIENT_INTERACT | Whether to enable interaction with Trace IDE (dev tools), including data visualization and process control. | YES/NO | + | LOSCFG_TRACE_FRAME_CORE_MSG | Whether to enable trace of the CPU ID, interruption state, and lock task state. | YES/NO | + | LOSCFG_TRACE_FRAME_EVENT_COUNT | Whether to enable trace of the event sequence number. | YES/NO | + | LOSCFG_TRACE_FRAME_MAX_PARAMS | Specifies the maximum number of parameters for event tracing. | INT | + | LOSCFG_TRACE_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). + +3. (Optional) Call **LOS_TraceStop** to stop trace and **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: -- LOS\_TraceReset —— trace\_reset -- LOS\_TraceEventMaskSet —— trace\_mask -- LOS\_TraceStart —— trace\_start -- LOS\_TraceStop —— trace\_stop -- LOS\_TraceRecordDump —— trace\_dump +- LOS_TraceReset —— trace_reset + +- LOS_TraceEventMaskSet —— trace_mask + +- LOS_TraceStart —— trace_start + +- LOS_TraceStop —— trace_stop + +- LOS_TraceRecordDump —— trace_dump + ### Development Example This example implements the following: -1. Create a trace task. -2. Set the event mask. -3. Start trace. -4. Stop trace. -5. Output trace data in the specified format. +1. Create a trace task. + +2. Set the event mask. + +3. Start trace. + +4. Stop trace. + +5. Output trace data in the specified format. + ### Sample Code 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**. + + ``` #include "los_trace.h" UINT32 g_traceTestTaskId; @@ -288,21 +193,21 @@ VOID Example_Trace(VOID) dprintf("trace start error\n"); return; } - /* Trigger a task switching event.*/ + /* Trigger a task switching event. */ LOS_TaskDelay(1); LOS_TaskDelay(1); LOS_TaskDelay(1); - /* Stop trace.*/ + /* Stop trace. */ LOS_TraceStop(); LOS_TraceRecordDump(FALSE); } -UINT32 Example_Trace_test(VOID){ +UINT32 ExampleTraceTest(VOID){ UINT32 ret; - TSK_INIT_PARAM_S traceTestTask; - /* Create a trace task. */ + TSK_INIT_PARAM_S traceTestTask = { 0 }; + /* Create a trace task. */ memset(&traceTestTask, 0, sizeof(TSK_INIT_PARAM_S)); traceTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Trace; - traceTestTask.pcName = "TestTraceTsk"; /* Trace task name*/ + traceTestTask.pcName = "TestTraceTsk"; /* Trace task name. */ traceTestTask.uwStackSize = 0x800; traceTestTask.usTaskPrio = 5; traceTestTask.uwResved = LOS_TASK_STATUS_DETACHED; @@ -311,21 +216,23 @@ UINT32 Example_Trace_test(VOID){ dprintf("TraceTestTask create failed .\n"); return LOS_NOK; } - /* Trace is started by default. Therefore, you can stop trace, clear the buffer, and then restart trace. */ + /* Trace is started by default. You can stop trace, clear the buffer, and restart trace. */ LOS_TraceStop(); LOS_TraceReset(); - /* Enable trace of the Task module events. */ + /* Enable trace of the Task module events. */ LOS_TraceEventMaskSet(TRACE_TASK_FLAG); return LOS_OK; } ``` + ### Verification The output is as follows: + ``` -*******TraceInfo begin******* +***TraceInfo begin*** clockFreq = 50000000 CurEvtIndex = 7 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 6 0x3706f804 0x45 0x1 0x0 0x1f 0x4 0x0 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. -- **EventType**: event type. For details, see **enum LOS\_TRACE\_TYPE** in the header file **los\_trace.h**. -- **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**. +- **EventType**: event type. For details, see **enum LOS_TRACE_TYPE** in the header file **los_trace.h**. + +- **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**. The following uses output No. 0 as an example. + ``` Index Time(cycles) EventType CurTask Identity params 0 0x366d5e88 0x45 0x1 0x0 0x1f 0x4 ``` -- **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. -- For details about the meanings of **Identity** and **params**, see the **TASK\_SWITCH\_PARAMS** macro. +- **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. + +- For details about the meanings of **Identity** and **params**, see the **TASK_SWITCH_PARAMS** macro. + + ``` #define TASK_SWITCH_PARAMS(taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus) \ taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus ``` -Because of **\#TYPE\#\_PARAMS\(IDENTITY, parma1...\) IDENTITY, ...**, **Identity** is **taskId \(0x0\)** and the first parameter is **oldPriority \(0x1f\)**. - ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->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**. + **Identity** is **taskId (0x0)**, and the first parameter is **oldPriority (0x1f)**. +> **NOTE**
+> 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. +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**. diff --git a/en/device-dev/kernel/kernel-small-apx-bitwise.md b/en/device-dev/kernel/kernel-small-apx-bitwise.md index a3760fc0c586a410de798654e2d4c3f75c2c39ce..7d2021ff322d40f8bccd7ad3cccb8742b0de1503 100644 --- a/en/device-dev/kernel/kernel-small-apx-bitwise.md +++ b/en/device-dev/kernel/kernel-small-apx-bitwise.md @@ -1,80 +1,42 @@ # Bitwise Operation - ## Basic Concepts -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. - -## 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. - -**Table 1** Bitwise operation module APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Setting the flag bit to 1 or 0

-

LOS_BitmapSet

-

Sets a flag bit of a PSW to 1.

-

LOS_BitmapClr

-

Sets a flag bit of a PSW to 0.

-

Obtaining the bit whose flag bit is 1

-

LOS_HighBitGet

-

Obtains the most significant bit of 1 in the PSW.

-

LOS_LowBitGet

-

Obtains the least significant bit of 1 in the PSW.

-

Operating continuous bits

-

LOS_BitmapSetNBits

-

Sets the continuous flag bits of a PSW to 1.

-

LOS_BitmapClrNBits

-

Sets the continuous flag bits of a PSW to 0.

-

LOS_BitmapFfz

-

Obtains the first 0 bit starting from the least significant bit (LSB).

-
- -## Development Example - -### Example Description +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** + +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. + + **Table 1** APIs of the bitwise operation module + +| Category | API Description | +| -------- | -------- | +| Setting a flag bit| - **LOS_BitmapSet**: sets a flag bit of a PSW to **1**.
- **LOS_BitmapClr**: sets a flag bit of a PSW to **0**. | +| Obtaining the bit whose flag bit is **1**| -**LOS_HighBitGet**: obtains the most significant bit of 1 in a PSW.
- **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**.
- **LOS_BitmapClrNBits**: sets the consecutive flag bits of a PSW to **0**.
- **LOS_BitmapFfz**: obtains the first 0 bit starting from the LSB. | + + +## Development Example + + +### Example Description This example implements the following: -1. Set a flag bit to **1**. -2. Obtain the most significant bit of flag bit 1. -3. Set a flag bit to **0**. -4. Obtain the least significant bit of the flag bit 1. +1. Set a flag bit to **1**. + +2. Obtain the MSB of flag bit 1. + +3. Set a flag bit to **0**. + +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**. ``` #include "los_bitmap.h" @@ -105,10 +67,12 @@ static UINT32 BitSample(VOID) } ``` + ### Verification The development is successful if the return result is as follows: + ``` Bitmap Sample! The flag is 0x10101010 @@ -117,4 +81,3 @@ LOS_HighBitGet:The highest one bit is 28, the flag is 0x10101110 LOS_BitmapClr: pos : 28, the flag is 0x00101110 LOS_LowBitGet: The lowest one bit is 4, the flag is 0x00101110 ``` - diff --git a/en/device-dev/kernel/kernel-small-apx-dll.md b/en/device-dev/kernel/kernel-small-apx-dll.md index e33e8e55d65e6a5e39fbb33e154557e2751148e9..1baa754b958dfbc5613eb7058e8ed4e24edfa376 100644 --- a/en/device-dev/kernel/kernel-small-apx-dll.md +++ b/en/device-dev/kernel/kernel-small-apx-dll.md @@ -8,19 +8,18 @@ A doubly linked list (DLL) is a linked data structure that consists of a set of ## Available APIs -The table below describes the DLL APIs. For more details about the APIs, see the API reference. - -| **Category**| **API**| -| -------- | -------- | -| Initializing a DLL| - **LOS_ListInit**: initializes a node as a DLL node.
- **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.
- **LOS_ListHeadInsert**: same as **LOS_ListAdd**.
- **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.
- **LOS_ListHeadInsertList**: inserts the head of a DLL to the head of this DLL.
- **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.
- **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.
- **LOS_DL_LIST_IS_END**: checks whether a node is the tail of the DLL.
- **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.
- **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.
- **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.
- **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.
- **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.
- **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.
- **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.| - +The table below describes APIs available for the DLL. For more details about the APIs, see the API reference. + +| Category | API Description | +| ------------------------ | ------------------------------------------------------------ | +| Initializing a DLL | - **LOS_ListInit**: initializes a node as a DLL node.
- **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.
- **LOS_ListHeadInsert**: same as **LOS_ListAdd**.
- **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.
- **LOS_ListHeadInsertList**: inserts the head of a DLL to the head of this DLL.
- **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.
- **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.
- **LOS_DL_LIST_IS_END**: checks whether a node is the tail of the DLL.
- **LOS_DL_LIST_IS_ON_QUEUE**: checks whether a node is in the DLL.| +| 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.
- **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.
- **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.
- **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.
- **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.
- **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 a DLL| - **LOS_DL_LIST_FOR_EACH_ENTRY**: traverses a DLL and obtains the address of the structure that contains the linked list node.
- **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 @@ -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. -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. @@ -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. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> - Pay attention to the operations operations of the front and back pointer of the node. -> +> **NOTE**
+> +> - 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. -> +> > - 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: @@ -63,7 +63,11 @@ This example implements the following: 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 sample code is as follows: ``` #include "stdio.h" @@ -109,6 +113,8 @@ static UINT32 ListSample(VOID) The development is successful if the return result is as follows: + + ``` Initial head Add listNode1 success diff --git a/en/device-dev/kernel/kernel-small-apx-library.md b/en/device-dev/kernel/kernel-small-apx-library.md index c99d339880983a28403409a2caf157a20875c47b..dbbc0a9d9b872a5a0fe0a2c703c1d8783d05b59f 100644 --- a/en/device-dev/kernel/kernel-small-apx-library.md +++ b/en/device-dev/kernel/kernel-small-apx-library.md @@ -1,45 +1,49 @@ # Standard Library -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. + ## Standard Library API Framework -**Figure 1** POSIX framework +**Figure 1** POSIX framework + ![](figures/posix-framework.png "posix-framework") 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. -## 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 #include #include -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif /* __cplusplus */ -#endif /* __cplusplus */ - #define THREAD_NUM 3 -int g_startNum = 0; /* Number of started threads */ -int g_wakenNum = 0; /* Number of wakeup threads */ +int g_startNum = 0; /* Number of threads to start */ +int g_wakenNum = 0; /* Number of threads to wake up */ struct testdata { pthread_mutex_t mutex; pthread_cond_t cond; } g_td; -/* - * Entry function of child threads. - */ -static void *ChildThreadFunc(void *arg) +/* Entry function of the child thread */ +static VOID *ChildThreadFunc(VOID *arg) { int rc; pthread_t self = pthread_self(); @@ -47,17 +51,17 @@ static void *ChildThreadFunc(void *arg) /* Acquire a mutex. */ rc = pthread_mutex_lock(&g_td.mutex); if (rc != 0) { - printf("ERROR:take mutex lock failed, error code is %d!\n", rc); + dprintf("ERROR:take mutex lock failed, error code is %d!\n", rc); goto EXIT; } /* The value of g_startNum is increased by 1. The value indicates the number of child threads that have acquired a mutex. */ g_startNum++; - /* Wait for the cond variable. */ + /* Wait for the cond variable. */ rc = pthread_cond_wait(&g_td.cond, &g_td.mutex); if (rc != 0) { - printf("ERROR: pthread condition wait failed, error code is %d!\n", rc); + dprintf("ERROR: pthread condition wait failed, error code is %d!\n", rc); (void)pthread_mutex_unlock(&g_td.mutex); goto EXIT; } @@ -65,52 +69,53 @@ static void *ChildThreadFunc(void *arg) /* Attempt to acquire a mutex, which is failed in normal cases. */ rc = pthread_mutex_trylock(&g_td.mutex); if (rc == 0) { - printf("ERROR: mutex gets an abnormal lock!\n"); + dprintf("ERROR: mutex gets an abnormal lock!\n"); goto EXIT; } /* The value of g_wakenNum is increased by 1. The value indicates the number of child threads that have been woken up by the cond variable. */ g_wakenNum++; - /* Unlock a mutex. */ + /* Release a mutex. */ rc = pthread_mutex_unlock(&g_td.mutex); if (rc != 0) { - printf("ERROR: mutex release failed, error code is %d!\n", rc); + dprintf("ERROR: mutex release failed, error code is %d!\n", rc); goto EXIT; } EXIT: return NULL; } -static int testcase(void) +static int ExamplePosix(VOID) { int i, rc; pthread_t thread[THREAD_NUM]; - /* Initialize a mutex. */ + /* Initialize the mutex. */ rc = pthread_mutex_init(&g_td.mutex, NULL); if (rc != 0) { - printf("ERROR: mutex init failed, error code is %d!\n", rc); + dprintf("ERROR: mutex init failed, error code is %d!\n", rc); goto ERROROUT; } /* Initialize the cond variable. */ rc = pthread_cond_init(&g_td.cond, NULL); if (rc != 0) { - printf("ERROR: pthread condition init failed, error code is %d!\n", rc); + dprintf("ERROR: pthread condition init failed, error code is %d!\n", rc); goto ERROROUT; } - /* Create child threads in batches. The number is specified by THREAD_NUM. */ + /* Create child threads in batches. */ for (i = 0; i < THREAD_NUM; i++) { rc = pthread_create(&thread[i], NULL, ChildThreadFunc, NULL); if (rc != 0) { - printf("ERROR: pthread create failed, error code is %d!\n", rc); + dprintf("ERROR: pthread create failed, error code is %d!\n", rc); 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) { usleep(100); } @@ -118,14 +123,14 @@ static int testcase(void) /* Acquire a mutex and block all threads using pthread_cond_wait. */ rc = pthread_mutex_lock(&g_td.mutex); 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; } - /* Release a mutex. */ + /* Release the mutex. */ rc = pthread_mutex_unlock(&g_td.mutex); 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; } @@ -133,7 +138,7 @@ static int testcase(void) /* Broadcast signals on the cond variable. */ rc = pthread_cond_signal(&g_td.cond); 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; } } @@ -142,73 +147,69 @@ static int testcase(void) /* Check whether all child threads are woken up. */ 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; } + 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++) { rc = pthread_join(thread[i], NULL); 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; } } + dprintf("all threads join ok\n"); /* Destroy the cond variable. */ rc = pthread_cond_destroy(&g_td.cond); 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; } return 0; ERROROUT: return -1; } +``` -/* - * Main function - */ -int main(int argc, char *argv[]) -{ - int rc; +#### Verification - /* Start the test function. */ - rc = testcase(); - if (rc != 0) { - printf("ERROR: testcase failed!\n"); - } + The output is as follows: - return 0; -} -#ifdef __cplusplus -#if __cplusplus -} -#endif /* __cplusplus */ -#endif /* __cplusplus */ +``` +pthread_create ok +all threads awaked +all threads join ok ``` ## 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 -1. 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 processes support only static priorities, which range from 10 (highest) to 31 (lowest). + +- 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 -**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. +**Example** -**h2****Sample Code** -Linux OS: +Linux: ``` int main(int argc, char *argv[]) @@ -226,13 +227,14 @@ int main(int argc, char *argv[]) perror("mmap"); 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); } ``` -OpenHarmony: + + OpenHarmony: ``` int main(int argc, char *argv[]) @@ -252,27 +254,32 @@ int main(int argc, char *argv[]) } ... munmap(addr, length); - close(fd); /* Close fd after the munmap is canceled. */ + close(fd); /* Close fd after the munmap is canceled. */ exit(EXIT_SUCCESS); } ``` + ### 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 -- 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. -- 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. +- The default behavior for signals does not include **STOP**, **CONTINUE**, or **COREDUMP**. -### Time +- 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. -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. +- 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 invoked only once even if the same signal is received multiple times. + + +### 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. diff --git a/en/device-dev/kernel/kernel-small-basic-atomic.md b/en/device-dev/kernel/kernel-small-basic-atomic.md index 12045b51bfb493d204ddde26a55c9f8bc29a28d7..2e90511144127670e55af081dc07d6e10fd76cf3 100644 --- a/en/device-dev/kernel/kernel-small-basic-atomic.md +++ b/en/device-dev/kernel/kernel-small-basic-atomic.md @@ -3,216 +3,98 @@ ## Basic Concepts -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. - -- LDREX Rx, \[Ry\] - - 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. - - Adds an exclusive access flag to the memory area pointed by **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. +## Working Principles - - If there is an exclusive access flag, the system: - - Updates the **Rx** register value to the memory pointed to by the **Ry** register. - - Sets the **Rf** register to **0**. +OpenHarmony has encapsulated the **LDREX** and **STREX** in the ARMv6 architecture to provide a set of atomic operation APIs. - - If there is no exclusive access flag: - - The memory is not updated. - - The system sets the **Rf** register to **1**. +- LDREX Rx, [Ry] + 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. + - Adds an exclusive access flag to the memory area pointed by **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. + - If there is an exclusive access flag, the system: + - Updates the **Rx** register value to the memory pointed to by the **Ry** register. + - Sets the **Rf** register to **0**. + - If there is no exclusive access flag: + - The memory is not updated. + - The system sets the **Rf** register to **1**. -- Flag register - - 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. +- Flag register + - 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. ## Development Guidelines + ### 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. - -**Table 1** Atomic operation APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Read

-

LOS_AtomicRead

-

Reads 32-bit atomic data.

-

LOS_Atomic64Read

-

Reads 64-bit atomic data.

-

Write

-

LOS_AtomicSet

-

Sets 32-bit atomic data.

-

LOS_Atomic64Set

-

Sets 64-bit atomic data.

-

Add

-

LOS_AtomicAdd

-

Adds 32-bit atomic data.

-

LOS_Atomic64Add

-

Adds 64-bit atomic data.

-

LOS_AtomicInc

-

Adds 1 to 32-bit atomic data.

-

LOS_Atomic64Inc

-

Adds 1 to 64-bit atomic data.

-

LOS_AtomicIncRet

-

Adds 1 to 32-bit atomic data and returns the data.

-

LOS_Atomic64IncRet

-

Adds 1 to 64-bit atomic data and returns the data.

-

Subtract

-

LOS_AtomicSub

-

Performs subtraction on 32-bit atomic data.

-

LOS_Atomic64Sub

-

Performs subtraction on 64-bit atomic data.

-

LOS_AtomicDec

-

Subtracts 1 from 32-bit atomic data.

-

LOS_Atomic64Dec

-

Subtracts 1 from 64-bit atomic data.

-

LOS_AtomicDecRet

-

Subtracts 1 from 32-bit atomic data and returns the result.

-

LOS_Atomic64DecRet

-

Subtracts 1 from 64-bit atomic data and returns the result.

-

Swap

-

LOS_AtomicXchgByte

-

Swaps 8-bit memory data.

-

LOS_AtomicXchg16bits

-

Swaps 16-bit memory data.

-

LOS_AtomicXchg32bits

-

Swaps 32-bit memory data.

-

LOS_AtomicXchg64bits

-

Swaps 64-bit memory data.

-

Compare and swap

-

LOS_AtomicCmpXchgByte

-

Compares and swaps 8-bit memory data.

-

LOS_AtomicCmpXchg16bits

-

Compares and swaps 16-bit memory data.

-

LOS_AtomicCmpXchg32bits

-

Compares and swaps 32-bit memory data.

-

LOS_AtomicCmpXchg64bits

-

Compares and swaps 64-bit memory data.

-
+The following table describes the APIs available for the OpenHarmony LiteOS-A kernel atomic operation module. + +**Table 1** APIs for atomic operations + +| Category | API | Description | +| ------------ | ----------------------- | --------------------------- | +| Read | LOS_AtomicRead | Reads 32-bit atomic data. | +| Read | LOS_Atomic64Read | Reads 64-bit atomic data. | +| Write | LOS_AtomicSet | Sets 32-bit atomic data. | +| Write | LOS_Atomic64Set | Sets 64-bit atomic data. | +| Add | LOS_AtomicAdd | Adds 32-bit atomic data. | +| Add | LOS_Atomic64Add | Adds 64-bit atomic data. | +| Add | LOS_AtomicInc | Adds 1 to 32-bit atomic data. | +| Add | LOS_Atomic64Inc | Adds 1 to 64-bit atomic data. | +| Add | LOS_AtomicIncRet | Adds 1 to 32-bit atomic data and returns the data. | +| Add | LOS_Atomic64IncRet | Adds 1 to 64-bit atomic data and returns the data. | +| Subtract | LOS_AtomicSub | Performs subtraction on 32-bit atomic data. | +| Subtract | LOS_Atomic64Sub | Performs subtraction on 64-bit atomic data. | +| Subtract | LOS_AtomicDec | Subtracts 1 from 32-bit atomic data. | +| Subtract | LOS_Atomic64Dec | Subtracts 1 from 64-bit atomic data. | +| Subtract | LOS_AtomicDecRet | Subtracts 1 from 32-bit atomic data and returns the result. | +| Subtract | LOS_Atomic64DecRet | Subtracts 1 from 64-bit atomic data and returns the result. | +| Swap | LOS_AtomicXchgByte | Swaps 8-bit memory data. | +| Swap | LOS_AtomicXchg16bits | Swaps 16-bit memory data. | +| Swap | LOS_AtomicXchg32bits | Swaps 32-bit memory data. | +| Swap | LOS_AtomicXchg64bits | Swaps 64-bit memory data. | +| Compare and swap| LOS_AtomicCmpXchgByte | Compares and swaps 8-bit memory data. | +| Compare and swap| LOS_AtomicCmpXchg16bits | Compares and swaps 16-bit memory data.| +| Compare and swap| LOS_AtomicCmpXchg32bits | Compares and swaps 32-bit memory data.| +| Compare and swap| LOS_AtomicCmpXchg64bits | Compares and swaps 64-bit memory data.| + ### 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. ->![](../public_sys-resources/icon-note.gif) **NOTE**
->Atomic operation APIs support only integer data. +> **NOTE**
+> Atomic operation APIs support only integers. + -### Development Example +### Development Example -Example Description +**Example Description** Call the atomic operation APIs and observe the result. -1. Create two tasks. - - Task 1: Call **LOS\_AtomicInc** to add the global variables 100 times. - - Task 2: Call **LOS\_AtomicDec** to subtract the global variables 100 times. +1. Create two tasks. + - Task 1: Call **LOS_AtomicInc** to add a global variable 100 times. + - Task 2: Call **LOS_AtomicDec** to subtract a global variable 100 times. -2. After the subtasks are complete, print the values of the global variables in the main task. +2. After the subtasks are complete, print the values of the global variable in the main task. **Sample Code** The sample code is as follows: + ``` #include "los_hwi.h" #include "los_atomic.h" @@ -275,7 +157,7 @@ UINT32 Example_AtomicTaskEntry(VOID) **Verification** + ``` g_sum = 0 ``` - diff --git a/en/device-dev/kernel/kernel-small-basic-interrupt.md b/en/device-dev/kernel/kernel-small-basic-interrupt.md index b84a71b17ddd6c99f9278514a7c514bfc4bc5781..b22e5e78ff75cf72ec14352aa7a37129b4f4e9ee 100644 --- a/en/device-dev/kernel/kernel-small-basic-interrupt.md +++ b/en/device-dev/kernel/kernel-small-basic-interrupt.md @@ -1,132 +1,131 @@ # Interrupt and Exception Handling -## Basic Concepts +## Basic Concepts 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 ++ 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. -**Figure 1** Interrupt vector table +**Figure 1** Interrupt vector table + ![](figures/interrupt-vector-table.png "interrupt-vector-table") -## Development Guidelines - -### Available APIs - -Exception handling is an internal mechanism and does not provide external APIs. The following table describes APIs available for the interrupt module. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Creating or deleting interrupts

-

LOS_HwiCreate

-

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.

-

LOS_HwiDelete

-

Deletes an interrupt.

-

Enabling and disabling all interrupts

-

LOS_IntUnLock

-

Enables all interrupts of the current processor.

-

LOS_IntLock

-

Disables all interrupts for the current processor.

-

LOS_IntRestore

-

Restores to the status before all interrupts are disabled by using LOS_IntLock.

-

Obtaining the maximum number of interrupts supported

-

LOS_GetSystemHwiMaximum

-

Obtains the maximum number of interrupts supported by the system.

-
- -### How to Develop - -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 + +## Development Guidelines + + +### Available APIs + +Exception handling is an internal mechanism and does not provide external APIs. The following tables describe the APIs available for the interrupt module. + +##### Creating or Deleting an Interrupt + +| API | Description | +|------------ | ----------------------------------------------------------- | +| 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.| +| LOS_HwiDelete | Deletes an interrupt based on the interrupt number. | + +##### Enabling or Disabling Interrupts + +| API | Description | +| -------------- | ------------------------------------------- | +| LOS_IntUnlock | Enables all interrupts for the current processor. | +| LOS_IntLock | Disables all interrupts for the current processor. | +| LOS_IntRestore | Restores the status in which the system was before **LOS_IntLock** is called.| + +##### Obtaining Interrupt Information + +| API | Description | +| ----------------------- | ------------------------ | +| LOS_GetSystemHwiMaximum | Obtains the maximum number of interrupts supported by the system.| + + + +### How to Develop + +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 + This example implements the following: -1. Create 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. +1. Create an interrupt. -``` +2. Delete an interrupt. + +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" /* Interrupt handler function*/ STATIC VOID HwiUsrIrq(VOID) { - printf("in the func HwiUsrIrq \n"); + PRINTK("in the func HwiUsrIrq \n"); } static UINT32 Example_Interrupt(VOID) { UINT32 ret; - HWI_HANDLE_T hwiNum = 7; - HWI_PRIOR_T hwiPrio = 3; + HWI_HANDLE_T hwiNum = 7; // The interrupt number is 7. + HWI_PRIOR_T hwiPrio = 3; // The interrupt priority is 3. HWI_MODE_T mode = 0; HWI_ARG_T arg = 0; -/* Create an interrupt.*/ + /* Create an interrupt. */ ret = LOS_HwiCreate(hwiNum, hwiPrio, mode, (HWI_PROC_FUNC)HwiUsrIrq, (HwiIrqParam *)arg); - if(ret == LOS_OK){ - printf("Hwi create success!\n"); + if (ret == LOS_OK) { + PRINTK("Hwi create success!\n"); } else { - printf("Hwi create failed!\n"); + PRINTK("Hwi create failed!\n"); return LOS_NOK; } - /* Delay 50 ticks. When a hardware interrupt occurs, call the HwiUsrIrq function.*/ + /* Delay 50 ticks. Call HwiUsrIrq when a hardware interrupt occurs. */ LOS_TaskDelay(50); - /* Delete an interrupt./ - ret = LOS_HwiDelete(hwiNum, (HwiIrqParam *)arg); - if(ret == LOS_OK){ - printf("Hwi delete success!\n"); + /* Delete the interrupt. */ + ret = LOS_HwiDelete(hwiNum, (HwiIrqParam *)arg); + if (ret == LOS_OK) { + PRINTK("Hwi delete success!\n"); } else { - printf("Hwi delete failed!\n"); + PRINTK("Hwi delete failed!\n"); return LOS_NOK; } return LOS_OK; } ``` -### Verification + +### Verification The development is successful if the return result is as follows: @@ -134,4 +133,3 @@ The development is successful if the return result is as follows: Hwi create success! Hwi delete success! ``` - diff --git a/en/device-dev/kernel/kernel-small-basic-process-process.md b/en/device-dev/kernel/kernel-small-basic-process-process.md index 413951926be6282146304660a198bc0546014067..33847a3d95060948d7737a5ed8cbff9a5c76b7cc 100644 --- a/en/device-dev/kernel/kernel-small-basic-process-process.md +++ b/en/device-dev/kernel/kernel-small-basic-process-process.md @@ -1,64 +1,66 @@ # Process -## Basic Concepts +## Basic Concepts -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 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\). -- 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. -- 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 process module provides multiple processes for users and implements switching and communication between processes, facilitating your management over service programs. -**Process States:** +- 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. -- Init: The process is being created. +- 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). -- Ready: The process is in the Ready queue and waits for scheduling by the CPU. -- 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. -- Zombies: The process stops running and waits for the parent process to reclaim its control block resources. +- 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. -**Figure 1** Process state transition -![](figures/process-state-transition.png "process-state-transition") +- Each user-mode process has its own memory space, which is invisible to other processes. In this way, processes are isolated from each other. -**Process State Transition:** +- 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. -- Init→Ready: +**Process States** - 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: The process is being created. -- Ready→Running: +- Ready: The process is in the Ready queue and waits for scheduling by the CPU. - 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: The process is running. -- Running→Pending: +- Pending: The process is blocked and suspended. When all threads in a process are blocked, the process is blocked and suspended. - 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. +- Zombies: The process stops running and waits for the parent process to reclaim its control block resources. -- Pending→Ready: + **Figure 1** Process state transition - 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. + ![](figures/process-state-transition.png "process-state-transition") -- Ready→Pending: +**Process State Transition** - 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. +- 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. -- Running→Ready: +- 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. - A process may change from the Running state to the Ready state in either of the following scenarios: +- 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. - 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. +- 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. -- Running→Zombies: +- 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. - 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. +- Running→Ready: + 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. + 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. -## Working Principles +- 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. + + +## 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. @@ -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. -**Figure 2** Process management +**Figure 2** Process management + ![](figures/process-management.png "process-management") -## Development Guidelines - -### Available APIs - -**Table 1** Process management module APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Process scheduling parameter control

-

LOS_GetProcessScheduler

-

Obtains the scheduling policy of the specified process.

-

LOS_SetProcessScheduler

-

Sets the scheduling parameters, including the priority and scheduling policy, for the specified process.

-

LOS_GetProcessPriority

-

Obtains the priority of the specified process.

-

LOS_SetProcessPriority

-

Sets the priority of the specified process.

-

Waiting for reclaiming child processes

-

LOS_Wait

-

Waits for the specified child process to terminate, and reclaims its resources.

-

Process group

-

LOS_GetProcessGroupID

-

Obtains the process group ID of the specified process.

-

LOS_GetCurrProcessGroupID

-

Obtains the process group ID of the current process.

-

Obtaining the process ID.

-

LOS_GetCurrProcessID

-

Obtains the ID of the current process.

-

User and user group

-

LOS_GetUserID

-

Obtains the user ID of the current process.

-

LOS_GetGroupID

-

Obtains the user group ID of the current process.

-

LOS_CheckInGroups

-

Checks whether the specified user group ID is in the user group of the current process.

-

Maximum number of processes supported

-

LOS_GetSystemProcessMaximum

-

Obtains the maximum number of processes supported by the system.

-
- -### How to Develop -Kernel-mode processes cannot be created. Therefore, kernel-mode process development is not involved. +## Development Guidelines + + +### Available APIs + +**Table 1** APIs for processes and process groups + +| API | Description | +| ------------------------- | ---------------------- | +| LOS_GetCurrProcessID | Obtains the ID of the current process. | +| LOS_GetProcessGroupID | Obtains the process group ID of the specified process.| +| LOS_GetCurrProcessGroupID | Obtains the process group ID of the current process.| + +**Table 2** APIs for users and user groups + +| API | Description | +| ----------------- | ---------------------------------------- | +| LOS_GetUserID | Obtains the user ID of the current process. | +| LOS_GetGroupID | Obtains the user group ID of the current process. | +| LOS_CheckInGroups | Checks whether the specified user group ID is in the user group of the current process.| ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->- 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. ->- 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. +**Table 3** APIs for process scheduling + +| API | API | +| ----------------------- | -------------------------------------------- | +| LOS_GetProcessScheduler | Obtains the scheduling policy of a process. | +| LOS_SetProcessScheduler | Sets scheduling parameters, including the priority and scheduling policy, for a process.| +| LOS_SetProcessPriority | Sets the process priority. | +| LOS_GetProcessPriority | Obtains the priority of a process. | + +**Table 4** APIs for obtaining system process information + +| API | Description | +| --------------------------- | -------------------------- | +| LOS_GetSystemProcessMaximum | Obtains the maximum number of processes supported by the system.| +| LOS_GetUsedPIDList | Obtains a list of used process IDs. | + +**Table 5** APIs for managing processes + +| API | Description | +| ---------- | -------------------------- | +| LOS_Fork | Creates a child process. | +| LOS_Wait | Waits for the child process to terminate, and reclaims its resources.| +| LOS_Waitid | Wait for the specified process to terminate. | +| LOS_Exit | Exits a process. | + + + +### How to Develop + +Kernel-mode processes cannot be created. Therefore, kernel-mode process development is not involved. +> **NOTE** +> +> - 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. +> - 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. diff --git a/en/device-dev/kernel/kernel-small-basic-process-scheduler.md b/en/device-dev/kernel/kernel-small-basic-process-scheduler.md index fdd199036e7bcb51cbdd57e52bdce0b273fec998..8af7150bd3ced5e5c914edf340f79ec238246cca 100644 --- a/en/device-dev/kernel/kernel-small-basic-process-scheduler.md +++ b/en/device-dev/kernel/kernel-small-basic-process-scheduler.md @@ -1,53 +1,48 @@ # Scheduler -## Basic Concepts +## Basic Concepts 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 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 -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. + +**Figure 1** Scheduling priority bucket queue -**Figure 1** Scheduling priority bucket queue ![](figures/scheduling-priority-bucket-queue.png "scheduling-priority-bucket-queue") 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. -**Figure 2** Scheduling process +**Figure 2** Scheduling process + ![](figures/scheduling-process.png "scheduling-process") -## Development Guidelines - -### Available APIs - - - - - - - - - - - - -

Function

-

API

-

Description

-

System scheduling

-

LOS_Schedule

-

Triggers system scheduling.

-
- -### How to Develop - ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->Scheduling cannot be triggered during the system initialization process. +## Development Guidelines + + +### Available APIs + +| API| Description| +| -------- | -------- | +| LOS_Schedule | Triggers system scheduling.| +| LOS_GetTaskScheduler | Obtains the scheduling policy of a task.| +| LOS_SetTaskScheduler | Sets the scheduling policy for a task.| +| LOS_GetProcessScheduler | Obtains the scheduling policy of a process.| +| LOS_SetProcessScheduler | Sets scheduling parameters, including the priority and scheduling policy, for a process.| + + +### How to Develop + +> **NOTE** +> +> Scheduling cannot be triggered during the system initialization process. diff --git a/en/device-dev/kernel/kernel-small-basic-process-thread.md b/en/device-dev/kernel/kernel-small-basic-process-thread.md index 5631cf62fb43f48d26b5016ac96534e24bdd7f37..96a97e237f8799864e5b9bd4bf01337ab334df56 100644 --- a/en/device-dev/kernel/kernel-small-basic-process-thread.md +++ b/en/device-dev/kernel/kernel-small-basic-process-thread.md @@ -1,315 +1,244 @@ # Task -## Basic Concepts + +## Basic Concepts 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. -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. -**Task Status Description** +**Task States** + +- Init: The task is being created. + +- Ready: The task is in the Ready queue and waits for scheduling by the CPU. + +- 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). + +- Exit: The task is complete and waits for the parent task to reclaim its control block resources. -- Init: The task is being created. -- Ready: The task is in the Ready queue and waits for scheduling by the CPU. -- 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\). -- Exit: The task is complete and waits for the parent task to reclaim its control block resources. + **Figure 1** Task state transition -**Figure 1** Task state transition -![](figures/task-state-transition.png "task-state-transition") + ![](figures/task-state-transition.png "task-state-transition") **Task State Transition** -- Init→Ready: +- Init→Ready: + 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: + 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. -- Ready→Running: +- 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 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. +- 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. -- Running→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 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. +- 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. -- Blocked→Ready: +- 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. - 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: +## Working Principles - 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. +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. -- Running→Ready: +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. - 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: +## Development Guidelines - 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. +### Available APIs -## Working Principles +**Table 1** APIs for creating and deleting a task -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. +| API | Description | +| ------------------ | ------------------------------------------------------------ | +| 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. | +| LOS_TaskCreateOnly | Creates a task and blocks it. The task will not be added to the Ready queue unless it is resumed. | +| LOS_TaskDelete | Deletes a task and reclaims the resources consumed by the task control block and task stack. | + +**Table 2** APIs for controlling task status + +| API | Description | +| --------------- | ------------------------------------------------------------ | +| LOS_TaskResume | Resumes a suspended task. | +| LOS_TaskSuspend | Suspends a task. The suspended task will be removed from the Ready queue. | +| LOS_TaskJoin | Blocks the current task until the specified task is complete, and reclaims its resources. | +| 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.| +| LOS_TaskDelay | Delays the current task for the specified time (number of ticks). | +| LOS_TaskYield | Moves the current task from the queue of the tasks with the same priority to the end of the Ready queue.| + +**Table 3** APIs for task scheduling -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. - -## Development Guidelines - -### Available APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Task creation and deletion

-

LOS_TaskCreateOnly

-

Creates a task and places the task in the Init state without scheduling.

-

LOS_TaskCreate

-

Creates a task and places it in the Init state for scheduling.

-

LOS_TaskDelete

-

Deletes the specified task.

-

Task status control

-

LOS_TaskResume

-

Resumes a suspended task.

-

LOS_TaskSuspend

-

Suspends the specified task.

-

LOS_TaskJoin

-

Suspends this task till the specified task is complete and the task control block resources are reclaimed.

-

LOS_TaskDetach

-

Changes the task attribute from joinable to detach. After the task of the detach attribute is complete, the task control block resources will be automatically reclaimed.

-

LOS_TaskDelay

-

Delays a task.

-

LOS_TaskYield

-

Adjusts the scheduling sequence of tasks that call the task priority.

-

Task scheduling control

-

LOS_TaskLock

-

Locks task scheduling.

-

LOS_TaskUnlock

-

Unlocks task scheduling.

-

Task priority control

-

LOS_CurTaskPriSet

-

Sets the priority for the current task.

-

LOS_TaskPriSet

-

Sets the priority for a specified task.

-

LOS_TaskPriGet

-

Obtains the priority of a specified task.

-

Obtaining task information

-

LOS_CurTaskIDGet

-

Obtains the ID of the current task.

-

LOS_TaskInfoGet

-

Obtains information about the specified task.

-

Binding tasks to CPU cores

-

LOS_TaskCpuAffiSet

-

Binds a specified task to the specified CPU. It is used only in multi-core scenarios.

-

LOS_TaskCpuAffiGet

-

Obtains the core binding information of the specified task. It is used only in multi-core scenarios.

-

Task scheduling parameter control

-

LOS_GetTaskScheduler

-

Obtains the scheduling policy of the specified task.

-

LOS_SetTaskScheduler

-

Sets the scheduling parameters, including the priority and scheduling policy, for the specified task.

-

Maximum number of tasks supported

-

LOS_GetSystemTaskMaximum

-

Obtains the maximum number of tasks supported by the system.

-
- -### How to Develop +| API | Description | +| -------------------- | ------------------------------------------------------------ | +| LOS_TaskLock | Locks task scheduling to prevent task switching. | +| 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. | +| LOS_GetTaskScheduler | Obtains the scheduling policy of a task. | +| LOS_SetTaskScheduler | Sets the scheduling parameters, including the priority and scheduling policy, for a task. | +| LOS_Schedule | Triggers active task scheduling. | + +**Table 4** APIs for obtaining task information + +| API | Description | +| ------------------------ | ------------------------ | +| LOS_CurTaskIDGet | Obtains the ID of the current task. | +| LOS_TaskInfoGet | Obtains task information. | +| LOS_GetSystemTaskMaximum | Obtains the maximum number of tasks supported by the system.| + +**Table 5** APIs for managing task priorities + +| API | Description | +| ----------------- | ------------------------------ | +| LOS_CurTaskPriSet | Sets a priority for the current task.| +| LOS_TaskPriSet | Sets a priority for a task. | +| LOS_TaskPriGet | Obtains the priority of a task. | + +**Table 6** APIs for setting CPU pinning + +| API | Description | +| ------------------ | ------------------------------------------- | +| LOS_TaskCpuAffiSet | Binds a task to the specified CPU core. This API is used only in multi-core CPUs.| +| LOS_TaskCpuAffiGet | Obtains information about the core binding of a task. This API is used only in multi-core CPUs. | + + + +### How to Develop The typical task development process is as follows: -1. Call **LOS\_TaskCreate** to create a task. - - Specify the execution entry function for the task. - - Specifies the task name. - - Specify the task stack size. - - 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-core binding attribute for multi-core environment. +1. Call **LOS_TaskCreate** to create a task. + - Specify the execution entry function for the task. + - Specifies the task name. + - Specify the task stack size. + - 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-core binding attribute for multi-core environment. -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**. +2. Run the service code to implement task scheduling. ->![](../public_sys-resources/icon-note.gif) **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. +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**. -### Development Example +> **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 UINT32 g_taskLoID; -UINT32 g_taskHiID; -#define TSK_PRIOR_HI 4 -#define TSK_PRIOR_LO 5 -UINT32 ExampleTaskHi(VOID) -{ +UINT32 g_taskHiID; +#define TSK_PRIOR_HI 4 +#define TSK_PRIOR_LO 5 +UINT32 ExampleTaskHi(VOID) +{ UINT32 ret; - 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.*/ + PRINTK("Enter TaskHi Handler.\n"); + /* 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); - if (ret != LOS_OK) { + if (ret != LOS_OK) { PRINTK("Delay Task Failed.\n"); - return LOS_NOK; - } - /* After 2 ticks elapse, the task is resumed and executed.*/ - PRINTK("TaskHi LOS_TaskDelay Done.\n"); - /* Suspend the task.*/ - ret = LOS_TaskSuspend(g_taskHiID); + return LOS_NOK; + } + /* After 2 ticks elapse, the task is resumed and executed. */ + PRINTK("TaskHi LOS_TaskDelay Done.\n"); + /* Suspend the task. */ + ret = LOS_TaskSuspend(g_taskHiID); if (ret != LOS_OK) { - PRINTK("Suspend TaskHi Failed.\n"); + PRINTK("Suspend TaskHi Failed.\n"); return LOS_NOK; - } - PRINTK("TaskHi LOS_TaskResume Success.\n"); + } + PRINTK("TaskHi LOS_TaskResume Success.\n"); return LOS_OK; } -/* Entry function of the lower-priority task */ +/* Entry function of the low-priority task. */ UINT32 ExampleTaskLo(VOID) -{ - UINT32 ret; - 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.*/ - ret = LOS_TaskDelay(2); - if (ret != LOS_OK) { - PRINTK("Delay TaskLo Failed.\n"); - return LOS_NOK; - } +{ + UINT32 ret; + PRINTK("Enter TaskLo Handler.\n"); + /* 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); + if (ret != LOS_OK) { + PRINTK("Delay TaskLo Failed.\n"); + return LOS_NOK; + } PRINTK("TaskHi LOS_TaskSuspend Success.\n"); - /* Resume the suspended task g_taskHiID.*/ + /* Resume the suspended task g_taskHiID. */ ret = LOS_TaskResume(g_taskHiID); if (ret != LOS_OK) { PRINTK("Resume TaskHi Failed.\n"); return LOS_NOK; - } - PRINTK("TaskHi LOS_TaskDelete Success.\n"); + } + PRINTK("TaskHi LOS_TaskDelete Success.\n"); return LOS_OK; -} -/* Task test entry function, which is used to create two tasks with different priorities.*/ -UINT32 ExampleTaskCaseEntry(VOID) -{ - UINT32 ret; +} +/* Create two tasks with different priorities in the task test entry function. */ +UINT32 ExampleTaskCaseEntry(VOID) +{ + UINT32 ret; TSK_INIT_PARAM_S initParam = {0}; - /* Lock task scheduling.*/ + /* Lock task scheduling. */ LOS_TaskLock(); PRINTK("LOS_TaskLock() Success!\n"); + /* Parameters used to initialize the high-priority task, the resources of which can be reclaimed by LOS_TaskJoin. */ initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskHi; - initParam.usTaskPrio = TSK_PRIOR_HI; + initParam.usTaskPrio = TSK_PRIOR_HI; initParam.pcName = "HIGH_NAME"; initParam.uwStackSize = LOS_TASK_MIN_STACK_SIZE; initParam.uwResved = LOS_TASK_ATTR_JOINABLE; - /* Create a task with a higher priority. The task will not be executed immediately after being created, because task scheduling is locked.*/ + /* Create a task with higher priority. The task will not be executed immediately after being created, because task scheduling is locked. */ ret = LOS_TaskCreate(&g_taskHiID, &initParam); if (ret != LOS_OK) { LOS_TaskUnlock(); PRINTK("ExampleTaskHi create Failed! ret=%d\n", ret); return LOS_NOK; - } + } PRINTK("ExampleTaskHi create Success!\n"); + /* Parameters used to initialize the low-priority task, which will be automatically destroyed after the task is complete. */ initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskLo; initParam.usTaskPrio = TSK_PRIOR_LO; initParam.pcName = "LOW_NAME"; initParam.uwStackSize = LOS_TASK_MIN_STACK_SIZE; initParam.uwResved = LOS_TASK_STATUS_DETACHED; - /* Create a task with a lower priority. The task will not be executed immediately after being created, because task scheduling is locked.*/ + /* Create a low-priority task. The task will not be executed immediately after being created, because task scheduling is locked. */ ret = LOS_TaskCreate(&g_taskLoID, &initParam); - if (ret!= LOS_OK) { - LOS_TaskUnlock(); + if (ret!= LOS_OK) { + LOS_TaskUnlock(); PRINTK("ExampleTaskLo create Failed!\n"); - return LOS_NOK; - } - PRINTK("ExampleTaskLo create Success!\n"); + return LOS_NOK; + } + PRINTK("ExampleTaskLo create Success!\n"); - /* Unlock task scheduling. The task with the highest priority in the Ready queue will be executed.*/ + /* Unlock task scheduling. The task with the highest priority in the Ready queue will be executed. */ LOS_TaskUnlock(); ret = LOS_TaskJoin(g_taskHiID, NULL); if (ret != LOS_OK) { @@ -319,11 +248,12 @@ UINT32 ExampleTaskCaseEntry(VOID) } while(1){}; return LOS_OK; -} +} ``` The development is successful if the return result is as follows: + ``` LOS_TaskLock() Success! ExampleTaskHi create Success! @@ -336,4 +266,3 @@ TaskHi LOS_TaskResume Success. TaskHi LOS_TaskDelete Success. Join ExampleTaskHi Success! ``` - diff --git a/en/device-dev/kernel/kernel-small-basic-softtimer.md b/en/device-dev/kernel/kernel-small-basic-softtimer.md index daa7ca000027e5723cb9e905b55aa9449ce537c9..959b895ab2949151b18fb1262a767b0879cb831c 100644 --- a/en/device-dev/kernel/kernel-small-basic-softtimer.md +++ b/en/device-dev/kernel/kernel-small-basic-softtimer.md @@ -1,133 +1,119 @@ # Software Timer -## Basic Concepts +## Basic Concepts -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: -- Disabling the software timer using a macro -- Creating a software timer -- Starting a software timer -- Stopping a software timer -- Deleting a software timer -- Obtaining the number of remaining ticks of a software timer +- Disabling the software timer using a macro -## Working Principles +- Creating a software timer -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. +- Starting a software timer + +- Stopping a software timer + +- Deleting a software timer + +- Obtaining the number of remaining ticks of a software timer -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. -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. +## Working Principles -Timer States +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**. -- OS\_SWTMR\_STATUS\_UNUSED +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 timer is not in use. When the timer module is initialized, all timer resources in the system are set to this state. +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\_CREATED +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. + +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. - 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. +A software timer can be in any of the following states: -- OS\_SWTMR\_STATUS\_TICKING +- OS_SWTMR_STATUS_UNUSED + + 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. - Periodic timer: This type of timer periodically triggers timer events until it is manually stopped. - One-shot timer deleted by calling an API -## Development Guidelines - -### Available APIs - -The following table describes APIs available for the OpenHarmony LiteOS-A software timer module. For more details about the APIs, see the API reference. - -**Table 1** Software timer APIs - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Creating or deleting timers

-

LOS_SwtmrCreate

-

Creates a software timer.

-

LOS_SwtmrDelete

-

Deletes a software timer.

-

Starting or stopping timers

-

LOS_SwtmrStart

-

Starts a software timer.

-

LOS_SwtmrStop

-

Stops a software timer.

-

Obtaining remaining ticks of a software timer

-

LOS_SwtmrTimeGet

-

Obtains the number of remaining ticks of a software timer.

-
- -### How to Develop + +## Development Guidelines + + +### Available APIs + +The following table describes the APIs of the software timer module of the OpenHarmony LiteOS-A kernel. + +**Table 1** APIs for software timers + +| Category | Description | +| ---------------------- | ------------------------------------------------------------ | +| Creating or deleting a timer | **LOS_SwtmrCreate**: creates a software timer.
**LOS_SwtmrDelete**: deletes a software timer.| +| Starting or stopping a timer | **LOS_SwtmrStart**: starts a software timer.
**LOS_SwtmrStop**: stops a software timer.| +| Obtaining remaining ticks of a software timer| **LOS_SwtmrTimeGet**: obtains the remaining ticks of a software timer. | + + +### How to Develop The typical development process of software timers is as follows: -1. Configure the software timer. - - 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 **OS\_SWTMR\_HANDLE\_QUEUE\_SIZE** \(maximum length of the software timer queue\). +1. Configure the software timer. + - 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 **OS_SWTMR_HANDLE_QUEUE_SIZE** (maximum length of the software timer queue). + +2. Call **LOS_SwtmrCreate** to create a software timer. + - Create a software timer with the specified timing duration, timeout handling function, and triggering mode. + - Return the function execution result (success or failure). + +3. Call **LOS_SwtmrStart** to start the 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. - - Return the function execution result \(success or failure\). +4. Call **LOS_SwtmrTimeGet** to obtain the remaining number of ticks of 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. +5. Call **LOS_SwtmrStop** to stop the software timer. ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->- 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. +6. Call **LOS_SwtmrDelete** to delete the software timer. -### Development Example +> **NOTE**
+> +> - 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. -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. +### 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** @@ -164,14 +150,14 @@ void Timer_example(void) UINT16 id2; // timer id 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. */ LOS_SwtmrCreate (1000, LOS_SWTMR_MODE_ONCE, Timer1_Callback, &id1, 1); - - /* Create a periodic software timer and execute callback function 2 every 100 ticks. */ + + /* Create a periodic software timer and invoke callback 2 every 100 ticks. */ LOS_SwtmrCreate(100, LOS_SWTMR_MODE_PERIOD, Timer2_Callback, &id2, 1); PRINTK("create Timer1 success\n"); - LOS_SwtmrStart (id1); // Start the one-shot software timer. + LOS_SwtmrStart(id1); // Start the one-shot software timer. dprintf("start Timer1 success\n"); LOS_TaskDelay(200); // Delay 200 ticks. LOS_SwtmrTimeGet(id1, &uwTick); // Obtain the number of remaining ticks of the one-short software timer. @@ -196,6 +182,7 @@ void Timer_example(void) **Output** + ``` create Timer1 success start Timer1 success @@ -226,4 +213,3 @@ tick_last1=2101 g_timercount2 =10 tick_last1=2201 ``` - diff --git a/en/device-dev/kernel/kernel-small-basic-time.md b/en/device-dev/kernel/kernel-small-basic-time.md index c58c25a6c467881bee6b9d4ef72ed8c2d379d8d3..749c684b822f5cb1663f2c1496021832927c6ff6 100644 --- a/en/device-dev/kernel/kernel-small-basic-time.md +++ b/en/device-dev/kernel/kernel-small-basic-time.md @@ -3,85 +3,64 @@ ## Basic Concepts -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. -- **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. + +- Tick - 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 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. -- **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. +## Development Guidelines +Before you start, learn about the system time and the APIs for time management. -The OpenHarmony time management module provides time conversion, statistics, and delay functions to meet users' time requirements. -## Development Guidelines +### Available APIs -The time management module provides APIs to implement conversion between the system running time, ticks, and seconds/milliseconds. +The following table describes APIs for OpenHarmony LiteOS-A time management. For more details about the APIs, see the API reference. -### Available APIs +**Table 1** APIs for time management + +| Category| API Description | +| -------- | ------------------------------------------------------------ | +| Time conversion| **LOS_MS2Tick**: converts milliseconds to ticks.
**LOS_Tick2MS**: converts ticks to milliseconds. | +| Time statistics| **LOS_TickCountGet**: obtains the number of current ticks.
**LOS_CyclePerTickGet**: obtains the number of cycles of each tick.| -The following table describes APIs available for the OpenHarmony LiteOS-A time management. For more details about the APIs, see the API reference. - -**Table 1** APIs of the time management module - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Time conversion

-

LOS_MS2Tick

-

Converts milliseconds into ticks.

-

LOS_Tick2MS

-

Converts ticks into milliseconds.

-

Time statistics

-

LOS_TickCountGet

-

Obtains the current number of ticks.

-

LOS_CyclePerTickGet

-

Obtains the number of cycles per tick.

-
### How to Develop -1. Call APIs to convert time. -2. Call APIs to perform time statistics. +1. Call APIs to convert time. + +2. Call APIs to perform time statistics. + +> **NOTE** +> +> - 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 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. ->![](public_sys-resources/icon-note.gif) **NOTE**
->- 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 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 -**Prerequisites**
+**Prerequisites** + 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]. -- **OS\_SYS\_CLOCK**: system clock, in Hz. +- **LOSCFG_BASE_CORE_TICK_PER_SECOND**: number of ticks/second. The value range is (0, 1000). + +- **OS_SYS_CLOCK**: system clock, in Hz. **Sample Code** @@ -92,15 +71,16 @@ VOID Example_TransformTime(VOID) { UINT32 uwMs; UINT32 uwTick; - uwTick = LOS_MS2Tick(10000);// Convert 10000 ms into ticks. + uwTick = LOS_MS2Tick(10000); // Convert 10000 ms to ticks. PRINTK("uwTick = %d \n",uwTick); - uwMs= LOS_Tick2MS(100); // Convert 100 ticks into ms. + uwMs= LOS_Tick2MS(100); // Convert 100 ticks to ms. PRINTK("uwMs = %d \n",uwMs); } ``` Time statistics and delay: + ``` VOID Example_GetTime(VOID) { @@ -133,6 +113,7 @@ The result is as follows: Time conversion: + ``` uwTick = 10000 uwMs = 100 @@ -140,9 +121,9 @@ uwMs = 100 Time statistics and delay: + ``` LOS_CyclePerTickGet = 49500 -LOS_TickCountGet = 5042 -LOS_TickCountGet after delay = 5242 +LOS_TickCountGet = 347931 +LOS_TickCountGet after delay = 348134 ``` - diff --git a/en/device-dev/kernel/kernel-small-basic-trans-event.md b/en/device-dev/kernel/kernel-small-basic-trans-event.md index 2aba10352fbf9691cb4ab825f00ec28564d14c44..7d478d71a13aebbfa152bebd7832496887ebdfb7 100644 --- a/en/device-dev/kernel/kernel-small-basic-trans-event.md +++ b/en/device-dev/kernel/kernel-small-basic-trans-event.md @@ -1,146 +1,145 @@ # Event -## Basic Concepts -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: -- One-to-many synchronization: A task waits for the triggering of multiple events. A task is woken up by one or multiple events. -- Many-to-many synchronization: Multiple tasks wait for the triggering of 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. 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. -- 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. -- 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. -- Multiple tasks can read and write the same event. -- The event read/write timeout mechanism is supported. +- 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 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. + +- 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. -## Working Principles +- The event read/write timeout mechanism is supported. + + +## Working Principles + + +### Event Control Block -### Event Control Block ``` /** -* Event control block data structure + * Event control block data structure */ typedef struct tagEvent { 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; ``` -### 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. +### 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. -- **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. +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. -**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 -![](figures/event-working-mechanism-for-small-systems.png "event-working-mechanism-for-small-systems") +- **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 +- **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 +**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 + + ![](figures/event-working-mechanism-for-small-systems.png "event-working-mechanism-for-small-systems") + + +## Development Guidelines + + +### Available APIs The following table describes APIs available for the OpenHarmony LiteOS-A event module. -**Table 1** Event module APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Initializing events

-

LOS_EventInit

-

Initializes an event control block.

-

Reading/Writing events

-

LOS_EventRead

-

Reads a specified type of event, with the timeout period of a relative time period in ticks.

-

LOS_EventWrite

-

Writes a specified type of event.

-

Clearing events

-

LOS_EventClear

-

Clears a specified type of event.

-

Checking the event mask

-

LOS_EventPoll

-

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.

-

Destroying events

-

LOS_EventDestroy

-

Destroys a specified event control block.

-
- -### How to Develop +**Table 1** APIs of the event module + +| Category| API Description | +| -------- | -------- | +| Initializing an event| **LOS_EventInit**: initializes an event control block.| +| Reading/Writing an event| - **LOS_EventRead**: reads an event, with a relative timeout period in ticks.
- **LOS_EventWrite**: writes an event. | +| Clearing events| **LOS_EventClear**: clears a specified type of events.| +| Checking the event mask| **LOS_EventPoll**: checks whether the specified event occurs.| +| Destroying events | **LOS_EventDestroy**: destroys an event control block.| + + +### How to Develop The typical event development process is as follows: -1. Initialize an event control block. -2. Block a read event control block. -3. Write related events. -4. Wake up a blocked task, read the event, and check whether the event meets conditions. -5. Handle the event control block. -6. Destroy an event control block. +1. Initialize an event control block. + +2. Block a read event. + +3. Write related events. + +4. Wake up a blocked task, read the event, and check whether the event meets conditions. + +5. Handle the event control block. + +6. Destroy an event control block. + +> **NOTE** +> +> - 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 ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->- 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. +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 +1. Create the **Example_Event** task in the **Example_TaskEntry** task with a higher priority than the **Example_TaskEntry** task. -### Example Description +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. -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. +4. The **Example_Event** task is executed. -### Sample Code +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: @@ -149,28 +148,28 @@ The sample code is as follows: #include "los_task.h" #include "securec.h" -/* Task ID*/ +/* Task ID */ UINT32 g_testTaskId; -/* Event control structure*/ +/* Event control structure */ EVENT_CB_S g_exampleEvent; -/* Type of the wait event*/ -#define EVENT_WAIT 0x00000001 - -/* Example task entry function*/ +/* Type of the wait event */ +#define EVENT_WAIT 0x00000001 +#define EVENT_TIMEOUT 500 +/* Example task entry function */ VOID Example_Event(VOID) { 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.*/ - printf("Example_Event wait event 0x%x \n", EVENT_WAIT); + /* 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. */ + dprintf("Example_Event wait event 0x%x \n", EVENT_WAIT); - event = LOS_EventRead(&g_exampleEvent, EVENT_WAIT, LOS_WAITMODE_AND, 100); + event = LOS_EventRead(&g_exampleEvent, EVENT_WAIT, LOS_WAITMODE_AND, EVENT_TIMEOUT); if (event == EVENT_WAIT) { - printf("Example_Event,read event :0x%x\n", event); + dprintf("Example_Event,read event :0x%x\n", event); } else { - printf("Example_Event,read event timeout\n"); + dprintf("Example_Event,read event timeout\n"); } } @@ -179,14 +178,14 @@ UINT32 Example_EventEntry(VOID) UINT32 ret; TSK_INIT_PARAM_S task1; - /* Initialize the event.*/ + /* Initialize the event. */ ret = LOS_EventInit(&g_exampleEvent); if (ret != LOS_OK) { - printf("init event failed .\n"); + dprintf("init event failed .\n"); return -1; } - /* Create a task.*/ + /* Create a task. */ (VOID)memset_s(&task1, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Event; task1.pcName = "EventTsk1"; @@ -194,39 +193,34 @@ UINT32 Example_EventEntry(VOID) task1.usTaskPrio = 5; ret = LOS_TaskCreate(&g_testTaskId, &task1); if (ret != LOS_OK) { - printf("task create failed.\n"); + dprintf("task create failed.\n"); return LOS_NOK; } /* Write the task wait event (g_testTaskId). */ - printf("Example_TaskEntry write event.\n"); + dprintf("Example_TaskEntry write event.\n"); ret = LOS_EventWrite(&g_exampleEvent, EVENT_WAIT); if (ret != LOS_OK) { - printf("event write failed.\n"); + dprintf("event write failed.\n"); return LOS_NOK; } - /* Clear the flag.*/ - printf("EventMask:%d\n", g_exampleEvent.uwEventID); + /* Clear the flag. */ + dprintf("EventMask:%d\n", g_exampleEvent.uwEventID); LOS_EventClear(&g_exampleEvent, ~g_exampleEvent.uwEventID); - printf("EventMask:%d\n", g_exampleEvent.uwEventID); - - /* Delete the task.*/ - ret = LOS_TaskDelete(g_testTaskId); - if (ret != LOS_OK) { - printf("task delete failed.\n"); - return LOS_NOK; - } + dprintf("EventMask:%d\n", g_exampleEvent.uwEventID); return LOS_OK; } ``` -### Verification + +### Verification The development is successful if the return result is as follows: + ``` Example_Event wait event 0x1 Example_TaskEntry write event. @@ -234,4 +228,3 @@ Example_Event,read event :0x1 EventMask:1 EventMask:0 ``` - diff --git a/en/device-dev/kernel/kernel-small-basic-trans-mutex.md b/en/device-dev/kernel/kernel-small-basic-trans-mutex.md index a911f97e1f894004b5cf48fea296982fe1d4d9b5..890215f8ec70319ae7875c34180e03ce769e9e24 100644 --- a/en/device-dev/kernel/kernel-small-basic-trans-mutex.md +++ b/en/device-dev/kernel/kernel-small-basic-trans-mutex.md @@ -1,196 +1,114 @@ # Mutex +## Basic Concepts -## Basic Concepts - -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: -- 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 + + 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\_INHERIT +- 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. + + 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: - 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_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. -- LOS\_MUX\_PRIO\_PROTECT +- 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. - 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. +- LOS_MUX_ERRORCHECK + + 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. -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: +## Working Principles -- LOS\_MUX\_NORMAL +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. - 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. +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. -- LOS\_MUX\_RECURSIVE +**Figure 1** Mutex working mechanism for the small system - 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. +![](figures/mutex-working-mechanism-for-small-systems.png "mutex-working-mechanism-for-small-systems") -- 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. +## Development Guidelines -## Working Principles +### Available APIs -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. + **Table 1** APIs of the mutex module -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. +| Category| API Description | +| -------- | -------- | +| Initializing or destroying a mutex| - **LOS_MuxInit**: initializes a mutex.
- **LOS_MuxDestroy**: destroys a mutex.| +| Requesting or releasing a mutex| - **LOS_MuxLock**: requests a mutex.
- **LOS_MuxTrylock**: requests a mutex without blocking.
- **LOS_MuxUnlock**: releases a mutex.| +| Verifying a mutex| - **LOS_MuxIsValid**: checks whether the mutex release is valid.
- **LOS_MuxAttrDestroy**: destroys the specified mutex attribute.| +| Setting and obtaining mutex attributes| - **LOS_MuxAttrGetType**: obtains the type attribute of a mutex.
- **LOS_MuxAttrSetType**: sets the type attribute for a mutex.
- **LOS_MuxAttrGetProtocol**: obtains the protocol attribute of a mutex.
- **LOS_MuxAttrSetProtocol**: sets the protocol attribute for a mutex.
- **LOS_MuxAttrGetPrioceiling**: obtains the priority upper limit attribute of a mutex.
- **LOS_MuxAttrSetPrioceiling**: sets the priority upper limit attribute for a mutex.
- **LOS_MuxGetPrioceiling**: obtains the priority upper limit of this mutex.
- **LOS_MuxSetPrioceiling**: sets the priority upper limit for this mutex. | -**Figure 1** Mutex working mechanism for small systems -![](figures/mutex-working-mechanism-for-small-systems.png "mutex-working-mechanism-for-small-systems") -## Development Guidelines - -### Available APIs - -**Table 1** Mutex module APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Initializing or destroying a mutex

-

LOS_MuxInit

-

Initializes a mutex.

-

LOS_MuxDestroy

-

Destroys the specified mutex.

-

Requesting or releasing a mutex

-

LOS_MuxLock

-

Requests the specified mutex.

-

LOS_MuxTrylock

-

Attempts to request the specified mutex in non-block mode.

-

LOS_MuxUnlock

-

Releases the specified mutex.

-

Verifying a mutex

-

LOS_MuxIsValid

-

Checks whether the mutex release is valid.

-

Initializing or destroying mutex attributes

-

LOS_MuxAttrInit

-

Initializes mutex attributes.

-

LOS_MuxAttrDestroy

-

Destroys the specified mutex attributes.

-

Setting and obtaining mutex attributes

-

LOS_MuxAttrGetType

-

Obtains the type attribute of a specified mutex.

-

LOS_MuxAttrSetType

-

Sets the type attribute of a specified mutex.

-

LOS_MuxAttrGetProtocol

-

Obtains the protocol attribute of a specified mutex.

-

LOS_MuxAttrSetProtocol

-

Sets the protocol attribute of a specified mutex.

-

LOS_MuxAttrGetPrioceiling

-

Obtains the priority upper limit attribute of a specified mutex.

-

LOS_MuxAttrSetPrioceiling

-

Sets the priority upper limit attribute of a specified mutex.

-

LOS_MuxGetPrioceiling

-

Obtains the mutex priority upper limit attribute.

-

LOS_MuxSetPrioceiling

-

Sets the mutex priority upper limit attribute.

-
- -### How to Develop +### How to Develop 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: -- 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. -- 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. +- 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 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. + +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. -3. Call **LOS\_MuxUnlock** to release a mutex. +- If no task is blocked by the specified mutex, the mutex is released successfully. -- 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. +4. Call **LOS_MuxDestroy** to destroy a mutex. -4. Call **LOS\_MuxDestroy** to destroy a mutex. +> **NOTE**
+> - 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. ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->- 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 +### Development Example -Example Description +#### Example Description 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. -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**. -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. +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. -**Sample Code** +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**. + +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 + +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: @@ -199,7 +117,7 @@ The sample code is as follows: #include "los_mux.h" /* Mutex */ -LosMux g_testMux; +LosMux g_testMutex; /* Task ID*/ UINT32 g_testTaskId01; UINT32 g_testTaskId02; @@ -207,48 +125,49 @@ UINT32 g_testTaskId02; VOID Example_MutexTask1(VOID) { UINT32 ret; + LOS_TaskDelay(50); - printf("task1 try to get mutex, wait 10 ticks.\n"); - /* Request a mutex.*/ - ret = LOS_MuxLock(&g_testMux, 10); + dprintf("task1 try to get mutex, wait 10 ticks.\n"); + /* Request a mutex. */ + ret = LOS_MuxLock(&g_testMutex, 10); if (ret == LOS_OK) { - printf("task1 get mutex g_testMux.\n"); - /* Release the mutex.*/ - LOS_MuxUnlock(&g_testMux); + dprintf("task1 get mutex g_testMux.\n"); + /* Release the mutex. */ + LOS_MuxUnlock(&g_testMutex); return; - } - if (ret == LOS_ETIMEDOUT ) { - printf("task1 timeout and try to get mutex, wait forever.\n"); - /* Request a mutex.*/ - ret = LOS_MuxLock(&g_testMux, LOS_WAIT_FOREVER); - if (ret == LOS_OK) { - printf("task1 wait forever, get mutex g_testMux.\n"); - /*Release the mutex.*/ - LOS_MuxUnlock(&g_testMux); - /* Delete the mutex. */ - LOS_MuxDestroy(&g_testMux); - printf("task1 post and delete mutex g_testMux.\n"); - return; - } + } + if (ret == LOS_ETIMEDOUT) { + dprintf("task1 timeout and try to get mutex, wait forever.\n"); + /* Request a mutex. */ + ret = LOS_MuxLock(&g_testMutex, LOS_WAIT_FOREVER); + if (ret == LOS_OK) { + dprintf("task1 wait forever, get mutex g_testMux.\n"); + /* Release the mutex. */ + LOS_MuxUnlock(&g_testMutex); + /* Delete the mutex. */ + LOS_MuxDestroy(&g_testMutex); + dprintf("task1 post and delete mutex g_testMux.\n"); + return; + } } return; } VOID Example_MutexTask2(VOID) { - printf("task2 try to get mutex, wait forever.\n"); - /* Request a mutex.*/ - (VOID)LOS_MuxLock(&g_testMux, LOS_WAIT_FOREVER); + dprintf("task2 try to get mutex, wait forever.\n"); + /* Request a mutex. */ + (VOID)LOS_MuxLock(&g_testMutex, LOS_WAIT_FOREVER); - printf("task2 get mutex g_testMux and suspend 100 ticks.\n"); + dprintf("task2 get mutex g_testMux and suspend 100 ticks.\n"); - /* Enable the task to enter sleep mode for 100 ticks.*/ + /* Enable the task to enter sleep mode for 100 ticks. */ LOS_TaskDelay(100); - printf("task2 resumed and post the g_testMux\n"); - /* Release the mutex.*/ - LOS_MuxUnlock(&g_testMux); + dprintf("task2 resumed and post the g_testMux\n"); + /* Release the mutex. */ + LOS_MuxUnlock(&g_testMutex); return; } @@ -258,13 +177,13 @@ UINT32 Example_MutexEntry(VOID) TSK_INIT_PARAM_S task1; TSK_INIT_PARAM_S task2; - /* Initializes the mutex./ - LOS_MuxInit(&g_testMux, NULL); + /* Initialize the mutex. */ + LOS_MuxInit(&g_testMutex, NULL); - /* Lock task scheduling.*/ + /* Lock task scheduling. */ LOS_TaskLock(); - /* Create task 1.*/ + /* Create task 1. */ memset(&task1, 0, sizeof(TSK_INIT_PARAM_S)); task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_MutexTask1; task1.pcName = "MutexTsk1"; @@ -272,11 +191,11 @@ UINT32 Example_MutexEntry(VOID) task1.usTaskPrio = 5; ret = LOS_TaskCreate(&g_testTaskId01, &task1); if (ret != LOS_OK) { - printf("task1 create failed.\n"); + dprintf("task1 create failed.\n"); return LOS_NOK; } - /* Create task 2.*/ + /* Create task 2. */ memset(&task2, 0, sizeof(TSK_INIT_PARAM_S)); task2.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_MutexTask2; task2.pcName = "MutexTsk2"; @@ -284,11 +203,11 @@ UINT32 Example_MutexEntry(VOID) task2.usTaskPrio = 4; ret = LOS_TaskCreate(&g_testTaskId02, &task2); if (ret != LOS_OK) { - printf("task2 create failed.\n"); + dprintf("task2 create failed.\n"); return LOS_NOK; } - /* Unlock task scheduling.*/ + /* Unlock task scheduling. */ LOS_TaskUnlock(); return LOS_OK; @@ -299,13 +218,13 @@ UINT32 Example_MutexEntry(VOID) The development is successful if the return result is as follows: + ``` -task1 try to get mutex, wait 10 ticks. task2 try to get mutex, wait forever. task2 get mutex g_testMux and suspend 100 ticks. +task1 try to get mutex, wait 10 ticks. task1 timeout and try to get mutex, wait forever. task2 resumed and post the g_testMux task1 wait forever, get mutex g_testMux. task1 post and delete mutex g_testMux. ``` - diff --git a/en/device-dev/kernel/kernel-small-basic-trans-queue.md b/en/device-dev/kernel/kernel-small-basic-trans-queue.md index 5e2cbc062c4b9c3ba2066e37594d01d0fd871a7e..578fcac6d76ed84eb3129374bff9cf834e6a02f8 100644 --- a/en/device-dev/kernel/kernel-small-basic-trans-queue.md +++ b/en/device-dev/kernel/kernel-small-basic-trans-queue.md @@ -1,7 +1,7 @@ # Queue -## Basic Concepts +## Basic Concepts 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,21 +11,30 @@ 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: -- Messages are queued in FIFO mode and can be read and written asynchronously. -- Both the read queue and write queue support the timeout mechanism. -- 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. -- 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. -- When a queue is created, the required dynamic memory space is automatically allocated in the queue API. +- Messages are queued in first-in-first-out (FIFO) mode and can be read and written asynchronously. -## Working Principles +- Both the read queue and write queue support the timeout mechanism. + +- 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. + +- 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. + +- When a queue is created, the required dynamic memory space is automatically allocated in the queue API. + + +## Working Principles + + +### Queue Control Block -### Queue Control Block ``` /** - * Data structure of the queue control block + * Data structure of the queue control block */ typedef struct { UINT8 *queueHandle; /**< Pointer to a queue handle */ @@ -43,121 +52,94 @@ typedef struct { Each queue control block contains information about the queue status. -- **OS\_QUEUE\_UNUSED**: The queue is not in use. -- **OS\_QUEUE\_INUSED**: The queue is in use. +- **OS_QUEUE_UNUSED**: The queue is not in use. + +- **OS_QUEUE_INUSED**: The queue is in use. + + +### Working Principles + +- The queue ID is returned when 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. -### Working Principles +- 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. -- 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. -- 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. +- 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. -**Figure 1** Reading and writing data in a queue -![](figures/reading-and-writing-data-in-a-queue-3.png "reading-and-writing-data-in-a-queue-3") +- 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 + + ![](figures/reading-and-writing-data-in-a-queue-3.png "reading-and-writing-data-in-a-queue-3") The preceding figure illustrates how to write data to the tail node only. Writing data to the head node is similar. -## Development Guidelines - -### Available APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Creating or deleting a message queue

-

LOS_QueueCreate

-

Creates a message queue. The system dynamically allocates the queue space.

-

LOS_QueueDelete

-

Deletes the specified queue based on the queue ID.

-

Reading or writing data in a queue (without the content contained in the address)

-

LOS_QueueRead

-

Reads data in the head node of the specified queue. The data in the queue node is an address.

-

LOS_QueueWrite

-

Writes the value of the input parameter bufferAddr (buffer address) to the tail node of the specified queue.

-

LOS_QueueWriteHead

-

Writes the value of the input parameter bufferAddr (buffer address) to the head node of the specified queue.

-

Reading or writing in a queue (with the content contained in the address)

-

LOS_QueueReadCopy

-

Reads data from the head node of the specified queue.

-

LOS_QueueWriteCopy

-

Writes the data saved in the input parameter bufferAddr to the tail node of the specified queue.

-

LOS_QueueWriteHeadCopy

-

Writes the data saved in the input parameter bufferAddr to the head node of the specified queue.

-

Obtaining queue information

-

LOS_QueueInfoGet

-

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.

-
- -### How to Develop - -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. -5. Call **LOS\_QueueDelete** to delete a queue. - ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->- 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 - -### Example Description - -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**. -5. Call **LOS\_QueueDelete** to delete a queue. - -### Sample Code + +## Development Guidelines + + +### Available APIs + +| Category| API Description | +| -------- | -------- | +| Creating or deleting a message queue| - **LOS_QueueCreate**: creates a message queue. The system dynamically allocates the queue space.
- **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.
- **LOS_QueueWrite**: writes the value of **bufferAddr** (buffer address) to the tail node of a queue.
- **LOS_QueueWrite**: writes the value of **bufferAddr** (buffer address) to the head node of a queue.| +| Reading or writing data (data and address) in a queue| - **LOS_QueueReadCopy**: reads data from the head node of a queue.
- **LOS_QueueWriteCopy**: writes the data saved in **bufferAddr** to the tail node of a queue.
- **LOS_QueueWriteHeadCopy**: writes the data saved in **bufferAddr** to the head node of a queue.| +| 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.| + + +### How to Develop + +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 data to the queue. + +3. Call **LOS_QueueRead** or **LOS_QueueReadCopy** to read data from the queue. + +4. Call **LOS_QueueInfoGet** to obtain queue information. + +5. Call **LOS_QueueDelete** to delete a queue. + +> **NOTE**
+> - 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 queue name and flags passed in when a queue is created are reserved for future use. +> +> - 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. +> +> - 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. +> +> - **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 + + +### Example Description + +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. + +2. Call **LOS_QueueCreate** to create a message queue. + +3. Task 1 sends a message in **SendEntry**. + +4. Task 2 receives message in **RecvEntry**. + +5. Call **LOS_QueueDelete** to delete the queue. + + +### Sample Code + +The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **ExampleQueue** function is called in **TestTaskEntry**. + +To avoid excessive printing, call **LOS_Msleep(5000)** to cause a short delay before calling **ExampleQueue**. The sample code is as follows: @@ -175,7 +157,7 @@ VOID SendEntry(VOID) ret = LOS_QueueWriteCopy(g_queue, abuf, len, 0); if(ret != LOS_OK) { - printf("send message failure, error: %x\n", ret); + dprintf("send message failure, error: %x\n", ret); } } @@ -185,30 +167,36 @@ VOID RecvEntry(VOID) CHAR readBuf[BUFFER_LEN] = {0}; UINT32 readLen = BUFFER_LEN; - // Sleep for 1s. - usleep(1000000); + LOS_Msleep(1000); ret = LOS_QueueReadCopy(g_queue, readBuf, &readLen, 0); if(ret != LOS_OK) { - printf("recv message failure, error: %x\n", ret); + dprintf("recv message failure, error: %x\n", ret); } - printf("recv message: %s\n", readBuf); + dprintf("recv message: %s\n", readBuf); ret = LOS_QueueDelete(g_queue); if(ret != LOS_OK) { - printf("delete the queue failure, error: %x\n", ret); + dprintf("delete the queue failure, error: %x\n", ret); } - printf("delete the queue success!\n"); + dprintf("delete the queue success!\n"); } UINT32 ExampleQueue(VOID) { - printf("start queue example\n"); + dprintf("start queue example\n"); UINT32 ret = 0; UINT32 task1, task2; TSK_INIT_PARAM_S initParam = {0}; + ret = LOS_QueueCreate("queue", 5, &g_queue, 0, 50); + if(ret != LOS_OK) { + dprintf("create queue failure, error: %x\n", ret); + } + + dprintf("create the queue success!\n"); + initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)SendEntry; initParam.usTaskPrio = 9; initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; @@ -217,7 +205,8 @@ UINT32 ExampleQueue(VOID) LOS_TaskLock(); ret = LOS_TaskCreate(&task1, &initParam); if(ret != LOS_OK) { - printf("create task1 failed, error: %x\n", ret); + dprintf("create task1 failed, error: %x\n", ret); + LOS_QueueDelete(g_queue); return ret; } @@ -225,29 +214,26 @@ UINT32 ExampleQueue(VOID) initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)RecvEntry; ret = LOS_TaskCreate(&task2, &initParam); if(ret != LOS_OK) { - printf("create task2 failed, error: %x\n", ret); + dprintf("create task2 failed, error: %x\n", ret); + LOS_QueueDelete(g_queue); return ret; } - ret = LOS_QueueCreate("queue", 5, &g_queue, 0, 50); - if(ret != LOS_OK) { - printf("create queue failure, error: %x\n", ret); - } - - printf("create the queue success!\n"); LOS_TaskUnlock(); + LOS_Msleep(5000); return ret; } ``` -### Verification + +### Verification The development is successful if the return result is as follows: + ``` -start test example +start queue example create the queue success! recv message: test message delete the queue success! ``` - diff --git a/en/device-dev/kernel/kernel-small-basic-trans-semaphore.md b/en/device-dev/kernel/kernel-small-basic-trans-semaphore.md index 31cf7a943e55c174be94905d70ad7c5a6d102dcb..22411251d4982ec959d2e1ebb9984c99fd1860f4 100644 --- a/en/device-dev/kernel/kernel-small-basic-trans-semaphore.md +++ b/en/device-dev/kernel/kernel-small-basic-trans-semaphore.md @@ -1,34 +1,38 @@ # Semaphore -## Basic Concepts +## Basic Concepts -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. Tasks waiting for the semaphore may exist. -- Positive number: The semaphore is available. +- **0**: The semaphore is unavailable. In this case, tasks waiting for the semaphore may exist. -The semaphore for exclusive access is different from the semaphore for synchronization: +- Positive number: The semaphore is available. -- 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. +The semaphore used for exclusive access to resources is different from the semaphore used for synchronization: -## Working Principles +- 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. + + +## Working Principles **Semaphore Control Block** + ``` /** - * Data structure of the semaphore control block + * Data structure of the semaphore control block */ typedef struct { UINT16 semStat; /* Semaphore status */ - UINT16 semType; /* Semaphore type*/ - UINT16 semCount; /* Semaphore count*/ - UINT16 semId; /* Semaphore index*/ - LOS_DL_LIST semList; /* Mount the task blocked by the semaphore.*/ + UINT16 semType; /* Semaphore type */ + UINT16 semCount; /* Semaphore count */ + UINT16 semId; /* Semaphore ID */ + LOS_DL_LIST semList; /* List of blocked tasks */ } LosSemCB; ``` @@ -36,102 +40,89 @@ typedef struct { Semaphore allows only a specified number of tasks to access a shared resource at a time. When the number of tasks accessing the resource reaches the limit, other tasks will be blocked until the semaphore is released. -- Semaphore initialization +- Semaphore initialization + + 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 + + Obtain a semaphore from the linked list of unused semaphores and assign an initial value to the semaphore. - 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. +- Semaphore request -- Semaphore creation + 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. - The system obtains a semaphore from the linked list of unused semaphores and assigns an initial value to the semaphore. +- Semaphore release -- Semaphore request + If no task is waiting for the semaphore, the counter is incremented by 1. Otherwise, wake up the first task in the wait queue. - 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. +- Semaphore deletion -- Semaphore release + Set a semaphore in use to the unused state and add it to the linked list of unused semaphores. - 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. +The following figure illustrates the semaphore working mechanism. -- Semaphore deletion +**Figure 1** Semaphore working mechanism for the small system - The system sets a semaphore in use to unused state and inserts it to the linked list of unused semaphores. +![](figures/semaphore-working-mechanism-for-small-systems.png "semaphore-working-mechanism-for-small-systems") -The following figure illustrates the semaphore working mechanism. +## Development Guidelines -**Figure 1** Semaphore working mechanism for small systems -![](figures/semaphore-working-mechanism-for-small-systems.png "semaphore-working-mechanism-for-small-systems") -## Development Guidelines - -### Available APIs - -**Table 1** Semaphore module APIs - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Creating or deleting a semaphore

-

LOS_SemCreate

-

Creates a semaphore and returns the semaphore ID.

-

LOS_BinarySemCreate

-

Creates a binary semaphore. The maximum counter value is 1.

-

LOS_SemDelete

-

Deletes a semaphore.

-

Requesting or releasing a semaphore

-

LOS_SemPend

-

Requests a specified semaphore and sets the timeout period.

-

LOS_SemPost

-

Posts (releases) a semaphore.

-
- -### How to Develop - -1. Call **LOS\_SemCreate** to create a semaphore. To create a binary semaphore, call **LOS\_BinarySemCreate**. -2. Call **LOS\_SemPend** to request a semaphore. -3. Call **LOS\_SemPost** to release a semaphore. -4. Call **LOS\_SemDelete** to delete a semaphore. - ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->As interrupts cannot be blocked, semaphores cannot be requested in block mode for interrupts. - -### Development Example - -### Example Description +### Available APIs + +**Table 1** APIs for creating and deleting a semaphore + +| API| Description| +| -------- | -------- | +| LOS_SemCreate | Creates a semaphore and returns the semaphore ID.| +| LOS_BinarySemCreate | Creates a binary semaphore. The maximum counter value is **1**.| +| LOS_SemDelete | Deletes a semaphore.| + +**Table 2** APIs for requesting and releasing a semaphore + +| API| Description| +| -------- | -------- | +| LOS_SemPend | Requests a semaphore and sets a timeout period.| +| LOS_SemPost | Releases a semaphore.| + + +### How to Develop + +1. Call **LOS_SemCreate** to create a semaphore. To create a binary semaphore, call **LOS_BinarySemCreate**. + +2. Call **LOS_SemPend** to request a semaphore. + +3. Call **LOS_SemPost** to release a semaphore. + +4. Call **LOS_SemDelete** to delete a semaphore. + +> **NOTE**
+> As interrupts cannot be blocked, semaphores cannot be requested in block mode for interrupts. + + +### Development Example + + +### Example Description 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**. -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. -5. Task **ExampleSem** is woken up after 400 ticks and deletes the semaphore. +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.) + +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. After that, delete the semaphore. + + +### Sample Code -### 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**. The sample code is as follows: @@ -144,33 +135,34 @@ static UINT32 g_testTaskId01; static UINT32 g_testTaskId02; /* Task priority */ -#define TASK_PRIO_TEST 5 +#define TASK_PRIO_LOW 5 +#define TASK_PRIO_HI 4 -/* Semaphore structure ID*/ +/* Semaphore structure ID */ static UINT32 g_semId; VOID ExampleSemTask1(VOID) { UINT32 ret; - printf("ExampleSemTask1 try get sem g_semId, timeout 10 ticks.\n"); + dprintf("ExampleSemTask1 try get sem g_semId, timeout 10 ticks.\n"); - /* Request the semaphore in scheduled block mode, with a wait timeout period of 10 ticks.*/ + /* Request the semaphore in scheduled block mode, with a wait timeout period of 10 ticks. */ ret = LOS_SemPend(g_semId, 10); - - /* The semaphore is acquired.*/ + /* The semaphore is acquired. */ if (ret == LOS_OK) { LOS_SemPost(g_semId); return; } - /* The semaphore is not acquired when the timeout period has expired.*/ + /* The semaphore is not acquired when the timeout period has expired. */ if (ret == LOS_ERRNO_SEM_TIMEOUT) { - printf("ExampleSemTask1 timeout and try get sem g_semId wait forever.\n"); + dprintf("ExampleSemTask1 timeout and try get sem g_semId wait forever.\n"); - /* Request the semaphore in permanent block mode.*/ + /* Request the semaphore in permanent block mode. */ ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER); - printf("ExampleSemTask1 wait_forever and get sem g_semId.\n"); + dprintf("ExampleSemTask1 wait_forever and get sem g_semId.\n"); if (ret == LOS_OK) { + dprintf("ExampleSemTask1 post sem g_semId.\n"); LOS_SemPost(g_semId); return; } @@ -180,20 +172,19 @@ VOID ExampleSemTask1(VOID) VOID ExampleSemTask2(VOID) { UINT32 ret; - printf("ExampleSemTask2 try get sem g_semId wait forever.\n"); + dprintf("ExampleSemTask2 try get sem g_semId wait forever.\n"); - /* Request the semaphore in permanent block mode.*/ + /* Request the semaphore in permanent block mode. */ ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER); - if (ret == LOS_OK) { - printf("ExampleSemTask2 get sem g_semId and then delay 20 ticks.\n"); + dprintf("ExampleSemTask2 get sem g_semId and then delay 20 ticks.\n"); } - /* Enable the task to enter sleep mode for 20 ticks.*/ + /* Enable the task to enter sleep mode for 20 ticks. */ LOS_TaskDelay(20); - printf("ExampleSemTask2 post sem g_semId.\n"); - /* Release the semaphore.*/ + dprintf("ExampleSemTask2 post sem g_semId.\n"); + /* Release the semaphore. */ LOS_SemPost(g_semId); return; } @@ -204,60 +195,65 @@ UINT32 ExampleSem(VOID) TSK_INIT_PARAM_S task1; TSK_INIT_PARAM_S task2; - /* Create a semaphore.*/ + /* Create a semaphore. */ LOS_SemCreate(0, &g_semId); - /* Lock task scheduling.*/ + /* Lock task scheduling. */ LOS_TaskLock(); - /* Create task 1.*/ + /* Create task 1. */ (VOID)memset_s(&task1, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); task1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask1; task1.pcName = "TestTask1"; task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - task1.usTaskPrio = TASK_PRIO_TEST; + task1.usTaskPrio = TASK_PRIO_LOW; ret = LOS_TaskCreate(&g_testTaskId01, &task1); if (ret != LOS_OK) { - printf("task1 create failed .\n"); + dprintf("task1 create failed .\n"); return LOS_NOK; } - /* Create task 2.*/ + /* Create task 2. */ (VOID)memset_s(&task2, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); task2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask2; task2.pcName = "TestTask2"; task2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - task2.usTaskPrio = (TASK_PRIO_TEST - 1); + task2.usTaskPrio = TASK_PRIO_HI; ret = LOS_TaskCreate(&g_testTaskId02, &task2); if (ret != LOS_OK) { - printf("task2 create failed.\n"); + dprintf("task2 create failed.\n"); return LOS_NOK; } - /* Unlock task scheduling.*/ + /* Unlock task scheduling. */ LOS_TaskUnlock(); + /* Enable the task to enter sleep mode for 400 ticks. */ + LOS_TaskDelay(400); + ret = LOS_SemPost(g_semId); - /* Enable the task to enter sleep mode for 400 ticks.*/ + /* Enable the task to enter sleep mode for 400 ticks. */ LOS_TaskDelay(400); - /* Delete the semaphore. */ + /* Delete the semaphore. */ LOS_SemDelete(g_semId); return LOS_OK; } ``` -### Verification + +### Verification The development is successful if the return result is as follows: + ``` ExampleSemTask2 try get sem g_semId wait forever. -ExampleSemTask2 get sem g_semId and then delay 20 ticks. ExampleSemTask1 try get sem g_semId, timeout 10 ticks. ExampleSemTask1 timeout and try get sem g_semId wait forever. +ExampleSemTask2 get sem g_semId and then delay 20 ticks. ExampleSemTask2 post sem g_semId. ExampleSemTask1 wait_forever and get sem g_semId. +ExampleSemTask1 post sem g_semId. ``` - diff --git a/en/device-dev/kernel/kernel-small-basic-trans-user-mutex.md b/en/device-dev/kernel/kernel-small-basic-trans-user-mutex.md index 423e46492a8944ddacf62b5d332de1f3ed9a219b..2af0a2c3b9b746f3cfd619baecac38a9c08308d8 100644 --- a/en/device-dev/kernel/kernel-small-basic-trans-user-mutex.md +++ b/en/device-dev/kernel/kernel-small-basic-trans-user-mutex.md @@ -1,62 +1,39 @@ # Futex -## Basic Concepts +## Basic Concepts -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 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 + + +## 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. -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. + +## Futex Design + +**Figure 1** Futex design -**Figure 1** Futex design ![](figures/futex-design.jpg "futex-design") -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. - -**Table 1** Futex module APIs - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Putting a thread to wait

-

OsFutexWait

-

Inserts a node representing a blocked thread into the futex list.

-

Waking up a thread

-

OsFutexWake

-

Wakes up a thread that is blocked by a specified lock.

-

Modifying the lock address

-

OsFutexRequeue

-

Adjusts the position of a specified lock in the futex list.

-
- ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->The futex system call and user-mode logic form a user-mode lock. Therefore, you are advised to use the locks via the user-mode POSIX APIs. +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. + +## Available APIs + +APIs of the futex module + +| Category | API | Description | +| -------------- | -------------- | ------------------------------------- | +| Putting a thread to wait | OsFutexWait | Inserts a node representing a blocked thread into the futex list.| +| Waking up a thread| OsFutexWake | Wakes up a thread that is blocked by a specified lock. | +| Modifying the lock address | OsFutexRequeue | Adjusts the position of a specified lock in the futex list. | +> **NOTE**
+> The futex system call and user-mode logic form a user-mode lock. Therefore, you are advised to use the locks via the user-mode POSIX APIs. diff --git a/en/device-dev/kernel/kernel-small-basic-trans-user-signal.md b/en/device-dev/kernel/kernel-small-basic-trans-user-signal.md index ee8d9eae741239fc9edaf45df50014ec8bcc0412..3ac3e5f80143ece60043a9180abf0abad092545a 100644 --- a/en/device-dev/kernel/kernel-small-basic-trans-user-signal.md +++ b/en/device-dev/kernel/kernel-small-basic-trans-user-signal.md @@ -1,84 +1,64 @@ # Signal -## Basic Concepts +## Basic Concepts -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 -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. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Registering the signal callback

-

signal

-

Registers the main signal entry, and registers and unregisters the callback function of a signal.

-

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.

-

Sending signals

-

kill

-

Sends a signal to a process or sends messages to a thread in a process, and sets signal flags for threads in a process.

-

pthread_kill

-

raise

-

alarm

-

abort

-

Triggering a callback

-

None

-

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.

-
+ **Table 1** Signal APIs (user-mode APIs) ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->The signal mechanism enables communication between user-mode programs. The user-mode POSIX APIs listed in the above table are recommended. ->Register a callback function. ->``` ->void *signal(int sig, void (*func)(int))(int); ->``` ->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. ->Register 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. ->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. +| Category | API | Description | +| ---------------- | --------------------------------------------------- | ------------------------------------------------------------ | +| 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.| +| Sending a signal | kill
pthread_kill
raise
alarm
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.| +> **NOTE**
+> 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. diff --git a/en/device-dev/kernel/kernel-small-bundles-ipc.md b/en/device-dev/kernel/kernel-small-bundles-ipc.md index cdde2e4e602dfe73c76158b2fd9119fcfc4d347b..50d3f5e7f61b76ffebcd43ea79a953ba4f7c86da 100644 --- a/en/device-dev/kernel/kernel-small-bundles-ipc.md +++ b/en/device-dev/kernel/kernel-small-bundles-ipc.md @@ -1,65 +1,38 @@ # LiteIPC -## Basic Concepts - -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 - -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** LiteIPC module APIs \(for LiteOS-A internal use only\) - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Module initialization

-

OsLiteIpcInit

-

Initializes the LiteIPC module.

-

IPC message memory pool

-

LiteIpcPoolInit

-

Initializes the IPC message memory pool of processes.

-

LiteIpcPoolReInit

-

Re-initializes the IPC message memory pool of processes.

-

LiteIpcPoolDelete

-

Releases the IPC message memory pool of processes.

-

Service management

-

LiteIpcRemoveServiceHandle

-

Deletes the specified Service.

-
- ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->LiteIPC module APIs are used for LiteOS-A internal use only. +## Basic Concepts +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) + +| Category | API Description | +| ------------- | ------------------------------------------------------------ | +| Module initialization | **OsLiteIpcInit**: initializes the LiteIPC module. | +| IPC message memory pool| - **LiteIpcPoolInit**: initializes the IPC message memory pool of a process.
- **LiteIpcPoolReInit**: reinitializes the IPC message memory pool of a process.
- **LiteIpcPoolDelete**: releases the IPC message memory pool of a process. | +| Service management | **LiteIpcRemoveServiceHandle**: deletes a service. | + +> **NOTE**
+> The APIs of the LiteIPC module are dedicated for LiteOS-A internal use only. diff --git a/en/device-dev/kernel/kernel-small-bundles-linking.md b/en/device-dev/kernel/kernel-small-bundles-linking.md index 78a6076a0239d6fa922c470425dccdf96990117a..2fc0d538c9f29b4699c655471c5ddb7c0c4d9241 100644 --- a/en/device-dev/kernel/kernel-small-bundles-linking.md +++ b/en/device-dev/kernel/kernel-small-bundles-linking.md @@ -1,59 +1,58 @@ # Dynamic Loading and Linking -## Basic Concepts + +## Basic Concepts 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** -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. -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. +- Dynamic linking allows multiple applications to share code. The minimum loading unit is page. Dynamic linking saves disk and memory space than static linking. + +- 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 -## Working Principles +**Figure 1** Dynamic loading process -**Figure 1** Dynamic loading process ![](figures/dynamic-loading-process.png "dynamic-loading-process") -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\). -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. +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 **-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 ![](figures/program-execution-process.png "program-execution-process") -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. -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. -5. The program continues to run. - -## Development Guidelines - -### Available APIs - -**Table 1** APIs of the kernel loader module - - - - - - - - - - - - -

Function

-

API

-

Description

-

Module initialization

-

LOS_DoExecveFile

-

Executes the specified user program based on the input parameters.

-
- -### 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. +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. + +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. + +5. The program continues to run. + + +## Development Guidelines + + +### Available APIs + +**Table 1** API of the kernel loader module + +| Category | API | Description | +| ---------- | ---------------- | -------------------------------- | +| Starting initialization| LOS_DoExecveFile | Executes the specified user program based on the input parameters.| + + +### 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. diff --git a/en/device-dev/kernel/kernel-small-bundles-share.md b/en/device-dev/kernel/kernel-small-bundles-share.md index 23f6b68a3e4601e0dc4d10783f15bb4616caee88..0414d8bc7730cfebe26b1c5a1f2eb915f98eaefa 100644 --- a/en/device-dev/kernel/kernel-small-bundles-share.md +++ b/en/device-dev/kernel/kernel-small-bundles-share.md @@ -1,21 +1,24 @@ # Virtual Dynamic Shared Object -## Basic Concepts -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 +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: -- Data page: provides the kernel-time data mapped to the user process. -- Code page: provides the logic for shielding system calls. +- Data page: provides the kernel-time data mapped to the user process. +- Code page: provides the logic for shielding system calls. + +**Figure 1** VDSO system design -**Figure 1** VDSO system design ![](figures/vdso-system-design.jpg "vdso-system-design") The VDSO mechanism involves the following steps: @@ -30,7 +33,7 @@ The VDSO mechanism involves the following steps: 5. Binds the VDSO symbols when the user program creates dynamic linking. -6. The VDSO code page intercepts specific system calls \(for example, **clock\_gettime\(CLOCK\_REALTIME\_COARSE, &ts\)**\). +6. The VDSO code page intercepts specific system calls (for example, **clock_gettime(CLOCK_REALTIME_COARSE, &ts)**). 7. The VDSO code page allows direct read of the mapped VDSO data page rather than invoking a system call. @@ -38,7 +41,10 @@ The VDSO mechanism involves the following steps: 9. Returns the data obtained from the VDSO data page to the user program. ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->- 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. - +> **NOTE**
+> +> - 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. diff --git a/en/device-dev/kernel/kernel-small-debug-memory-corrupt.md b/en/device-dev/kernel/kernel-small-debug-memory-corrupt.md index 86e96a509e36d8b451fadb2b17543c82c7fe8d70..5429d3174fee9be17d1f66ce41d92b7920bb8eb1 100644 --- a/en/device-dev/kernel/kernel-small-debug-memory-corrupt.md +++ b/en/device-dev/kernel/kernel-small-debug-memory-corrupt.md @@ -1,42 +1,52 @@ # Memory Corruption Check -## Basic Concepts +## Basic Concepts 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 -**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 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**
+> 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. +## Development Guidelines ->![](../public_sys-resources/icon-caution.gif) **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. -## Development Guidelines +### How to Develop -### How to Develop +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 +### Development Example This example implements the following: -1. Requests 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. +1. Request two physically adjacent memory blocks. + +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** +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 #include #include "los_memory.h" @@ -44,10 +54,10 @@ The sample code is as follows: void MemIntegrityTest(void) { - /* Request two physically adjacent memory blocks.*/ + /* Request two physically adjacent memory blocks. */ void *ptr1 = 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. */ memset(ptr1, 0, 8 + 4); LOS_MemIntegrityCheck(LOSCFG_SYS_HEAP_ADDR); } @@ -55,24 +65,26 @@ void MemIntegrityTest(void) **Verification** + 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.*/ +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 + 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.*/ + 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.*/ + 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 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 */ ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-memory-info.md b/en/device-dev/kernel/kernel-small-debug-memory-info.md index 7e49011370211aab32ba94e1a578b99f77e857b7..ddfbc57c500d6638f48968860f1e40a34c04e164 100644 --- a/en/device-dev/kernel/kernel-small-debug-memory-info.md +++ b/en/device-dev/kernel/kernel-small-debug-memory-info.md @@ -1,61 +1,67 @@ # Memory Information Statistics -## Basic Concepts + +## Basic Concepts 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:
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 -**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 -### How to Develop +### How to Develop Key structure: -``` + +```c typedef struct { - UINT32 totalUsedSize; // Memory usage of the memory pool - UINT32 totalFreeSize; // Remaining memory 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 freeNodeNum; // 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. - 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) // This function is disabled by default and can be enabled using the **menuconfig** tool. + 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(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 +### Development Example This example implements the following: -1. Creates 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. +1. Create a monitoring task to obtain information about the memory pool. + +2. Call **LOS_MemInfoGet** to obtain the basic information about the memory pool. + +3. Calculate the memory usage and fragmentation rate. **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: -``` +```c #include #include #include "los_task.h" @@ -66,15 +72,14 @@ 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; /* 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); + dprintf("usage = %d, fragment = %d, maxFreeSize = %d, totalFreeSize = %d, waterLine = %d\n", usage, fragment, poolStatus.maxFreeNodeSize, poolStatus.totalFreeSize, poolStatus.usageWaterLine); } int MemTest(void) @@ -88,18 +93,20 @@ int MemTest(void) taskStatus.usTaskPrio = 10; ret = LOS_TaskCreate(&taskID, &taskStatus); if (ret != LOS_OK) { - printf("task create failed\n"); - return -1; + dprintf("task create failed\n"); + return LOS_NOK; } - return 0; + return LOS_OK; } ``` **Verification** + The result is as follows: +The data may vary depending on the running environment. + ``` usage = 22, fragment = 3, maxFreeSize = 49056, totalFreeSize = 50132, waterLine = 1414 ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-memory-leak.md b/en/device-dev/kernel/kernel-small-debug-memory-leak.md index d67b32bff12085d5f85c831aef31cae9a5f76491..df901f9b1140d19783b8c4e1c4b1a19457fd39af 100644 --- a/en/device-dev/kernel/kernel-small-debug-memory-leak.md +++ b/en/device-dev/kernel/kernel-small-debug-memory-leak.md @@ -1,127 +1,151 @@ # Memory Leak Check -## Basic Concepts +## Basic Concepts -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 -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**. -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. +## Function Configuration +**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. -## Development Guidelines -### How to Develop +## 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. -The node information output by calling **LOS\_MemUsedNodeShow** is in the following format: +### How to Develop -- 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. +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. + +The node information output by calling **LOS_MemUsedNodeShow** is in the following format:
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. -You can determine the specific memory location of the node based on the LR addresses and the assembly file. ``` -node size LR[0] LR[1] LR[2] -0x10017320: 0x528 0x9b004eba 0x9b004f60 0x9b005002 -0x10017848: 0xe0 0x9b02c24e 0x9b02c246 0x9b008ef0 -0x10017928: 0x50 0x9b008ed0 0x9b068902 0x9b0687c4 +node size LR[0] LR[1] LR[2] +0x10017320: 0x528 0x9b004eba 0x9b004f60 0x9b005002 +0x10017848: 0xe0 0x9b02c24e 0x9b02c246 0x9b008ef0 +0x10017928: 0x50 0x9b008ed0 0x9b068902 0x9b0687c4 0x10017978: 0x24 0x9b008ed0 0x9b068924 0x9b0687c4 -0x1001799c: 0x30 0x9b02c24e 0x9b02c246 0x9b008ef0 -0x100179cc: 0x5c 0x9b02c24e 0x9b02c246 0x9b008ef0 +0x1001799c: 0x30 0x9b02c24e 0x9b02c246 0x9b008ef0 +0x100179cc: 0x5c 0x9b02c24e 0x9b02c246 0x9b008ef0 ``` ->![](../public_sys-resources/icon-caution.gif) **CAUTION:** ->Enabling memory leak check affects memory application performance. LR addresses will be recorded for each memory node, increasing memory overhead. +> **CAUTION** +> Enabling memory leak check affects memory application performance. LR addresses will be recorded for each memory node, increasing memory overhead. + -### Development Example +### Development Example This example implements the following: -1. Call **OsMemUsedNodeShow** to print information about all nodes. -2. Simulate a memory leak by requesting memory without releasing it. -3. Call **OsMemUsedNodeShow** to print information about all nodes. -4. Compare the logs to obtain information about the node where a memory leak occurred. -5. Locate the code based on the LR address. +1. Call **OsMemUsedNodeShow** to print information about all nodes. + +2. Simulate a memory leak by requesting memory without releasing it. + +3. Call **OsMemUsedNodeShow** to print information about all nodes. + +4. Compare the logs to obtain information about the node where a memory leak occurred. + +5. Locate the code based on the LR address. + **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**. + The sample code is as follows: -``` +```c #include #include #include "los_memory.h" #include "los_config.h" +#define TEST_NEW_POOL_SIZE 2000 +#define TEST_MALLOC_SIZE 8 + void MemLeakTest(void) { - OsMemUsedNodeShow(LOSCFG_SYS_HEAP_ADDR); - void *ptr1 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8); - void *ptr2 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8); - OsMemUsedNodeShow(LOSCFG_SYS_HEAP_ADDR); + VOID *pool = NULL; + + /* Create a memory pool. */ + pool = LOS_MemAlloc(OS_SYS_MEM_ADDR, TEST_NEW_POOL_SIZE); + (VOID)LOS_MemInit(pool, TEST_NEW_POOL_SIZE); + + OsMemUsedNodeShow(pool); + void *ptr1 = LOS_MemAlloc(pool, TEST_MALLOC_SIZE); + void *ptr2 = LOS_MemAlloc(pool, TEST_MALLOC_SIZE); + OsMemUsedNodeShow(pool); + + /* Release the memory pool. */ + (VOID)LOS_MemDeInit(pool); } ``` + **Verification** + The log is as follows: ``` -node size LR[0] LR[1] LR[2] -0x20001b04: 0x24 0x08001a10 0x080035ce 0x080028fc -0x20002058: 0x40 0x08002fe8 0x08003626 0x080028fc -0x200022ac: 0x40 0x08000e0c 0x08000e56 0x0800359e -0x20002594: 0x120 0x08000e0c 0x08000e56 0x08000c8a -0x20002aac: 0x56 0x08000e0c 0x08000e56 0x08004220 - -node size LR[0] LR[1] LR[2] -0x20001b04: 0x24 0x08001a10 0x080035ce 0x080028fc -0x20002058: 0x40 0x08002fe8 0x08003626 0x080028fc -0x200022ac: 0x40 0x08000e0c 0x08000e56 0x0800359e -0x20002594: 0x120 0x08000e0c 0x08000e56 0x08000c8a -0x20002aac: 0x56 0x08000e0c 0x08000e56 0x08004220 -0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6 -0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000 +/* Log for the first OsMemUsedNodeShow. Because the memory pool is not allocated, there is no memory node. */ +node LR[0] LR[1] LR[2] + + +/* Log for the second OsMemUsedNodeShow. There are two memory nodes. */ +node LR[0] LR[1] LR[2] +0x00402e0d90: 0x004009f040 0x0040037614 0x0040005480 +0x00402e0db0: 0x004009f04c 0x0040037614 0x0040005480 + ``` + The difference between the two logs is as follows. The following memory nodes are suspected to have blocks with a memory leak. ``` -0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6 -0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000 +0x00402e0d90: 0x004009f040 0x0040037614 0x0040005480 +0x00402e0db0: 0x004009f04c 0x0040037614 0x0040005480 ``` + The following is part of the assembly file: ``` - MemLeakTest: - 0x80041d4: 0xb510 PUSH {R4, LR} - 0x80041d6: 0x4ca8 LDR.N R4, [PC, #0x2a0] ; g_memStart - 0x80041d8: 0x0020 MOVS R0, R4 - 0x80041da: 0xf7fd 0xf93e BL LOS_MemUsedNodeShow ; 0x800145a - 0x80041de: 0x2108 MOVS R1, #8 - 0x80041e0: 0x0020 MOVS R0, R4 - 0x80041e2: 0xf7fd 0xfbd9 BL LOS_MemAlloc ; 0x8001998 - 0x80041e6: 0x2108 MOVS R1, #8 - 0x80041e8: 0x0020 MOVS R0, R4 - 0x80041ea: 0xf7fd 0xfbd5 BL LOS_MemAlloc ; 0x8001998 - 0x80041ee: 0x0020 MOVS R0, R4 - 0x80041f0: 0xf7fd 0xf933 BL LOS_MemUsedNodeShow ; 0x800145a - 0x80041f4: 0xbd10 POP {R4, PC} - 0x80041f6: 0x0000 MOVS R0, R0 +4009f014: 7d 1e a0 e3 mov r1, #2000 +4009f018: 00 00 90 e5 ldr r0, [r0] +4009f01c: 67 7a fe eb bl #-398948 +4009f020: 7d 1e a0 e3 mov r1, #2000 +4009f024: 00 40 a0 e1 mov r4, r0 +4009f028: c7 79 fe eb bl #-399588 +4009f02c: 04 00 a0 e1 mov r0, r4 +4009f030: 43 78 fe eb bl #-401140 +4009f034: 04 00 a0 e1 mov r0, r4 +4009f038: 08 10 a0 e3 mov r1, #8 +4009f03c: 5f 7a fe eb bl #-398980 +4009f040: 04 00 a0 e1 mov r0, r4 +4009f044: 08 10 a0 e3 mov r1, #8 +4009f048: 5c 7a fe eb bl #-398992 +4009f04c: 04 00 a0 e1 mov r0, r4 +4009f050: 3b 78 fe eb bl #-401172 +4009f054: 3c 00 9f e5 ldr r0, [pc, #60] +4009f058: 40 b8 fe eb bl #-335616 +4009f05c: 04 00 a0 e1 mov r0, r4 +4009f060: 2c 7a fe eb bl #-399184 ``` -The memory node addressed by **0x080041ee** is not released after being requested in **MemLeakTest**. +The memory node addressed by **0x4009f040** is not released after being allocated in **MemLeakTest**. diff --git a/en/device-dev/kernel/kernel-small-debug-perf.md b/en/device-dev/kernel/kernel-small-debug-perf.md new file mode 100644 index 0000000000000000000000000000000000000000..819365eb087c7e13d0853ce1149447981f785a22 --- /dev/null +++ b/en/device-dev/kernel/kernel-small-debug-perf.md @@ -0,0 +1,267 @@ +# 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 + +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). + + **Table 1** APIs of the perf module + +| Category| Description| +| -------- | -------- | +| Starting or stopping sampling| **LOS_PerfInit**: initializes perf.
**LOS_PerfStart**: starts sampling.
**LOS_PerfStop**: stops sampling. | +| 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.
**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 +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. The code snippet is as follows: + +```c +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. + + +## 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**. + + | Configuration 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->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. */ +VOID test(VOID) +{ + VOID *p = NULL; + int i; + for (i = 0; i < TEST_TIME; i++) { + p = LOS_MemAlloc(m_aucSysMem1, TEST_MALLOC_SIZE); + if (p == NULL) { + PRINT_ERR("test alloc failed\n"); + return; + } + + (VOID)LOS_MemFree(m_aucSysMem1, p); + } +} + +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; + + //LOS_PerfInit(NULL, 0); + + + PerfConfigAttr attr = { + .eventsCfg = { + .type = PERF_EVENT_TYPE_SW, + .events = { + [0] = {PERF_COUNT_SW_TASK_SWITCH, 0xff}, /* Collect task scheduling information. */ + [1] = {PERF_COUNT_SW_MEM_ALLOC, 0xff}, /* Collect memory allocation information. */ + + PERF_COUNT_SW_TASK_SWITCH + }, + .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); // 2: set the section id to 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 = {0}; + UINT32 taskID; + /* Create a perf task. */ + perfTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)perfTestHwEvent; + perfTestTask.pcName = "TestPerfTsk"; /* Test task name. */ + perfTestTask.uwStackSize = 0x1000; // 0x8000: perf test task stack size + perfTestTask.usTaskPrio = 5; // 5: perf test task priority + ret = LOS_TaskCreate(&taskID, &perfTestTask); + if (ret != LOS_OK) { + PRINT_ERR("PerfTestTask create failed. 0x%x\n", ret); + return LOS_NOK; + } + return LOS_OK; +} +LOS_MODULE_INIT(perfTestHwEvent, LOS_INIT_LEVEL_KMOD_EXTENDED); +``` + + +#### Verification + + The output is as follows: + +``` +type: 2 +events[0]: 1, 0xff +events[1]: 3, 0xff +predivided: 1 +sampleType: 0x60 +needSample: 0 +------count mode------ +[task switch] eventType: 0x1 [core 0]: 0 +[mem alloc] eventType: 0x3 [core 0]: 5 +time used: 0.005000(s) +--------sample mode------ +type: 2 +events[0]: 1, 0xff +events[1]: 3, 0xff +predivided: 1 +sampleType: 0x60 +needSample: 1 +dump perf data, addr: 0x402c3e6c length: 0x5000 +time used: 0.000000(s) +num: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 +hex: 00 ffffffef ffffffef ffffffef 02 00 00 00 14 00 00 00 60 00 00 00 02 00 00 00 + +The print information may vary depending on the running environment. +``` + +- 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. diff --git a/en/device-dev/kernel/kernel-small-debug-process-cpu.md b/en/device-dev/kernel/kernel-small-debug-process-cpu.md index 5801bb007bc9edc1b075363a34ba57eb67e3c498..00946584c794a9c2a4258131846da9ec32b0dabb 100644 --- a/en/device-dev/kernel/kernel-small-debug-process-cpu.md +++ b/en/device-dev/kernel/kernel-small-debug-process-cpu.md @@ -3,35 +3,34 @@ ## Basic Concepts -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 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 +- 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. - 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. +- 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. -- 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. +## Working Principles -- Interrupt CPUP +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. - 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. +OpenHarmony provides the following types of CPUP information: +- System CPUP -## Working Principles +- Process CPUP -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. +- Task CPUP -OpenHarmony provides the following types of CPUP information: - -- System CPUP -- Process CPUP -- Task CPUP -- Interrupt CPUP +- Interrupt CPUP The CPUP is calculated as follows: @@ -43,136 +42,111 @@ 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 -## Development Guidelines - -### Available APIs - -**Table 1** CPUP module APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

System CPUP

-

LOS_HistorySysCpuUsage

-

Obtains the historical CPUP of the system.

-

Process CPUP

-

LOS_HistoryProcessCpuUsage

-

Obtains the historical CPUP of a specified process.

-

LOS_GetAllProcessCpuUsage

-

Obtains the historical CPUP of all processes in the system.

-

Task CPUP

-

LOS_HistoryTaskCpuUsage

-

Obtains the historical CPUP of a specified task.

-

Interrupt CPUP

-

LOS_GetAllIrqCpuUsage

-

Obtains the historical CPUP of all interrupts in the system.

-
- -### How to Develop - -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 is not created, return an error code. - -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 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. - - 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\_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 CPUP has not been initialized or has invalid input parameters, return an error code. - - -### Development Example + +## Development Guidelines + + +### Available APIs + + **Table 1** CPUP module APIs + +| Category| API| Description| +| -------- | -------- | -------- | +| System CPUP| LOS_HistorySysCpuUsage | Obtains the historical CPUP of the system.| +| Process CPUP| LOS_HistoryProcessCpuUsage | Obtains the historical CPUP of a specified process.| +| Process CPUP| LOS_GetAllProcessCpuUsage | Obtains the historical CPUP of all processes in the system.| +| Task CPUP| LOS_HistoryTaskCpuUsage | Obtains the historical CPUP of a specified task.| +| Interrupt CPUP| LOS_GetAllIrqCpuUsage | Obtains the historical CPUP of all interrupts in the system.| +| Reset| LOS_CpupReset | Resets CPUP data.| + + +### How to Develop + +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 is not created, return an error code. + +3. Call **LOS_GetAllProcessCpuUsage** to obtain the CPUP of all processes. + - 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 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. + +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 CPUP is not initialized or has invalid input parameters, return an error code. + + +### Development Example 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. -Prerequisites +3. Obtain the historical system CPUP in different modes. -The CPUP control is enabled in the **menuconfig** configuration. +4. Obtain the CPUP of the created test task. + +5. Obtain the CPUP of the created test task in different modes. + +Prerequisites: + +The CPUP control is enabled in the **menuconfig** configuration. **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**. The sample code is as follows: -``` + +```c #include "los_task.h" -#include "los_cpup.h" +#include "los_cpup.h" #define MODE 4 -UINT32 g_cpuTestTaskID; -VOID ExampleCpup(VOID) -{ - printf("entry cpup test example\n"); - while(1) { - usleep(100); +UINT32 g_cpuTestTaskID; +VOID ExampleCpup(VOID) +{ + int i = 0; + dprintf("entry cpup test example\n"); + for (i = 0; i < 10; i++) { + usleep(100); // 100: delay for 100ms } } -UINT32 ItCpupTest(VOID) -{ +UINT32 CpupTest(VOID) +{ UINT32 ret; UINT32 cpupUse; - TSK_INIT_PARAM_S cpupTestTask = { 0 }; + 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; + cpupTestTask.pcName = "TestCpupTsk"; + cpupTestTask.uwStackSize = 0x800; // 0x800: cpup test task stack size + cpupTestTask.usTaskPrio = 5; // 5: cpup test task priority ret = LOS_TaskCreate(&g_cpuTestTaskID, &cpupTestTask); - if(ret != LOS_OK) { + if (ret != LOS_OK) { printf("cpupTestTask create failed .\n"); return LOS_NOK; } - usleep(100); + usleep(100); // 100: delay for 100ms - /* Obtain the historical CPUP of the system. */ - cpupUse = LOS_HistorySysCpuUsage(CPU_LESS_THAN_1S); - printf("the history system cpu usage in all time: %u.%u\n", + /* Obtain the historical CPUP of the system. */ + cpupUse = LOS_HistorySysCpuUsage(CPUP_LAST_ONE_SECONDS); + dprintf("the history system cpu usage in all time: %u.%u\n", cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT); - /* Obtain the CPUP of the specified task (cpupTestTask in this example).*/ - cpupUse = LOS_HistoryTaskCpuUsage(g_cpuTestTaskID, CPU_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; + /* Obtain the CPUP of the specified task (cpupTestTask in this example). */ + cpupUse = LOS_HistoryTaskCpuUsage(g_cpuTestTaskID, CPUP_LAST_ONE_SECONDS); + dprintf("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; } ``` @@ -180,9 +154,12 @@ UINT32 ItCpupTest(VOID) The development is successful if the return result is as follows: + ``` entry cpup test example the history system cpu usage in all time: 3.0 cpu usage of the cpupTestTask in all time: TaskID:10 usage: 0.0 + +The print information may vary depending on the running environment. ``` diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-cpup.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-cpup.md index 746b920933106047cb22d223404e4b090425fe9f..ac22848f4fce6660fbadb46f091d4134cb87a44f 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-cpup.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-cpup.md @@ -1,55 +1,41 @@ # cpup -## Command Function +## Command Function -This command is used to query the CPU usage \(CPU percent\) of the system. +This command is used to query the CPU percent (CPUP) of the system. -## Syntax -cpup \[_mode_\] \[_taskID_\] +## Syntax -## Parameters +cpup [_mode_] [_taskID_] -**Table 1** Parameter description - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

mode

-
  • Displays the CPU usage of the system within the last 10 seconds by default.
  • 0: displays the CPU usage within the last 10 seconds.
  • 1: displays the CPU usage within the last 1 second.
  • Other value: displays the total CPU usage since the system is started.
-

[0,0xFFFFFFFF]

-

taskID

-

Specifies the task ID.

-

[0,0xFFFFFFFF]

-
+## Parameters -## Usage +**Table 1** Parameter description -- If no parameter is specified, the CPU usage of the system within the last 10 seconds is displayed. -- If only **mode** is specified, the CPU usage within the specified period is displayed. -- If both **mode** and **taskID** are specified, the CPU usage of the specified task within the given period is displayed. +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| mode | Displays the CPUP of the system within the last 10 seconds by default.
- **0**: displays the CPUP within the last 10 seconds.
- **1**: displays the CPUP within the last 1 second.
- Other numbers: display the total CPUP since the system starts.| [0, 0xFFFFFFFF] | +| taskID | Specifies the task ID.| [0, 0xFFFFFFFF] | -## Example -Run **cpup 1 5**. +## Usage Guidelines -## Output +- If no parameter is specified, the CPU usage of the system within the last 10 seconds is displayed. + +- If only **mode** is specified, the CPU usage within the specified period is displayed. + +- If both **mode** and **taskID** are specified, the CPU usage of the specified task within the given period is displayed. + + +## Example + +Run **cpup 1 5**. + + +## Output CPU usage of task 5 in the last one second: @@ -58,4 +44,3 @@ OHOS # cpup 1 5pid 5 CpuUsage in 1s: 0.0 ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-date.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-date.md index b232540382d344f2a18fb8424665e759f6301013..33a4f5d76af4afa3facc3503a1e400ce05b911f1 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-date.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-date.md @@ -1,69 +1,56 @@ # date -## Command Function + +## Command Function This command is used to query the system date and time. -## Syntax - -- date -- date --help -- date +\[_Format_\] -- date -u - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

--help

-

Displays help information.

-

N/A

-

+Format

-

Prints the date and time in the specified Format.

-

Placeholders listed in --help

-

-u

-

Displays UTC instead of the current time zone.

-

N/A

-
- -## Usage - -- If no parameter is specified, the system UTC date and time are displayed by default. -- The **--help**, **+Format**, and **-u** parameters are mutually exclusive. -- Currently, this command cannot be used to set the time or date. - -## Example - -Run **date +%Y--%m--%d**. - -## Output + +## Syntax + +- date + +- date --help + +- date +[_Format_] + +- date -u + + +## Parameters + +**Table 1** Parameter description + +| Parameter | Description | Value Range | +| ------- | ------------------------------ | ---------------------- | +| --help | Displays help information. | N/A | +| +Format | Prints the date and time in the specified format.| Placeholders listed in **--help**| +| -u | Displays UTC (not the current time zone). | N/A | + + +## Usage Guidelines + +- If no parameter is specified, the system date and time in UTC format are displayed by default. + +- The **--help**, **+Format**, and **-u** parameters are mutually exclusive. + +- Currently, this command cannot be used to set the time or date. + +## Note + +The shell does not support **date -u**. mksh supports it. To switch to mksh, run **cd bin** and **./mksh**. + +## Example + +Run **date +%Y--%m--%d**. + + +## Output System date in the specified format: + ``` OHOS:/$ date +%Y--%m--%d 1970--01--01 ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-dmesg.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-dmesg.md index 71950cfa70ab6e746e2f958a9d59bc5612698a3c..492d6017b621fe36de23bfc1ec199b6a320d910a 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-dmesg.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-dmesg.md @@ -1,108 +1,61 @@ # dmesg -## Command Function + +## Command Function This command is used to display system boot and running information. -## Syntax + +## Syntax dmesg -dmesg \[_-c/-C/-D/-E/-L/-U_\] - -dmesg -s \[_size_\] - -dmesg -l \[_level_\] - -dmesg \> \[_fileA_\] - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

-c

-

Prints content in the buffer and clears the buffer.

-

N/A

-

-C

-

Clears the buffer.

-

N/A

-

-D/-E

-

Disables or enables printing to the console.

-

N/A

-

-L/-U

-

Disables or enables printing via the serial port.

-

N/A

-

-s size

-

Sets the size of the buffer.

-

N/A

-

-l level

-

Sets the buffering level.

-

0 - 5

-

> fileA

-

Writes the content in the buffer to the specified file.

-

N/A

-
- -## Usage - -- 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. -- The parameters followed by hyphens \(-\) are mutually exclusive. - 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. - - -## Example - -Run **dmesg\> dmesg.log**. - -## Output - -Writing the content in the buffer to the **dmesg.log** file: +dmesg [_-c/-C/-D/-E/-L/-U_] + +dmesg -s [_size_] + +dmesg -l [_level_] + +dmesg > [_fileA_] + + +## Parameters + +**Table 1** Parameter description + +| Parameter | Description | Value Range | +| --------------- | ---------------------------------------- | --------------- | +| -c | Prints content in the buffer and clears the buffer. | N/A | +| -C | Clears the buffer. | N/A | +| -D/-E | Disables or enables printing to the console. | N/A | +| -L/-U | Disables or enables printing via the serial port. | N/A | +| -s size | Sets the size of the buffer. size specifies the buffer size to set.| N/A | +| -l level | Sets the buffering level. | [0, 5] | +| > fileA | Writes the content in the buffer to a file. | N/A | + + +## Usage Guidelines + +- 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**. + Debug ---> Enable a Debug Version ---> Enable Shell ---> Enable Shell dmesg + +- If no parameter is specified, all content in the buffer is printed. + +- The parameters followed by hyphens (-) are mutually exclusive. + 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. + + +## Example + +Run **dmesg> dmesg.log**. + + +## Output + +Write the content in the buffer to the **dmesg.log** file. ``` OHOS # dmesg > dmesg.log Dmesg write log to dmesg.log success ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-exec.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-exec.md index d928f722e2a0dd97883b1305b601d4198d345bf6..bcd235842be3f23326f6845ee8b90d01ae4f1323 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-exec.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-exec.md @@ -1,54 +1,42 @@ # exec -## Command Function +## Command Function -This command is a built-in shell command used to execute user-mode programs. +This command is a built-in shell command used to execute basic user-mode programs. -## Syntax -exec <_executable-file_\> +## Syntax -## Parameters +exec <*executable-file*> -**Table 1** Parameter description - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

executable-file

-

Indicates a valid executable file.

-

N/A

-
+## Parameters -## Usage +**Table 1** Parameter description + +| Parameter | Description | +| --------------- | ------------------ | +| executable-file | Specifies a valid executable file.| + + +## Usage Guidelines 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. -## Example -Example: +## Example -Run **exec helloworld**. +Run **exec helloworld**. + + +## Output -## Output ``` OHOS # exec helloworld OHOS # hello world! ``` ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->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. - +> **NOTE**
+> 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. diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-free.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-free.md index 7922bd0a47ef4172d90aacdea2061f45eac7f9c9..936df019edf15824d1996fa0ee28288a2b88b547 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-free.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-free.md @@ -1,87 +1,43 @@ # free -## Command Function + +## Command Function This command is used to display the memory usage in the system. -## Syntax - -free \[_-b | -k | -m | -g | -t_\] - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

No parameter

-

Displays the memory usage in bytes.

-

N/A

-

--help/-h

-

Displays the parameters supported by the free command.

-

N/A

-

-b

-

Displays the memory usage in bytes.

-

N/A

-

-k

-

Displays the memory usage in KiB.

-

N/A

-

-m

-

Displays the memory usage in MiB.

-

N/A

-

-g

-

Displays the memory usage in GiB.

-

N/A

-

-t

-

Displays the memory usage in TiB.

-

N/A

-
- -## Usage - -None - -## Example - -Run **free**, **free -k**, and **free -m**, respectively. - -## Output + +## Syntax + +free [_-b | -k | -m | -g | -t_] + + +## Parameters + +**Table 1** Parameter description + +| Parameter| Description | +| -------- | -------- | +| No parameter| Displays the memory usage in bytes.| +| --help/-h | Displays the parameters supported by the **free** command.| +| -b | Displays the memory usage in bytes.| +| -k | Display the memory waterline in KiB.| +| -m | Display the memory waterline in MiB.| +| -g | Displays the memory usage in GiB.| +| -t | Displays the memory usage in TiB.| + + +## Usage Guidelines + +None. + + +## Example + +Run **free**, **free -k**, and **free -m**, respectively. + + +## Output + ``` OHOS:/$ free @@ -101,40 +57,13 @@ Mem: 2 2 0 0 0 Swap: 0 0 0 ``` -**Table 2** Output - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

total

-

Total size of the dynamic memory pool

-

used

-

Size of the used memory

-

free

-

Size of the unallocated memory

-

shared

-

Size of the shared memory

-

buffers

-

Size of the buffer

-
+**Table 2** Output description + +| Parameter| Description| +| -------- | -------- | +| total | Total size of the dynamic memory pool.| +| used | Size of the used memory.| +| free | Size of the unallocated memory.| +| shared | Size of the shared memory.| +| buffers | Size of the buffer.| diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-help.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-help.md index afdf6852c2381d5d2ba09920016a197611c85fcc..e36d6a784f5629eb90e622f7b4ee166bb6243b9e 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-help.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-help.md @@ -1,36 +1,43 @@ # help -## Command Function + +## Command Function This command is used to display all commands in the OS and some Toybox commands. -## Syntax + +## Syntax help -## Parameters -None +## Parameters + +None. + -## Usage +## Usage Guidelines -You can run **help** to display all commands in the current OS. +You can run **help** to display all commands in the current OS. -## Example -Run **help**. +## Example -## Output +Run **help**. + + +## Output All commands in the system: + ``` After shell prompt "OHOS # ": Use ` [args ...]` to run built-in shell commands listed above. Use `exec [args ...]` or `./ [args ...]` to run external commands. OHOS:/$ help -*******************shell commands:************************* +***shell commands:* arp cat cat_logmpp cd chgrp chmod chown cp cpup date dhclient dmesg dns format free help hi3881 hwi @@ -44,11 +51,10 @@ watch writeproc After shell prompt "OHOS # ": Use ` [args ...]` to run built-in shell commands listed above. Use `exec [args ...]` or `./ [args ...]` to run external commands. -*******************toybox commands:************************ +***toybox commands: chgrp chmod chown cp date du free help ifconfig kill ls mkdir mount mv ping ps reboot rm rmdir top touch umount uname Use `toybox help [command]` to show usage information for a specific command. Use `shell` to enter interactive legacy shell. Use `alias` to display command aliases. ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-hwi.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-hwi.md index 52854b1cfa54f3aa3607f9ca2e43ac506d2edfce..c9f9cca164a3b251e34e95f2ca4608537b49d8f8 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-hwi.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-hwi.md @@ -1,155 +1,120 @@ # hwi -## Command Function + +## Command Function This command is used to query information about interrupts. -## Syntax -hwi +## Syntax -## Parameters - -None - -## Usage - -- Run **hwi** to display the interrupt IDs, count of interrupts, and registered interrupt names of the system. -- If **LOSCFG\_CPUP\_INCLUDE\_IRQ** is enabled, the interrupt handling time \(ATime\), CPU usage, and type of each interrupt are also displayed. - -## Example - -Run **hwi**. - -## Output - -- Interrupt information \(**LOSCFG\_CPUP\_INCLUDE\_IRQ** disabled\): - - ``` - OHOS # hwi - InterruptNo Count Name - 0: 0: - 1: 1025641: - 2: 0: - 29: 824049: - 37: 0: rtc_alarm - 38: 24: uart_pl011 - 48: 3: GPIO - 59: 0: - 62: 530: MMC_IRQ - 63: 70: MMC_IRQ - 64: 280: ETH - 67: 58: tde - 68: 0: JPGE_0 - 69: 0: IVE - 70: 0: VGS - 72: 0: VEDU_0 - 73: 0: nnie0 - 74: 0: nnie_gdc0 - 75: 0: VPSS - 76: 0: VI_PROC0 - 77: 0: JPEGD_0 - 83: 49455: HIFB_SOFT_INT - 87: 0: AIO interrupt - 88: 0: VI_CAP0 - 89: 0: MIPI_RX - 90: 49455: VO int - 91: 49456: HIFB Int - 96: 17601: MMC_IRQ - 100: 0: SPI_HI35XX - 101: 0: SPI_HI35XX - 102: 0: SPI_HI35XX - ``` - -- Interrupt information \(**LOSCFG\_CPUP\_INCLUDE\_IRQ** enabled\): - - ``` - OHOS # hwi - InterruptNo Count ATime(us) CPUUSE CPUUSE10s CPUUSE1s Mode Name - 0: 0 0 0.0 0.0 0.0 normal - 1: 937031 0 0.1 0.1 0.1 normal - 2: 0 0 0.0 0.0 0.0 normal - 29: 726166 5 0.54 0.57 0.59 normal - 37: 0 0 0.0 0.0 0.0 normal rtc_alarm - 38: 17 5 0.0 0.0 0.0 normal uart_pl011 - 48: 3 4 0.0 0.0 0.0 normal GPIO - 59: 0 0 0.0 0.0 0.0 normal - 62: 531 1 0.0 0.0 0.0 normal MMC_IRQ - 63: 69 1 0.0 0.0 0.0 normal MMC_IRQ - 64: 292 2 0.0 0.0 0.0 normal ETH - 67: 54 76 0.0 0.0 0.0 shared tde - 68: 0 0 0.0 0.0 0.0 shared JPGE_0 - 69: 0 0 0.0 0.0 0.0 shared IVE - 70: 0 0 0.0 0.0 0.0 shared VGS - 72: 0 0 0.0 0.0 0.0 shared VEDU_0 - 73: 0 0 0.0 0.0 0.0 shared nnie0 - 74: 0 0 0.0 0.0 0.0 shared nnie_gdc0 - 75: 0 0 0.0 0.0 0.0 shared VPSS - 76: 0 0 0.0 0.0 0.0 shared VI_PROC0 - 77: 0 0 0.0 0.0 0.0 shared JPEGD_0 - 83: 45529 8 0.5 0.5 0.5 shared HIFB_SOFT_INT - 87: 0 0 0.0 0.0 0.0 shared AIO interrupt - 88: 0 0 0.0 0.0 0.0 shared VI_CAP0 - 89: 0 0 0.0 0.0 0.0 shared MIPI_RX - 90: 45534 11 0.6 0.7 0.7 shared VO int - 91: 45533 2 0.1 0.1 0.1 shared HIFB Int - 96: 17383 2 0.0 0.0 0.0 normal MMC_IRQ - 100: 0 0 0.0 0.0 0.0 normal SPI_HI35XX - 101: 0 0 0.0 0.0 0.0 normal SPI_HI35XX - 102: 0 0 0.0 0.0 0.0 normal SPI_HI35XX - ``` - - **Table 1** Output - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

InterruptNo

-

Interrupt ID

-

Count

-

Number of interrupts

-

Name

-

Registered interrupt name

-

ATime

-

Interrupt handling time

-

CPUUSE

-

CPU usage

-

CPUUSE10s

-

CPU usage within the last 10 seconds

-

CPUUSE1s

-

CPU usage within the last 1 second

-

mode

-

Interrupt type, which can be any of the following:

-
  • normal: non-shared interrupt.
  • shared: shared interrupt.
-
+hwi +## Parameters + +None. + + +## Usage Guidelines + +- Run **hwi** to display the interrupt IDs, count of interrupts, and registered interrupt names of the system. + +- If **LOSCFG_CPUP_INCLUDE_IRQ** is enabled, the interrupt handling time (ATime), CPU usage, and type of each interrupt are also displayed. + + +## Example + +Run **hwi**. + + +## Output + +- Interrupt information (**LOSCFG_CPUP_INCLUDE_IRQ** disabled): + + ``` + OHOS # hwi + InterruptNo Count Name + 0: 0: + 1: 1025641: + 2: 0: + 29: 824049: + 37: 0: rtc_alarm + 38: 24: uart_pl011 + 48: 3: GPIO + 59: 0: + 62: 530: MMC_IRQ + 63: 70: MMC_IRQ + 64: 280: ETH + 67: 58: tde + 68: 0: JPGE_0 + 69: 0: IVE + 70: 0: VGS + 72: 0: VEDU_0 + 73: 0: nnie0 + 74: 0: nnie_gdc0 + 75: 0: VPSS + 76: 0: VI_PROC0 + 77: 0: JPEGD_0 + 83: 49455: HIFB_SOFT_INT + 87: 0: AIO interrupt + 88: 0: VI_CAP0 + 89: 0: MIPI_RX + 90: 49455: VO int + 91: 49456: HIFB Int + 96: 17601: MMC_IRQ + 100: 0: SPI_HI35XX + 101: 0: SPI_HI35XX + 102: 0: SPI_HI35XX + ``` + +- Interrupt information (**LOSCFG_CPUP_INCLUDE_IRQ** enabled): + + ``` + OHOS # hwi + InterruptNo Count ATime(us) CPUUSE CPUUSE10s CPUUSE1s Mode Name + 0: 0 0 0.0 0.0 0.0 normal + 1: 937031 0 0.1 0.1 0.1 normal + 2: 0 0 0.0 0.0 0.0 normal + 29: 726166 5 0.54 0.57 0.59 normal + 37: 0 0 0.0 0.0 0.0 normal rtc_alarm + 38: 17 5 0.0 0.0 0.0 normal uart_pl011 + 48: 3 4 0.0 0.0 0.0 normal GPIO + 59: 0 0 0.0 0.0 0.0 normal + 62: 531 1 0.0 0.0 0.0 normal MMC_IRQ + 63: 69 1 0.0 0.0 0.0 normal MMC_IRQ + 64: 292 2 0.0 0.0 0.0 normal ETH + 67: 54 76 0.0 0.0 0.0 shared tde + 68: 0 0 0.0 0.0 0.0 shared JPGE_0 + 69: 0 0 0.0 0.0 0.0 shared IVE + 70: 0 0 0.0 0.0 0.0 shared VGS + 72: 0 0 0.0 0.0 0.0 shared VEDU_0 + 73: 0 0 0.0 0.0 0.0 shared nnie0 + 74: 0 0 0.0 0.0 0.0 shared nnie_gdc0 + 75: 0 0 0.0 0.0 0.0 shared VPSS + 76: 0 0 0.0 0.0 0.0 shared VI_PROC0 + 77: 0 0 0.0 0.0 0.0 shared JPEGD_0 + 83: 45529 8 0.5 0.5 0.5 shared HIFB_SOFT_INT + 87: 0 0 0.0 0.0 0.0 shared AIO interrupt + 88: 0 0 0.0 0.0 0.0 shared VI_CAP0 + 89: 0 0 0.0 0.0 0.0 shared MIPI_RX + 90: 45534 11 0.6 0.7 0.7 shared VO int + 91: 45533 2 0.1 0.1 0.1 shared HIFB Int + 96: 17383 2 0.0 0.0 0.0 normal MMC_IRQ + 100: 0 0 0.0 0.0 0.0 normal SPI_HI35XX + 101: 0 0 0.0 0.0 0.0 normal SPI_HI35XX + 102: 0 0 0.0 0.0 0.0 normal SPI_HI35XX + ``` + +**Table 1** Output description + +| Parameter| Description| +| -------- | -------- | +| InterruptNo | Interrupt number.| +| Count | Number of interrupts.| +| Name | Registered interrupt name.| +| ATime | Interrupt handling time.| +| CPUUSE | CPU usage.| +| CPUUSE10s | CPU usage in the last 10s.| +| CPUUSE1s | CPU usage in the last 1s.| +| mode | Interrupt type, which can be any of the following:
- **normal**: non-shared interrupt.
- **shared**: shared interrupt.| diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-kill.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-kill.md index 841bcc90ac36ced0dc75a32e52defdcb89d51aff..4a68f5b68c533902900407f3c0e3769ee898b8ce 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-kill.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-kill.md @@ -1,125 +1,101 @@ # kill -## Command Function - -This command is used to send a signal to a specified process. - -## Syntax - -kill \[-l \[_signo_\] | _-s signo_ | _-signo_\] _pid..._ - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

--help

-

Displays the parameters supported by the kill command.

-

N/A

-

-l

-

Lists the names and numbers of signals.

-

N/A

-

-s

-

Sends signals

-

N/A

-

signo

-

Specifies the signal number.

-

[1,30]

-

pid

-

Specifies the process ID.

-

[1,MAX_INT]

-
- ->![](../public_sys-resources/icon-notice.gif) **NOTICE:** ->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 - -- 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 - -- Query the process list before killing process 42. - - ``` - OHOS:/$ ps - allCpu(%): 4.67 sys, 195.33 idle - PID PPID PGID UID Status VirtualMem ShareMem PhysicalMem CPUUSE10s PName - 1 -1 1 0 Pending 0x33b000 0xbb000 0x4db02 0.0 init - 2 -1 2 0 Pending 0xdabc08 0 0xdabc08 1.14 KProcess - 3 1 3 7 Pending 0x72e000 0x1a3000 0x1d24c2 0.0 foundation - 4 1 4 8 Pending 0x362000 0xbb000 0x5c6ff 0.0 bundle_daemon - 5 1 5 1 Pending 0xdfa000 0x2e7000 0x1484f0 0.0 appspawn - 6 1 6 0 Pending 0x688000 0x137000 0x11bca0 0.0 media_server - 7 1 7 0 Pending 0x9d2000 0x103000 0xa1cdf 0.88 wms_server - 8 1 8 2 Pending 0x1f5000 0x48000 0x47dc2 0.2 mksh - 12 1 12 0 Pending 0x4d4000 0x112000 0xe0882 0.0 deviceauth_service - 13 1 13 0 Pending 0x34f000 0xbd000 0x51799 0.0 sensor_service - 14 1 14 2 Pending 0x34e000 0xb3000 0x52184 0.0 ai_server - 15 1 15 0 Pending 0x61f000 0x13b000 0x168071 0.45 softbus_server - 42 8 42 2 Pending 0x1c1000 0x3a000 0x1106a 0.9 test_demo - 43 8 43 2 Running 0x1d7000 0x3a000 0x1e577 0.0 toybox - ``` - -- 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. - - ``` - OHOS:/$ kill -s 9 42 - OHOS:/$ - [1] + Killed ./nfs/test_demo - OHOS:/$ ps - allCpu(%): 4.73 sys, 195.27 idle - PID PPID PGID UID Status VirtualMem ShareMem PhysicalMem CPUUSE10s PName - 1 -1 1 0 Pending 0x33b000 0xbb000 0x4e01c 0.0 init - 2 -1 2 0 Pending 0xda5fa4 0 0xda5fa4 1.14 KProcess - 3 1 3 7 Pending 0x72e000 0x1a3000 0x1d29dc 0.0 foundation - 4 1 4 8 Pending 0x362000 0xbb000 0x5cc19 0.0 bundle_daemon - 5 1 5 1 Pending 0xdfa000 0x2e7000 0x148a0a 0.0 appspawn - 6 1 6 0 Pending 0x688000 0x137000 0x11c1ba 0.0 media_server - 7 1 7 0 Pending 0x9d2000 0x103000 0xa21f9 0.89 wms_server - 8 1 8 2 Pending 0x1f5000 0x48000 0x482dc 0.2 mksh - 12 1 12 0 Pending 0x4d4000 0x112000 0xe0d9c 0.0 deviceauth_service - 13 1 13 0 Pending 0x34f000 0xbd000 0x51cb3 0.0 sensor_service - 14 1 14 2 Pending 0x34e000 0xb3000 0x5269e 0.0 ai_server - 15 1 15 0 Pending 0x61f000 0x13b000 0x16858b 0.51 softbus_server - 45 8 45 2 Running 0x1d7000 0x3a000 0x1e9f5 0.0 toybox - ``` - -- Run the **kill -100 31** command. - -## Output - -**Example 1**: The signal is successfully sent to process 42. + +## Command Function + +This command is used to send a signal to a process to terminate the abnormal application. + + +## Syntax + +kill [-l [_signo_] | _-s signo_ | _-signo_] *pid...* + + +## Parameters + +**Table 1** Parameter description + +| Parameter | Description | Value Range | +| ------ | -------------------------- | ----------- | +| --help | Displays the parameters supported by the **kill** command.| N/A | +| -l | Lists the names and numbers of signals. | N/A | +| -s | Sends a signal. | N/A | +| signo | Specifies the signal number. | [1, 30] | +| pid | Specifies the process ID. | [1, MAX_INT] | + +> **NOTICE**
+> 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 Guidelines + +- 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]. + +## 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. + + ``` + OHOS:/$ ps + allCpu(%): 4.67 sys, 195.33 idle + PID PPID PGID UID Status VirtualMem ShareMem PhysicalMem CPUUSE10s PName + 1 -1 1 0 Pending 0x33b000 0xbb000 0x4db02 0.0 init + 2 -1 2 0 Pending 0xdabc08 0 0xdabc08 1.14 KProcess + 3 1 3 7 Pending 0x72e000 0x1a3000 0x1d24c2 0.0 foundation + 4 1 4 8 Pending 0x362000 0xbb000 0x5c6ff 0.0 bundle_daemon + 5 1 5 1 Pending 0xdfa000 0x2e7000 0x1484f0 0.0 appspawn + 6 1 6 0 Pending 0x688000 0x137000 0x11bca0 0.0 media_server + 7 1 7 0 Pending 0x9d2000 0x103000 0xa1cdf 0.88 wms_server + 8 1 8 2 Pending 0x1f5000 0x48000 0x47dc2 0.2 mksh + 10 5 5 101 Pending 0x11ec000 0x2f9000 0x206047 0.93 com.example.launcher + 12 1 12 0 Pending 0x4d4000 0x112000 0xe0882 0.0 deviceauth_service + 13 1 13 0 Pending 0x34f000 0xbd000 0x51799 0.0 sensor_service + 14 1 14 2 Pending 0x34e000 0xb3000 0x52184 0.0 ai_server + 15 1 15 0 Pending 0x61f000 0x13b000 0x168071 0.45 softbus_server + 42 8 42 2 Pending 0x1c1000 0x3a000 0x1106a 0.9 test_demo + 43 8 43 2 Running 0x1d7000 0x3a000 0x1e577 0.0 toybox + ``` + +- 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. + + ``` + OHOS:/$ kill -s 9 42 + OHOS:/$ + [1] + Killed ./nfs/test_demo + OHOS:/$ ps + allCpu(%): 4.73 sys, 195.27 idle + PID PPID PGID UID Status VirtualMem ShareMem PhysicalMem CPUUSE10s PName + 1 -1 1 0 Pending 0x33b000 0xbb000 0x4e01c 0.0 init + 2 -1 2 0 Pending 0xda5fa4 0 0xda5fa4 1.14 KProcess + 3 1 3 7 Pending 0x72e000 0x1a3000 0x1d29dc 0.0 foundation + 4 1 4 8 Pending 0x362000 0xbb000 0x5cc19 0.0 bundle_daemon + 5 1 5 1 Pending 0xdfa000 0x2e7000 0x148a0a 0.0 appspawn + 6 1 6 0 Pending 0x688000 0x137000 0x11c1ba 0.0 media_server + 7 1 7 0 Pending 0x9d2000 0x103000 0xa21f9 0.89 wms_server + 8 1 8 2 Pending 0x1f5000 0x48000 0x482dc 0.2 mksh + 10 5 5 101 Pending 0x11ec000 0x2f9000 0x206561 0.93 com.example.launcher + 12 1 12 0 Pending 0x4d4000 0x112000 0xe0d9c 0.0 deviceauth_service + 13 1 13 0 Pending 0x34f000 0xbd000 0x51cb3 0.0 sensor_service + 14 1 14 2 Pending 0x34e000 0xb3000 0x5269e 0.0 ai_server + 15 1 15 0 Pending 0x61f000 0x13b000 0x16858b 0.51 softbus_server + 45 8 45 2 Running 0x1d7000 0x3a000 0x1e9f5 0.0 toybox + ``` + +- Run the **kill -100 31** command. + + +## Output + +The command output is as follows: + +Example 1: The signal is successfully sent to process 42. + ``` OHOS:/$ kill -s 9 42 @@ -131,10 +107,10 @@ Process 42 is killed. **Example 2**: The signal fails to be sent to process 31. + ``` OHOS:/$ kill -100 31 kill: Unknown signal '(null)' ``` -**Unknown signal '\(null\)'** is displayed because the **signo** value **100** exceeds the value range \[0, 64\]. - +**Unknown signal '(null)'** is displayed because the **signo** value **100** exceeds the value range [0, 64]. diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-log.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-log.md index 9809d169a35146e4a886a8706dbb30fb56162322..21f7dd52765eeda6b59b5896144446ec15aca850 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-log.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-log.md @@ -1,71 +1,62 @@ # log -## Command Function + +## Command Function This command is used to set and query log configuration. -## Syntax -log level \[_levelNum_\] +## Syntax + +log level [_levelNum_] + + -## Parameters +## Parameters -**Table 1** Parameter description +**Table 1** Parameter description - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

levelNum

-

Specifies the level of logs to print.

-

[0,5]

-
+| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| levelNum | Specifies the level of logs to print.| [0, 5] | -## Usage -- This command depends on **LOSCFG\_SHELL\_LK**. Before using this command, select **Enable Shell lk** on **menuconfig**. +## Usage Guidelines - **Debug** ---\> **Enable a Debug Version** ---\> **Enable Shell** ---\> **Enable Shell lK** +- This command can be used only after **LOSCFG_SHELL_LK** is enabled. Before using this command, set **Enable Shell lk** to **Yes** on **menuconfig**. + **Debug** ---> **Enable a Debug Version** ---> **Enable Shell** ---> **Enable Shell lK** -- The **log level** command is used to set the log level, which can be any of the following: +- The **log level** command sets the log level, which can be any of the following: + TRACE_EMG = 0, - TRACE\_EMG = 0, + TRACE_COMMON = 1, - TRACE\_COMMON = 1, + TRACE_ERROR = 2, - TRACE\_ERROR = 2, + TRACE_WARN = 3, - TRACE\_WARN = 3, + TRACE_INFO = 4, - TRACE\_INFO = 4, + TRACE_DEBUG = 5 - TRACE\_DEBUG = 5 + If the log level specified is not within the value range, a message will be displayed. - If the log level specified is not within the value range, a message will be displayed. +- If **[levelNum]** is not specified, this command displays the current log level and how to use it. -- If **\[levelNum\]** is not specified, this command queries the current log level. The usage method is also displayed. -- If the log level is set to **4** or **5** in the source code of the open-source small system, a large number of logs will be printed. +- If the log level is set to **4** or **5** in the source code of an OpenHarmony small system, a large number of logs will be printed. -## Example -Run **log level 3**. +## Example -## Output +Run **log level 3**. + + +## Output + +The log print level is set to WARN. -Setting the log print level to WARN: ``` OHOS # log level 3 Set current log level WARN ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-memcheck.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-memcheck.md index 673393acbf78cce8379196dc0b8436565c4a9c2d..62e0005ebec2cc6d3f9cf34cbd4165d09074700e 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-memcheck.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-memcheck.md @@ -1,36 +1,45 @@ # memcheck -## Command Function + +## Command Function 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 + +## Syntax memcheck -## Parameters -None +## Parameters + +None. + + +## Usage Guidelines -## Usage +- 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 -Run **memcheck**. +## Example -## Output +Run **memcheck**. -Example 1: All nodes in the memory pool are complete. +Run **memcheck**, and memory overwriting occurs. + + +## Output + +Example 1: No error is detected. ``` OHOS # memcheck system memcheck over, all passed! ``` -Example 2: Out-of-bounds memory access is detected. +Example 2: Memory overwriting is detected. ``` [L0S DLnkCheckMenl 349, memory check @@ -43,7 +52,7 @@ puмExcBuffAddr pc = 0x803ad7a4 puwExcBuffAddr lr = 0x803ad7a4 puwExcBuffAddr sp = 0х80cb7de0 puwExcBuffAddr fp = 0x80cb7dec -*******backtrace begin******* +***backtrace begin*** traceback 0 -- lr = 0х8037cb84 traceback 0 -- fp = 0х80cb7e1c traceback 1 -- lr = 0х8037033c @@ -55,4 +64,3 @@ traceback 3 -- fp = 0х80cb7ea4 traceback 4 -- lr = 0x803ad9e8 traceback 4 -- fp = 9x11111111 ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-oom.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-oom.md index 9372b8ae18ee255fba9f5abd8c9ca7c1a3a3946b..e9b1c0e806c3e05c83d1188a86f7e1dc67e075cc 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-oom.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-oom.md @@ -1,82 +1,56 @@ # oom -## Command Function + +## Command Function This command is used to query and set the low memory threshold and the PageCache reclaim threshold. -## Syntax + +## Syntax oom -oom -i \[_interval_\] +oom -i [_interval_] -oom -m \[_mem byte_\] +oom -m [_mem byte_] -oom -r \[_mem byte_\] +oom -r [_mem byte_] oom -h | --help -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

-i [interval]

-

Sets the interval (in ms) for checking the Out Of Memory (OOM) thread task.

-

100 to 10000

-

-m [mem byte]

-

Sets the low memory threshold (in MB).

-

0 (disables the low memory check) to 1

-

-r [mem byte]

-

Sets the PageCache reclaim threshold.

-

Ranging from the low memory threshold to the maximum available system memory

-

-h | --help

-

Displays help information.

-

N/A

-
- -## Usage - -If no parameter is specified, this command displays the current OOM configuration. - ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->If the system memory is insufficient, the system displays a message indicating the insufficiency. - -## Example + +## Parameters + +**Table 1** Parameter description + +| Parameter | Description | Value Range | +| ----------------------- | ------------------------------- | ------------------------------------------------------------ | +| -i [interval] | Sets the interval (in ms) for checking the Out Of Memory (OOM) thread task.| [100, 10000] | +| -m [mem byte] | Sets the low memory threshold (in MB). | 0 to 1
The value **0** means not to perform the low memory threshold check. | +| -r [mem byte] | Sets the PageCache reclaim threshold. | Low memory threshold to the maximum available memory of the system
Generally, the size of a PageCache is 4 KB. Sometimes, it is 16 KB to 64 KB. | +| -h \| --help | Displays help information. | N/A | + + +## Usage Guidelines + + If no parameter is specified, this command displays the current OOM configuration. + +> **NOTE**
+> If the system memory is insufficient, the system displays a message indicating the insufficiency. + + +## Example Run the following commands: -- oom -- oom -i 100 +- oom +- oom -i 100 + -## Output +## Output + +Example 1: The OOM configuration is displayed by default. -Example 1: displaying OOM configuration ``` OHOS:/$ oom @@ -88,6 +62,7 @@ OHOS:/$ oom Information displayed when the system memory is insufficient: + ``` T:20 Enter:IT MEM 00M 001 [oom] OS is in low memory state @@ -124,7 +99,7 @@ R10 = 0xa0a0a0a R11 = 0x20e20c8c R12 = 0х0 CPSR = 0х80000010 -*******backtrace beain******* +***backtrace beain*** traceback 0 -- lr = 0x9242e1c fp = 0х20e20cc4 lr in /usr/bin/testsuits apr 0x4be1c traceback 1 -- 1r = 0х92430cc fp = 0x20e20cdc lr in /usr/bin/testsuits app --> 0x4c0cc traceback 2 -- 1r = 0x9396ab0 fp = 0x20e20cec lr in /usr/bin/testsuits app -> 0х19fab0 @@ -133,49 +108,23 @@ traceback 4 -- lr = 0x92427d4 fp = 0x20e20d44 lr in /usr/bin/testsuits app --> 0 traceback 5 -- 1r = 0x20c4df50 fp = 0хb0b0b0b 1r in /1ib/libc.so - -> 0x62f50 ``` -Example 2: setting the OOM check interval to 100 ms + +Example 2: The OOM check interval is set to 100 ms. + + ``` OHOS:/$ oom -i 100 [oom] set oom check interval (100)ms successful ``` -**Table 2** Output - - - - - - - - - - - - - - - - - - - - - - -

Output

-

Description

-

[oom] OS is in low memory state

-

total physical memory: 0x1bcf000(byte), used: 0x1b50000(byte), free: 0x7f000(byte), low memory threshold: 0x80000(byte)

-

The operating system has low memory.

-

The available physical memory in the operating system is 0x1bcf000 bytes, 0x1b50000 bytes have been used, and 0x7f000 bytes are available. The current low memory threshold is 0x80000 bytes.

-

[oom] candidate victim process init pid: 1, actual phy mem byte: 82602

-

Memory usage of each process. The physical memory occupied by the init process is 82602 bytes.

-

[oom] candidate victim process UserProcess12 pid: 12, actual phy mem byte: 25951558

-

The actual 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.

-
+**Table 2** Output description + +| Parameter | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| [oom] OS is in low memory state
total physical memory: 0x1bcf000(byte), used: 0x1b50000(byte), free: 0x7f000(byte), low memory threshold: 0x80000(byte) | The OS has low memory.
The total physical memory is **0x1bcf000** bytes, **0x1b50000** bytes are used, and **0x7f000** bytes are left.
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. | diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-pmm.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-pmm.md index ffa823db63ab1ff65a94f364c5f461e158b20096..18b86951a2c522947589659e795aa783d8f2a54b 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-pmm.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-pmm.md @@ -1,26 +1,32 @@ # pmm -## Command Function + +## Command Function This command is used to check the usage of the physical pages of the system memory and the page cache. -## Syntax + +## Syntax pmm -## Parameters -None +## Parameters + +None. + + +## Usage Guidelines + +This command is available only in the **Debug** version. -## Usage -This command is available only in the **Debug** version. +## Example -## Example +Run **pmm**. -Run **pmm**. -## Output +## Output Usage of physical pages: @@ -49,62 +55,17 @@ Vnode number = 67 Vnode memory size = 10720(B) ``` -**Table 1** Output - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

phys_seg

-

Address of the physical page control block

-

base

-

First physical page address, that is, start address of the physical page memory

-

size

-

Size of the physical page memory

-

free_pages

-

Number of free physical pages

-

active anon

-

Number of active anonymous pages in the page cache

-

inactive anon

-

Number of inactive anonymous pages in the page cache

-

active file

-

Number of active file pages in the page cache

-

inactive file

-

Number of inactive file pages in the page cache

-

pmm pages

-

total: total number of physical pages.

-

used: number of used physical pages.

-

free: number of free physical pages.

-
+**Table 1** Output description + +| Parameter| Description| +| -------- | -------- | +| phys_seg | Address of the physical page control block.| +| base | First physical page address, that is, start address of the physical page memory.| +| size | Size of the physical page memory.| +| free_pages | Number of free physical pages.| +| active anon | Number of active anonymous pages in the page cache.| +| inactive anon | Number of inactive anonymous pages in the page cache.| +| active file | Number of active file pages in the page cache.| +| inactive file | Number of inactive file pages in the page cache.| +| pmm pages | **total** indicates the total number of physical pages.
**used** indicates the number of used physical pages.
**free** indicates the number of idle physical pages. | diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-reboot.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-reboot.md index 000cc3873b7069ad2711a73b818a5330ebb775c3..1946b80351426b884b1a6c5e18e649e5c3b153ca 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-reboot.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-reboot.md @@ -1,26 +1,31 @@ # reboot -## Command Function + +## Command Function This command is used to restart a device. -## Syntax + +## Syntax reboot -## Parameters -None +## Parameters + +None. + + +## Usage Guidelines -## Usage +After the **reboot** command is executed, the device restarts immediately. -After the **reboot** command is executed, the device restarts immediately. -## Example +## Example reboot -## Output -None +## Output +None. diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-reset.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-reset.md index 7fca8b04a7cebdd6fb998c3f8472c7b1950faa3e..d8e9151e3b61ea9ec08674c5dff9ced753d16a44 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-reset.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-reset.md @@ -1,26 +1,31 @@ # reset -## Command Function + +## Command Function This command is used to restart a device. -## Syntax + +## Syntax reset -## Parameters -None +## Parameters + +None. + + +## Usage Guidelines -## Usage +After the **reset** command is executed, the device restarts immediately. -After the **reset** command is executed, the device restarts immediately. -## Example +## Example -Run **reset**. +Run **reset**. -## Output -None +## Output +None. diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-sem.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-sem.md index 61e9c5cce389ef7a90eb244f224ded03f00664d1..b079f1880ad5a4f2dc289a0497997694db7b5562 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-sem.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-sem.md @@ -1,58 +1,44 @@ # sem -## Command Function + +## Command Function This command is used to query information about kernel semaphores. -## Syntax -sem \[_ID__ / fulldata_\] +## Syntax + +sem [_ID__ / fulldata_] + + +## Parameters + +**Table 1** Parameter description -## Parameters +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| ID | Specifies the semaphore ID.| [0, 1023] or [0x0, 0x3FF]| +| fulldata | Displays information about all semaphores in use.
The displayed information includes **SemID**, **Count**, **Original Count**, **Creator TaskEntry**, and **Last Access Time**. | N/A | -**Table 1** Parameter description - - - - - - - - - - - - - - - -

Parameter

-

Parameters

-

Value Range

-

ID

-

Specifies the semaphore ID.

-

[0, 1023] or [0x0, 0x3FF]

-

fulldata

-

Queries information about all the semaphores in use. The information includes SemID, Count, OriginalCount, Creator(TaskEntry), and LastAccessTime.

-

N/A

-
+## Usage Guidelines -## Usage +- 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. -- The **fulldata** parameter depends on **LOSCFG\_DEBUG\_SEMAPHORE**. Before using this parameter, select **Enable Semaphore Debugging** on **menuconfig**. +- If **ID** is specified, the use of the specified semaphore is displayed. - 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**. + **Debug** ---> **Enable a Debug Version** ---> **Enable Debug LiteOS Kernel Resource** ---> E**nable Semaphore Debugging** -## Example +## Example -- Run **sem**. -- Configure **LOSCFG\_DEBUG\_SEMAPHORE** and run **sem fulldata**. +- Run **sem**. -## Output +- Configure **LOSCFG_DEBUG_SEMAPHORE** and run **sem fulldata**. + + +## Output Example 1: brief semaphore information @@ -81,31 +67,17 @@ OHOS # sem 0x00000006 0 ``` -**Table 2** Output - - - - - - - - - - - - - -

Parameter

-

Description

-

SemID

-

Semaphore ID

-

Count

-

Number of times that the semaphore is used

-
- ->![](../public_sys-resources/icon-note.gif) **NOTE** ->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. +**Table 2** Output description + +| Parameter| Description| +| -------- | -------- | +| SemID | Semaphore ID.| +| Count | Number of times that the semaphore is used.| + +> **NOTE**
+> 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. Example 2: detailed semaphore information @@ -141,40 +113,12 @@ Used Semaphore List: 0x38 0x1 0x1 0x404978fc 0x395 ``` -**Table 3** Output description - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

SemID

-

Semaphore ID

-

Count

-

Number of times that the semaphore is used

-

OriginalCount

-

Original count of the semaphore

-

Creator

-

Address of the entry function of the thread used to create the semaphore

-

LastAccessTime

-

Last time when the semaphore was accessed

-
+**Table 3** Output description +| Parameter| Description| +| -------- | -------- | +| SemID | Semaphore ID.| +| Count | Number of times that the semaphore is used.| +| OriginalCount | Original count of the semaphore.| +| Creator | Address of the entry function of the thread used to create the semaphore.| +| LastAccessTime | Last time when the semaphore was accessed.| diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-stack.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-stack.md index da1aad64eac9f0e54ce8fe75f41a8da78ef344ef..9f04a4e979c0789f75b62c9adc36ac7f6ec520e5 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-stack.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-stack.md @@ -1,27 +1,32 @@ # stack -## Command Function +## Command Function This command is used to check the usage of each stack in the system. -## Syntax + +## Syntax stack -## Parameters -None +## Parameters + +None. + + +## Usage Guidelines + +None. -## Usage -None +## Example -## Example +Run **stack**. -Run **stack**. -## Output +## Output System stack usage: @@ -35,40 +40,12 @@ OHOS # stack exc_stack 0 0x405c9000 0x1000 0x0 ``` -**Table 1** Output - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

stack name

-

Name of the stack

-

cpu id

-

CPU ID

-

stack addr

-

Stack address

-

total size

-

Total stack size

-

used size

-

Size of the stack used

-
+**Table 1** Output description +| Parameter| Description| +| -------- | -------- | +| stack name | Name of the stack.| +| cpu id | CPU number.| +| stack addr | Stack address.| +| total size | Total stack size.| +| used size | Size of the stack used.| diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-su.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-su.md index 7e23b3b60dcd0ee80701d5d42b0f4ac267e444d2..479daa7ece87d057cba58783ce7aa50ff223a930 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-su.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-su.md @@ -1,56 +1,43 @@ # su -## Command Function + +## Command Function This command is used to switch the user account. -## Syntax -su \[_uid_\] \[_gid_\] +## Syntax + +su [_uid_] [_gid_] + + +## Parameters + +**Table 1** Parameter description -## Parameters +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| uid | Specifies the ID of the target user.| - Left blank
- [0, 60000] | +| gid | Specifies the ID of the target user group.| - Left blank
- [0, 60000] | -**Table 1** Parameter description - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

uid

-

Specifies the ID of the target user.

-
  • Left blank
  • [0,60000]
-

gid

-

Specifies the ID of the target user group.

-
  • Left blank
  • [0,60000]
-
+## Usage Guidelines -## Usage +- If no parameter is specified, the **su** command switches to user **root** by default. The **uid** and **gid** for user **root** are both **0**. -- If no parameter is specified, the **su** command switches to user **root** by default. The **uid** and **gid** for user **root** are both **0**. -- If **uid** and **gid** are specified, this command allows commands to be executed as the user with the specified **uid** and **gid**. -- If the input parameter is out of the range, an error message will be printed. +- If **uid** and **gid** are specified, this command allows commands to be executed as the user with the specified **uid** and **gid**. -## Example +- If the input parameter is out of the range, an error message will be printed. -Run **su 1000 1000**. -## Output +## Example -Switching to the user with both **uid** and **gid** of **1000**: +Run **su 1000 1000**. + + +## Output + +The user with both **uid** and **gid** of **1000** is switched. ``` OHOS # ls @@ -63,4 +50,3 @@ Directory /data/system/param: -rw-r--r-- O u:1000 g:1000 hello 2.txt -гw-r--r-- 0 u:0 g:0 hello_1.txt ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-swtmr.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-swtmr.md index a764d66fc83e1d7d8b2e2eabacfbefc3a61462f7..b436a80e4911073c6df1db96ff6b56e4752d13b0 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-swtmr.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-swtmr.md @@ -1,50 +1,42 @@ # swtmr -## Command Function +## Command Function This command is used to query information about system software timers. -## Syntax -swtmr \[_ID_\] +## Syntax -## Parameters +swtmr [_ID_] -**Table 1** Parameter description - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

ID

-

Specifies the ID of a software timer.

-

[0,0xFFFFFFFF]

-
+## Parameters -## Usage +**Table 1** Parameter description -- If no parameter is specified, information about all software timers is displayed. -- If the **ID** parameter is specified, information about the specified software timer is displayed. +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| ID | Specifies the ID of a software timer.| [0, 0xFFFFFFFF] | -## Example + +## Usage Guidelines + +- If no parameter is specified, information about all software timers is displayed. + +- If the **ID** parameter is specified, information about the specified software timer is displayed. + + +## Example Run the following commands: -- swtmr -- swtmr 1 +- swtmr + +- swtmr 1 -## Output + +## Output Example 1: information about all software timers @@ -76,56 +68,19 @@ SwTmrID State Mode Interval Count Arg handlerAddr 0x00000001 Ticking Period 1000 841 0x00000000 0x4037fc04 ``` -**Table 2** Output - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

SwTmrID

-

ID of the software timer

-

State

-

Status of the software timer

-

The value can be UnUsed, Created, or Ticking.

-

Mode

-

Mode of the software timer

-

The value can be Once, Period, or NSD (one-shot timer that will not be automatically deleted after the timer has expired).

-

Interval

-

Number of ticks for the software timer

-

Count

-

Number of times that the software timer has been used

-

Arg

-

Input parameter

-

handlerAddr

-

Address of the callback

-
- ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->- 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. - + **Table 2** Output description + +| Parameter| Description| +| -------- | -------- | +| SwTmrID | ID of the software timer.| +| State | Status of the software timer.
The status may be **UnUsed**, **Created**, or **Ticking**.| +| Mode | Mode of the software timer.
The value can be **Once**, **Period**, or **NSD** (one-shot timer that will not be automatically deleted after the timer has expired).| +| Interval | Number of ticks for the software timer.| +| Count | Number of times that the software timer has been used.| +| Arg | Input parameter.| +| handlerAddr | Address of the callback.| + +> **NOTE**
+> - 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. diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-sysinfo.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-sysinfo.md index c1a81444f8b4af508906bd02a7ca500a36e7c0ad..b476c06d33d370470e0d291593a99a516b92ea4a 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-sysinfo.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-sysinfo.md @@ -1,26 +1,32 @@ # systeminfo -## Command Function + +## Command Function This command is used to display the resource usage of the current operating system, including tasks, semaphores, mutexes, queues, and software timers. -## Syntax + +## Syntax systeminfo -## Parameters -None +## Parameters + +None. + -## Usage +## Usage Guidelines -None +None. -## Example -Run **systeminfo**. +## Example -## Output +Run **systeminfo**. + + +## Output Usage of system resources: @@ -34,60 +40,15 @@ OHOS:/$ systeminfo SwTmr 20 1024 YES ``` -**Table 1** Output - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Module

-

Module name

-

Used

-

Used resources

-

Total

-

Total resources

-

Enabled

-

Whether the module is enabled

-

Task

-

Task

-

Sem

-

Semaphore

-

Mutex

-

Mutex

-

Queue

-

Message queue

-

SwTmr

-

Software timer

-
- +**Table 1** Output description + +| Parameter | Description | +| ------- | -------------- | +| Module | Module name. | +| Used | Used resources. | +| Total | Total resources. | +| Enabled | Whether the module is enabled.| +| Task | Task. | +| Sem | Semaphore. | +| Queue | Using queues. | +| SwTmr | Software timer. | diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-task.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-task.md index 2510d417ccf6bc7e9d398daadf9941bd87e0cb1c..704943bc02067ad14ef153420227beff568ec773 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-task.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-task.md @@ -1,47 +1,38 @@ # task -## Command Function + +## Command Function This command is used to query information about processes and threads. -## Syntax + +## Syntax task/task -a -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

-a

-

Displays all information.

-

N/A

-
- -## Usage + +## Parameters + +**Table 1** Parameter description + +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| -a | Displays all information.| N/A | + + +## Usage Guidelines If no parameter is specified, partial task information is displayed by default. -## Example -Run **task**. +## Example + +Run **task**. -## Output -Task information \(partial\): +## Output + +Task information (partial): ``` OHOS # task @@ -55,6 +46,7 @@ OHOS # task 6 1 6 0 Pending 0x688000 0x137000 0x11c518 0.0 media_server 7 1 7 0 Pending 0x9d2000 0x103000 0xa1ddf 0.89 wms_server 8 1 1 1000 Running 0x2bf000 0x8f000 0x2a8c6 0.0 shell + 9 5 5 101 Pending 0x11ea000 0x2f9000 0x20429d 0.97 com.example.launcher 11 1 11 0 Pending 0x4d4000 0x112000 0xe0ad7 0.0 deviceauth_service 12 1 12 0 Pending 0x34f000 0xbd000 0x519ee 0.0 sensor_service 13 1 13 2 Pending 0x34e000 0xb3000 0x523d9 0.0 ai_server @@ -68,75 +60,19 @@ OHOS # task 7 2 0x3 -1 Pending 0x4e20 0xa5c 0.0 0 PlatformWorkerThread ``` -**Table 2** Output - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

PID

-

Process ID

-

PPID

-

Parent process ID

-

PGID

-

Process group ID

-

UID

-

User ID

-

Status

-

Current task status

-

CPUUSE10s

-

CPU usage within last 10 seconds

-

PName

-

Process name

-

TID

-

Task ID

-

StackSize

-

Size of the task stack

-

WaterLine

-

Peak value of the stack used

-

MEMUSE

-

Memory usage

-

TaskName

-

Task name

-
- +**Table 2** Output description + +| Parameter| Description| +| -------- | -------- | +| PID | Process ID.| +| PPID | Parent process ID.| +| PGID | Process group ID.| +| UID | User ID.| +| Status | Current task status.| +| CPUUSE10s | CPU usage within last 10 seconds.| +| PName | Name of the process.| +| TID | Task ID.| +| StackSize | Size of the task stack.| +| WaterLine | Peak value of the stack used.| +| MEMUSE | Memory usage.| +| TaskName | Task name.| diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-top.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-top.md index 4fa4959b1b082d0394b78ef271ac9b89a4f29901..34473f90c320656aecea022849e401b515b08c18 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-top.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-top.md @@ -1,56 +1,40 @@ # top -## Command Function + +## Command Function This command is used to query process and thread information. -## Syntax - -top \[_-a_\] - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Default Value

-

Value Range

-

--help

-

Displays the parameters supported by the top command.

-

N/A

-
  

-a

-

Displays detailed information.

-

N/A

-
  
- -## Usage - -If no parameter is specified, this command displays process and thread information of some tasks by default. - -## Example - -Run **top**. - -## Output + +## Syntax + +top [_-a_] + + +## Parameters + +**Table 1** Parameter description + +| Parameter | Description | +| ------ | --------------------------- | +| --help | Displays the parameters supported by the **top** command.| +| -a | Displays detailed information. | + + +## Usage Guidelines + +If no parameter is specified, partial task information is displayed by default. + +## Note + +Currently, the shell does not support this command. mksh supports it. To switch to mksh, run **cd bin** and **./mksh**. + +## Example + +Run **top**. + + +## Output Command output @@ -97,75 +81,19 @@ OHOS:/$ top 64 2 0x3 -1 Pending 0x4000 0x244 0.0 0 USB_NGIAN_BULK_TasK ``` -**Table 2** Output description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

PID

-

Process ID

-

PPID

-

Parent process ID

-

PGID

-

Process group ID

-

UID

-

User ID

-

Status

-

Current task status

-

CPUUSE10s

-

CPU usage within last 10 seconds

-

PName

-

Process name

-

TID

-

Task ID

-

StackSize

-

Size of the task stack

-

WaterLine

-

Peak value of the stack used

-

MEMUSE

-

Memory usage

-

TaskName

-

Task name

-
- +**Table 2** Output description + +| Parameter | Description | +| --------- | ----------------- | +| PID | Process ID. | +| PPID | Parent process ID. | +| PGID | Process group ID. | +| UID | User ID. | +| Status | Current task status. | +| CPUUSE10s | CPU usage within last 10 seconds.| +| PName | Name of the process. | +| TID | Task ID. | +| StackSize | Size of the task stack. | +| WaterLine | Peak value of the stack used. | +| MEMUSE | Memory usage. | +| TaskName | Task name. | diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-uname.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-uname.md index 525cb31fef3903869fc35b478203e734cebde25d..ab22f6a1c51e0c1f12f4e78eb84415a52d218d29 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-uname.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-uname.md @@ -1,84 +1,56 @@ # uname -## Command Function + +## Command Function This command is used to display the name, version creation time, system name, and version information of the current operating system. -## Syntax - -uname \[_-a | -s | -r | -m | -n | -v | --help_\] - -**Table 1** Parameters - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Parameters

-

--help

-

Displays help information.

-

No parameter

-

Displays the operating system name by default.

-

-a

-

Displays all information.

-

-s

-

Displays the operating system name.

-

-r

-

Displays the kernel release version.

-

-m

-

Displays the operating system architecture name.

-

-n

-

Displays the network domain name of the host.

-

-v

-

Displays version information.

-
- -## Usage - -- 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**. - -## Example + +## Syntax + +uname [_-a | -s | -r | -m | -n | -v | --help_] + + +**Table 1** Parameter description + +| Parameter | Description | +| ------ | ----------------------- | +| --help | Displays help information.| +| No parameter| Displays the operating system name by default. | +| -a | Displays all data. | +| -s | Displays the operating system name. | +| -r | Displays the kernel release version. | +| -m | Displays the operating system architecture name. | +| -n | Displays the network domain name of the host. | +| -v | Displays version information. | + + +## Usage Guidelines + +- 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**. + +## 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: -- uname -a -- uname -ms +- uname -a + +- uname -ms -## Output + +## Output Example 1: all information of the operating system ``` OHOS:/$ uname -a -LiteOS hisilicon 2.0.x.x Huawei LiteOS 2.0.x.x Oct 21 2021 17:39:32 Cortex-A7 +LiteOS hisilicon 2.0.0.37 LiteOS 2.0.0.37 Oct 21 2021 17:39:32 Cortex-A7 OHOS:/$ ``` @@ -89,4 +61,3 @@ OHOS:/$ uname -ms LiteOS Cortex-A7 OHOS:/$ ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-vmm.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-vmm.md index cce14dd6bbca807f007073d792efcfb8e3577823..860a23db1d717ca3d2d79df7184491a2cbb969d9 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-vmm.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-vmm.md @@ -1,60 +1,40 @@ # vmm -## Command Function + +## Command Function This command is used to query the virtual memory used by a process. -## Syntax - -- vmm \[_-a / -h / --help_\] -- vmm \[_pid_\] - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

-a

-

Displays the virtual memory usage of all processes.

-

N/A

-

-h | --help

-

Displays help information.

-

N/A

-

pid

-

Specifies the ID of the process to query.

-

[0,63]

-
- -## Usage + +## Syntax + +- vmm [_-a / -h / --help_] + +- vmm [_pid_] + + +## Parameters + +**Table 1** Parameter description + +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| -a | Displays the virtual memory usage of all processes.| N/A | +| -h \| --help | Displays help information.| N/A | +| pid | Specifies the ID of the process to query.| [0, 63] | + + +## Usage Guidelines By default, this command displays the virtual memory usage of all processes. -## Example -Run **vmm 3**. +## Example -## Output +Run **vmm 3**. + + +## Output Virtual memory usage of process 3: @@ -82,92 +62,25 @@ OHOS # vmm 3 0x408c3ce0 /lib/libc++.so 0x23cb0000 0x00001000 CH US RD WR 1 1 ``` -**Table 2** Basic process information - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

PID

-

Process ID

-

aspace

-

Address of the virtual memory control block

-

name

-

Process name

-

base

-

Start address of the virtual memory

-

size

-

Size of virtual memory

-

pages

-

Number of used physical pages

-
- -**Table 3** Virtual memory region information - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

region

-

Address of the control block in the virtual memory region

-

name

-

Name of the virtual memory region

-

base

-

Start address of the virtual memory region

-

size

-

Size of the virtual memory region

-

mmu_flags

-

MMU mapping attribute of the virtual memory region

-

pages

-

Number of used physical pages, including that of the shared memory

-

pg/ref

-

Number of used physical pages

-
- +**Table 2** Basic process information + +| Parameter| Description| +| -------- | -------- | +| PID | Process ID.| +| aspace | Address of the virtual memory control block.| +| name | Process name.| +| base | Start address of the virtual memory.| +| size | Total Virtual Memory.| +| pages | Number of used physical pages.| + +**Table 3** Virtual memory interval information + +| Parameter| Description| +| -------- | -------- | +| region | Address of the control block in the virtual memory region.| +| name | Name of the virtual memory region.| +| base | Start address of the virtual memory region.| +| size | Size of the virtual memory region.| +| mmu_flags | MMU mapping attribute of the virtual memory region.| +| pages | Number of used physical pages, including that of the shared memory.| +| pg/ref | Number of used physical pages.| diff --git a/en/device-dev/kernel/kernel-small-debug-shell-cmd-watch.md b/en/device-dev/kernel/kernel-small-debug-shell-cmd-watch.md index 343634d384010dd73dc69708e9d000a92925900e..9282a3edb469f6f01e78b13f5c72bb7cc11e9e64 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-cmd-watch.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-cmd-watch.md @@ -1,88 +1,44 @@ # watch -## Command Function + +## Command Function This command is used to periodically run the specified command and display its execution result. -## Syntax - -- watch -- watch \[_-c/-n/-t/--count/--interval/-no-title/--over_\] \[_command_\] - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Default Value

-

Value Range

-

-c / --count

-

Specifies the number of times that the specified command is executed.

-

0xFFFFFF

-

(0, 0xFFFFFF]

-

-n / --interval

-

Specifies the interval (in seconds) for periodically running the specified command.

-

1s

-

(0, 0xFFFFFF]

-

-t / -no-title

-

Disables time display on the top.

-

N/A

-

N/A

-

command

-

Specifies the command to be monitored.

-

N/A

-

N/A

-

--over

-

Stops the current command monitoring.

-

N/A

-

N/A

-
- -## Usage - -You can run the **watch --over** command to stop monitoring of the specified command. - -## Example - -Run **watch -n 2 -c 6 task**. - -## Output - -Example: The **task** command is executed six times at an interval of 2 seconds. + +## Syntax + +- watch + +- watch [_-c/-n/-t/--count/--interval/-no-title/--over_] [_command_] + + +## Parameters + + **Table 1** Parameter description + +| Parameter| Description| Default Value| Value Range| +| -------- | -------- | -------- | -------- | +| -c / --count | Specifies the number of times that the specified command is executed.| 0xFFFFFF | (0, 0xFFFFFF]| +| -n / --interval | Specifies the interval for running the command, in seconds.| 1s | (0, 0xFFFFFF]| +| -t / -no-title | Disables time display on the top.| N/A | N/A | +| command | Specifies the command to be monitored.| N/A | N/A | +| --over | Stops the current command monitoring.| N/A | N/A | + + +## Usage Guidelines + +You can run the **watch --over** command to stop monitoring of the specified command. + + +## Example + +Run **watch -n 2 -c 6 task**. + + +## Output + +Example: The **task** command is executed six times at an interval of 2 seconds. ``` OHOS # watch -n 2 -c 6 task @@ -121,4 +77,3 @@ OHOS # 17 2 0x3 0 Running 0x3000 0x73c 0.0 0 shellcmd_watch 18 2 0x3 -1 Pending 0x2710 0x3ac 0.0 0 GPIO_IRQ_TSK_0_4 ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-cat.md b/en/device-dev/kernel/kernel-small-debug-shell-file-cat.md index 7a4fd54ccea998e7a1621eeb2a7d082f1ab5865d..d11c33deb1a565600d0117a21b2e0b4db2e14b02 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-cat.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-cat.md @@ -1,50 +1,41 @@ # cat -## Command Function + + +## Command Function This command is used to display the content of a text file. -## Syntax -cat \[_pathname_\] +## Syntax + +cat [_pathname_] + -## Parameters +## Parameters -**Table 1** Parameter description +**Table 1** Parameter description - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

pathname

-

Specifies the file path.

-

An existing file

-
+| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| pathname | Specifies the file path. | An existing file | -## Usage -Run the **cat** \[_pathname_\] command to display the content of a text file. +## Usage Guidelines -## Example +Run the **cat** [*pathname*] command to display the content of a text file. -Run **cat hello-harmony.txt**. -## Output +## Example -Content of **hello-harmony.txt** +Run **cat hello-openharmony.txt**. + + +## Output + +Content of **hello-openharmony.txt** ``` -OHOS # cat hello-harmony.txt -OHOS # Hello Harmony ;) +OHOS # cat hello-openharmony.txt +OHOS # Hello openharmony ;) ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-cd.md b/en/device-dev/kernel/kernel-small-debug-shell-file-cd.md index 187e454a2ad69814abdd8f15adab12cb39370872..5318eeb638bd75e0f9b52d4d95bc8575208905b3 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-cd.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-cd.md @@ -1,51 +1,46 @@ # cd -## Command Function +## Command Function This command is used to change the current working directory. -## Syntax -cd \[_path_\] +## Syntax -## Parameters +cd [_path_] -**Table 1** Parameter description - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

path

-

Specifies the target file path.

-

You must have the execution (search) permission for the specified directory.

-
+## Parameters -## Usage +**Table 1** Parameter description -- If **path** is not specified, this command switches to the root 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 two dots \(..\) represents the parent directory. -- You can run **cd -** to alternate between two directories that are recently accessed. +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| path | Specifies the path of the new directory. | You must have the execution (search) permission on the specified directory.| -## Example -Run **cd ..**. +## Usage Guidelines -## Output +- If **path** is not specified, this command switches to the root 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 two dots (..) represents the parent directory. + +- You can run **cd -** to alternate between two directories that are recently accessed. + + +## Example + +Run **cd ..**. + + +## Output Parent directory information: @@ -55,4 +50,3 @@ OHOS:/$ ls bin etc nfs sdcard system tmp vendor dev lib proc storage test usr ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-chgrp.md b/en/device-dev/kernel/kernel-small-debug-shell-file-chgrp.md index af1df3355499e935a6df4931e722282d5826c268..9163aaa988a3a7789cfc2ef40d2bca0bb8296a3c 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-chgrp.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-chgrp.md @@ -1,55 +1,43 @@ # chgrp -## Command Function + +## Command Function This command is used to change the file group. -## Syntax -chgrp \[_group_\] \[_pathname_\] +## Syntax + +chgrp [_group_] [_pathname_] + + +## Parameters -## Parameters +**Table 1** Parameter description -**Table 1** Parameter description +| Parameter | Description | Value Range | +| -------- | ---------- | -------------- | +| group | Specifies the target file group.| [0, 0xFFFFFFFF] | +| pathname | Specifies the file path. | An existing file | - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

group

-

Specifies the target file group.

-

[0, 0xFFFFFFFF]

-

pathname

-

Specifies the file path.

-

An existing file

-
-## Usage +## Usage Guidelines -- Specify **group** to change the file group. -- For the FAT file system, this command cannot be used to change user group IDs. +- Specify **group** to change the file group. +- For the FAT file system, this command cannot be used to change user group IDs. -## Example +## Note -Run **chgrp 100 testfile**. +Currently, the shell does not support this command. -## Output +## Example -Changing the group ID of the **testfile** file in the **dev/** directory to **100** +Run **chgrp 100 testfile**. + + +## Output + +Change the group ID of the **testfile** file in the **dev/** directory to **100**. ``` OHOS:/dev$ ll testfile @@ -59,4 +47,3 @@ OHOS:/dev$ ll testfile -rw-r--r-- 0 0 100 0 1970-01-01 00:00 testfile OHOS:/dev$ ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-chmod.md b/en/device-dev/kernel/kernel-small-debug-shell-file-chmod.md index 200131874538c91c07404b94982ec77e30dcb7d4..6220230d65d4b717e9f2c481fce11f24e138bb58 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-chmod.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-chmod.md @@ -1,62 +1,50 @@ # chmod -## Command Function + +## Command Function This command is used to change file operation permissions. -## Syntax -chmod \[_mode_\] \[_filename_\] +## Syntax + +chmod [_mode_] [_filename_] + + +## Parameters + +**Table 1** Parameter description -## Parameter Description +| Parameter | Description | Value Range | +| -------- | ------------------------------------------------------------ | -------------- | +| 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] | +| filename | Specifies the file path. | An existing file | -**Table 1** Parameters - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

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]

-

filename

-

Specifies the file name.

-

An existing file

-
+## Usage Guidelines -## Usage +- Specify **mode** to change file permissions. -- Specify **mode** to change file permissions. -- 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 +## Note -Change the permissions on the **hello-harmony.txt** file to **644** and **777**. +Currently, the shell does not support this command. -## Output +## Example -Modifying the permissions on the **hello-harmony.txt** file in the **/dev** directory: +Change the permissions on the **hello-openharmony.txt** file to **644** and **777**. + + +## Output + +Modify the permissions on the **hello-openharmony.txt** file in the **/dev** directory. ``` -OHOS:/dev$ chmod 644 hello-harmony.txt -OHOS:/dev$ ll hello-harmony.txt --rw-r--r-- 0 0 0 0 1970-01-01 00:00 hello-harmony.txt -OHOS:/dev$ chmod 777 hello-harmony.txt -OHOS:/dev$ ll hello-harmony.txt --rwxrwxrwx 0 0 0 0 1970-01-01 00:00 hello-harmony.txt +OHOS:/dev$ chmod 644 hello-openharmony.txt +OHOS:/dev$ ll hello-openharmony.txt +-rw-r--r-- 0 0 0 0 1970-01-01 00:00 hello-openharmony.txt +OHOS:/dev$ chmod 777 hello-openharmony.txt +OHOS:/dev$ ll hello-openharmony.txt +-rwxrwxrwx 0 0 0 0 1970-01-01 00:00 hello-openharmony.txt ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-chown.md b/en/device-dev/kernel/kernel-small-debug-shell-file-chown.md index 3a4006df874d5723184968c92472a6aeefed8f1e..fdc738d7ea66ae707c243cf650f8b946761f1a51 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-chown.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-chown.md @@ -1,54 +1,42 @@ # chown -## Command Function + +## Command Function This command is used to change the owner of a file. -## Syntax - -chown \[_owner_\] \[_pathname_\] - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

owner

-

Specifies the file owner.

-

[0,0xFFFFFFFF]

-

pathname

-

Specifies the file path.

-

An existing file

-
- -## Usage + +## Syntax + +chown [_owner_] [_pathname_] + + +## Parameters + +**Table 1** Parameter description + +| Parameter | Description | Value Range | +| -------- | ------------ | -------------- | +| owner | Specifies the file owner. | [0, 0xFFFFFFFF] | +| pathname | Specifies the file path. | An existing file | + + +## Usage Guidelines This command does not apply to the FAT file system. -## Example +## Note + +Currently, the shell does not support this command. -Run **chown 100 testfile**. +## Example -## Output +Run **chown 100 testfile**. -Changing the UID of the **testfile** file in **/dev** to **100**: + +## Output + +Change the UID of the **testfile** file in **/dev** to **100**. ``` OHOS:/dev$ touch testfile @@ -58,4 +46,3 @@ OHOS:/dev$ chown 100 testfile OHOS:/dev$ ll testfile -rw-r--r-- 0 100 100 0 1970-01-01 00:00 testfile ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-cp.md b/en/device-dev/kernel/kernel-small-debug-shell-file-cp.md index b191a7fb5260b869905b47bad385db78c273afe4..c484883580547181041426680f1f797cc77d5a55 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-cp.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-cp.md @@ -1,80 +1,63 @@ # cp -## Command Function + +## Command Function This command is used to create a copy for a file. -## Syntax - -cp \[_SOURCEFILE_\] \[_DESTFILE_\] - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

--help

-

Displays help information.

-

N/A

-

SOURCEFILE

-

Specifies the path of the source file.

-

This command does not support copy of a directory, but supports copy of multiple files at a time.

-

DESTFILE

-

Specifies the destination file path.

-

Both a directory and a file are supported.

-
- -## Usage - -- 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** 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. -- If **DESTFILE** specifies 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. - ->![](../public_sys-resources/icon-notice.gif) **NOTICE:** ->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 - -Run **cp hello-OHOS.txt hello-harmony.txt ./tmp/**. - -## Output - -Copying **hello-OHOS.txt** and **hello-harmony.txt** to **/tmp/**: + +## Syntax + +cp [_SOURCEFILE_] [_DESTFILE_] + + +## Parameters + + **Table 1** Parameter description + +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| --help | Displays help information.| N/A | +| SOURCEFILE | Specifies the file to copy.| This command does not support copy of a directory, but supports copy of multiple files at a time.| +| DESTFILE | Specifies the file to create.| Both a directory and a file are supported.| + + +## Usage Guidelines + +- 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. + +- 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 **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. + +> **NOTICE**
+> 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 + +Run **cp hello-OHOS.txt hello-openharmony.txt ./tmp/**. + + +## Output + +Copy **hello-OHOS.txt** and **hello-openharmony.txt** to **/tmp/**. ``` OHOS:/$ ls bin hello-OHOS.txt proc system vendor -dev hello-harmony.txt sdcard userdata +dev hello-openharmony.txt sdcard userdata etc lib storage usr OHOS:/$ mkdir tmp -OHOS:/$ cp hello-OHOS.txt hello-harmony.txt tmp/ +OHOS:/$ cp hello-OHOS.txt hello-openharmony.txt tmp/ OHOS:/$ ll tmp total 0 -rwxrwxrwx 1 0 0 0 1979-12-31 00:00 hello-OHOS.txt* --rwxrwxrwx 1 0 0 0 1979-12-31 00:00 hello-harmony.txt* +-rwxrwxrwx 1 0 0 0 1979-12-31 00:00 hello-openharmony.txt* ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-du.md b/en/device-dev/kernel/kernel-small-debug-shell-file-du.md index 8dd89bfaa3a1f573d8ec82be44b0b54704d5f309..6d72b8c51adba6d46addb80594f91a8bc66e08dc 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-du.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-du.md @@ -1,86 +1,50 @@ # du -## Command Function + +## Command Function This command is used to query the disk space occupied by a file. -## Syntax - -du \[_-kKmh_\] \[_file..._\] - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

--help

-

Displays the parameters supported by the du command.

-

N/A

-

-k

-

Displays the occupied blocks, each of which is 1024 bytes by default.

-

N/A

-

-K

-

Displays the occupied blocks, each of which is 512 bytes (POSIX).

-

N/A

-

-m

-

Displays the disk space in MB.

-

N/A

-

-h

-

Displays the disk space in human-readable format K, M, and G, for example, 1K, 243M, or 2G.

-

N/A

-

file

-

Specifies the target file.

-

N/A

-
- -## Usage - -- The **du** command is used to obtain the disk usage of a file rather than a directory. -- The value of **file** must be the file name. It cannot contain the directory where the file is located. - -## Example - -Run **du -h testfile**. - -## Output - -Command output + +## Syntax + +du [_-kKmh_] [_file..._] + + +## Parameters + +**Table 1** Parameter description + +| Parameter | Description | +| ------ | ------------------------------------------------------------ | +| --help | Displays the parameters supported by the **du** command. | +| -k | Displays the occupied blocks, each of which is 1024 bytes by default. | +| -K | Displays the occupied blocks, each of which is 512 bytes (POSIX). | +| -m | Displays the disk space in MB. | +| -h | Displays the disk space in human-readable format K, M, and G, for example, **1K**, **243M**, or **2G**.| +| file | Specifies the target file. | + + +## Usage Guidelines + +- The **du** command is used to obtain the disk usage of a file rather than a directory. + +- The value of **file** must be the file name. It cannot contain the directory where the file is located. + +## Note + +Currently, the shell does not support this command. mksh supports it. To switch to mksh, run **cd bin** and **./mksh**. + +## Example + +Run **du -h testfile**. + + +## Output + +Disk space occupied by **testfile**. ``` OHOS:/$ du -h testfile 1.8K testfile ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-format.md b/en/device-dev/kernel/kernel-small-debug-shell-file-format.md index 7801ff31c3b49d0318f49b2957ec6e9eda3049f0..e9bef26ce5e90769d493a6ff1742aeb8115dc1eb 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-format.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-format.md @@ -1,67 +1,48 @@ # format -## Command Function +## Command Function This command is used for disk formatting. -## Syntax - -format <_dev\_inodename_\> <_sectors_\> <_option_\> \[_label_\] - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

dev_inodename

-

Specifies the device name.

-

sectors

-

Specifies the size of the allocated memory unit or sector. The value 0 indicates null. (The value must be 0 or a power of 2. 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.)

-

option

-
Specifies the file system type. The options are as follows:
  • 0x01: FMT_FAT
  • 0x02: FMT_FAT32
  • 0x07: FMT_ANY
  • 0x08: FMT_ERASE (not supported by the USB flash drive)
-
-

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.

-

label

-

Specifies the volume label name. This parameter is optional, and the value is a string. If null is specified for this parameter, the previously set volume label name is cleared.

-
- -## Usage - -- 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. -- An invalid **sectors** value may cause exceptions. - -## Example - -Run **format /dev/mmcblk0 128 2**. - -## Output - -Formatting an MMC: + +## Syntax + +format <*dev*inodename_> <*sectors*> <*option*> [_label_] + + +## Parameters + +**Table 1** Parameter description + +| Parameter| Description| +| -------- | -------- | +| dev_inodename | Specifies the device name. | +| sectors | Specifies the size of the allocated memory unit or sector.
The value must be **0** or a power of **2**.
The value **0** means to leave this parameter blank.
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. | +| option | Specifies the file system type. The options are as follows:
- **0x01**: FMT_FAT
- **0x02**: FMT_FAT32
- **0x07**: FMT_ANY
- **0x08**: FMT_ERASE (USB does not support this option.)
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.| +| label | Specifies the volume label name. This parameter is optional, and the value is a string.
If **null** is specified for this parameter, the previously set volume label name is cleared. | + + +## Usage Guidelines + +- 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. + +- An invalid **sectors** value may cause exceptions. + + +## Example + +Run **format /dev/mmcblk0 128 2**. + + +## Output + +Format an MMC. ``` OHOS # format /dev/mmcblk1 128 2 Format to FAT32, 128 sectors per cluster. format /dev/mmcblk1 Success ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-ls.md b/en/device-dev/kernel/kernel-small-debug-shell-file-ls.md index 0c8f1abbe920bd74558301b4e2dc61a3882d8a42..b292d00f160227250b9478e2c5cc53f1f7eaa508 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-ls.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-ls.md @@ -1,290 +1,92 @@ # ls -## Command Function - -This command is used to display the content of a specified directory. - -## Syntax - -ls \[_-ACHLSZacdfhiklmnopqrstux1_\] \[_--color_\[_=auto_\]\] \[_directory..._\] - ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->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 - -**Table 1** Command parameter description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

--help

-

Displays parameters supported by the ls command and their usage.

-

N/A

-

-a

-

Displays all files, including .hidden files.

-

N/A

-

-b

-

Escapes non-graphical characters.

-

N/A

-

-c

-

Uses ctime as the file timestamp. This parameter must be used together with -l.

-

N/A

-

-d

-

Displays only the directory, rather than listing the content of the directory.

-

N/A

-

-i

-

Displays the node ID of a file.

-

N/A

-

-p

-

Adds a slash (/) after the directory.

-

N/A

-

-q

-

Displays non-printable characters, such as "?".

-

N/A

-

-s

-

Provides information about the memory occupied by the directory and its members, in 1024 bytes.

-

N/A

-

-u

-

Uses the last access time of the file as the timestamp. This option is used together with -l.

-

N/A

-

-A

-

Lists all files except implied . and ..

-

N/A

-

-H

-

Follows symbolic links listed in the command line.

-

N/A

-

-L

-

Follows symbolic links.

-

N/A

-

-Z

-

Displays security context.

-

N/A

-

path

-

If path is left blank, the content of the current directory is displayed.

-

If path is an invalid file name, the following failure message is displayed:

-

ls error: No such directory

-

If path is a valid directory, the content of that directory is displayed.

-

Left blank or a valid directory

-
- -**Table 2** Output parameters - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

-1

-

Lists one file per line.

-

N/A

-

-c

-

Lists entries by column.

-

N/A

-

-g

-

Like -l, but do not list owner.

-

N/A

-

-h

-

Displays the total size of files in the directory, in KiB.

-

N/A

-

-l

-

Displays detailed information about files in the directory.

-

N/A

-

-m

-

Fills width with a list of entries separated by a comma.

-

N/A

-

-n

-

Like -l, but lists numeric user and group IDs.

-

N/A

-

-o

-

Like -l, but do not list group information.

-

N/A

-

-x

-

Lists entries by line, instead of by column.

-

N/A

-

-ll

-

Lists the file time attribute as ns.

-

N/A

-

--color

-

Colorizes the output.

-

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.

-
- -**Table 3** Sorting parameters \(sorted by the initial letter by default\) - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

-f

-

Do not sort.

-

N/A

-

-r

-

Reverse order while sorting.

-

N/A

-

-t

-

Sort by time, newest first.

-

N/A

-

-S

-

Sort by file size, largest first.

-

N/A

-
- -## Usage - -None - ->![](../public_sys-resources/icon-notice.gif) **NOTICE:** ->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**. - -## Example + +## Command Function + +This command is used to display the content of a directory. + + +## Syntax + +ls [_-ACHLSZacdfhiklmnopqrstux1_] [_--color_[_=auto_]] [_directory..._] + +> **NOTE**
+> 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**. + + +## Parameters + +**Table 1** Command parameter description + +| Parameter | Description | Value Range | +| ------ | ------------------------------------------------------------ | ----------------------------- | +| --help | Displays parameters supported by the **ls** command and their usage. | N/A | +| -a | Displays all files, including hidden files. | N/A | +| -b | Escapes non-graphical characters. | N/A | +| -c | Uses **ctime** as the file timestamp. This parameter must be used together with **-l**. | N/A | +| -d | Displays only the directory, rather than listing the content of the directory. | N/A | +| -i | Displays the node ID of a file. | N/A | +| -p | Adds a slash (/) after the directory. | N/A | +| -q | Displays non-printable characters, such as "?". | N/A | +| -s | Provides information about the memory occupied by the directory and its members, in 1024 bytes. | N/A | +| -u | Uses the last access time of the file as the timestamp. This option is used together with **-l**. | N/A | +| -A | Lists all files except implied . and .. | N/A | +| -H | Follows symbolic links listed in the command line. | N/A | +| -L | Follows symbolic links. | N/A | +| -Z | Displays security context. | N/A | +| path | Specifies the path of the target directory.
If **path** is left blank, the content of the current directory is displayed.
If **path** is an invalid directory, "ls error: No such directory." is displayed.

If **path** is a valid directory, the content of the specified directory is displayed. | Left blank
A valid directory| + +**Table 2** Output format parameters + +| Parameter | Description | +| ------- | --------------------------------------- | +| -1 | Lists one file per line. | +| -c | Lists entries by column. | +| -g | Like **-l**, but do not list the owner. | +| -h | Displays the total size of files in the directory, in KiB.| +| -l | Displays detailed information about files in the directory. | +| -m | Fills width with a list of entries separated by a comma. | +| -n | Like **-l**, but lists numeric user and group IDs.| +| -o | Like **-l**, but do not list group information. | +| -x | Lists entries by line, instead of by column. | +| -ll | Lists the file time attribute as ns. | + +**Table 3** Parameters for sorting (by the initial letter by default) + +| Parameter| Description | +| ---- | ------------------------------------------ | +| -f | Do not sort. | +| -r | Sorts in reverse order. | +| -t | Sorts by time, newest first.| +| -S | Sorts by file size, largest first. | + +**Table 4** Color printing + +| Parameter| Default Configuration | +| ---- | ------------------------------------------ | +| --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. | + +## Usage Guidelines + +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**. + + +## Note + +The shell does not support **ls** parameters. mksh supports them. To switch to mksh, run **cd bin** and **./mksh**. + +## Example Run the following commands: -- ls -- ll +- ls -## Output +- ll -Example 1: **ls** command output + +## Output + +Example 1: **ls** command output ``` OHOS:/$ ls @@ -292,7 +94,7 @@ bin etc nfs sdcard system usr dev lib proc storage userdata vendor ``` -Example 2: **ll** command output +Example 2: **ll** command output ``` OHOS:/$ ll @@ -310,4 +112,3 @@ drwxrwxrwx 1 0 0 2048 2021-11-21 17:52 userdata/ drwxrwxrwx 1 0 0 2048 2021-11-21 17:52 usr/ drwxrwxrwx 1 0 0 2048 2021-11-21 17:52 vendor/ ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-lsfd.md b/en/device-dev/kernel/kernel-small-debug-shell-file-lsfd.md index fe035b1c141dfcda3223df3c99335f1cc7901376..ba2902d4c4ed1a1c638879d2737090a3575b3188 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-lsfd.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-lsfd.md @@ -1,25 +1,29 @@ # lsfd -## Command Function +## Command Function This command is used to display the file descriptors and names of the files that are open. -## Syntax + +## Syntax lsfd -## Usage -Run the **lsfd** command to display file descriptors and names of the opened files. +## Usage Guidelines + +Run the **lsfd** command to display file descriptors and names of the opened files. + -## Example +## Example -Run **lsfd**. +Run **lsfd**. -## Output -Example: **lsfd** command output +## Output + +Example: **lsfd** command output ``` OHOS # lsfd @@ -57,4 +61,3 @@ OHOS # lsfd 33 /dev/lite_ipc 34 /dev/lite_ipc ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-mkdir.md b/en/device-dev/kernel/kernel-small-debug-shell-file-mkdir.md index 09b1935ecc8727ff43d148059c12afca27342ef9..4c68734912dfb23c61c6032011c239c196751ead 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-mkdir.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-mkdir.md @@ -1,80 +1,53 @@ # mkdir -## Command Function +## Command Function This command is used to create a directory. -## Syntax - -mkdir \[_-vp_\] \[_-m mode_\] \[_dirname..._\] - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

--help

-

Displays the parameters supported by the mkdir command.

-

N/A

-

-m

-

Sets the permissions on the directory to create.

-

N/A

-

-p

-

Creates parent and child directories recursively.

-

N/A

-

-v

-

Prints detailed information about the directory creation process.

-

N/A

-

directory

-

Specifies the directory to create.

-

N/A

-
- -## Usage - ->![](../public_sys-resources/icon-notice.gif) **NOTICE:** ->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 + +## Syntax + +mkdir [_-vp_] [_-m mode_] [_dirname..._] + + +## Parameters + +**Table 1** Parameter description + +| Parameter | Description | +| --------- | ------------------------------ | +| --help | Displays the parameters supported by the **mkdir** command. | +| -m | Sets the permissions on the directory to create. | +| -p | Creates parent and child directories recursively. | +| -v | Prints detailed information about the directory creation process.| +| directory | Specifies the directory to create. | + + +## Usage Guidelines + +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. + +## 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: -- mkdir testpath -- mkdir -m 777 testpath -- mkdir -pv testpath01/testpath02/testpath03 +- mkdir testpath + +- mkdir -m 777 testpath + +- mkdir -pv testpath01/testpath02/testpath03 + +## Output + +Example 1: Create a directory named **testpath**. -## Output ``` OHOS:/tmp$ mkdir testpath @@ -83,7 +56,8 @@ total 2 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. + ``` OHOS:/tmp$ mkdir -m 777 testpath @@ -92,7 +66,8 @@ total 2 drwxrwxrwx 1 0 0 2048 1979-12-31 00:00 testpath/ ``` -Example 3: creating directories recursively +Example 3: Create directories recursively. + ``` OHOS:/tmp$ mkdir -pv testpath01/testpath02/testpath03 @@ -109,4 +84,3 @@ OHOS:/tmp$ ll testpath01/testpath02/ total 2 drwxrwxrwx 1 0 0 2048 1979-12-31 00:00 testpath03/ ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-mount.md b/en/device-dev/kernel/kernel-small-debug-shell-file-mount.md index 9fccd3e4eaf981e0b072ea03cd9d71c4a41e1aac..67d89d93284a78550b470b35ed84ebdad20c1980 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-mount.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-mount.md @@ -1,84 +1,47 @@ # mount -## Command Function +## Command Function This command is used to mount a device to a specified directory. -## Syntax - -mount \[_-f_\] \[_-t TYPE_\] \[_-o OPTION,_\] \[\[_DEVICE_\] _DIR_\] - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

--help

-

Displays the parameters supported by the mount command.

-

N/A

-

-f

-

Fakes mounting the file system (no mounting is actually performed).

-

N/A

-

-t

-

Specifies the file system type.

-

vfat, yaffs, jffs, ramfs, nfs, procfs, romfs

-

-o

-

Specifies the mount options.

-

N/A

-

DEVICE

-

Specifies the device to mount (in the format of the device directory).

-

A device in the system

-

DIR

-

Specifies the directory.

-

You must have the execution (search) permission on the specified directory.

-

N/A

-
- -## Usage - -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 - -Run **mount -t nfs 192.168.1.3:/nfs nfs**. - -## Output - -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 + +## Syntax + +mount [_-f_] [_-t TYPE_] [_-o OPTION,_] [[_DEVICE_] _DIR_] + + +## Parameters + +**Table 1** Parameter description + +| Parameter | Description | Value Range | +| ------ | ----------------------------------------------------------- | ------------------------------------------------------------ | +| --help | Displays the parameters supported by the **mount** command. | N/A | +| -f | Fakes mounting the file system (no mounting is actually performed). | N/A | +| -t | Specifies the file system type. | vfat, yaffs, jffs, ramfs, nfs, procfs, romfs| +| -o | Specifies the mount options. | N/A | +| DEVICE | Specifies the device to mount (in the format of the device directory). | A device in the system | +| DIR | Specifies the directory.
You must have the execution (search) permission on the specified directory.| N/A | + + +## Usage Guidelines + +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. + +## 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**. + + +## 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. + ``` OHOS:/$ mkdir nfs @@ -90,4 +53,3 @@ OHOS:/$ ls nfs/ OHOS_Image.bin hello rootfs_vfat.img dev_tools mksh_rootfs_vfat.img test_demo ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-mv.md b/en/device-dev/kernel/kernel-small-debug-shell-file-mv.md index 880b14485c22069f023f256961485e33f6afb82c..cd2a0950cc8122c93f4550df899c254d77c617e1 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-mv.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-mv.md @@ -1,96 +1,58 @@ # mv -## Command Function +## Command Function This command is used to move files. -## Syntax - -mv \[_-fivn_\] _SOURCE... DEST_ - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

-help

-

Displays help information.

-

N/A

-

-f

-

Forcibly overwrites the target file.

-

N/A

-

-i

-

Provides a prompt before moving a file that would overwrite an existing file. Enter y to overwrite the file or enter n to cancel the operation.

-

N/A

-

-n

-

Do not overwrite any existing file or directory.

-

N/A

-

-v

-

This parameter does not take effect although it is supported by the latest Toybox code.

-

N/A

-

SOURCE

-

Specifies the path of the source file.

-

This command cannot be used to move a directory. It can be used to move multiple files at a time.

-

DEST

-

Specifies the destination file path.

-

Both a directory and a file are supported.

-
- -## Usage - -- **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 file, the directory for this file must exist. -- If the destination file already exists, it will be overwritten. - -## Example + +## Syntax + +mv [_-fivn_] *SOURCE... DEST* + + +## Parameters + +**Table 1** Parameter description + +| Parameter | Description | Value Range | +| ------ | ------------------------------------------------------------ | ----------------------------------------------- | +| -help | Displays help information. | N/A | +| -f | Forcibly overwrites the target file. | N/A | +| -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 | +| -n | Do not overwrite any existing file or directory. | N/A | +| -v | This parameter does not take effect although it is supported by the latest Toybox code. | N/A | +| SOURCE | Specifies the file to move. | This command cannot be used to move a directory. It can be used to move multiple files at a time.| +| DEST | Specifies the destination file path. | Both a directory and a file are supported. | + + +## Usage Guidelines + +- **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. + +- 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 the destination file already exists, it will be overwritten. + +## 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: -- mv -i test.txt testpath/ -- mv test?.txt testpath/ \(Move **test3.txt**, **testA.txt**, and **test\_.txt**\) +- mv -i test.txt testpath/ -## Output +- mv test?.txt testpath/ (Move **test3.txt**, **testA.txt**, and **test_.txt**) + + +## Output + +Example 1: Move a file. -Example 1: moving a file ``` OHOS:/$ touch test.txt @@ -112,7 +74,8 @@ bin etc proc storage test.txt userdata vendor dev lib sdcard system testpath usr ``` -Example 2: moving files using wildcards +Example 2: Move files. + ``` OHOS:/$ ls @@ -125,4 +88,3 @@ dev lib sdcard system testpath usr OHOS:/$ ls testpath/ test.txt test3.txt testA.txt test_.txt ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-partinfo.md b/en/device-dev/kernel/kernel-small-debug-shell-file-partinfo.md index 6f0ed999752060343314708afe218e1488cf0128..e4e329496a5bcd91754577a27b94a32abda1d162 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-partinfo.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-partinfo.md @@ -1,49 +1,40 @@ # partinfo -## Command Function +## Command Function This command is used to query information about the partitions of a hard disk or SD card identified by the system. -## Syntax -partinfo <_dev\_inodename_\> +## Syntax -## Parameters +partinfo <*dev*inodename_> -**Table 1** Parameter description - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

dev_inodename

-

Specifies the name of the partition to be queried.

-

A valid partition name

-
+## Parameters -## Usage + **Table 1** Parameter description -None +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| dev_inodename | Specifies the name of the partition to be queried.| A valid partition name| -## Example -Run **partinfo /dev/mmcblk0p0**. +## Usage Guidelines -## Output +None. + + +## Example + +Run **partinfo /dev/mmcblk0p0**. + + +## Output System partition information: + ``` OHOS # partinfo /dev/mmcblk0p0 part info : @@ -55,4 +46,3 @@ part filesystem : 00 part sec start : 20480 part sec count : 102400 ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-pwd.md b/en/device-dev/kernel/kernel-small-debug-shell-file-pwd.md index 87513f7f67fe226d6b87c8281f0a31f6444b42e7..5315935c5b1f5f643ec2c6d9f7a695f8b51cb3ff 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-pwd.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-pwd.md @@ -1,32 +1,37 @@ # pwd -## Command Function +## Command Function This command is used to display the current path. -## Syntax + +## Syntax pwd -## Parameters -None +## Parameters + +None. + + +## Usage Guidelines -## Usage +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. -## Example +## Example -Run **pwd**. +Run **pwd**. -## Output + +## Output Current path: + ``` OHOS:/sdcard/nfs$ pwd /sdcard/nfs ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-rm.md b/en/device-dev/kernel/kernel-small-debug-shell-file-rm.md index b535c90a4feab46cedd8f82d8398ef75da4b0777..c01d029ab70633ec6a50044abacb339403e3189c 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-rm.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-rm.md @@ -1,74 +1,53 @@ # rm -## Command Function +## Command Function This command is used to delete a file or folder. -## Syntax - -rm \[_-fv_\] _FILE or rm_ \[_-rv_\] \[_PATH_ | _filename_\]... - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

-r

-

Deletes empty or non-empty directories.

-

N/A

-

-f

-

Deletes a file or directory forcibly without confirmation. No error will be reported when a file that does not exist is to be deleted.

-

N/A

-

-v

-

Displays the deletion process.

-

N/A

-

PATH/filename

-

Specifies the name of the file or directory to delete. The value can be a path.

-

N/A

-
- -## Usage - -- The **rm** command can be used to delete multiple files or folders at a time. -- You can run **rm -r** to delete a non-empty directory. -- If the **rm** command without **-f** is used to delete a file that does not exist, an error will be reported. - -## Example + +## Syntax + +rm [_-fv_] *FILE or rm* [_-rv_] [_PATH_ | _filename_]... + + +## Parameters + +**Table 1** Parameter description + +| Parameter | Description | +| ------------- | ------------------------------------------------ | +| -r | Deletes empty or non-empty directories. | +| -f | Deletes a file or directory forcibly without confirmation. No error will be reported when a file that does not exist is to be deleted.| +| -v | Displays the deletion process. | +| PATH/filename | Specifies the name of the file or directory to delete. The value can be a path. | + + +## Usage Guidelines + +- The **rm** command can be used to delete multiple files or folders at a time. + +- You can run **rm -r** to delete a non-empty directory. + +- If the **rm** command without **-f** is used to delete a file that does not exist, an error will be reported. + +## Note + +The shell does not support **-v** or **-f**. mksh supports them. To switch to mksh, run **cd bin** and **./mksh**. + +## Example Run the following commands: -- rm testfile -- rm -r testpath/ +- rm testfile + +- rm -r testpath/ -## Output -Example 1: deleting **testfile** +## Output + +Example 1: Delete **testfile**. + ``` OHOS:/$ ls @@ -80,7 +59,8 @@ bin etc proc storage userdata vendor dev lib sdcard system usr ``` -Example 2: deleting **testpath**, a non-empty directory +Example 2: Delete **testpath**, a non-empty directory. + ``` OHOS:/$ ls @@ -91,4 +71,3 @@ OHOS:/$ ls bin etc proc storage userdata vendor dev lib sdcard system usr ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-rmdir.md b/en/device-dev/kernel/kernel-small-debug-shell-file-rmdir.md index 70cf25e12419964077362426fb5f15d58092ba50..f0ad3c729b29cc570368f6acdc878b3fbd0ba1e2 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-rmdir.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-rmdir.md @@ -1,71 +1,46 @@ # rmdir -## Command Function +## Command Function This command is used to delete a directory. -## Syntax - -rmdir \[_-p_\] \[_dirname..._\] - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

--help

-

Displays the parameters supported by the rmdir command.

-

N/A

-

-p

-

Deletes a path.

-

N/A

-

--ignore-fail-on-non-empty

-

Suppresses the error message when a non-empty directory is to be deleted.

-

N/A

-

dir

-

Specifies the name of the directory to delete. The directory must be empty. A path is supported.

-

N/A

-
- -## Usage - -- The **rmdir** command can only be used to delete directories. -- The **rmdir** command can delete only one directory at a time. -- The **rmdir** command can delete only empty directories. - -## Example - -Run **rmdir dir**. - -## Output - -Deleting the directory **dir**: + +## Syntax + +rmdir [_-p_] [_dirname..._] + + +## Parameters + +**Table 1** Parameter description + +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| --help | Displays the parameters supported by the **rmdir** command.| N/A | +| -p | Deletes a path.| N/A | +| --ignore-fail-on-non-empty | Suppresses the error message when a non-empty directory is to be deleted.| N/A | +| dir | Specifies the name of the directory to delete. The directory must be empty. A path is supported.| N/A | + + +## Usage Guidelines + +- The **rmdir** command can only be used to delete directories. + +- The **rmdir** command can delete only one directory at a time. + +- The **rmdir** command can delete only empty directories. + + +## Example + +Run **rmdir dir**. + + +## Output + +Delete the directory **dir**. + ``` OHOS:/test$ mkdir dir @@ -74,4 +49,3 @@ dir OHOS:/test$ rmdir dir/ OHOS:/test$ ls ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-statfs.md b/en/device-dev/kernel/kernel-small-debug-shell-file-statfs.md index c38afd907c2de80ad20cf76d6af622462d398a9e..5b58c139561ba6bb1c27e4a44ad99fffc16e0722 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-statfs.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-statfs.md @@ -1,48 +1,37 @@ # statfs -## Command Function +## Command Function This command is used to print information about a file system, such as the type, total size, and available size. -## Syntax -statfs \[_directory_\] +## Syntax -## Parameters +statfs [_directory_] -**Table 1** Parameter description - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

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.

-
+## Parameters -## Usage +**Table 1** Parameter description + +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| 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.| + + +## Usage Guidelines The printed information varies depending on the file system. -## Example + +## Example The following uses the NFS as an example: -Run **statfs /nfs**. +Run **statfs /nfs**. -**statfs** command output +**statfs** command output ``` OHOS # statfs ./nfs @@ -57,4 +46,3 @@ statfs got: total size: 808742490112 Bytes free size: 255618461696 Bytes ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-sync.md b/en/device-dev/kernel/kernel-small-debug-shell-file-sync.md index 33670c9ca1cf5026325f11b933ab7335e46a6539..524ddd7802d3c8bc315cd838c88dd57541dfee04 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-sync.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-sync.md @@ -1,28 +1,33 @@ # sync -## Command Function +## Command Function -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 + +## Syntax sync -## Parameters -None +## Parameters + +None. + + +## Usage Guidelines + +- The **sync** command is used to refresh the cache. If no SD card is inserted, no operation will be performed. -## Usage +- When an SD card is inserted, the cache information is synchronized to the SD card. If the synchronization is successful, no information is displayed. -- 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. -## Example +## 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. -## Output -None +## Output +None. diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-touch.md b/en/device-dev/kernel/kernel-small-debug-shell-file-touch.md index e2ef6986f051af559c6af8c77f26309b53123371..e21f277dd4a8f78c54744d88a8570343b9355d7b 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-touch.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-touch.md @@ -1,64 +1,54 @@ # touch -## Command Function +## Command Function -- This command is used to create an empty file in a specified directory. -- If this command is executed to create an existing file, the execution will be successful but the timestamp will not be updated. +- This command is used to create an empty file in a specified directory. -## Syntax +- If this command is executed to create an existing file, the execution will be successful but the timestamp will not be updated. -touch \[_filename_\] -## Parameters +## Syntax -**Table 1** Parameter description +touch [_filename_] - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

--help

-

Displays the parameters supported by the touch command.

-

N/A

-

filename

-

Specifies the name of the file to create.

-

N/A

-
-## Usage +## Parameters -- The **touch** command creates an empty file that is readable and writeable. -- You can use the **touch** command to create multiple files at a time. + **Table 1** Parameter description - >![](../public_sys-resources/icon-notice.gif) **NOTICE:** - >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. +| Parameter | Description | Value Range| +| -------- | --------------------------- | -------- | +| --help | Displays the parameters supported by the **touch** command.| N/A | +| filename | Specifies the name of the file to create. | N/A | -## Example +## Usage Guidelines + +- The **touch** command creates an empty file that is readable and writeable. + +- You can use the **touch** command to create multiple files at a time. + + > **NOTICE**
+ > 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 + +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: -- touch file.c -- touch testfile1 testfile2 testfile3 +- touch file.c -## Output +- touch testfile1 testfile2 testfile3 + + +## Output + +Example 1: Create a file named **file.c**. -Example 1: creating the **file.c** file ``` OHOS:/tmp$ ls @@ -70,7 +60,8 @@ total 0 -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. + ``` *OHOS:/tmp$ @@ -82,4 +73,3 @@ total 0 -rwxrwxrwx 1 0 0 0 1979-12-31 00:00 testfile3* OHOS:/tmp$ ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-umount.md b/en/device-dev/kernel/kernel-small-debug-shell-file-umount.md index a3b41c10707376fc70af957aeb20adcd0fdbb797..1125ae02c52e19154a60a6b3174c480adcfa4af9 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-umount.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-umount.md @@ -1,84 +1,61 @@ # umount -## Command Function - -This command is used to unmount a specified file system. - -## Syntax - -umount \[_-a \[-t TYPE\]_\] \[_dir_\] - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

--help

-

Displays the parameters supported by the umount command.

-

N/A

-

-a

-

Unmounts all file systems mounted.

-

N/A

-

-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

-

dir

-

Specifies the directory from which the file system is to be unmounted.

-

Directory mounted with the file system

-
- -## Usage - -By specifying the **dir** parameter in the **unmount** command, you can unmount the specified file system from the directory. - -## Example +## Command Function + +This command is used to unmount a file system. + + +## Syntax + +umount [_-a [-t TYPE]_] [_dir_] + + +## Parameters + +**Table 1** Parameter description + +| Parameter | Description | Value Range | +| ------ | ------------------------------------------------------------ | -------------------------- | +| --help | Displays the parameters supported by the **umount** command. | N/A | +| -a | Unmounts all file systems mounted. | N/A | +| -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 | +| dir | Specifies the directory from which the file system is to be unmounted. | Directory mounted with the file system| + + +## Usage Guidelines + +By specifying the **dir** parameter in the **unmount** command, you can unmount the specified file system. + +## Note + +The shell does not support this command. mksh supports it. To switch to mksh, run **cd bin** and **./mksh**. + +## Example Run the following commands: -- umount ./nfs -- umount -a -t nfs +- umount ./nfs + +- umount -a -t nfs -## Output -**unmount** command output: +## Output + + + +Example 1: Unmount the file system from **./nfs**. -Example 1: unmounting the file system from **./nfs** ``` OHOS:/$ umount ./nfs/ umount ok ``` -Example 2: unmounting all NFS directories +Example 2: Unmount all NFS directories. + ``` OHOS:/$ umount -a -t nfs umount ok ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-file-write.md b/en/device-dev/kernel/kernel-small-debug-shell-file-write.md index f48ee11f17a53f04a3e1a197942e43dc6e167af1..41174409524abf0e7f486abad36da5fb73709746 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-file-write.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-file-write.md @@ -1,63 +1,52 @@ # writeproc -## Command Function +## Command Function -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. -## Syntax -writeproc <_data_\> \>\> /proc/<_filename_\> +## Syntax -## Parameters +writeproc <*data*> >> /proc/<*filename*> -**Table 1** Parameter description - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

data

-

Specifies the string to be entered, which ends with a space. If you need to enter a space, use "" to enclose the space.

-

N/A

-

filename

-

Specifies the proc file to which data is to be passed.

-

N/A

-
+## Parameters -## Usage +**Table 1** Parameter description -The proc file implements its own **write** command. Calling the **writeproc** command will pass the input parameters to the **write** command. +| Parameter | Description | +| -------- | ---------------------------------------------------------- | +| data | Specifies the string to write, which ends with a space. If you need to write a space, use **""** to enclose the space. | +| filename | Specifies the proc file to which **data** is to write. | ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->The procfs file system does not support multi-thread access. -## Example +## Usage Guidelines -Run **writeproc test \>\> /proc/uptime**. +The proc file system implements its own **write()** function. Calling the **writeproc** command will pass input parameters to the **write()** function. -## Output +> **NOTE**
+> The procfs file system does not support multi-thread access. -OHOS \# writeproc test \>\> /proc/uptime +## Note -\[INFO\]write buf is: test +Currently, the shell does not support this command. -test \>\> /proc/uptime +## Example ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->The uptime proc file temporarily implements the **write** command. The **INFO** log is generated by the implemented **test** command. +Run **writeproc test >> /proc/uptime**. + + +## Output + +``` +OHOS \# writeproc test >> /proc/uptime + +[INFO]write buf is: test + +test >> /proc/uptime +``` + +> **NOTE**
+> The **uptime** proc file temporarily implements the **write()** function. The **INFO** log is generated by the **test()** function. diff --git a/en/device-dev/kernel/kernel-small-debug-shell-magickey.md b/en/device-dev/kernel/kernel-small-debug-shell-magickey.md index 80248ba4e5fbc59fbef823ca8b34e8584709c243..9af3ed1cceb676fa0a39c20126184874eb3d6382 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-magickey.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-magickey.md @@ -3,24 +3,30 @@ ## When to Use -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 -1. Configure the macro **LOSCFG_ENABLE_MAGICKEY**. +The magic key depends on the macro **LOSCFG_ENABLE_MAGICKEY**. - 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. +To configure **LOSCFG_ENABLE_MAGICKEY**: - > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** - > - > On **menuconfig**, you can move the cursor to **LOSCFG_ENABLE_MAGICKEY** and enter a question mark (?) to view help Information. - -2. Press **Ctrl+R** to enable the magic key. +1. Run the **make menuconfig** command in **kernel/liteos_a**. +2. Locate the **Debug** option and select **Enable MAGIC KEY**. + +This option is selected by default. If it is not selected, the magic key is invalid. + +> **NOTE**
+> On **menuconfig**, you can move the cursor to **LOSCFG_ENABLE_MAGICKEY** and enter a question mark (?) to view help information. + +## How to Use + +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. The functions of the magic key are as follows: @@ -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!". - > ![icon-notice.gif](public_sys-resources/icon-notice.gif) **NOTICE**
- > 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. + > **NOTE**
+ > 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. diff --git a/en/device-dev/kernel/kernel-small-debug-shell-net-arp.md b/en/device-dev/kernel/kernel-small-debug-shell-net-arp.md index 87b2afa6260a345d8e47c09398acf62b08c2ada0..c4c6ce48042d9ff0783ecf36fa874e68bafb72d6 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-net-arp.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-net-arp.md @@ -1,73 +1,44 @@ # arp -## Command Function +## Command Function -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. -## Syntax + +## Syntax arp -arp \[_-i IF_\] -s _IPADDR HWADDR_ - -arp \[_-i IF_\] -d _IPADDR_ - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

No parameter

-

Queries the content of the ARP cache table.

-

N/A

-

-i IF

-

Specifies the network port. This parameter is optional.

-

N/A

-

-s IPADDR

-

HWADDR

-

Adds an ARP entry. The second parameter is the IP address and MAC address of the other host on the LAN.

-

N/A

-

-d IPADDR

-

Deletes an ARP entry.

-

N/A

-
- -## Usage - -- 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 - -Run the **arp** command. - -ARP cache table: +arp [_-i IF_] -s *IPADDR HWADDR* + +arp [_-i IF_] -d *IPADDR* + + +## Parameters + +**Table 1** Parameter description + +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| No parameter| Prints the content of the ARP cache table.| N/A | +| -i IF | Specifies the network port. This parameter is optional.| N/A | +| -s IPADDR
HWADDR | Adds an ARP entry. The second parameter is the IP address and MAC address of the other host on the LAN.| N/A | +| -d IPADDR | Deletes an ARP entry.| N/A | + + +## Usage Guidelines + +- 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 protocol stack is enabled. + + +## Example + +Run **arp**. + +ARP cache table information: ``` OHOS # arp @@ -75,35 +46,11 @@ Address HWaddress Iface Type 192.168.1.10 E6:2B:99:2C:4B:20 eth0 static ``` -**Table 2** Output description - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Address

-

IPv4 address of a network device.

-

HWaddress

-

MAC address of a network device.

-

Iface

-

Name of the port used by the ARP entry.

-

Type

-

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.

-
+**Table 2** Parameter description +| 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. | diff --git a/en/device-dev/kernel/kernel-small-debug-shell-net-dhclient.md b/en/device-dev/kernel/kernel-small-debug-shell-net-dhclient.md index afb2a55f32fe6475e94f19765a822036c28fb4e1..d48ba68bb62e7ac2baceead92d7fa440b2c6417d 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-net-dhclient.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-net-dhclient.md @@ -1,62 +1,45 @@ # dhclient -## Command Function - -This command is used to set and query **dhclient** parameters. - -## Syntax - -- dhclient <_netif name_\> -- dhclient -x <_netif name_\> - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

-h | --help

-

Displays parameters supported by the dhclient command and their usage.

-

N/A

-

<netif name>

-

Enables Dynamic Host Configuration Protocol (DHCP) for a network interface card (NIC).

-

NIC name, eth0

-

-x <netif name>

-

Disables DHCP for a NIC.

-

NIC name, eth0

-
- -## Usage +## Command Function + +This command is used to set and query **dhclient** parameters. + + +## Syntax + +- dhclient <*netif name*> + +- dhclient -x <*netif name*> + + +## Parameters + +**Table 1** Parameter description + +| Parameter | Description | Value Range | +| ------------------------------- | -------------------------------------------- | ---------------- | +| -h \| --help | Displays parameters supported by the **dhclient** command and their usage.| N/A | +| <netif name> | Enables Dynamic Host Configuration Protocol (DHCP) for a network interface card (NIC). | NIC name, **eth0**| +| -x <netif name> | Disables DHCP for a NIC. | NIC name, **eth0**| + + +## Usage Guidelines Run the following commands: -- dhclient eth0 -- dhclient -x eth0 +- dhclient eth0 + +- dhclient -x eth0 + +## Note + +Currently, the shell does not support this command. -## Example +## Example + +Example 1: Enable DHCP for eth0. -Example 1: enabling DHCP for eth0 ``` OHOS:/$ dhclient eth0 @@ -69,7 +52,9 @@ eth0 ip:192.168.1.10 netmask:255.255.255.0 gateway:192.168.1.1 OHOS:/$ ``` -Example 2: disabling DHCP for eth0 + +Example 2: Disable DHCP for eth0. + ``` OHOS:/$ dhclient -x eth0 @@ -81,4 +66,3 @@ lo ip:127.0.0.1 netmask:255.0.0.0 gateway:127.0.0.1 eth0 ip:0.0.0.0 netmask:0.0.0.0 gateway:0.0.0.0 HWaddr 42:da:81:bc:58:94 MTU:1500 Running Default Link UP ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-net-ifconfig.md b/en/device-dev/kernel/kernel-small-debug-shell-net-ifconfig.md index be7d8a835a2944e3303cf6a4a182f8bebf42da94..017f799e49c00a0d8f75aef2b6b6af1ed701b86d 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-net-ifconfig.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-net-ifconfig.md @@ -1,313 +1,157 @@ # ifconfig -## Command Function +## Command Function This command can be used to: -- Query and set parameters of a network interface card \(NIC\), such as the IP address, network mask, gateway, and MAC address. -- Enable or disable a NIC. +- Query and set parameters of a network interface card (NIC), such as the IP address, network mask, gateway, and MAC address. -## Syntax +- Enable or disable a NIC. -ifconfig \[option\] + +## Syntax + +ifconfig [option] option: -- \[_-a_\] -- <_interface_\> <_address_\> \[_netmask _\] \[_gateway _\] -- \[_hw ether _\] \[_mtu _\] -- \[_inet6 add _\] -- \[_inet6 del _\] -- \[_up|down_\] - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

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

-

-a

-

Displays data sent and received by the protocol stack.

-

N/A

-

interface

-

Specifies the NIC name, for example, eth0.

-

N/A

-

address

-

Specifies the IP address, for example, 192.168.1.10. The NIC name must be specified.

-

N/A

-

netmask

-

Specifies the subnet mask, for example, 255.255.255.0.

-

N/A

-

gateway

-

Specifies the gateway, for example, 192.168.1.1.

-

N/A

-

hw ether

-

Specifies the MAC address, for example, 00:11:22:33:44:55. Currently, only the ether hardware type is supported.

-

N/A

-

mtu

-

Specifies the MTU size, for example, 1000.

-
  • IPv4:

    [68,1500]

    -
  • IPv6:

    [1280, 1500]

    -
-

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

-

del

-

Deletes an IPv6 address. You need to specify the NIC name and add the inet6 option. For details, see the example.

-

N/A

-

up

-

Enables the data processing function of the NIC. The NIC name must be specified.

-

N/A

-

down

-

Disables the data processing function of the NIC. The NIC name must be specified.

-

N/A

-
- -## Usage - -- The **ifconfig** command can be used only after the TCP/IP stack is enabled. -- Detecting an IP address conflict takes time. Each time you run the **ifconfig** command to set an IP address, there is a delay of about 2 seconds. - -## Example - -- ifconfig eth0 192.168.100.31 netmask 255.255.255.0 gateway 192.168.100.1 hw ether 00:49:cb:6c:a1:31 -- ifconfig -a -- ifconfig eth0 inet6 add 2001:a:b:c:d:e:f:d -- ifconfig eth0 inet6 del 2001:a:b:c:d:e:f:d - -## Output - -- Example 1: setting network parameters - - ``` - OHOS:/$ ifconfig eth0 192.168.100.31 netmask 255.255.255.0 gateway 192.168.100.1 hw ether 00:49:cb:6c:a1:31 - OHOS:/$ ifconfig - lo ip:127.0.0.1 netmask:255.0.0.0 gateway:127.0.0.1 - ip6: ::1/64 - HWaddr 00 MTU:0 Running Link UP - eth0 ip:192.168.100.31 netmask:255.255.255.0 gateway:192.168.100.1 - HWaddr 00:49:cb:6c:a1:31 MTU:1500 Running Default Link UP - ``` - - The following table describes the output parameters. - - **Table 2** Output description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

ip

-

IP address of the board

-

netmask

-

Subnet mask

-

gateway

-

Gateway

-

HWaddr

-

MAC address of the board

-

MTU

-

Maximum transmission unit

-

Running/Stop

-

Indicates whether the NIC is running.

-

Default

-

Indicates that the NIC is connected to the default gateway.

-

Link UP/Down

-

Connection status of the NIC

-
- -- Example 2: obtaining protocol stack statistics - - ``` - OHOS # ifconfig -a - RX packets:6922 errors:0 ip dropped:4312 link dropped:67 overrun:0 bytes:0 (0.0 B) - RX packets(ip6):3 errors:0 dropped:0 overrun:0 bytes:0 (0.0 B) - TX packets:1394 errors:0 link dropped:67 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. - - **Table 3** ifconfig -a output description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

RX packets

-

Number of normal packets received at the IP layer.

-

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.

-

RX dropped

-

Number of packets discarded at the IP layer. Packets are discarded due to packet errors, packet forwarding failures, and disabled local NICs.

-

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.

-

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.

-

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.

-

TX dropped

-

Number of packets that the MAC layer discards due to delivery failures, for example, the NIC driver fails to process the packets.

-

TX overrun

-

Reserved.

-

TX bytes

-

Total length of the packets successfully sent or forwarded at the IP layer.

-
- -- Example 3: setting an IPv6 address - - ``` - OHOS:/$ ifconfig eth0 inet6 add 2001:a:b:c:d:e:f:d - NetifStatusCallback(eth0): nsc event: 0x8 - NetifStatusCallback(eth0): nsc status changed: 0 - NetifStatusCallback(eth0): nsc event: 0x200 - NetifStatusCallback(eth0): nsc event: 0x8 - NetifStatusCallback(eth0): nsc status changed: 1 - NetifStatusCallback(eth0): nsc event: 0x200 - NetifStatusCallback(eth0): nsc event: 0x200 - OHOS:/$ ifconfig - lo ip:127.0.0.1 netmask:255.0.0.0 gateway:127.0.0.1 - ip6: ::1/64 - HWaddr 00 MTU:0 Running Link UP - eth0 ip:192.168.1.10 netmask:255.255.255.0 gateway:192.168.1.1 - ip6: 2001:A:B:C:D:E:F:D/64 - HWaddr 66:2f:e5:bd:24:e6 MTU:1500 Running Default Link UP - ``` - -- Example 4: deleting an IPv6 address - - ``` - OHOS:/$ ifconfig eth0 inet6 del 2001:a:b:c:d:e:f:d - NetifStatusCallback(eth0): nsc event: 0x200 - OHOS:/$ ifconfig - lo ip:127.0.0.1 netmask:255.0.0.0 gateway:127.0.0.1 - ip6: ::1/64 - HWaddr 00 MTU:0 Running Link UP - eth0 ip:192.168.1.10 netmask:255.255.255.0 gateway:192.168.1.1 - HWaddr 66:2f:e5:bd:24:e6 MTU:1500 Running Default Link UP - ``` +- [_-a_] + +- <*interface*> <*address*> [_netmask <mask>_] [_gateway <address>_] + +- [_hw ether <address>_] [_mtu <size>_] + +- [_inet6 add <address>_] + +- [_inet6 del <address>_] + +- [_up|down_] + + +## Parameters + +**Table 1** Parameter description + +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| 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 | +| -a | Displays data sent and received by the protocol stack.| N/A | +| interface | Specifies the NIC name, for example, **eth0**.| N/A | +| address | Specifies the IP address, for example, **192.168.1.10**. The NIC name must be specified.| N/A | +| netmask | Specifies the subnet mask, for example, **255.255.255.0**.| N/A | +| gateway | Specifies the gateway, for example, **192.168.1.1**.| N/A | +| hw ether | Specifies the MAC address, for example, **00:11:22:33:44:55**. Currently, only the **ether** hardware type is supported.| N/A | +| mtu | Specifies the MTU size, for example, **1000**.| - IPv4: [68, 1500]
- IPv6:[1280, 1500] | +| 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 | +| del | Deletes an IPv6 address. You need to specify the NIC name and add the **inet6** option. For details, see the example.| N/A | +| up | Enables the data processing function of the NIC. The NIC name must be specified.| N/A | +| down | Disables the data processing function of the NIC. The NIC name must be specified.| N/A | +## Usage Guidelines + +- This command can be used only after the TCP/IP stack is enabled. + +- Detecting an IP address conflict takes time. Each time you run the **ifconfig** command to set an IP address, there is a delay of about 2 seconds. + + +## Example + +- ifconfig eth0 192.168.100.31 netmask 255.255.255.0 gateway 192.168.100.1 hw ether 00:49:cb:6c:a1:31 + +- ifconfig -a + +- ifconfig eth0 inet6 add 2001:a:b:c:d:e:f:d + +- ifconfig eth0 inet6 del 2001:a:b:c:d:e:f:d + + +## Output + +- Example 1: Set network parameters. + + ``` + OHOS:/$ ifconfig eth0 192.168.100.31 netmask 255.255.255.0 gateway 192.168.100.1 hw ether 00:49:cb:6c:a1:31 + OHOS:/$ ifconfig + lo ip:127.0.0.1 netmask:255.0.0.0 gateway:127.0.0.1 + ip6: ::1/64 + HWaddr 00 MTU:0 Running Link UP + eth0 ip:192.168.100.31 netmask:255.255.255.0 gateway:192.168.100.1 + HWaddr 00:49:cb:6c:a1:31 MTU:1500 Running Default Link UP + ``` + + + + **Table 2** Parameter description + + | Parameter| Description| + | -------- | -------- | + | ip | IP address of the board.| + | netmask | Subnet mask.| + | gateway | Gateway.| + | HWaddr | MAC address of the board.| + | MTU | Maximum transmission unit.| + | Running/Stop | Whether the NIC is running.| + | Default | Indicates that the NIC is connected to the default gateway.| + | Link UP/Down | Connection status of the NIC.| + +- Example 2: Obtain protocol stack statistics. + + ``` + OHOS # ifconfig -a + RX packets:6922 errors:0 ip dropped:4312 link dropped:67 overrun:0 bytes:0 (0.0 B) + RX packets(ip6):3 errors:0 dropped:0 overrun:0 bytes:0 (0.0 B) + TX packets:1394 errors:0 link dropped:67 overrun:0 bytes:0(0.0 B) + TX packets(ip6):3 errors:0 overrun:0 bytes:0(0.0 B) + ``` + + + + **Table 3** ifconfig -a parameter description + + | Parameter| Description| + | -------- | -------- | + | RX packets | Number of normal packets received at the IP layer.| + | 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.| + | RX dropped | Number of packets discarded at the IP layer. Packets are discarded due to packet errors, packet forwarding failures, and disabled local NICs.| + | 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.| + | 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.| + | 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.| + | TX dropped | Number of packets that the MAC layer discards due to delivery failures, for example, the NIC driver fails to process the packets.| + | TX overrun | Not used currently.| + | TX bytes | Total length of the packets successfully sent or forwarded at the IP layer.| + +- Example 3: Set an IPv6 address. + + ``` + OHOS:/$ ifconfig eth0 inet6 add 2001:a:b:c:d:e:f:d + NetifStatusCallback(eth0): nsc event: 0x8 + NetifStatusCallback(eth0): nsc status changed: 0 + NetifStatusCallback(eth0): nsc event: 0x200 + NetifStatusCallback(eth0): nsc event: 0x8 + NetifStatusCallback(eth0): nsc status changed: 1 + NetifStatusCallback(eth0): nsc event: 0x200 + NetifStatusCallback(eth0): nsc event: 0x200 + OHOS:/$ ifconfig + lo ip:127.0.0.1 netmask:255.0.0.0 gateway:127.0.0.1 + ip6: ::1/64 + HWaddr 00 MTU:0 Running Link UP + eth0 ip:192.168.1.10 netmask:255.255.255.0 gateway:192.168.1.1 + ip6: 2001:A:B:C:D:E:F:D/64 + HWaddr 66:2f:e5:bd:24:e6 MTU:1500 Running Default Link UP + ``` + +- Example 4: Delete an IPv6 address. + + ``` + OHOS:/$ ifconfig eth0 inet6 del 2001:a:b:c:d:e:f:d + NetifStatusCallback(eth0): nsc event: 0x200 + OHOS:/$ ifconfig + lo ip:127.0.0.1 netmask:255.0.0.0 gateway:127.0.0.1 + ip6: ::1/64 + HWaddr 00 MTU:0 Running Link UP + eth0 ip:192.168.1.10 netmask:255.255.255.0 gateway:192.168.1.1 + HWaddr 66:2f:e5:bd:24:e6 MTU:1500 Running Default Link UP + ``` diff --git a/en/device-dev/kernel/kernel-small-debug-shell-net-ipdebug.md b/en/device-dev/kernel/kernel-small-debug-shell-net-ipdebug.md index e3dcce0bd9ac649fa5fb5ad82b8f77d714afae9c..1fd84191a319b96a2459080e1834bf712a70e49e 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-net-ipdebug.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-net-ipdebug.md @@ -1,21 +1,24 @@ # ipdebug -## Command Function +## Command Function -**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 + +## Syntax ipdebug -## Example -Run the **ipdebug** command. +## Example + +Run the **ipdebug** command. -## Output -**ipdebug** command output: +## Output + +**ipdebug** command output: ``` OHOS # ipdebug @@ -52,4 +55,3 @@ FE80::4639:C4FF:FE94:5D44 FE80::4639:C4FF:FE94:5D44 pmtu 1500 age 6 FE80::4639:C4FF:FE94:5D44 invalidation_timer 1784 flags 0 -------------------------------------------------------------------- ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-net-netstat.md b/en/device-dev/kernel/kernel-small-debug-shell-net-netstat.md index a383b945766d96178bdf52cd532a315bed2ed6b2..0e2052c802089979c566cba06648e2390700cc13 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-net-netstat.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-net-netstat.md @@ -1,29 +1,37 @@ # netstat -## Command Function +## Command Function -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 + +## Syntax netstat -## Parameters -None +## Parameters -## Usage +None. -netstat -## Example +## Usage Guidelines + +None. + +## Note -Run **netstat**. +Currently, the shell does not support this command. -## Output +## Example -**netstat** print information +Run **netstat**. + + +## Output + +**netstat** output information: ``` OHOS # netstat @@ -41,50 +49,16 @@ udp 0 0 127.0.0.1:62180 127.0.0.1:62179 udp 0 0 127.0.0.1:62178 127.0.0.1:62177 ``` -**Table 1** Output description - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Proto

-

Protocol type.

-

Recv-Q

-

Amount of data that is not read by the user.

-

For Listen TCP, the value indicates the number of TCP connections that have finished three-way handshake but are not accepted by users.

-

Send-Q

-

For a TCP connection, this value indicates the amount of data that has been sent but not acknowledged.

-

For a UDP connection, this value indicates the amount of data buffered before IP address resolution is complete.

-

Local Address

-

Local IP address and port number.

-

Foreign Address

-

Remote IP address and port number.

-

State

-

TCP connection status. This parameter is meaningless for UDP.

-
- ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->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. +**Table 1** Output description + +| Parameter | Description | +| -------------------- | ------------------------------------------------------------ | +| Proto | Protocol type. | +| Recv-Q | Amount of data that is not read by the user.
For Listen TCP, the value indicates the number of TCP connections that have finished the three-way handshake but are not accepted by users. | +| Send-Q | For a TCP connection, this value indicates the amount of data that has been sent but not acknowledged.
For a UDP connection, this value indicates the amount of data buffered before IP address resolution is complete.| +| Local Address | Local IP address and port number. | +| Foreign Address | Remote IP address and port number. | +| State | TCP connection status. This parameter is meaningless for UDP. | +> **NOTE**
+> 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. diff --git a/en/device-dev/kernel/kernel-small-debug-shell-net-ntpdate.md b/en/device-dev/kernel/kernel-small-debug-shell-net-ntpdate.md index f3fa527279212dab09ad895b48872ca143a67926..5f6605457b77f0f71ca6b8f9d5bc1f0bba4f5089 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-net-ntpdate.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-net-ntpdate.md @@ -1,51 +1,41 @@ # ntpdate -## Command Function +## Command Function This command is used to synchronize system time from the server. -## Syntax -ntpdate \[_SERVER\_IP1_\] \[_SERVER\_IP2_\]... +## Syntax -## Parameters +ntpdate [_SERVER_IP1_] [_SERVER_IP2_]... -**Table 1** Parameter description - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

SERVER_IP

-

Specifies the IP address of the NTP server.

-

N/A

-
+## Parameters -## Usage +**Table 1** Parameter description -Run the **ntpdate **\[_SERVER\_IP1_\] \[_SERVER\_IP2_\]... command. **ntpdate** obtains and displays the time of the first server with a valid IP address. +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| SERVER_IP | Specifies the IP address of the NTP server.| N/A | -## Example -Run **ntpdate 192.168.1.3 **to update the system time. +## Usage Guidelines + +Run the **ntpdate [_SERVER_IP1_] [_SERVER_IP2_]...** command to obtain and display the time of the first server with a valid IP address. + + +## Example + +Run **ntpdate 192.168.1.3 **to update the system time. + + +## Output -## Output ``` OHOS # ntpdate 192.168.1.3 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. diff --git a/en/device-dev/kernel/kernel-small-debug-shell-net-ping.md b/en/device-dev/kernel/kernel-small-debug-shell-net-ping.md index 5c709aaaf0bae7a78dda6e8cc5060c6832d176fb..2abc781addc72da998a4a4c89ba375a8c05c2263 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-net-ping.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-net-ping.md @@ -1,100 +1,51 @@ # ping -## Command Function +## Command Function This command is used to test an IPv4 connection. -## Syntax - -ping _\[-4\] \[-c cnt\] \[-f\] \[-i interval\] \[-q\] \[-s size\] _ - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

--help

-

Displays the parameters supported by the ping command.

-

N/A

-

-4

-

Forcibly pings the destination address using the IPv4 protocol.

-

0-65500

-

-c CNT

-

Specifies the number of execution times. The default value is 3.

-

1-65535

-

-f

-

Pings an IPv4 address in implicit mode. The default parameter configuration is equivalent to -c 15 -i 0.2.

-

N/A

-

-i interval

-

Specifies the interval (in ms) for sending a ping packet.

-

1-200

-

-q

-

Implicitly pings an IPv4 address. If the host is active, the ping stops after true is received.

-

N/A

-

-s SIZE

-

Specifies the size of a ping packet, in bytes. The default size is 56 bytes.

-

0-4088

-

IP

-

Specifies the IPv4 address to test.

-

N/A

-
- -## Usage - -- The **ping** command is used to check whether the destination IP address is reachable. -- If the destination IP address is unreachable, the system displays a message indicating that the request times out. -- If no route is available to the destination IP address, an error message is displayed. -- This command can be used only after the TCP/IP stack is enabled. - -## Example - -Run **ping 192.168.1.3**. - -## Output - -Pinging a TFTP server IP address: + +## Syntax + +ping *[-4] [-c cnt] [-f] [-i interval] [-q] [-s size] <IP>* + + +## Parameters + +**Table 1** Parameter description + +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| --help | Displays the parameters supported by the **ping** command.| N/A | +| -4 | Forcibly pings the destination address using the IPv4 protocol.| 0-65500 | +| -c CNT | Specifies the number of execution times. The default value is **3**.| 1-65535 | +| -f | Pings an IPv4 address in implicit mode. The default parameter configuration is equivalent to **-c 15 -i 0.2**.| N/A | +| -i interval | Specifies the interval (in ms) for sending a ping packet.| 1-200 | +| -q | Implicitly pings an IPv4 address. If the host is still alive, the ping stops after **true** is returned.| N/A | +| -s SIZE | Specifies the size of a ping packet, in bytes. The default size is **56** bytes.| 0-4088 | +| IP | Specifies the IPv4 address of the network to test.| N/A | + + +## Usage Guidelines + +- The **ping** command is used to check whether the destination IP address is reachable. + +- If the destination IP address is unreachable, the system displays a message indicating that the request times out. + +- If no route is available to the destination IP address, an error message is displayed. + +- This command can be used only after the TCP/IP protocol stack is enabled. + + +## Example + +Run **ping 192.168.1.3**. + + +## Output + +Ping a TFTP server IP address. ``` OHOS:/$ ping 192.168.1.3 @@ -106,4 +57,3 @@ Ping 192.168.1.3 (192.168.1.3): 56(84) bytes. 3 packets transmitted, 3 received, 0% packet loss round-trip min/avg/max = 0/0/0 ms ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-net-ping6.md b/en/device-dev/kernel/kernel-small-debug-shell-net-ping6.md index e1ec3b85298b9e1a10a048518f13339cf1f111a7..cc71b56b59673cbf9063097ae44c59ede5ea1abc 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-net-ping6.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-net-ping6.md @@ -1,120 +1,98 @@ # ping6 -## Command Function +## Command Function This command is used to test an IPv6 network connection. -## Syntax - -ping6 _\[-c count\] \[-I interface / sourceAddress\] destination_ - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

-c count

-

Specifies the number of execution times. If this parameter is not specified, the default value is 4.

-

1~65535

-

-I interface

-

Performs an IPv6 ping operation for a specified NIC.

-

N/A

-

-I sourceAddress

-

Specifies the source IPv6 address.

-

N/A

-

destination

-

Specifies the IP address of the destination host.

-

N/A

-
- -## Usage - -- If the destination IPv6 address is unreachable, the system displays a message indicating that the request times out. -- If no route is available to the destination IPv6 address, an error message is displayed. -- This command can be used only after the TCP/IP protocol stack is enabled. - -## Example - -- ping6 2001:a:b:c:d:e:f:b -- ping6 -c 3 2001:a:b:c:d:e:f:b -- ping6 -I eth0 2001:a:b:c:d:e:f:b -- ping6 -I 2001:a:b:c:d:e:f:d 2001:a:b:c:d:e:f:b - -## Output - -1. Output of **ping6 2001:a:b:c:d:e:f:b**: - - ``` - OHOS # ping6 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data. - 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=1 time<1 ms - 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=2 time<1 ms - 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=3 time<1 ms - 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=4 time<1 ms - --- 2001:a:b:c:d:e:f:b/64 ping statistics --- - 4 packets transmitted, 4 received, 0.00% packet loss, time 20ms - rtt min/avg/max = 0/0.00/0 ms - ``` - -2. Output of **ping6 -c 3 2001:a:b:c:d:e:f:b**: - - ``` - OHOS # ping6 -c 3 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data. - 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=1 time<1 ms - 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=2 time<1 ms - 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=3 time<1 ms - --- 2001:a:b:c:d:e:f:b/64 ping statistics --- - 3 packets transmitted, 3 received, 0.00% packet loss, time 20ms - rtt min/avg/max = 0/0.00/0 ms - ``` - -3. Output of **ping6 -I eth0 2001:a:b:c:d:e:f:b**: - - ``` - OHOS # ping6 -I eth0 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data. - 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=1 time=10 ms - 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=2 time<1 ms - 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=3 time<1 ms - 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=4 time<1 ms - --- 2001:a:b:c:d:e:f:b/64 ping statistics --- - 4 packets transmitted, 4 received, 0.00% packet loss, time 30msrtt min/avg/max = 0/2.50/10 ms - ``` - -4. Output of **ping6 -I 2001:a:b:c:d:e:f:d 2001:a:b:c:d:e:f:b**: - - ``` - OHOS # ping6 -I 2001:a:b:c:d:e:f:d 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data. - 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=1 time<1 ms - 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=2 time<1 ms - 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=3 time<1 ms - 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=4 time<1 ms - --- 2001:a:b:c:d:e:f:b/64 ping statistics --- - 4 packets transmitted, 4 received, 0.00% packet loss, time 20msrtt min/avg/max = 0/0.00/0 ms - ``` +## Syntax +ping6 *[-c count] [-I interface / sourceAddress] destination* + + +## Parameters + +**Table 1** Parameter description + +| Parameter | Description | Value Range| +| --------------------- | ----------------------------------- | -------- | +| -c count | Specifies the number of execution times. If this parameter is not specified, the default value is **4**.| [1, 65535] | +| -I interface | Specifies the NIC for performing the ping operation. | N/A | +| -I sourceAddress | Specifies the source IPv6 address. | N/A | +| destination | Specifies the IP address of the destination host. | N/A | + + +## Usage Guidelines + +- If the destination IPv6 address is unreachable, "Request Timed Out" will be displayed. + +- If no route is available to the destination IPv6 address, "Destinatin Host Unreachable" will be displayed. + +- This command can be used only after the TCP/IP stack is enabled. + +## Note + +Currently, the shell does not support this command. + +## Example + +- ping6 2001:a:b:c:d:e:f:b + +- ping6 -c 3 2001:a:b:c:d:e:f:b + +- ping6 -I eth0 2001:a:b:c:d:e:f:b + +- ping6 -I 2001:a:b:c:d:e:f:d 2001:a:b:c:d:e:f:b + + +## Output + +1. Output of **ping6 2001:a:b:c:d:e:f:b**: + + ``` + OHOS # ping6 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data. + 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=1 time<1 ms + 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=2 time<1 ms + 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=3 time<1 ms + 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=4 time<1 ms + --- 2001:a:b:c:d:e:f:b/64 ping statistics --- + 4 packets transmitted, 4 received, 0.00% packet loss, time 20ms + rtt min/avg/max = 0/0.00/0 ms + ``` + +2. Output of **ping6 -c 3 2001:a:b:c:d:e:f:b**: + + ``` + OHOS # ping6 -c 3 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data. + 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=1 time<1 ms + 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=2 time<1 ms + 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=3 time<1 ms + --- 2001:a:b:c:d:e:f:b/64 ping statistics --- + 3 packets transmitted, 3 received, 0.00% packet loss, time 20ms + rtt min/avg/max = 0/0.00/0 ms + ``` + +3. Output of **ping6 -I eth0 2001:a:b:c:d:e:f:b**: + + ``` + OHOS # ping6 -I eth0 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data. + 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=1 time=10 ms + 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=2 time<1 ms + 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=3 time<1 ms + 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=4 time<1 ms + --- 2001:a:b:c:d:e:f:b/64 ping statistics --- + 4 packets transmitted, 4 received, 0.00% packet loss, time 30msrtt min/avg/max = 0/2.50/10 ms + ``` + +4. Output of **ping6 -I 2001:a:b:c:d:e:f:d 2001:a:b:c:d:e:f:b**: + + ``` + OHOS # ping6 -I 2001:a:b:c:d:e:f:d 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data. + 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=1 time<1 ms + 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=2 time<1 ms + 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=3 time<1 ms + 56 bytes from 2001:A:B:C:D:E:F:B : icmp_seq=4 time<1 ms + --- 2001:a:b:c:d:e:f:b/64 ping statistics --- + 4 packets transmitted, 4 received, 0.00% packet loss, time 20msrtt min/avg/max = 0/0.00/0 ms + ``` diff --git a/en/device-dev/kernel/kernel-small-debug-shell-net-telnet.md b/en/device-dev/kernel/kernel-small-debug-shell-net-telnet.md index 8f20d27c6d8f9f31ea7f77f27145e6aea87586c0..ff9fc0686ed420aca866b2691d31ea75720745ef 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-net-telnet.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-net-telnet.md @@ -1,63 +1,46 @@ # telnet -## Command Function +## Command Function This command is used to enable or disable the Telnet server service. -## Syntax -telnet \[_on | off_\] +## Syntax -## Parameters +telnet [_on | off_] -**Table 1** Parameter description - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

on

-

Enables the Telnet server service.

-

N/A

-

off

-

Disables the Telnet server service.

-

N/A

-
+## Parameters -## Usage +**Table 1** Parameter description -- 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. +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| on | Enables the telnet server service.| N/A | +| off | Disables the telnet server service.| N/A | - >![](../public_sys-resources/icon-notice.gif) **NOTICE:** - >Telnet is used for debugging and is disabled by default. Do not use it in formal products. +## Usage Guidelines -## Example +- 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. -Run **telnet on**. +- Currently, multiple clients (Telnet + IP) cannot connect to the development board at the same time. + > **NOTICE**
+ > Telnet is used for debugging and is disabled by default. Do not use it in formal products. -## Output + +## Example + +Run **telnet on**. + + +## Output Command output: + ``` OHOS # telnet on OHOS # start telnet server successfully, waiting for connection. ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-shell-net-tftp.md b/en/device-dev/kernel/kernel-small-debug-shell-net-tftp.md index d5fd3fb26a5f92d87861acac6ac609c95d241ff0..ca0227eed99e2e0c6a162c867eff3a0d329b05eb 100644 --- a/en/device-dev/kernel/kernel-small-debug-shell-net-tftp.md +++ b/en/device-dev/kernel/kernel-small-debug-shell-net-tftp.md @@ -1,81 +1,52 @@ # tftp -## Command Function - -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. - -## Syntax - -./bin/tftp _<-g/-p\>_ _-l_ _\[FullPathLocalFile\] -r \[RemoteFile\] \[Host\]_ - -## Parameters - -**Table 1** Parameter description - - - - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value Range

-

-g/-p

-

Specifies the file transfer direction.

-
  • -g: downloads files from the TFTP server.
  • -p: uploads files to the TFTP server.
-

N/A

-

-l FullPathLocalFile

-

Specifies the complete path of a local file.

-

N/A

-

-r RemoteFile

-

Specifies the file name on the server.

-

N/A

-

Host

-

Specifies the server IP address.

-

N/A

-
- -## Usage - -1. Deploy a TFTP server on the server and configure the TFTP server correctly. -2. Use the **tftp** command to upload and download files on the OpenHarmony board. -3. The size of the file to be transferred cannot exceed 32 MB. - - >![](../public_sys-resources/icon-notice.gif) **NOTICE:** - >TFTP is used for debugging and disabled by default. Do not use it in formal products. - - -## Example - -Download the **out** file from the server. - -## Output +## Command Function + +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. + + +## Syntax + +./bin/tftp *<-g/-p>**-l**[FullPathLocalFile] -r [RemoteFile] [Host]* + + +## Parameters + +**Table 1** Parameter description + +| Parameter| Description| Value Range| +| -------- | -------- | -------- | +| -g/-p | Specifies the file transfer direction.
- **-g**: obtains a file from the TFTP server.
- **-p**: uploads a file to the TFTP server.| N/A | +| -l FullPathLocalFile | Specifies the complete path of a local file.| N/A | +| -r RemoteFile | Specifies the file name on the server.| N/A | +| Host | Specifies the server IP address.| N/A | + + +## Usage Guidelines + +1. Deploy a TFTP server on the server and configure the TFTP server correctly. + +2. Use the **tftp** command to upload files from or download files to an OpenHarmony board. + +3. The size of the file to be transferred cannot exceed 32 MB. + > **NOTICE**
+ > TFTP is used for debugging and disabled by default. Do not use it in formal products. + + +## Example + +Download the **out** file from the server. + + +## Output + ``` OHOS # ./bin/tftp -g -l /nfs/out -r out 192.168.1.2 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. diff --git a/en/device-dev/kernel/kernel-small-debug-trace.md b/en/device-dev/kernel/kernel-small-debug-trace.md index df41fd67f3d7d2ddc196e1ea4ddc3c10e701aa95..16831db5798ed777d5394c0fe61176dcdccf04b4 100644 --- a/en/device-dev/kernel/kernel-small-debug-trace.md +++ b/en/device-dev/kernel/kernel-small-debug-trace.md @@ -28,92 +28,89 @@ 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). - **Table 1** APIs of the trace module +**Table 1** APIs of the trace module | Category| Description| | -------- | -------- | -| Starting/Stopping trace| **LOS_TraceStart**: starts trace.
**LOS_TraceStop**: stops trace. | -| Managing trace records| **LOS_TraceRecordDump**: dumps data from the trace buffer.
**LOS_TraceRecordGet**: obtains the start address of the trace buffer.
**LOS_TraceReset**: clears events in the trace buffer. | +| Starting/Stopping trace| **LOS_TraceStart**: starts trace.
**LOS_TraceStop**: stops trace.| +| Managing trace records| **LOS_TraceRecordDump**: dumps data from the trace buffer.
**LOS_TraceRecordGet**: obtains the start address of the trace buffer.
**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.| | 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.
**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 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. - - **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. - Example: - - ``` - Perform simple instrumentation for reading and writing files fd1 and fd2. - Set TYPE to 1 for read operations and 2 for write operations. - Insert the following to the position where the fd1 file is read: - 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. - - 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. - - The **IDENTITY** and **Params** are the same as those of simple instrumentation. - Example: - - ``` - 1. Set the event mask (module-level event type) in enum LOS_TRACE_MASK. - Format: TRACE_#MOD#_FLAG (MOD indicates the module name) +| Performing function instrumentation| **LOS_TRACE_EASY**: performs simple instrumentation.
**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 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. + - **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. Example: - 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. - #TYPE# is the #TYPE# defined in step 2. - Example: - #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 modify the parameters as required. - If no parameter is specified, events of this type are not traced. - #define FS_READ_PARAMS(fp, fd, flag, size) // File reading events are not traced. - 4. Insert a code stub in a proper position. - Format: LOS_TRACE(#TYPE#, #TYPE#_PARAMS(IDENTITY, parma1...)) - LOS_TRACE(FS_READ, fp, fd, flag, size); // Code stub for reading files. - The parameters following #TYPE# are the input parameter of the **FS_READ_PARAMS** function in step 3. - ``` - - > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
- > The trace event types and parameters can be modified 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**. - -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. - -Example: + ``` + Perform simple instrumentation for reading and writing files fd1 and fd2. + Set TYPE to 1 for read operations and 2 for write operations. + Insert the following to the position where the fd1 file is read: + 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. + - 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. + - The **IDENTITY** and **Params** are the same as those of simple instrumentation. + Example: -``` -BOOL Example_HwiNumFilter(UINT32 hwiNum) -{ - if ((hwiNum == TIMER_INT) || (hwiNum == DMA_INT)) { - return TRUE; - } - return FALSE; -} -LOS_TraceHwiFilterHookReg(Example_HwiNumFilter); -``` + ``` + 1. Set the event mask (module-level event type) in enum LOS_TRACE_MASK. + Format: TRACE_#MOD#_FLAG (MOD indicates the module name) + Example: + 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. + #TYPE# is the #TYPE# defined in step 2. + Example: + #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 modify the parameters as required. + If no parameter is specified, events of this type are not traced. + #define FS_READ_PARAMS(fp, fd, flag, size) // File reading events are not traced. + 4. Insert a code stub in a proper position. + Format: LOS_TRACE(#TYPE#, #TYPE#_PARAMS(IDENTITY, parma1...)) + LOS_TRACE(FS_READ, fp, fd, flag, size); // Code stub for reading files. + #The parameters following #TYPE# are the input parameter of the **FS_READ_PARAMS** function in step 3. + ``` + + > **NOTE**
+ > 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**. + +- 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. + Example: + + ```c + BOOL Example_HwiNumFilter(UINT32 hwiNum) + { + if ((hwiNum == TIMER_INT) || (hwiNum == DMA_INT)) { + return TRUE; + } + return FALSE; + } + LOS_TraceHwiFilterHookReg(Example_HwiNumFilter); + ``` The interrupt events with interrupt ID of **TIMER_INT** or **DMA_INT** are not traced. @@ -128,8 +125,8 @@ The trace character device is added in **/dev/trace**. You can use **read()**, * - **ioctl()**: performs user-mode trace operations, including: - -``` + +```c #define TRACE_IOC_MAGIC 'T' #define TRACE_START _IO(TRACE_IOC_MAGIC, 1) #define TRACE_STOP _IO(TRACE_IOC_MAGIC, 2) @@ -151,25 +148,24 @@ For details, see [User-Mode Development Example](kernel-small-debug-trace.md#use The typical trace process is as follows: 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**. - -| Configuration Item | menuconfig Option| Description| Value| -| -------- | -------- | -------- | -------- | -| 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_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_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
 ->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_BUFFER_SIZE | Trace record buffer size | Specifies the trace buffer size.| INT | + + | Item| menuconfig Option| Description| Value| + | -------- | -------- | -------- | -------- | + | 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_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_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 -> 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_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). 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. @@ -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.) -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 @@ -207,50 +203,53 @@ This example implements the following: ### 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. + The sample code is as follows: -``` +```c #include "los_trace.h" UINT32 g_traceTestTaskId; VOID Example_Trace(VOID) -{ - UINT32 ret; +{ + UINT32 ret; LOS_TaskDelay(10); /* Start trace. */ - ret = LOS_TraceStart(); - if (ret != LOS_OK) { - dprintf("trace start error\n"); - return; - } - /* Trigger a task switching event. */ - LOS_TaskDelay(1); - LOS_TaskDelay(1); - LOS_TaskDelay(1); - /* Stop trace. */ - LOS_TraceStop(); + ret = LOS_TraceStart(); + if (ret != LOS_OK) { + dprintf("trace start error\n"); + return; + } + /* Trigger a task switching event. */ + LOS_TaskDelay(1); + LOS_TaskDelay(1); + LOS_TaskDelay(1); + /* Stop trace. */ + LOS_TraceStop(); LOS_TraceRecordDump(FALSE); } -UINT32 Example_Trace_test(VOID){ - UINT32 ret; - TSK_INIT_PARAM_S traceTestTask; - /* Create a trace task. */ - memset(&traceTestTask, 0, sizeof(TSK_INIT_PARAM_S)); - traceTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Trace; - traceTestTask.pcName = "TestTraceTsk"; /* Test task name. */ - traceTestTask.uwStackSize = 0x800; - traceTestTask.usTaskPrio = 5; - traceTestTask.uwResved = LOS_TASK_STATUS_DETACHED; - ret = LOS_TaskCreate(&g_traceTestTaskId, &traceTestTask); - if(ret != LOS_OK){ - dprintf("TraceTestTask create failed .\n"); - return LOS_NOK; - } +UINT32 Example_Trace_test(VOID) +{ + UINT32 ret; + TSK_INIT_PARAM_S traceTestTask; + /* Create a trace task. */ + memset(&traceTestTask, 0, sizeof(TSK_INIT_PARAM_S)); + traceTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Trace; + traceTestTask.pcName = "TestTraceTsk"; /* Test task name. */ + traceTestTask.uwStackSize = 0x800; // 0x800: trace test task stack size + traceTestTask.usTaskPrio = 5; // 5: trace test task priority + traceTestTask.uwResved = LOS_TASK_STATUS_DETACHED; + ret = LOS_TaskCreate(&g_traceTestTaskId, &traceTestTask); + if (ret != LOS_OK) { + dprintf("TraceTestTask create failed .\n"); + return LOS_NOK; + } /* Trace is started by default. Therefore, you can stop trace, clear the buffer, and then start trace. */ - LOS_TraceStop(); - LOS_TraceReset(); - /* Enable trace of the Task module events. */ - LOS_TraceEventMaskSet(TRACE_TASK_FLAG); + LOS_TraceStop(); + LOS_TraceReset(); + /* Enable trace of the Task module events. */ + LOS_TraceEventMaskSet(TRACE_TASK_FLAG); return LOS_OK; } LOS_MODULE_INIT(Example_Trace_test, LOS_INIT_LEVEL_KMOD_EXTENDED); @@ -266,7 +265,7 @@ The output is as follows: ***TraceInfo begin*** clockFreq = 50000000 CurEvtIndex = 7 -Index Time(cycles) EventType CurTask Identity params +Index Time(cycles) EventType CurTask Identity params 0 0x366d5e88 0x45 0x1 0x0 0x1f 0x4 0x0 1 0x366d74ae 0x45 0x0 0x1 0x0 0x8 0x1f 2 0x36940da6 0x45 0x1 0xc 0x1f 0x4 0x9 @@ -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. -- **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. -- **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. @@ -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. -``` +```c #define TASK_SWITCH_PARAMS(taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus) \ taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus ``` Because of **#TYPE#_PARAMS(IDENTITY, parma1...) IDENTITY, ...**, **Identity** is **taskId (0x0)** and the first parameter is **oldPriority (0x1f)**. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > 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**. diff --git a/en/device-dev/kernel/kernel-small-debug-user.md b/en/device-dev/kernel/kernel-small-debug-user.md index 3a852dae6af647df07ad01dacf12d4cd6dcd92f1..fbdfc0d131f8018f3ceeac1fd9764e99ca5db79f 100644 --- a/en/device-dev/kernel/kernel-small-debug-user.md +++ b/en/device-dev/kernel/kernel-small-debug-user.md @@ -1,11 +1,10 @@ # User-Mode Memory Debugging ## Basic Concepts +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 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. +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. ## Working Principles @@ -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. - **Figure 1** Heap memory node linked list +**Figure 1** Heap memory node linked list - ![](figures/heap-memory-node-linked-list.png "heap-memory-node-linked-list") +![](figures/heap-memory-node-linked-list.png "heap-memory-node-linked-list") -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. 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. - **Figure 2** Heap memory node information +**Figure 2** Heap memory node information - ![](figures/heap-memory-node-information.png "heap-memory-node-information") +![](figures/heap-memory-node-information.png "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. @@ -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. - **Figure 3** Process of locating the code line for a memory leak +**Figure 3** Process of locating the code line for a memory leak - ![](figures/process-of-locating-the-code-lines-for-a-memory-leak.png "process-of-locating-the-code-lines-for-a-memory-leak") +![](figures/process-of-locating-the-code-lines-for-a-memory-leak.png "process-of-locating-the-code-lines-for-a-memory-leak") ### Heap Memory Statistics @@ -46,25 +45,33 @@ You can collect statistics on the percentage of heap memory requested by each th ### 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. + + **Figure 4** Adding a check value to the node header information + + ![](figures/adding-a-check-value-to-the-node-header-information.png "adding-a-check-value-to-the-node-header-information") + + 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. + + **Figure 5** Process of releasing memory + + ![](figures/process-of-releasing-memory.png "process-of-releasing-memory") + + + +- Requested memory greater than 0x1c000 bytes - **Figure 4** Adding a check value to the node header information - - ![](figures/adding-a-check-value-to-the-node-header-information.png "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. - - **Figure 5** Process of releasing memory - - ![](figures/process-of-releasing-memory.png "process-of-releasing-memory") + When the requested memory is greater than 0x1c000 bytes, **malloc** uses **mmap** to allocate memory. -- 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. + 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** - ![](figures/layout-of-the-memory-allocated-by-using-the-mmap-mechanism-of-malloc.png "layout-of-the-memory-allocated-by-using-the-mmap-mechanism-of-malloc") + ![](figures/layout-of-the-memory-allocated-by-using-the-mmap-mechanism-of-malloc.png "layout-of-the-memory-allocated-by-using-the-mmap-mechanism-of-malloc") ### Usage Guide #### Available APIs @@ -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. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE**
> 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: The sample code explicitly calls the related APIs of the memory debugging module to check the memory. -``` +```c #include #include #include @@ -127,7 +134,8 @@ The sample code explicitly calls the related APIs of the memory debugging module #define MALLOC_LEAK_SIZE 0x300 -void func(void) { +void func(void) +{ char *ptr = malloc(MALLOC_LEAK_SIZE); memset(ptr, '3', MALLOC_LEAK_SIZE); } @@ -156,17 +164,18 @@ $ clang -o mem_check mem_check.c -funwind-tables -rdynamic -g -mfloat-abi=softfp ``` -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** +> > - In this example, the compiler path is written into an environment variable in the **.bashrc** file. -> +> > - When compiling user programs and required libraries, add the option **-funwind-tables -rdynamic -g** for stack backtracking. -> +> > - The **-mfloat-abi=softfp**, **-mcpu=cortex-a7**, and **-mfpu=neon-vfpv4** options specify the floating-point calculation optimization, chip architecture, and FPU, which must be the same as the compilation options used by the libc library. Otherwise, the libc library file cannot be found during the link time. -> +> > - **-target arm-liteos** specifies the path of the library files related to the compiler. -> +> > - **--sysroot=/home//harmony/out/hispark_taurus/ipcamera_hispark_taurus/sysroot** specifies the root directory of the compiler library files. In this example, the OpenHarmony project code is stored in **/home//harmony**. The **out/hispark_taurus/ipcamera_hispark_taurus** directory indicates the product specified by the **hb set** command during compilation. In this example, **ipcamera_hispark_taurus** is the product specified. -> +> > - **$(clang -mfloat-abi=softfp -mcpu=cortex-a7 -mfpu=neon-vfpv4 -target arm-liteos -print-file-name=libunwind.a)** specifies the path of the unwind library. @@ -175,7 +184,7 @@ $ clang -o mem_check mem_check.c -funwind-tables -rdynamic -g -mfloat-abi=softfp ``` OHOS # ./mem_check -OHOS # +OHOS # ==PID:4== Heap memory statistics(bytes): // Heap memory statistics [Check point]: // Call stack of the check point #00: [0x86c] -> mem_check @@ -293,14 +302,15 @@ kill -37 # Check whether the head node of the heap memory is complete. The sample code constructs a memory problem and uses the command line to perform memory debugging. -``` +```c #include #include #include #define MALLOC_LEAK_SIZE 0x300 -void func(void) { +void func(void) +{ char *ptr = malloc(MALLOC_LEAK_SIZE); memset(ptr, '3', MALLOC_LEAK_SIZE); } @@ -317,7 +327,7 @@ int main() ##### Compilation -For details, see [Compilation](kernel-small-debug-user.md#compilation). +For details, see [Compilation](#compilation). ##### Running the mwatch Command @@ -325,9 +335,9 @@ For details, see [Compilation](kernel-small-debug-user.md#compilation). ``` OHOS # ./mem_check --mwatch // Run the task command to obtain the mem_check process PID, which is 4. -OHOS # +OHOS # OHOS # kill -35 4 // Check heap memory statistics. -OHOS # +OHOS # ==PID:4== Heap memory statistics(bytes): [Check point]: #00: [0x58dfc] -> /lib/libc.so @@ -337,7 +347,7 @@ OHOS # ==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s) OHOS # kill -36 4 // Check for heap memory leaks. -OHOS # +OHOS # ==PID:4== Detected memory leak(s): [Check point]: #00: [0x2da4c] -> /lib/libc.so @@ -355,7 +365,7 @@ OHOS # ==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). OHOS # kill -37 4 // Check the integrity of the head node of the heap memory. -OHOS # +OHOS # Check heap integrity ok! ``` @@ -391,131 +401,132 @@ Now using addr2line ... ##### Running the mrecord Command 1. Run the user program and specify the path of the file that stores the memory debugging information. - + ``` OHOS # ./mem_check --mrecord /storage/check.txt ``` 2. Run the **kill -35 <*pid*>** command to collect statistics on the memory information. The information is exported to a file. Run the **cat** command to view the information. - + ``` OHOS # kill -35 4 OHOS # Memory statistics information saved in /storage/pid(4)_check.txt - + OHOS # cat /storage/pid(4)_check.txt - + ==PID:4== Heap memory statistics(bytes): [Check point]: #00: [0x5973c] -> /lib/libc.so - + [TID: 18, Used: 0x640] - + ==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s) ``` 3. Run the **kill -36 <*pid*>** command to check memory integrity. The information is exported to a file. Run the **cat** command to view the information. - + ``` OHOS # kill -36 4 OHOS # Leak check information saved in /storage/pid(4)_check.txt - + OHOS # cat /storage/pid(4)_check.txt - + ==PID:4== Heap memory statistics(bytes): [Check point]: #00: [0x5973c] -> /lib/libc.so - + [TID: 18, Used: 0x640] - + ==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s) - + ==PID:4== Detected memory leak(s): [Check point]: #00: [0x2e38c] -> /lib/libc.so #01: [0x5973c] -> /lib/libc.so - + [TID:18 Leak:0x320 byte(s)] Allocated from: #00: [0x724] -> mem_check #01: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so - + [TID:18 Leak:0x320 byte(s)] Allocated from: #00: [0x6ec] -> mem_check #01: [0x740] -> mem_check #02: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so - + ==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). ``` 4. Run the **kill -9 <*pid*>** command to kill the current process. After the process exits, a memory integrity check is performed by default. The check result is output to a file. You can run the **cat** command to view it. - + ``` OHOS # kill -9 4 OHOS # Leak check information saved in /storage/pid(4)_check.txt - + Check heap integrity ok! - + OHOS # cat /storage/pid(4)_check.txt - OHOS # + OHOS # ==PID:4== Heap memory statistics(bytes): [Check point]: #00: [0x5973c] -> /lib/libc.so - + [TID: 18, Used: 0x640] - + ==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s) - + ==PID:4== Detected memory leak(s): [Check point]: #00: [0x2e38c] -> /lib/libc.so #01: [0x5973c] -> /lib/libc.so - + [TID:18 Leak:0x320 byte(s)] Allocated from: #00: [0x724] -> mem_check #01: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so - + [TID:18 Leak:0x320 byte(s)] Allocated from: #00: [0x6ec] -> mem_check #01: [0x740] -> mem_check #02: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so - + ==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). - + ==PID:4== Detected memory leak(s): [Check point]: #00: [0x2e38c] -> /lib/libc.so #01: [0x11b2c] -> /lib/libc.so - + [TID:18 Leak:0x320 byte(s)] Allocated from: #00: [0x724] -> mem_check #01: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so - + [TID:18 Leak:0x320 byte(s)] Allocated from: #00: [0x6ec] -> mem_check #01: [0x740] -> mem_check #02: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so - + ==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). ``` -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE**
> 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 ### Use After Free (UAF) -- Requested memory block less than or equal to 0x1c000 bytes: - After the memory is released: - +- Requested memory less than or equal to 0x1c000 bytes: + Read operation: If the magic number (0xFEFEFEFE) is read from the memory block released, UAF occurs. - - > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+ + > **NOTE** + > > 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. - 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). @@ -527,16 +538,17 @@ Double free errors occur when **free()** is called more than once with the same ### Heap Memory Node Corrupted - 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. - + ``` - OHOS # ./mem_check --mwatch - OHOS # + OHOS # ./mem_check --mwatch + OHOS # ==PID:6== Memory integrity information: [TID:28 allocated addr: 0x272e1ea0, size: 0x120] The possible attacker was allocated from: #00: [0x640e8] -> /lib/libc.so - #01: [0x21d0] -> mem_check + #01: [0x21d0] -> mem_check ``` You can use the call stack parsing script to parse the call stack information. diff --git a/en/device-dev/kernel/kernel-small-memory-lms.md b/en/device-dev/kernel/kernel-small-memory-lms.md index 277cbea8a28268a9c4597be980a22bb69f8f85f8..937f088a803a8058ad045e27a231b5f662ceacbc 100644 --- a/en/device-dev/kernel/kernel-small-memory-lms.md +++ b/en/device-dev/kernel/kernel-small-memory-lms.md @@ -59,23 +59,20 @@ The user mode provides only the LMS check library. It does not provide external The typical process for enabling LMS is as follows: 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**. - - | Macro| menuconfig Option| Description| Value:| + + | Macro| menuconfig Option| Description| Value | | -------- | -------- | -------- | -------- | | LOSCFG_KERNEL_LMS | Enable Lms Feature | Whether to enable LMS.| YES/NO | | LOSCFG_LMS_MAX_RECORD_POOL_NUM | Lms check pool max num | Maximum number of memory pools that can be checked by LMS.| INT | | LOSCFG_LMS_LOAD_CHECK | Enable lms read check | Whether to enable LMS read check.| YES/NO | | LOSCFG_LMS_STORE_CHECK | Enable lms write check | Whether to enable LMS write check.| YES/NO | | LOSCFG_LMS_CHECK_STRICT | Enable lms strict check, byte-by-byte | Whether to enable LMS byte-by-byte check.| YES/NO | - - -2. Modify the build script of the target module. +2. Modify the build 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: + The modifications vary depending on the compiler (GCC or Clang) used. The following is an example: ``` if ("$ohos_build_compiler_specified" == "gcc") { @@ -113,9 +110,10 @@ This example implements the following: #### Kernel-Mode Sample Code - The sample code is as follows: +The functions of the sample code can be added to **TestTaskEntry** in **kernel /liteos_a/testsuites /kernel /src /osTest.c** for testing. +The sample code is as follows: -``` +```c #define PAGE_SIZE (0x1000U) #define INDEX_MAX 20 UINT32 g_lmsTestTaskId; @@ -141,31 +139,32 @@ static VOID LmsTestUseAfterFree(VOID) PRINTK("\n######%s start ######\n", __FUNCTION__); UINT32 i; CHAR *str = (CHAR *)LOS_MemAlloc(g_testLmsPool, INDEX_MAX); - LOS_MemFree(g_testLmsPool, str); + (VOID)LOS_MemFree(g_testLmsPool, str); PRINTK("str[%2d]=0x%2x ", 0, str[0]); /* trigger use after free at str[0] */ PRINTK("\n######%s stop ######\n", __FUNCTION__); } VOID LmsTestCaseTask(VOID) -{ +{ testPoolInit(); LmsTestOsmallocOverflow(); LmsTestUseAfterFree(); } -UINT32 Example_Lms_test(VOID){ - UINT32 ret; - TSK_INIT_PARAM_S lmsTestTask; - /* Create a task for LMS. */ - memset(&lmsTestTask, 0, sizeof(TSK_INIT_PARAM_S)); +UINT32 Example_Lms_test(VOID) +{ + UINT32 ret; + TSK_INIT_PARAM_S lmsTestTask; + /* Create a task for LMS. */ + memset(&lmsTestTask, 0, sizeof(TSK_INIT_PARAM_S)); lmsTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)LmsTestCaseTask; - lmsTestTask.pcName = "TestLmsTsk"; /* Test task name. */ - lmsTestTask.uwStackSize = 0x800; - lmsTestTask.usTaskPrio = 5; - lmsTestTask.uwResved = LOS_TASK_STATUS_DETACHED; - ret = LOS_TaskCreate(&g_lmsTestTaskId, &lmsTestTask); - if(ret != LOS_OK){ - PRINT_ERR("LmsTestTask create failed .\n"); - return LOS_NOK; - } + lmsTestTask.pcName = "TestLmsTsk"; /* Test task name. */ + lmsTestTask.uwStackSize = 0x800; // 0x800: LMS test task stack size + lmsTestTask.usTaskPrio = 5; // 5: LMS test task priority + lmsTestTask.uwResved = LOS_TASK_STATUS_DETACHED; + ret = LOS_TaskCreate(&g_lmsTestTaskId, &lmsTestTask); + if (ret != LOS_OK) { + PRINT_ERR("LmsTestTask create failed .\n"); + return LOS_NOK; + } return LOS_OK; } LOS_MODULE_INIT(Example_Lms_test, LOS_INIT_LEVEL_KMOD_EXTENDED); @@ -260,7 +259,7 @@ The key output information is as follows: ### 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: The code is as follows: -``` +```c static void BufWriteTest(void *buf, int start, int end) { for (int i = start; i <= end; i++) { @@ -335,7 +334,7 @@ static void BufReadTest(void *buf, int start, int end) static void LmsMallocTest(void) { printf("\n-------- LmsMallocTest Start --------\n"); - char *buf = (char *)malloc(16); + char *buf = (char *)malloc(16); // 16: buffer size for test BufReadTest(buf, -1, 16); free(buf); printf("\n-------- LmsMallocTest End --------\n"); @@ -343,7 +342,7 @@ static void LmsMallocTest(void) static void LmsFreeTest(void) { printf("\n-------- LmsFreeTest Start --------\n"); - char *buf = (char *)malloc(16); + char *buf = (char *)malloc(16); // 16: buffer size for test free(buf); BufReadTest(buf, 1, 1); free(buf); @@ -352,7 +351,7 @@ static void LmsFreeTest(void) int main(int argc, char * const * argv) { printf("\n############### Lms Test start ###############\n"); - char *tmp = (char *)malloc(5000); + char *tmp = (char *)malloc(5000); // 5000: temp buffer size LmsMallocTest(); LmsFreeTest(); printf("\n############### Lms Test End ###############\n"); diff --git a/en/device-dev/kernel/kernel-small-start-kernel.md b/en/device-dev/kernel/kernel-small-start-kernel.md index 01c4373ac8b51dc17a9ea91985c98688f4965311..c96beb9191fd8f04aadba8b35b7194fb5d90362e 100644 --- a/en/device-dev/kernel/kernel-small-start-kernel.md +++ b/en/device-dev/kernel/kernel-small-start-kernel.md @@ -3,20 +3,22 @@ ## Kernel Startup Process -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 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. - **Figure 1** Kernel startup process
- ![](figures/kernel-startup-process-2.png "kernel-startup-process-2") +**Figure 1** Kernel startup process +![](figures/kernel-startup-process-2.png "kernel-startup-process-2") - **Table 1** Start framework -| Level | Startup Description | +**Table 1** Kernel startup framework + +| API| Description| | -------- | -------- | | LOS_INIT_LEVEL_EARLIEST | Earliest initialization.
The initialization is architecture-independent. The board and subsequent modules initialize the pure software modules on which they depend.
Example: trace module| | LOS_INIT_LEVEL_ARCH_EARLY | Early initialization of the architecture.
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* | LOS_INIT_LEVEL_KMOD_BASIC | Initialization of the kernel basic modules.
Initialize the basic modules that can be detached from the kernel.
Example: VFS initialization| | LOS_INIT_LEVEL_KMOD_EXTENDED | Initialization of the kernel extended modules.
Initialize the extended modules that can be detached from the kernel.
Example: initialization of system call, ProcFS, Futex, HiLog, HiEvent, and LiteIPC| | LOS_INIT_LEVEL_KMOD_TASK | Kernel task creation.
Create kernel tasks (kernel tasks and software timer tasks).
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** 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** - - -``` +```c /* Header file of the kernel startup framework */ #include "los_init.h" -... /* Initialization function of the new module */ unsigned int OsSampleModInit(void) { PRINTK("OsSampleModInit SUCCESS!\n"); - ...... } -... + /* Register the new module at the target level of the kernel startup framework. */ LOS_MODULE_INIT(OsSampleModInit, LOS_INIT_LEVEL_KMOD_EXTENDED); ``` - **Verification** - - ``` + main core booting up... + +/* The print information may vary depending on the running environment. */ +... + +/* Print the initialization function of the new module in the test code. */ 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. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> -> 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. -> +> **NOTE** +> +> 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. diff --git a/en/device-dev/kernel/kernel-small-start-user.md b/en/device-dev/kernel/kernel-small-start-user.md index 40f586e1576f07bd9223d03aa2fbc7681cec086d..96535ef581fb6edcdde458f94085e65cdd04b034 100644 --- a/en/device-dev/kernel/kernel-small-start-user.md +++ b/en/device-dev/kernel/kernel-small-start-user.md @@ -1,17 +1,21 @@ # Startup in User Mode -## Startup of the Root Process in User Mode + +## Startup of the Root Process in User Mode The root process is the first user-mode process in the system. The process ID is 1. The root process is the ancestor of all user-mode processes. -**Figure 1** Process tree +**Figure 1** Process tree + ![](figures/process-tree.png "process-tree") -### Startup Process of the Root Process + +### Startup Process of the Root Process Use the link script to place the following init startup code to the specified location in the system image. -``` + +```c #define LITE_USER_SEC_ENTRY __attribute__((section(".user.entry"))) LITE_USER_SEC_ENTRY VOID OsUserInit(VOID *args) { @@ -23,38 +27,38 @@ LITE_USER_SEC_ENTRY VOID OsUserInit(VOID *args) } ``` -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. -2. A process space is created to start the **/bin/init** process. +Use **OsUserInitProcess** to start the **init** process. The procedure is as follows: -### Responsibilities of the Root Process +1. The kernel calls **OsLoadUserInit** to load the code for startup. -- Starts key system programs or services, such as shell. +2. A process space is created to start the **/bin/init** process. - >![](../public_sys-resources/icon-note.gif) **NOTE** - > - >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). +### Responsibilities of the Root Process -- Monitors the process for reclaiming the orphan process and clears the zombie processes in child processes. +- 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). -## Running Programs in User Mode +- The root process monitors the process for reclaiming the orphan process and clears the zombie processes in child processes. -A user-mode program can be started in either of the following ways: - -- Run the shell command to start the process. - - ``` - OHOS $ exec helloworld - OHOS $ ./helloworld - OHOS $ /bin/helloworld - ``` +## Running Programs in User Mode +A user-mode program can be started in either of the following ways: -- Start a new process by calling the POSIX API. +- Using shell commands - Use the **Fork\(\)** method to create a process, and call the **exec\(\)** method to execute a new process. + ``` + OHOS $ exec helloworld + OHOS $ ./helloworld + OHOS $ /bin/helloworld + ``` +- Using POSIX APIs + Use **Fork()** to create a process, and call **exec()** to execute a process.