summaryrefslogtreecommitdiff
path: root/documentation/6.components
diff options
context:
space:
mode:
authorChen Wang <[email protected]>2025-02-24 09:58:36 +0800
committerRbb666 <[email protected]>2025-02-25 11:27:58 +0800
commit75722c49981b43fa205989183f9958e199aaad2e (patch)
tree893e7a66fa93a2b063a7594fe72881b21b1a241d /documentation/6.components
parentd9b36c8d181571922fd339ff2749c5eae62c6704 (diff)
doxygen: reorganize directory structure
The original directory structure was too flat and inconvenient to view. The directory is now reorganized according to the first-level chapters, and some sub-chapters are moved to the second-level directory. Note: documentation/env is not moved to documentation/4.tool because there are too many external places that reference this path, especially in bsp, so this directory path remains as it is. Signed-off-by: Chen Wang <[email protected]>
Diffstat (limited to 'documentation/6.components')
-rw-r--r--documentation/6.components/at/at.md897
-rw-r--r--documentation/6.components/at/figures/at_framework.jpgbin0 -> 7339 bytes
-rw-r--r--documentation/6.components/at/figures/at_multiple_client.jpgbin0 -> 36370 bytes
-rw-r--r--documentation/6.components/dlmodule/README.md314
-rw-r--r--documentation/6.components/filesystem/README.md1027
-rw-r--r--documentation/6.components/filesystem/figures/elm-fat-mkfs.pngbin0 -> 23054 bytes
-rw-r--r--documentation/6.components/filesystem/figures/fs-dir-mg.pngbin0 -> 11026 bytes
-rw-r--r--documentation/6.components/filesystem/figures/fs-dir.pngbin0 -> 22278 bytes
-rw-r--r--documentation/6.components/filesystem/figures/fs-layer.pngbin0 -> 18662 bytes
-rw-r--r--documentation/6.components/filesystem/figures/fs-mg.pngbin0 -> 9881 bytes
-rw-r--r--documentation/6.components/filesystem/figures/fs-reg-block.pngbin0 -> 21169 bytes
-rw-r--r--documentation/6.components/filesystem/figures/fs-reg.pngbin0 -> 13283 bytes
-rw-r--r--documentation/6.components/finsh/figures/finsh-hd.pngbin0 -> 91748 bytes
-rw-r--r--documentation/6.components/finsh/figures/finsh-mdk.pngbin0 -> 45606 bytes
-rw-r--r--documentation/6.components/finsh/figures/finsh-run.pngbin0 -> 17630 bytes
-rw-r--r--documentation/6.components/finsh/finsh.md562
-rw-r--r--documentation/6.components/network/figures/net-hello.pngbin0 -> 44524 bytes
-rw-r--r--documentation/6.components/network/figures/net-layer.pngbin0 -> 12927 bytes
-rw-r--r--documentation/6.components/network/figures/net-osi.pngbin0 -> 16082 bytes
-rw-r--r--documentation/6.components/network/figures/net-recv.pngbin0 -> 21245 bytes
-rw-r--r--documentation/6.components/network/figures/net-send.pngbin0 -> 14327 bytes
-rw-r--r--documentation/6.components/network/figures/net-tcp-s.pngbin0 -> 43570 bytes
-rw-r--r--documentation/6.components/network/figures/net-tcp.pngbin0 -> 17782 bytes
-rw-r--r--documentation/6.components/network/figures/net-udp-client.pngbin0 -> 49302 bytes
-rw-r--r--documentation/6.components/network/figures/net-udp-server.pngbin0 -> 40904 bytes
-rw-r--r--documentation/6.components/network/figures/net-udp.pngbin0 -> 12961 bytes
-rw-r--r--documentation/6.components/network/network.md779
-rw-r--r--documentation/6.components/pm/figures/pm_architecture.pngbin0 -> 15831 bytes
-rw-r--r--documentation/6.components/pm/figures/pm_description.pngbin0 -> 14859 bytes
-rw-r--r--documentation/6.components/pm/figures/pm_sequence.pngbin0 -> 19281 bytes
-rw-r--r--documentation/6.components/pm/figures/pm_system.pngbin0 -> 23448 bytes
-rw-r--r--documentation/6.components/pm/pm.md430
-rw-r--r--documentation/6.components/posix/README.md2604
-rw-r--r--documentation/6.components/sal/figures/sal_frame.jpgbin0 -> 40676 bytes
-rw-r--r--documentation/6.components/sal/sal.md825
-rw-r--r--documentation/6.components/ulog/figures/ulog_async_vs_sync.pngbin0 -> 27242 bytes
-rw-r--r--documentation/6.components/ulog/figures/ulog_example.pngbin0 -> 64169 bytes
-rw-r--r--documentation/6.components/ulog/figures/ulog_example_all_format.pngbin0 -> 66053 bytes
-rw-r--r--documentation/6.components/ulog/figures/ulog_example_async.pngbin0 -> 62413 bytes
-rw-r--r--documentation/6.components/ulog/figures/ulog_example_filter20.pngbin0 -> 89831 bytes
-rw-r--r--documentation/6.components/ulog/figures/ulog_example_filter30.pngbin0 -> 87573 bytes
-rw-r--r--documentation/6.components/ulog/figures/ulog_example_filter40.pngbin0 -> 85829 bytes
-rw-r--r--documentation/6.components/ulog/figures/ulog_example_hexdump.pngbin0 -> 73641 bytes
-rw-r--r--documentation/6.components/ulog/figures/ulog_example_syslog.pngbin0 -> 83596 bytes
-rw-r--r--documentation/6.components/ulog/figures/ulog_framework.pngbin0 -> 15082 bytes
-rw-r--r--documentation/6.components/ulog/figures/ulog_framework_backend.pngbin0 -> 46447 bytes
-rw-r--r--documentation/6.components/ulog/figures/ulog_menuconfig_async.pngbin0 -> 45191 bytes
-rw-r--r--documentation/6.components/ulog/figures/ulog_menuconfig_format.pngbin0 -> 35114 bytes
-rw-r--r--documentation/6.components/ulog/figures/ulog_syslog_format.pngbin0 -> 9234 bytes
-rw-r--r--documentation/6.components/ulog/ulog.md800
-rw-r--r--documentation/6.components/utest/figures/UtestAppStruct-1.pngbin0 -> 8311 bytes
-rw-r--r--documentation/6.components/utest/figures/UtestRunLogShow.pngbin0 -> 470209 bytes
-rw-r--r--documentation/6.components/utest/figures/testcase-runflowchart.jpgbin0 -> 26094 bytes
-rw-r--r--documentation/6.components/utest/utest.md274
54 files changed, 8512 insertions, 0 deletions
diff --git a/documentation/6.components/at/at.md b/documentation/6.components/at/at.md
new file mode 100644
index 0000000000..9507ecc3bd
--- /dev/null
+++ b/documentation/6.components/at/at.md
@@ -0,0 +1,897 @@
+@page page_component_at AT Commands
+
+# Introduction to AT Commands
+
+The AT command set was originally a control protocol invented by Dennis Hayes, initially used to control dial-up modems. Later, with the upgrade of network bandwidth, low-speed dial-up modems with very low speed essentially exited the general market, but the AT command set was retained. However, the AT command set lived on when major mobile phone manufacturers jointly developed a set of commands to control the GSM modules of mobile phones. The AT command set evolved on this basis and added the GSM 07.05 standard and the later GSM 07.07 standard to achieve more robust standardization.
+
+After seeing use in GPRS control, 3G modules and similar devices, AT commands gradually become the de facto standard in product development. Nowadays, AT commands are also widely used in embedded development. AT commands are the protocol interfaces of the main chip and communication module. The hardware interface is usually the serial port, so the main control device can complete various operations through simple commands and hardware design.
+
+**AT commands are a way of facilitating device connections and data communication between an AT Server and an AT Client.** The basic structure is shown below:
+
+![AT Command Set](figures/at_framework.jpg)
+
+1. The AT command consists of three parts: prefix, body, and terminator. The prefix consists of the character AT; the body consists of commands, parameters, and possibly used data; the terminator typically is `<CR><LF>` (`"\r\n"`).
+
+2. The implementation of AT functionality requires the AT Server and the AT Client to work together.
+
+3. An AT Server mainly receives commands sent by the AT Client, interprets the received commands and parameter formats, and delivers corresponding response data or actively sends data.
+
+4. An AT Client is mainly used to send commands, wait for the AT Server to respond, and parse the AT Server response data or the actively sent data to obtain related information.
+
+5. A variety of data communication methods (UART, SPI, etc.) are supported between an AT Server and an AT Client. Currently, the most commonly used communications protocol is UART.
+
+6. The data that the AT Server sends to the AT Client is divided into two types: response data and URC data.
+
+- Response Data: The AT Server response status and information received by the AT Client after sending the command.
+
+- URC Data: Data that the AT Server actively sends to the AT Client generally appears only in some special cases, such as when a WiFi connection is disconnected, while it's receiving TCP data, etc. These situations often require special user handling.
+
+With the popularization of AT commands, more and more embedded products use AT commands. The AT commands are used as the protocol interfaces of the main chip and the communication module. The hardware interface is generally a serial port, so that the master device can performs a variety of operations using simple commands and hardware design.
+
+Although the AT command set has standardization to a certain degree, the AT commands supported by different chips are not completely unified, which directly increases the complexity to use. There is no uniform way to handle the sending and receiving of AT commands and the parsing of data.
+
+In order to facilitate the user to use AT commands which can be easily adapted to different AT modules, RT-Thread provides AT components for AT Device connectivity and data communication. The implementation of the AT components consists of both a client and a server.
+
+# Introduction to AT Components
+
+The AT component is based on the implementation of the `AT Server` and `AT Client` of the RT-Thread system. The component completes the AT command transmission, command format and parameter parsing, command response, response data reception, response data parsing, URC data processing, etc..
+
+**Command data interaction process.**
+
+Through the AT component, the device can use the serial port to connect to other devices to send and receive parsed data. It can be used as an AT Server to allow other devices or even the computer to connect to complete the response of sending data. It can also start the CLI mode in the local shell to enable the device to support AT Server and AT Client at the same time. The usage of both modes simultaneously is mostly used for device development and debugging.
+
+**AT component resource usage:**
+
+- AT Client: 4.6K ROM and 2.0K RAM;
+
+- AT Server: 4.0K ROM and 2.5K RAM;
+
+- AT CLI: 1.5K ROM and almost no RAM is used.
+
+Overall, the AT component resources are extremely small, making them ideal for use in embedded devices with limited resources. The AT component code is primarily located in `rt-thread/components/net/at/`. What follows are the main function of both AT Servers and AT Clients.
+
+**Main Functions of AT Server:**
+
+- Basic commands: A variety of common basic commands are implemented (ATE, ATZ, etc.);
+- Command compatibility: Commands are case-insensitive, which increases command compatibility;
+- Command detection: Commands support custom parameter expressions and implement self-detection of received command parameters;
+- Command registration: User-defined commands can be easily added, in a way, similar to how the `finsh/msh` command is added;
+- Debug mode: An AT Server CLI command line interaction mode is provided, which is mainly used for device debugging.
+
+**Main Functions of AT Client:**
+
+- URC data processing: The complete URC data processing method;
+- Data analysis: Supports the analysis of custom response data, and facilitates the acquisition of relevant information in the response data;
+- Debug mode: Provides AT Client CLI command line interaction mode, mainly used for device debugging;
+- AT Socket: An extension of AT Client function, it uses the AT command set to send and receive as the basis. This is implemented through the standard BSD Socket API, which completes the data sending and receiving function, and enables users to implement complete device networking and data communication through AT commands.
+- Multi-client support: The AT component supports multiple clients running simultaneously.
+
+# AT Server
+
+## AT Server Configuration ###
+
+When we use the AT Server feature in the AT component, we need to define the following configuration in rtconfig.h:
+
+| **Macro Definition** | **Description** |
+| ---- | ---- |
+|RT_USING_AT| Enable AT component |
+|AT_USING_SERVER |Enable AT Server function|
+|AT_SERVER_DEVICE |Define the serial communication device name used by AT Server on the device to ensure that it is not used and the device name is unique, such as `uart3` device.|
+|AT_SERVER_RECV_BUFF_LEN|The maximum length of data received by the AT Server device|
+|AT_CMD_END_MARK_CRLF|Determine the line terminator of the received command |
+|AT_USING_CLI | Enable server-command-line interaction mode |
+|AT_DEBUG|Enable AT component DEBUG mode to display more debug log information |
+|AT_PRINT_RAW_CMD | Enable real-time display AT command communication data mode for easy debugging |
+
+For different AT devices, there are several formats of the line terminator for the sending commands: `"\r\n"`、`"\r"`、`"\n"` - the user needs to select the corresponding line terminator in accordance to the device type connected to the AT Server and then determine the end of transmission command, defined as follows:
+
+| **Macro Definition** | **Terminator** |
+| ---- | ---- |
+| AT_CMD_END_MARK_CRLF | `"\r\n"` |
+| AT_CMD_END_MARK_CR | `"\r"` |
+| AT_CMD_END_MARK_LF | `"\n"` |
+
+The above configuration options can be added by Env tool. The specific path in Env is as follows:
+
+```c
+RT-Thread Components --->
+ Network --->
+ AT commands --->
+ [*] Enable AT commands
+ [*] Enable debug log output
+ [*] Enable AT commands server
+ (uart3) Server device name
+ (256) The maximum length of server data accepted
+ The commands new line sign (\r\n) --->
+ [ ] Enable AT commands client
+ [*] Enable command-line interface for AT commands
+ [ ] Enable print RAW format AT command communication data
+```
+
+After the add configuration is complete, you can use the command line to rebuild the project, or use `scons` to compile.
+
+## AT Server Initialization
+
+After enabling the AT Server in Env, you need to initialize it at startup to enable the AT Server function. If the component has been initialized automatically, no additional initialization is required. Otherwise, you need to call the following function in the initialization task:
+
+```c
+int at_server_init(void);
+```
+The AT Server initialization function, which belongs to the application layer function, needs to be called before using the AT Server function or using the AT Server CLI function. `at_server_init()` function completes initialization of resources stored by AT commands, such as data segment initialization, AT Server device initialization, and semaphore usage by the AT Server. It also creates an at_server thread for parsing the received data in the AT Server.
+
+After the AT Server is successfully initialized, the device can be used as an AT Server to connect to an AT Client's serial device for data communication, or use a serial-to-USB conversion tool to connect to a PC, so that the PC-side serial debugging assistant can communicate with the AT Client.
+
+## Add custom AT commands
+
+At present, the format of the AT command set used by AT devices of different manufacturers does not have a completely uniform standard, so the AT Server in the AT component only supports some basic general AT commands, such as ATE, AT+RST, etc. These commands can only be used to meet the basic operation of the device. If users want to use more functions, they need to implement custom AT Server commands for different AT devices. The AT component provides an AT command addition method similar to the FinSH/msh command addition method, which is convenient for users to implement the required commands.
+
+The basic commands currently supported by AT Server are as follows:
+
+- AT: AT test command;
+- ATZ: The device is restored to factory settings;
+- AT+RST: Reboot device;
+- ATE: ATE1 turns on echo, ATE0 turns off echo;
+- AT&L: List all commands;
+- AT+UART: Set the serial port information.
+
+AT commands can implement different functions depending on the format of the incoming parameters. For each AT command, there are up to four functions, as described below:
+
+- Test Function: `AT+<x>=?`, used to query the command's parameter, format and value range;
+- Query Function: `AT+<x>?`, used to return the current value of the command parameter;
+- Setting Function: `AT+<x>=...`, used for user-defined parameter values;
+- Execution Function: `AT+<x>`, used to perform related operations.
+
+The four functions of each command do not need to be fully implemented. When you add an AT Server command, you can implement one or several of the above functions according to your needs. Unimplemented functions can be represented by `NULL`. Then the custom function can be added to the list of basic commands. The addition method is similar to the way the `finsh/msh` commands are added. The function for adding commands is as follows:
+
+```c
+AT_CMD_EXPORT(_name_, _args_expr_, _test_, _query_, _setup_, _exec_);
+```
+
+|**Parameter** |**Description** |
+| ---------- | ------------------------------- |
+| `_name_ ` | AT command name |
+| `_args_expr_` | AT command parameter expression; (NULL means no parameter, `<>` means mandatory parameter and `[]` means optional parameter) |
+| `_test_` | AT test function name; (NULL means no parameter) |
+| `_query_` | AT query function name; (ibid.) |
+| `_setup_` | AT setup function name; (ibid.) |
+| `_exec_` | AT performs the function name; (ibid.) |
+
+The AT command registration example is as follows. The `AT+TEST` command has two parameters. The first parameter is a mandatory parameter, and the second parameter is an optional parameter. The command implements the query function and the execution function:
+
+```c
+static at_result_t at_test_exec(void)
+{
+ at_server_printfln("AT test commands execute!");
+
+ return 0;
+}
+static at_result_t at_test_query(void)
+{
+ at_server_printfln("AT+TEST=1,2");
+
+ return 0;
+}
+
+AT_CMD_EXPORT("AT+TEST", =<value1>[,<value2>], NULL, at_test_query, NULL, at_test_exec);
+```
+
+## AT Server APIs
+
+### Send Data to the Client (no newline)
+
+```c
+void at_server_printf(const char *format, ...);
+```
+
+This function is used by the AT Server to send fixed-format data to the corresponding AT Client serial device through the serial device. The data ends without a line break. Used to customize the function functions of AT commands in AT Server.
+
+| **Parameter** | **D**escription |
+|------|-------------------------|
+| format | Customize the expression of the input data |
+| ... | Input data list, variable parameters |
+
+### Send Data to the Client (newline)
+
+```c
+void at_server_printfln(const char *format, ...);
+```
+
+This function is used by the AT Server to send fixed-format data to the corresponding AT Client serial device through the serial device, with a newline at the end of the data. Used to customize the function functions of AT commands in AT Server.
+
+| **Parameter** | **Description** |
+|------|-------------------------|
+| format | Customize the expression of the input data |
+| ... | Input data list, variable parameters |
+
+### Send Command Execution Results to the Client
+
+```c
+void at_server_print_result(at_result_t result);
+```
+
+This function is used by the AT Server to send command execution results to the corresponding AT Client serial device through the serial device. The AT component provides a variety of fixed command execution result types. When you customize a command, you can use the function to return the result directly;
+
+| **Parameter** | **Description** |
+|------|-----------------|
+| result | Command execution result type |
+
+The command execution result type in the AT component is given in the enumerated type, as shown in the following table:
+
+| Types of Command Execution Result | Description |
+|------------------------|------------------|
+| AT_RESULT_OK | Command Execution Succeeded |
+| AT_RESULT_FAILE | Command Execution Failed |
+| AT_RESULT_NULL | Command No Result |
+| AT_RESULT_CMD_ERR | Command Input Error |
+| AT_RESULT_CHECK_FAILE | Parameter Expression Matching Error |
+| AT_RESULT_PARSE_FAILE | Parameter Parsing Error |
+
+See the following code to learn how to use the `at_server_print_result` function:
+
+```c
+static at_result_t at_test_setup(const char *args)
+{
+ if(!args)
+ {
+ /* If the parameter error after incoming orders, returns expression match error results */
+ at_server_print_result(AT_RESULT_CHECK_FAILE);
+ }
+
+ /* Return to successful execution under normal conditions */
+ at_server_print_result(AT_RESULT_OK);
+ return 0;
+}
+static at_result_t at_test_exec(void)
+{
+ // execute some functions of the AT command.
+
+ /* This command does not need to return results */
+ at_server_print_result(AT_RESULT_NULL);
+ return 0;
+}
+AT_CMD_EXPORT("AT+TEST", =<value1>,<value2>, NULL, NULL, at_test_setup, at_test_exec);
+```
+
+### Parsing Input Command Parameters
+
+```c
+int at_req_parse_args(const char *req_args, const char *req_expr, ...);
+```
+
+Among the four functions of an AT command, only the setting function has an input parameter, and the input parameter is to remove the rest of the AT command. For example, for a given command input `"AT+TEST=1,2,3,4"`, set the input parameter of the function to the parameter string `"=1,2,3,4"`.
+
+The command parsing function is mainly used in the AT function setting function, which is used to parse the incoming string parameter and obtain corresponding multiple input parameters for performing the following operations. The standard `sscanf` parsing grammar used in parsing grammar here will also be described in detail later in the AT Client parameter parsing function.
+
+| **Parameter** | **Description** |
+|---------|-----------------------------------------------|
+| req_args | The incoming parameter string of the request command |
+| req_expr | Custom parameter parsing expression for parsing the above incoming parameter data |
+| ... | Output parsing parameter list, which is a variable parameter |
+| **Return** | -- |
+| >0 | Successful, returns the number of variable parameters matching the parameter expression |
+| =0 | Failed, no parameters matching the parameter expression |
+| -1 | Failed, parameter parsing error |
+
+See the following code to learn how to use the at_server_print_result function:
+
+```c
+static at_result_t at_test_setup(const char *args)
+{
+ int value1,value2;
+
+ /* The input standard format of args should be "=1, 2", "=%d, %d" is a custom parameter parsing expression, and the result is parsed and stored in the value1 and value2 variables. */
+ if (at_req_parse_args(args, "=%d,%d", &value1, &value2) > 0)
+ {
+ /* Data analysis succeeds, echoing data to AT Server serial device */
+ at_server_printfln("value1 : %d, value2 : %d", value1, value2);
+
+ /* The data is parsed successfully. The number of parsing parameters is greater than zero. The execution is successful. */
+ at_server_print_result(AT_RESULT_OK);
+ }
+ else
+ {
+ /* Data parsing failed, the number of parsing parameters is not greater than zero, and the parsing failure result type is returned. */
+ at_server_print_result(AT_RESULT_PARSE_FAILE);
+ }
+ return 0;
+}
+/* Add the "AT+TEST" command to the AT command list. The command parameters are formatted as two mandatory parameters <value1> and <value2>. */
+AT_CMD_EXPORT("AT+TEST", =<value1>,<value2>, NULL, NULL, at_test_setup, NULL);
+```
+
+### Porting-related interfaces
+
+The AT Server supports a variety of basic commands (ATE, ATZ, etc.) by default. The function implementation of some commands is related to hardware or platform and requires user-defined implementation. The AT component source code `src/at_server.c` file gives the weak function definition of the migration file. The user can create a new migration file in the project to implement the following function to complete the migration interface, or modify the weak function to complete the migration interface directly in the file.
+
+1. Device restart function: `void at_port_reset(void);`. This function completes the device soft restart function and is used to implement the basic command AT+RST in AT Server.
+
+2. The device restores the factory settings function: `void at_port_factory_reset(void);`. This function completes the device factory reset function and is used to implement the basic command ATZ in AT Server.
+
+3. Add a command table in the link script (add only in gcc, no need to add in Keil and IAR).
+
+If you use the gcc toolchain in your project, you need to add the *section* corresponding to the AT server command table in the link script. Refer to the following link script:
+
+```c
+/* Constant data goes into FLASH */
+.rodata :
+{
+ ...
+
+ /* section information for RT-thread AT package */
+ . = ALIGN(4);
+ __rtatcmdtab_start = .;
+ KEEP(*(RtAtCmdTab))
+ __rtatcmdtab_end = .;
+ . = ALIGN(4);
+} > CODE
+```
+
+# AT Client
+
+## AT Client Configuration
+
+When using the AT Client feature in the AT component, the following configuration in rtconfig.h needs to be defined:
+
+```c
+#define RT_USING_AT
+#define AT_USING_CLIENT
+#define AT_CLIENT_NUM_MAX 1
+#define AT_USING_SOCKET
+#define AT_USING_CLI
+#define AT_PRINT_RAW_CMD
+```
+
+- `RT_USING_AT`: Used to enable or disable the AT component;
+
+- `AT_USING_CLIENT`: Used to enable the AT Client function;
+
+- `AT_CLIENT_NUM_MAX`: Maximum number of AT clients supported at the same time.
+
+- `AT_USING_SOCKET`: Used by the AT client to support the standard BSD Socket API and enable the AT Socket function.
+
+- `AT_USING_CLI`: Used to enable or disable the client command line interaction mode.
+
+- `AT_PRINT_RAW_CMD`: Used to enable the real-time display mode of AT command communication data for easy debugging.
+
+The above configuration options can be added directly to the `rtconfig.h` file or added by the Env. The specific path in Env is as follows:
+
+```c
+RT-Thread Components --->
+ Network --->
+ AT commands --->
+ [*] Enable AT commands
+ [ ] Enable debug log output
+ [ ] Enable AT commands server
+ [*] Enable AT commands client
+ (1) The maximum number of supported clients
+ [*] Enable BSD Socket API support by AT commnads
+ [*] Enable command-line interface for AT commands
+ [ ] Enable print RAW format AT command communication data
+```
+
+After the configuration is complete, you can use the command line to rebuild the project, or use `scons` to compile.
+
+## AT Client Initialization
+
+After configuring the AT Client, you need to initialize it at startup to enable the AT Client function. If the component has been initialized automatically, no additional initialization is required. Otherwise, you need to call the following function in the initialization task:
+
+```c
+int at_client_init(const char *dev_name, rt_size_t recv_bufsz);
+```
+
+The AT Client initialization function, which belongs to the application layer function, needs to be called before using the AT Client function or using the AT Client CLI function. The `at_client_init()` function completes the initialization of the AT Client device, the initialization of the AT Client porting function, the semaphore and mutex used by the AT Client, and other resources, and creates the `at_client` thread for parsing the data received in the AT Client and for processing the URC data.
+
+## AT Client data receiving and sending
+
+The main function of the AT Client is to send AT commands, receive data, and parse data. The following is an introduction to the processes and APIs related to AT Client data reception and transmission.
+
+Related structure definition:
+
+```c
+struct at_response
+{
+ /* response buffer */
+ char *buf;
+ /* the maximum response buffer size */
+ rt_size_t buf_size;
+ /* the number of setting response lines
+ * == 0: the response data will auto return when received 'OK' or 'ERROR'
+ * != 0: the response data will return when received setting lines number data */
+ rt_size_t line_num;
+ /* the count of received response lines */
+ rt_size_t line_counts;
+ /* the maximum response time */
+ rt_int32_t timeout;
+};
+typedef struct at_response *at_response_t;
+```
+
+In the AT component, this structure is used to define a control block for AT command response data, which is used to store or limit the data format of the AT command response data.
+
+- `buf` is used to store the received response data. Note that the data stored in the buf is not the original response data, but the data of the original response data removal terminator (`"\r\n"`). Each row of data in the buf is split by '\0' to make it easy to get data by row.
+- `buf_size` is a user-defined length of the received data that is most supported by this response. The length of the return value is defined by the user according to his own command.
+- `line_num` is the number of rows that the user-defined response data needs to receive. **If there is no response line limit requirement, it can be set to 0.**
+- `line_counts` is used to record the total number of rows of this response data.
+- `timeout` is the user-defined maximum response time for this response data.
+
+`buf_size`, `line_num`, `timeout` parameters in the structure are restricted conditions, which are set when the structure is created, and other parameters are used to store data parameters for later data analysis.
+
+Introduction to related API interfaces:
+
+### Create a Response Structure
+
+```c
+at_response_t at_create_resp(rt_size_t buf_size, rt_size_t line_num, rt_int32_t timeout);
+```
+
+| **Parameter** | **Description** |
+|---------|-----------------------------------------|
+| buf_size | Maximum length of received data supported by this response |
+| line_num | This response requires the number of rows of data to be returned. The number of rows is divided by a standard terminator (such as "\r\n"). If it is 0, it will end the response reception after receiving the "OK" or "ERROR" data; if it is greater than 0, it will return successfully after receiving the data of the current set line number. |
+| timeout | The maximum response time of the response data, receiving data timeout will return an error |
+| **Return** | -- |
+| != NULL | Successful, return a pointer to the response structure |
+| = NULL | Failed, insufficient memory |
+
+This function is used to create a custom response data receiving structure for later receiving and parsing the send command response data.
+
+### Delete a Response Structure
+
+```c
+void at_delete_resp(at_response_t resp);
+```
+
+| **Parameter** | **Description** |
+|----|-------------------------|
+| resp | The response structure pointer to be deleted |
+
+This function is used to delete the created response structure object, which is generally paired with the **at_create_resp** creation function.
+
+### Set the Parameters of Response Structure
+
+```c
+at_response_t at_resp_set_info(at_response_t resp, rt_size_t buf_size, rt_size_t line_num, rt_int32_t timeout);
+```
+
+| **Parameter** | **Description** |
+|---------|----------------------------------|
+| resp | Response structure pointer that has been created |
+| buf_size | Maximum length of received data supported by this response |
+| line_num | This response requires the number of rows of data to be returned. The number of lines is divided by the standard terminator. If it is 0, the response is received after receiving the "OK" or "ERROR" data. If it is greater than 0, the data is successfully returned after receiving the data of the currently set line number. |
+| timeout | The maximum response time of the response data, receiving data timeout will return an error. |
+| **Return** | -- |
+| != NULL | Successful, return a pointer to the response structure |
+| = NULL | Failed, insufficient memory |
+
+This function is used to set the response structure information that has been created. It mainly sets the restriction information on the response data. It is generally used after creating the structure and before sending the AT command. This function is mainly used to send commands when the device is initialized, which can reduce the number of times the response structure is created and reduce the code resource occupation.
+
+### Send a Command and Receive a Response
+
+```c
+rt_err_t at_exec_cmd(at_response_t resp, const char *cmd_expr, ...);
+```
+
+| **Parameter** | **Description** |
+|---------|-----------------------------|
+| resp | Response structure body pointer created |
+| cmd_expr | Customize the expression of the input command |
+| ... | Enter the command data list, a variable parameter |
+| **Return** | -- |
+| >=0 | Successful |
+| -1 | Failed |
+| -2 | Failed, receive response timed out |
+
+This function is used by the AT Client to send commands to the AT Server and wait for a response. `resp` is a pointer to the response structure that has been created. The AT command uses the variable argument input of the match expression. **You do not need to add a command terminator at the end of the input command.**
+
+Refer to the following code to learn how to use the above AT commands to send and receive related functions:
+
+```c
+/*
+ * Program listing: AT Client sends commands and receives response routines
+ */
+
+#include <rtthread.h>
+#include <at.h> /* AT component header file */
+
+int at_client_send(int argc, char**argv)
+{
+ at_response_t resp = RT_NULL;
+
+ if (argc != 2)
+ {
+ LOG_E("at_cli_send [command] - AT client send commands to AT server.");
+ return -RT_ERROR;
+ }
+
+ /* Create a response structure, set the maximum support response data length to 512 bytes, the number of response data lines is unlimited, and the timeout period is 5 seconds. */
+ resp = at_create_resp(512, 0, rt_tick_from_millisecond(5000));
+ if (!resp)
+ {
+ LOG_E("No memory for response structure!");
+ return -RT_ENOMEM;
+ }
+
+ /* Send AT commands and receive AT Server response data, data and information stored in the resp structure */
+ if (at_exec_cmd(resp, argv[1]) != RT_EOK)
+ {
+ LOG_E("AT client send commands failed, response error or timeout !");
+ return -ET_ERROR;
+ }
+
+ /* Command sent successful */
+ LOG_D("AT Client send commands to AT Server success!");
+
+ /* Delete response structure */
+ at_delete_resp(resp);
+
+ return RT_EOK;
+}
+#ifdef FINSH_USING_MSH
+#include <finsh.h>
+/* Output at_Client_send to msh */
+MSH_CMD_EXPORT(at_Client_send, AT Client send commands to AT Server and get response data);
+#endif
+```
+
+The implementation principle of sending and receiving data is relatively simple. It mainly reads and writes the serial port device bound by the AT client, and sets the relevant number of rows and timeout to limit the response data. It is worth noting that the `res` response needs to be created first. The structure passed `in_exec_cmd` function is for data reception. When the `at_exec_cmd` function's parameter `resp` is NULL, it means that the data sent this time **does not consider processing the response data and directly returns the result**.
+
+## AT Client Data Parsing Method
+
+After the data is normally acquired, the response data needs to be parsed, which is one of the important functions of the AT Client. Parsing of data in the AT Client provides a parsed form of a custom parsing expression whose parsing syntax uses the standard `sscanf` parsing syntax. Developers can use the custom data parsing expression to respond to useful information in the data, provided that the developer needs to review the relevant manual in advance to understand the basic format of the AT Server device response data that the AT Client connects to. The following is a simple AT Client data parsing method through several functions and routines.
+
+### Get Response Data for the Specified Line Number
+
+```c
+const char *at_resp_get_line(at_response_t resp, rt_size_t resp_line);
+```
+
+| **Parameter** | **Description** |
+|----------|-----------------------------|
+| resp |Response structure pointer |
+| resp_line | Required line number for obtaining data |
+| **Return** | -- |
+| != NULL | Successful, return a pointer to the corresponding line number data |
+| = NULL | Failed, input line number error |
+
+This function is used to get a row of data with the specified line number in the AT Server response data. The line number is judged by the standard data terminator. The above send and receive functions `at_exec_cmd` have recorded and processed the data and line numbers of the response data in the `resp` response structure, where the data information of the corresponding line number can be directly obtained.
+
+### Get Response Data by the Specified Keyword
+
+```c
+const char *at_resp_get_line_by_kw(at_response_t resp, const char *keyword);
+```
+
+| **Parameter** | **Description** |
+|-------|-----------------------------|
+| resp |Response structure pointer |
+| keyword | Keyword information |
+| **Return** | -- |
+| != NULL | Successful, return a pointer to the corresponding line number data |
+| = NULL | Failed, no keyword information found |
+
+This function is used to get a corresponding row of data by keyword in the AT Server response data.
+
+### Parse Response Data for the Specified Line Number
+
+```c
+int at_resp_parse_line_args(at_response_t resp, rt_size_t resp_line, const char *resp_expr, ...);
+```
+
+| **Parameter** | **Description** |
+|----------|---------------------------------|
+| resp |Response structure pointer |
+| resp_line | Parsed data line number required, **from the start line number count 1** |
+| resp_expr | Custom parameter parsing expression |
+| ... | Parsing the parameter list as a variable parameter |
+| **Return** | -- |
+| >0 | Successful, return the number of parameters successfully parsed |
+| =0 | Failed, no parameters matching the parsing expression |
+| -1 | Failed, parameter parsing error |
+
+This function is used to get a row of data with the specified line number in the AT Server response data, and parse the parameters in the row data.
+
+### Parse Response Data for a Row with Specified Keyword
+
+```c
+int at_resp_parse_line_args_by_kw(at_response_t resp, const char *keyword, const char *resp_expr, ...);
+```
+
+| **Parameter** | **Description** |
+|----------|---------------------------------|
+| resp |Response structure pointer |
+| keyword | Keyword information |
+| resp_expr | Custom parameter parsing expression |
+| ... | Parsing the parameter list as a variable parameter |
+| **Return** | -- |
+| >0 | Successful, return the number of parameters successfully parsed |
+| =0 | Failed, no parameters matching the parsing expression |
+| -1 | Failed, parameter parsing error |
+
+This function is used to get a row of data containing a keyword in the AT Server response data and parse the parameters in the row data.
+
+The data parsing syntax uses the standard `sscanf` syntax, the content of the syntax is more, developers can search their parsing syntax, here two procedures are used to introduce the simple use method.
+
+### Serial Port Configuration Information Analysis Example
+
+The data sent by the client:
+
+```c
+AT+UART?
+```
+
+The response data obtained by the client:
+
+```c
+UART=115200,8,1,0,0\r\n
+OK\r\n
+```
+
+The pseudo code is parsed as follows:
+
+```c
+/* Create a server response structure, the maximum length of user-defined receive data is 64 */
+resp = at_create_resp(64, 0, rt_tick_from_millisecond(5000));
+
+/* Send data to the server and receive response data in the resp structure */
+at_exec_cmd(resp, "AT+UART?");
+
+/* Analyze the serial port configuration information, 1 means parsing the first line of response data, '%*[^=]' means ignoring the data before the equal sign */
+at_resp_parse_line_args(resp, 1,"%*[^=]=%d,%d,%d,%d,%d", &baudrate, &databits, &stopbits, &parity, &control);
+printf("baudrate=%d, databits=%d, stopbits=%d, parity=%d, control=%d\n",
+ baudrate, databits, stopbits, parity, control);
+
+/* Delete server response structure */
+at_delete_resp(resp);
+```
+
+### IP and MAC Address Resolution Example
+
+The data sent by the client:
+
+```c
+AT+IPMAC?
+```
+
+The response data obtained by the server:
+
+```c
+IP=192.168.1.10\r\n
+MAC=12:34:56:78:9a:bc\r\n
+OK\r\n
+```
+
+The pseudo code is parsed as follows:
+
+```c
+/* Create a server response structure, the maximum length of user-defined receive data is 128 */
+resp = at_create_resp(128, 0, rt_tick_from_millisecond(5000));
+
+at_exec_cmd(resp, "AT+IPMAC?");
+
+/* Customize the parsing expression to parse the information in the current line number data */
+at_resp_parse_line_args(resp, 1,"IP=%s", ip);
+at_resp_parse_line_args(resp, 2,"MAC=%s", mac);
+printf("IP=%s, MAC=%s\n", ip, mac);
+
+at_delete_resp(resp);
+```
+
+The key to parsing data is to correctly define the expression. Because the response data of the different device manufacturers is not unique to the response data of the AT device, only the form of the custom parsing expression can be obtained to obtain the required information. The design of the `at_resp_parse_line_args` parsing parameter function is based on the `sscanf` data parsing method. Before using it, the developer needs to understand the basic parsing syntax and then design the appropriate parsing syntax in combination with the response data. If the developer does not need to parse the specific parameters, you can use the `at_resp_get_line` function to get the specific data of a row.
+
+## AT Client URC Data Processing
+
+The processing of URC data is another important feature of AT Client. URC data is the data that is actively sent by the server. It cannot be received by the above data sending and receiving functions. The URC data format and function are different for different devices. Therefore, the URC data processing mode needs to be customized. The AT component provides a list management method for the processing of URC data. Users can customize the addition of URC data and its execution functions to the management list, so the processing of URC data is also the main porting work of AT Client.
+
+Related structure:
+
+```c
+struct at_urc
+{
+ const char *cmd_prefix; // URC data prefix
+ const char *cmd_suffix; // URC data suffix
+ void (*func)(const char *data, rt_size_t size); // URC data execution function
+};
+typedef struct at_urc *at_urc_t;
+```
+
+Each URC data has a structure control block that defines and determines the prefix and suffix of the URC data, as well as the execution function of the URC data. A piece of data can be defined as URC data only if it matches the prefix and suffix of the URC exactly. The URC data execution function is executed immediately after the matching URC data is obtained. So developers adding a URC data requires a custom matching prefix, suffix, and execution function.
+
+
+### URC Data List Initialization
+
+```c
+void at_set_urc_table(const struct at_urc *table, rt_size_t size);
+```
+
+| **Parameter** | **Description** |
+|-----|-----------------------|
+| table | URC data structure array pointer |
+| size | Number of URC data |
+
+This function is used to initialize the developer-defined URC data list, mainly used in the AT Client porting function.
+
+The example of AT Client migration is given below. This example mainly shows the specific processing of URC data in the `at_client_port_init()` porting function. The developer can directly apply it to his own porting file, or customize the implementation function to complete the AT Client porting.
+
+```c
+static void urc_conn_func(const char *data, rt_size_t size)
+{
+ /* WIFI connection success information */
+ LOG_D("AT Server device WIFI connect success!");
+}
+
+static void urc_recv_func(const char *data, rt_size_t size)
+{
+ /* Received data from the server */
+ LOG_D("AT Client receive AT Server data!");
+}
+
+static void urc_func(const char *data, rt_size_t size)
+{
+ /* Device startup information */
+ LOG_D("AT Server device startup!");
+}
+
+static struct at_urc urc_table[] = {
+ {"WIFI CONNECTED", "\r\n", urc_conn_func},
+ {"+RECV", ":", urc_recv_func},
+ {"RDY", "\r\n", urc_func},
+};
+
+int at_client_port_init(void)
+{
+ /* Add multiple URC data to the URC list and execute the URC function when receiving data that matches both the URC prefix and the suffix */
+ at_set_urc_table(urc_table, sizeof(urc_table) / sizeof(urc_table[0]));
+ return RT_EOK;
+}
+```
+
+## AT Client Other APIs Introduction
+
+### Send Specified Length Data
+
+```c
+rt_size_t at_client_send(const char *buf, rt_size_t size);
+```
+
+| **Parameter** | **Description** |
+|----|-----------------------------|
+| buf | Pointer to send data |
+| size | Length of data sent |
+| **Return** | -- |
+| >0 | Successful, return the length of the data sent |
+| <=0 | Failed |
+
+This function is used to send the specified length data to the AT Server device through the AT Client device, which is mostly used for the AT Socket function.
+
+### Receive Specified Length Data
+
+```c
+rt_size_t at_client_recv(char *buf, rt_size_t size,rt_int32_t timeout);
+```
+
+| **Parameter** | **Description** |
+|----|-----------------------------|
+| buf | Pointer to receive data |
+| size | Maximum length for receiving data |
+| timeout | Receive data timeout (tick) |
+| **Return** | -- |
+| >0 | Successful, return the length of the data received successfully |
+| <=0 | Failed, receiving data error or timeout |
+
+This function is used to receive data of a specified length through the AT Client device, and is mostly used for the AT Socket function. This function can only be used in URC callback handlers.
+
+### Set the line terminator for receiving data
+
+```c
+void at_set_end_sign(char ch);
+```
+
+| Parameter | 描述 |
+| ----- | ----- |
+|ch | Line terminator |
+| **Return** | **描述** |
+|- | - |
+
+This function is used to set the line terminator, which is used to judge the end of a row of data received by the client, and is mostly used for the AT Socket function.
+
+### Waiting for module initialization to complete
+
+```c
+int at_client_wait_connect(rt_uint32_t timeout);
+```
+
+| Parameter | Description |
+| ----- | ----- |
+|timeout | Waiting timeout |
+| **Return** | **Description** |
+|0 | Successful |
+|<0 | Failed, no data returned during the timeout period |
+
+This function is used to cyclically send AT commands when the AT module starts, until the module responds to the data, indicating that the module is successfully started.
+
+## AT Client Multi-Client Support
+
+In general, the device as the AT Client only connects to one AT module (the AT module acts as the AT Server) and can directly use the above functions of data transmission and reception and command parsing. In a few cases, the device needs to connect multiple AT modules as the AT Client. In this case, the multi-client support function of the device is required.
+
+The AT component provides support for multi-client connections and provides two different sets of function interfaces: **Single-Client Mode Functions** and **Multi-Client Mode Functions**.
+
+- Single-Client Mode Function: This type of function interface is mainly used when the device is connected to only one AT module, or when the device is connected to multiple AT modules, it is used in the **first AT client**.
+
+- Multi-Client Mode Function: This type of function interface mainly uses devices to connect multiple AT modules.
+
+The advantages and disadvantages of the two different mode functions and in different application scenarios are as follows:
+
+![at client modes comparison](figures/at_multiple_client.jpg)
+
+The single client mode function definition is mainly different from the single connection mode function. The definition of the incoming client object is different. The single client mode function uses the first initialized AT client object by default, and the multi-client mode function can pass in the user-defined custom client object. The function to get the client object is as follows:
+
+```c
+at_client_t at_client_get(const char *dev_name);
+```
+
+This function obtains the AT client object created by the device through the incoming device name, which is used to distinguish different clients when connecting multiple clients.
+
+The single client mode and multi-client mode function interface definitions differ from the following functions::
+
+| Single-Client Mode Functions | Multi-Client Mode Functions |
+| ----------------------------| ---------------------------------------|
+| at_exec_cmd(...) | at_obj_exec_cmd(client, ...) |
+| at_set_end_sign(...) | at_obj_set_end_sign(client, ...) |
+| at_set_urc_table(...) | at_obj_set_urc_table(client, ...) |
+| at_client_wait_connect(...) | at_client_obj_wait_connect(client, ...) |
+| at_client_send(...) | at_client_obj_send(client, ...) |
+| at_client_recv(...) | at_client_obj_recv(client, ...) |
+
+The two modes of client data transmission and parsing are basically the same, and the function usage process is different, as shown below:
+
+```c
+/* Single client mode function usage */
+
+at_response_t resp = RT_NULL;
+
+at_client_init("uart2", 512);
+
+resp = at_create_resp(256, 0, 5000);
+
+/* Send commands using a single client mode function */
+at_exec_cmd(resp, "AT+CIFSR");
+
+at_delete_resp(resp);
+```
+
+```c
+/* Multi-client mode functions usage */
+
+at_response_t resp = RT_NULL;
+at_client_t client = RT_NULL;
+
+/* Initialize two AT clients */
+at_client_init("uart2", 512);
+at_client_init("uart3", 512);
+
+/* Get the corresponding AT client object by name */
+client = at_client_get("uart3");
+
+resp = at_create_resp(256, 0, 5000);
+
+/* Send commands using multi-client mode functions */
+at_obj_exec_cmd(client, resp, "AT+CIFSR");
+
+at_delete_resp(resp);
+```
+
+The process differences used by other functions are similar to the above `at_obj_exec_cmd()` function. The main function is to obtain the client object through the `at_client_get()` function, and then determine which client is the client through the incoming object to achieve multi-client support.
+
+# FAQs
+
+## Q: What should I do if the log on the shell shows an error when enabling the AT command to send and receive data real-time printing function. ?
+
+**A:** Increase the baudrate of the serial port device corresponding to the shell to 921600, improve the serial port printing speed, and prevent the printing error when the data is too large.
+
+## Q: When the AT Socket function is started, the compile prompt "The AT socket device is not selected, please select it through the env menuconfig".
+
+**A:** After the AT Socket function is enabled, the corresponding device model is enabled in the at device package by default. Enter the at device package, configure the device as an ESP8266 device, configure WIFI information, re-generate the project, compile and download.
+
+## Q: AT Socket function data reception timeout or data reception is not complete.
+
+**A:** The error may be that the receive data buffer in the serial device used by the AT is too small (RT_SERIAL_RB_BUFSZ default is 64 bytes), and the data is overwritten after the data is not received in time. The buffer size of the serial port receiving data (such as 256 bytes) is appropriately increased.
diff --git a/documentation/6.components/at/figures/at_framework.jpg b/documentation/6.components/at/figures/at_framework.jpg
new file mode 100644
index 0000000000..6bc88adc3c
--- /dev/null
+++ b/documentation/6.components/at/figures/at_framework.jpg
Binary files differ
diff --git a/documentation/6.components/at/figures/at_multiple_client.jpg b/documentation/6.components/at/figures/at_multiple_client.jpg
new file mode 100644
index 0000000000..e800d69779
--- /dev/null
+++ b/documentation/6.components/at/figures/at_multiple_client.jpg
Binary files differ
diff --git a/documentation/6.components/dlmodule/README.md b/documentation/6.components/dlmodule/README.md
new file mode 100644
index 0000000000..fa6aa7d35b
--- /dev/null
+++ b/documentation/6.components/dlmodule/README.md
@@ -0,0 +1,314 @@
+@page page_component_dlmodule Dynamic Module: dlmodule
+
+In traditional desktop operating systems, user space and kernel space are separate. The application runs in user space, and the kernel and kernel modules run in kernel space. The kernel module can be dynamically loaded and deleted to extend the kernel functionality. `dlmodule` is a software component of the dynamic module loading mechanism provided in kernel space of RT-Thread. In versions of RT-Thread v3.1.0, this was also called the `Application Module`. After RT-Thread v3.1.0 and later, it returned to the tradition and was named after the `dynamic module`.
+
+`dlmodule` is more of an ELF format loader. The code segment and data segment of a separately compiled elf file are loaded into memory, and the symbols are parsed and bound to the API address exported by the kernel. The elf files are primarily placed on file systems under RT-Thread.
+
+# Introduction
+
+The dynamic module provides a mechanism for dynamically loading program modules for RT-Thread. Because it is also compiled independently of the kernel, it is more flexible to use. In terms of implementation, this is a mechanism to separate the kernel from the dynamic modules. Through this mechanism, the kernel and dynamic modules can be compiled separately, and at runtime, the compiled dynamic modules are loaded into the kernel through the module loader in the kernel.
+
+In the dynamic module of RT-Thread, two formats are currently supported:
+
+* `.mo` is an executable dynamic module that is suffixed with `.mo` when compiled; it can be loaded, and a main thread is automatically created in the system to execute `main()` function in this dynamic module; at the same time, `main(int argc, char**argv)` can also accept arguments on the command line.
+* `.so` is a dynamic library compiled with `.so` as a suffix; it can be loaded and resided in memory, and some set of functions is used by other programs (code or dynamic modules in the kernel).
+
+The current RT-Thread architecture supporting dynamic modules mainly includes ARM architecture and x86 architecture, and will be extended to MIPS and RISC-V architecture in the future. The RT-Thread kernel firmware section can use a variety of compiler toolchains, such as GCC, ARMCC, IAR and other toolchains; however, dynamic module partial compilation currently only supports GNU GCC toolchain compilation. Therefore, compiling the RT-Thread module requires downloading GCC tools, such as CodeSourcery's arm-none-eabi toolchain. In general, it's best to use kernel and dynamic modules to compile with the same toolchain (so that it doesn't produce inconsistent behavior in *libc*). In addition, dynamic modules can only be loaded into RAM and used for symbol resolution binding to the API address exported by the kernel. Instead of running directly in XIP mode based on Flash (because Flash can't modify the code segment again).
+
+# Using Dynamic Module
+
+When you want to use the dynamic modules in your system, you need to compile a firmware that supports dynamic modules, as well as dynamic modules that need to be run. The following two parts are compiling firmware and compiling dynamic modules.
+
+## Compile Firmware
+
+When you want to use the dynamic module, you need to open the corresponding option in the firmware configuration, use menuconfig to open the following configuration:
+
+```c
+ RT-Thread Components --->
+ POSIX layer and C standard library --->
+ [*] Enable dynamic module with dlopen/dlsym/dlclose feature
+```
+
+Also open the configuration options of the file system:
+
+```c
+ RT-Thread Components --->
+ Device virtual file system --->
+ [*] Using device virtual file system
+```
+
+The configuration parameters required for dynamic module compilation are set in *rtconfig.py* file corresponding to bsp:
+
+```Python
+M_CFLAGS = CFLAGS + '-mlong-calls -fPIC'
+M_CXXFLAGS = CXXFLAGS + '-mlong-calls -fPIC'
+M_LFLAGS = DEVICE + CXXFLAGS + '-Wl,--gc-sections,-z,max-page-size=0x4' +\
+ '-shared -fPIC -nostartfiles -nostdlib -static-libgcc'
+M_POST_ACTION = STRIP + '-R .hash $TARGET\n' + SIZE + '$TARGET \n'
+M_BIN_PATH = r'E:\qemu-dev310\fatdisk\root'
+```
+
+The relevant explanation is as follows:
+
+* **M_CFLAGS**: C code compilation parameters used in dynamic module compilation, generally compiled here in PIC mode (that is, the code address supports floating mode execution);
+- **M_CXXFLAGS**: C++ code compilation parameters used in dynamic module compilation, parameters similar to M_CFLAGS above;
+- **M_LFLAGS**: Parameters when the dynamic module is linked. The same is the PIC method, and is linked in a shared library (partial link);
+- **M_POST_ACTION**: the action to be performed after the dynamic module is compiled. Here, the elf file is stripped to reduce the size of the elf file.
+- **M_BIN_PATH**: When the dynamic module is successfully compiled, whether the corresponding dynamic module file needs to be copied to a unified place;
+
+Basically, these compilation configuration parameters for the ARM9, Cortex-A, and Cortex-M series are the same.
+
+The kernel firmware also exports some function APIs to the dynamic module via `RTM(function)`. All exported symbols information in firmware can be listed by command A under MSH:
+
+```
+list_symbols
+```
+
+The `dlmodule` loader also parses the symbols that need to be parsed in the dynamic module according to the symbol table exported here to complete the final binding action.
+
+This symbol table will be placed in a special section named `RTMSymTab`, so the corresponding firmware link script also needs to retain this area, and will not be removed by the linker optimization. You can add the corresponding information in the link script:
+
+```text
+/* section information for modules */
+. = ALIGN(4);
+__rtmsymtab_start = .;
+KEEP(*(RTMSymTab))
+__rtmsymtab_end = .;
+```
+
+Then execute the `scons` under the BSP project directory and generate the firmware without errors. Execute the command in the BSP project directory:
+
+`scons --target=ua -s`
+
+to generate the kernel header file search path and global macro definitions that need to be included when compiling the dynamic module.
+
+## Compile Dynamic Module
+
+There is a separate repository on github: [rtthread-apps](https://github.com/RT-Thread/rtthread-apps) , which contains some examples of dynamic modules and dynamic libraries.
+
+Its directory structure is as follows:
+
+| **Directory** | **Description** |
+| --- | ---------------- |
+| cxx | Demonstrates how to program in C++ using dynamic modules |
+| hello | A "hello world" example |
+| lib | Example of dynamic library |
+| md5 | Generate md5 code for a file |
+| tools | *Python/SConscript* scripts required for dynamic module compilation |
+| ymodem | Download a file to the file system through the serial port using the YModem protocol |
+
+You can clone this repository locally and compile it with the scons from the command line. For Windows platforms, the ENV tool is recommended.
+
+After entering the console command line, enter the directory where the `rtthread-apps` repo is located (the same, please ensure that the full path of this directory does not contain spaces, Chinese characters, etc.), and set two variables:
+
+* RTT_ROOT: points to the root directory of the RT-Thread code;
+- BSP_ROOT: points to the project directory of the BSP;
+
+Use follow commands on Windows in Env tool(assuming the BSP used is qemu-vexpress-a9):
+
+```c
+set RTT_ROOT=d:\your_rtthread
+set BSP_ROOT=d:\your_rtthread\bsp\qemu-vexpress-a9
+```
+
+to set the corresponding environment variable. Then use the following command to compile the dynamic module, such as the hello example:
+
+```
+scons --app=hello
+```
+
+After compiling successfully, it will generate a `hello.mo` file in the `rtthread-apps/hello` directory.
+
+You can also compile dynamic libraries, such as the lib example:
+
+```
+scons --lib=lib
+```
+
+After compiling successfully, it will generate the `lib.so` file in the `rtthread-apps/lib` directory.
+
+We can put these `mo` and `so` files under the RT-Thread file system. Under msh, you can simply execute the `hello.mo` dynamic module as a `hello` command:
+
+```c
+msh />ls
+Directory /:
+hello.mo 1368
+lib.so 1376
+msh />hello
+msh />Hello, world
+```
+
+After calling hello, the main function in `hello.mo` will be executed, and the corresponding dynamic module will be exited after execution. The code for `hello/main.c` is as follows:
+
+```c
+#include <stdio.h>
+
+int main(int argc, char *argv[])
+{
+ printf("Hello, world\n");
+
+ return 0;
+}
+```
+
+# APIs of Dynamic Module
+
+In addition to dynamically loading and executing dynamic modules via msh, dynamic modules can be loaded or unloaded using the dynamic module API provided by RT-Thread in the main program.
+
+## Load Dynamic Module
+
+```c
+struct rt_dlmodule *dlmodule_load(const char* pgname);
+```
+
+|**Parameter**|**Description**|
+| ---- | ---- |
+| pgname | Dynamic module path |
+|**Return**| —— |
+| Dynamic module pointer | Successfully loaded |
+| RT_NULL | Failed |
+
+This function loads the dynamic module from the file system into memory, and if it is loaded correctly, returns a pointer to the module. This function does not create a thread to execute this dynamic module, just load the module into memory and parse the symbolic address.
+
+## Execute Dynamic Module
+
+```c
+struct rt_dlmodule *dlmodule_exec(const char* pgname, const char* cmd, int cmd_size);
+```
+
+|**Parameter**|**Description**|
+| ---- | ---- |
+| pgname | Dynamic module path |
+| cmd | Command line string including the dynamic module command itself |
+| cmd_size | Command line string size |
+|**Return**| —— |
+| Dynamic module pointer | Run successfully |
+| RT_NULL | Failed |
+
+This function loads the dynamic module according to the `pgname` path and starts a thread to execute `main` of the dynamic module. At the same time, `cmd` is passed as the command line Parameter to `main` entry of the dynamic module.
+
+## Exit Dynamic Module
+
+```c
+void dlmodule_exit(int ret_code);
+```
+
+|**Parameter**|**Description**|
+| ---- | ---- |
+| ret_code | Module's return parameter |
+
+This function is called by the module runtime, it can set the return value of the module exit `ret_code`, and then exit from the module.
+
+## Find Dynamic Modules
+
+```c
+struct rt_dlmodule *dlmodule_find(const char *name);
+```
+
+|**Parameter**|**Description**|
+| ---- | ---- |
+| name | Module name |
+|**Return**| —— |
+| Dynamic module pointer | Successful |
+| RT_NULL | Failed |
+
+This function uses `name` to find out if there is already a dynamic module loaded in the system.
+
+## Return Dynamic Module
+
+```c
+struct rt_dlmodule *dlmodule_self(void);
+```
+
+|**Return**|**Description**|
+| ---- | ---- |
+| Dynamic module pointer | Successful |
+| RT_NULL | Failed |
+
+This function returns a pointer of the dynamic module in the calling context.
+
+## Find Symbol
+
+```c
+rt_uint32_t dlmodule_symbol_find(const char *sym_str);
+```
+
+|**Parameter**|**Description**|
+| ---- | ---- |
+| sym_str | Symbol name |
+|**Return**| —— |
+| Symbol address | Successful |
+| 0 | Failed |
+
+This function returns the symbol address based on the symbol name.
+
+# Libdl API of POSIX Standard
+
+The POSIX standard libdl API is also supported in RT-Thread dlmodule. It is similar to loading a dynamic library into memory (and parsing some of the symbol information). This dynamic library provides the corresponding set of function operations. The libdl API needs to include the header files: `#include <dlfcn.h>`
+
+## Open Dynamic Library
+
+```c
+void * dlopen (const char * pathname, int mode);
+```
+
+|**Parameter**|**Description**|
+| ---- | ---- |
+| pathname | Dynamic library path name |
+| mode | The mode when opening a dynamic library, not used in RT-Thread |
+|**Return**| —— |
+| Dynamic library handle (`struct dlmodule` structure pointer) | Successful |
+| NULL | Failed |
+
+This function is similar to the `dlmodule_load` , which loads the dynamic library from the file system and returns the handle pointer of the dynamic library.
+
+## Find Symbol
+
+```c
+void* dlsym(void *handle, const char *symbol);
+```
+
+|**Parameter**|**Description**|
+| ---- | ---- |
+| handle | Dynamic library handle, return value of `dlopen` |
+| symbol | The symbol address to return |
+|**Return**| —— |
+| symbol address | Successful |
+| NULL | Failed |
+
+This function looks in the dynamic library `handle` for the presence of the symbol of `symbol` , if there is an address that returns it.
+
+## Close Dynamic Library
+
+```
+int dlclose (void *handle);
+```
+
+|**Parameter**|**Description**|
+| ---- | ---- |
+| handle | Dynamic library handle |
+|**Return**| —— |
+| 0 | Successful |
+| Negative number | Failed |
+
+This function closes the dynamic library pointed to by `handle` and unloads it from memory. It should be noted that when the dynamic library is closed, the symbolic address originally returned by `dlsym` will no longer be available. If you still try to access it, it may cause a fault error.
+
+# FAQs
+
+Please refer to @ref page_env for issues related to the Env tool.
+
+## Q: Dynamic modules cannot be run successfully according to the documentation.
+
+**A:** Please update the RT-Thread source code to version 3.1.0 and above.
+
+## Q: Compile the project with the scons command, prompting "undefined reference to __rtmsymtab_start".
+
+**A:** Please refer to the qemu-vexpress-a9 BSP GCC link script file *link.lds* to add the following to the TEXT section of the project's GCC link script.
+
+```
+ /* section information for modules */
+ . = ALIGN(4);
+ __rtmsymtab_start = .;
+ KEEP(*(RTMSymTab))
+ __rtmsymtab_end = .;
+```
diff --git a/documentation/6.components/filesystem/README.md b/documentation/6.components/filesystem/README.md
new file mode 100644
index 0000000000..7f7fc0bbb6
--- /dev/null
+++ b/documentation/6.components/filesystem/README.md
@@ -0,0 +1,1027 @@
+@page page_component_vfs Virtual File System
+
+In early days, the amount of data to be stored in embedded systems was relatively small and data types were relatively simple.
+The data were stored by directly writing to a specific address in storage devices. However, with today modern technology, embedded device's functions are getting complicated and required more data storage. Therefore, we need new data management methods to simplify and organize the data storage.
+
+A file system is made up of abstract data types and also a mechanism for providing data access, retrieve, implements, and store them in hierarchical structure. A folder contains multiple files and a file contains multiple organized data on the file system. This chapter explains about the RT-Thread file system, architecture, features and usage of virtual file system in RT-Thread OS.
+
+# An Introduction to DFS
+
+Device File System (DFS) is a virtual file system component and name structure is similar to UNIX files and folders. Following is the files and folders structure:
+
+The root directory is represented by "/". For example, if users want to access to f1.bin file under root directory, it can be accessed by "/f1.bin". If users want to access to f1.bin file under /2019 folder, it can be accessed by "/data/2019/f1.bin" according to their folder paths as in UNIX/Linux unlike Windows System.
+
+## The Architecture of DFS
+
+The main features of the RT-Thread DFS component are:
+
+- Provides a unified POSIX file and directory operations interface for applications: read, write, poll/select, and more.
+- Supports multiple types of file systems, such as FatFS, RomFS, DevFS, etc., and provides management of common files, device files, and network file descriptors.
+- Supports multiple types of storage devices such as SD Card, SPI Flash, Nand Flash, etc.
+
+The hierarchical structure of DFS is shown in the following figure, which is mainly divided into POSIX interface layer, virtual file system layer and device abstraction layer.
+
+![The hierarchical structure of DFS](figures/fs-layer.png)
+
+## POSIX Interface Layer
+
+POSIX stands for Portable Operating System Interface of UNIX (POSIX). The POSIX standard defines the interface standard that the operating system should provide for applications. It is a general term for a series of API standards defined by IEEE for software to run on various UNIX operating systems.
+
+The POSIX standard is intended to achieve software portability at the source code level. In other words, a program written for a POSIX-compatible operating system should be able to compile and execute on any other POSIX operating system (even from another vendor). RT-Thread supports the POSIX standard interface, so it is easy to port Linux/Unix programs to the RT-Thread operating system.
+
+On UNIX-like systems, normal files, device files, and network file descriptors are the same. In the RT-Thread operating system, DFS is used to achieve this uniformity. With the uniformity of such file descriptors, we can use the `poll/select` interface to uniformly poll these descriptors and bring convenience to the implement of the program functions.
+
+Using the `poll/select` interface to block and simultaneously detect whether a group of I/O devices which support non-blocking have events (such as readable, writable, high-priority error output, errors, etc.) until a device trigger the event was or exceed the specified wait time. This mechanism can help callers find devices that are currently ready, reducing the complexity of programming.
+
+## Virtual File System Layer
+
+Users can register specific file systems to DFS, such as FatFS, RomFS, DevFS, etc. Here are some common file system types:
+
+* FatFS is a Microsoft FAT format compatible file system developed for small embedded devices. It is written in ANSI C and has good hardware independence and portability. It is the most commonly used file system type in RT-Thread.
+* The traditional RomFS file system is a simple, compact, read-only file system that does not support dynamic erasing and saving or storing data in order, thus it supports applications to run in XIP (execute In Place) method and save RAM space while the system is running.
+* The Jffs2 file system is a log flash file system. It is mainly used for NOR flash memory, based on MTD driver layer, featuring: readable and writable, supporting data compression, Hash table based log file system, and providing crash/power failure security protection, write balance support, etc..
+* DevFS is the device file system. After the function is enabled in the RT-Thread operating system, the devices in the system can be virtualized into files in the `/dev` folder, so that the device can use the interfaces such as `read` and `write` according to the operation mode of the file to operate.
+* NFS (Network File System) is a technology for sharing files over a network between different machines and different operating systems. In the development and debugging phase of the operating system, this technology can be used to build an NFS-based root file system on the host and mount it on the embedded device, which can easily modify the contents of the root file system.
+* UFFS is short for Ultra-low-cost Flash File System. It is an open source file system developed by Chinese people and used for running Nand Flash in small memory environments such as embedded devices. Compared with the Yaffs file system which often used in embedded devices, it has the advantages of less resource consumption, faster startup speed and free.
+
+## Device Abstraction Layer
+
+The device abstraction layer abstracts physical devices such as SD Card, SPI Flash, and Nand Flash into devices that are accessible to the file system. For example, the FAT file system requires that the storage device be a block device type.
+
+Different file system types are implemented independently of the storage device driver, so the file system function can be correctly used after the drive interface of the underlying storage device is docked with the file system.
+
+# Mount Management
+
+The initialization process of the file system is generally divided into the following steps:
+
+1. Initialize the DFS component.
+2. Initialize a specific type of file system.
+3. Create a block device on the memory.
+4. Format the block device.
+5. Mount the block device to the DFS directory.
+6. When the file system is no longer in use, you can unmount it.
+
+## Initialize the DFS Component
+
+The initialization of the DFS component is done by the dfs_init() function. The dfs_init() function initializes the relevant resources required by DFS and creates key data structures that allow DFS to find a specific file system in the system and get a way to manipulate files within a particular storage device. This function will be called automatically if auto-initialization is turned on (enabled by default).
+
+## Registered File System
+
+After the DFS component is initialized, you also need to initialize the specific type of file system used, that is, register a specific type of file system into DFS. The interface to register the file system is as follows:
+
+```c
+int dfs_register(const struct dfs_filesystem_ops *ops);
+```
+
+|**Parameter**|**Description** |
+|----------|------------------------------------|
+| ops | a collection of operation functions of the file system |
+|**return**|**——** |
+| 0 | file registered successfully |
+| -1 | file fail to register |
+
+This function does not require user calls, it will be called by the initialization function of different file systems, such as the elm-FAT file system's initialization function `elm_init()`. After the corresponding file system is enabled, if automatic initialization is enabled (enabled by default), the file system initialization function will also be called automatically.
+
+The `elm_init()` function initializes the elm-FAT file system, which calls the `dfs_register(`) function to register the elm-FAT file system with DFS. The file system registration process is shown below:
+
+![Register file system](figures/fs-reg.png)
+
+## Register a Storage Device as a Block Device
+
+Only block devices can be mounted to the file system, so you need to create the required block devices on the storage device. If the storage device is SPI Flash, you can use the "Serial Flash Universal Driver Library SFUD" component, which provides various SPI Flash drivers, and abstracts the SPI Flash into a block device for mounting. The process of registering block device is shown as follows:
+
+![The timing diagram of registering block device](figures/fs-reg-block.png)
+
+## Format the file system
+
+After registering a block device, you also need to create a file system of the specified type on the block device, that is, format the file system. You can use the `dfs_mkfs()` function to format the specified storage device and create a file system. The interface to format the file system is as follows:
+
+```c
+int dfs_mkfs(const char * fs_name, const char * device_name);
+```
+
+|**Parameter** |**Description** |
+|-------------|----------------------------|
+| fs_name | type of the file system |
+| device_name | name of the block device |
+|**return** |**——** |
+| 0 | file system formatted successfully |
+| -1 | fail to format the file system |
+
+The file system type (fs_name) possible values and the corresponding file system is shown in the following table:
+
+|**Value** |**File System Type** |
+|-------------|----------------------------|
+| elm | elm-FAT file system |
+| jffs2 | jffs2 journaling flash file system |
+| nfs | NFS network file system |
+| ram | RamFS file system |
+| rom | RomFS read-only file system |
+| uffs | uffs file system |
+
+Take the elm-FAT file system format block device as an example. The formatting process is as follows:
+
+![Formatted file system](figures/elm-fat-mkfs.png)
+
+You can also format the file system using the `mkfs` command. The result of formatting the block device sd0 is as follows:
+
+```shell
+msh />mkfs sd0 # Sd0 is the name of the block device, the command will format by default
+sd0 is elm-FAT file system
+msh />
+msh />mkfs -t elm sd0 # Use the -t parameter to specify the file system type as elm-FAT file system
+```
+
+## Mount file system
+
+In RT-Thread, mounting refers to attaching a storage device to an existing path. To access a file on a storage device, we must mount the partition where the file is located to an existing path and then access the storage device through this path. The interface to mount the file system is as follows:
+
+```c
+int dfs_mount(const char *device_name,
+ const char *path,
+ const char *filesystemtype,
+ unsigned long rwflag,
+ const void *data);
+```
+
+|**Parameter** |**Description** |
+|----------------|------------------------------|
+| device_name | the name of the block device that has been formatted |
+| path | the mount path |
+| filesystemtype | The type of the mounted file system. Possible values can refer to the dfs_mkfs() function description. |
+| rwflag | read and write flag bit |
+| data | private data for a specific file system |
+|**return** | **——** |
+| 0 | file system mounted successfully |
+| -1 | file system mount fail to be mounted |
+
+If there is only one storage device, it can be mounted directly to the root directory `/`.
+
+## Unmount a file system
+
+When a file system does not need to be used anymore, it can be unmounted. The interface to unmount the file system is as follows:
+
+```c
+int dfs_unmount(const char *specialfile);
+```
+
+|**Parameter** |**Description** |
+|-------------|--------------------------|
+| specialfile | mount path |
+|**return** |**——** |
+| 0 | unmount the file system successfully |
+| -1 | fail to unmount the file system |
+
+# Document Management
+
+This section introduces the functions that are related to the operation of the file. The operation of the file is generally based on the file descriptor fd, as shown in the following figure:
+
+![common function of file management](figures/fs-mg.png)
+
+## Open and Close Files
+
+To open or create a file, you can call the following open() function:
+
+```c
+int open(const char *file, int flags, ...);
+```
+
+|**Parameter** |**Description** |
+|------------|--------------------------------------|
+| file | file names that are opened or created |
+| flags | Specify the way to open the file, and values can refer to the following table. |
+|**return** |**——** |
+| file descriptor | file opened successfully |
+| -1 | fail to open the file |
+
+A file can be opened in a variety of ways, and multiple open methods can be specified at the same time. For example, if a file is opened by O_WRONLY and O_CREAT, then when the specified file which need to be open does not exist, it will create the file first and then open it as write-only. The file opening method is as follows:
+
+|**Parameter**|**Description** |
+|----------|-----------------------|
+| O_RDONLY | open file in read-only mode |
+| O_WRONLY | open file in write-only mode |
+| O_RDWR | open file in read-write mode |
+| O_CREAT | if the file to be open does not exist, then you can create the file |
+| O_APPEND | When the file is read or written, it will start from the end of the file, that is, the data written will be added to the end of the file in an additional way. |
+| O_TRUNC | empty the contents of the file if it already exists |
+
+If you no longer need to use the file, you can use the `close()` function to close the file, and `close()` will write the data back to disk and release the resources occupied by the file.
+
+```
+int close(int fd);
+```
+
+|**Parameter**|**Description** |
+|----------|--------------|
+| fd | file descriptor |
+|**return**|**——** |
+| 0 | file closed successfully |
+| -1 | fail to close the file |
+
+## Read and Write Data
+
+To read the contents of a file, use the `read()` function:
+
+```c
+int read(int fd, void *buf, size_t len);
+```
+
+|**Parameter**|**Description** |
+|----------|------------------------------------------|
+| fd | file descriptor |
+| buf | buffer pointer |
+| len | read number of bytes of the files |
+|**return**|**——** |
+| int | the number of bytes actually read |
+| 0 | read data has reached the end of the file or there is no readable data |
+| -1 | read error, error code to view the current thread's errno |
+
+This function reads the `len` bytes of the file pointed to by the parameter `fd` into the memory pointed to by the `buf pointer`. In addition, the read/write position pointer of the file moves with the byte read.
+
+To write data into a file, use the `write()` function:
+
+```c
+int write(int fd, const void *buf, size_t len);
+```
+
+|**Parameter**|**Description** |
+|----------|---------------------------------------|
+| fd | file descriptor |
+| buf | buffer pointer |
+| len | the number of bytes written to the file |
+|**return**|**——** |
+| int | the number of bytes actually written |
+| -1 | write error, error code to view the current thread's errno |
+
+This function writes `len` bytes in the memory pointed out by the `buf pointer` into the file pointed out by the parameter `fd`. In addition, the read and write location pointer of the file moves with the bytes written.
+
+## Rename
+
+To rename a file, use the `rename()` function:
+
+```
+int rename(const char *old, const char *new);
+```
+
+|**Parameter**|**Description** |
+|----------|--------------|
+| old | file's old name |
+| new | new name |
+|**return**|**——** |
+| 0 | change the name successfully |
+| -1 | fail to change the name |
+
+This function changes the file name specified by the parameter `old` to the file name pointed to by the parameter `new`. If the file specified by `new` already exists, the file will be overwritten.
+
+## Get Status
+
+To get the file status, use the following `stat()` function:
+
+```c
+int stat(const char *file, struct stat *buf);
+```
+
+|**Parameter**|**Description** |
+|----------|--------------------------------------------|
+| file | file name |
+| buf | structure pointer to a structure that stores file status information |
+|**return**|**——** |
+| 0 | access status successfully |
+| -1 | fail to access to status |
+
+## Delete Files
+
+Delete a file in the specified directory using the `unlink()` function:
+
+```
+int unlink(const char *pathname);
+```
+
+|**Parameter**|**Description** |
+|----------|------------------------|
+| pathname | specify the absolute path to delete the file |
+|**return**|**——** |
+| 0 | deleted the file successfully |
+| -1 | fail to deleted the file |
+
+## Synchronize File Data to Storage Devices
+
+Synchronize all modified file data in memory to the storage device using the `fsync()` function:
+
+```c
+int fsync(int fildes);
+```
+
+|**Parameter**|**Description** |
+|----------|--------------|
+| fildes | file descriptor |
+|**Return**|**——** |
+| 0 | synchronize files successfully |
+| -1 | fail to synchronize files |
+
+## Query file system related information
+
+Use the `statfs()` function to query file system related information.
+
+```c
+int statfs(const char *path, struct statfs *buf);
+```
+
+|**Parameter**|**Description** |
+|----------|----------------------------------|
+| path | file system mount path |
+| buf | structure pointer for storing file system information |
+|**Return**|**——** |
+| 0 | query file system information successfully |
+| -1 | fail to query file system information |
+
+## Monitor I/O device status
+
+To monitor the I/O device for events, use the `select()` function:
+
+```c
+int select( int nfds,
+ fd_set *readfds,
+ fd_set *writefds,
+ fd_set *exceptfds,
+ struct timeval *timeout);
+```
+
+|**Parameter** |**Description** |
+|-----------|---------------------------------------------------------|
+| nfds | The range of all file descriptors in the collection, that is, the maximum value of all file descriptors plus 1 |
+| readfds | Collection of file descriptors that need to monitor read changes |
+| writefds | Collection of file descriptors that need to monitor write changes |
+| exceptfds | Collection of file descriptors that need to be monitored for exceptions |
+| timeout | timeout of **select** |
+|**return** |**——** |
+| positive value | a read/write event or error occurred in the monitored file collection |
+| 0 | waiting timeout, no readable or writable or erroneous files |
+| negative value | error |
+
+Use the `select()` interface to block and simultaneously detect whether a group of non-blocking I/O devices have events (such as readable, writable, high-priority error output, errors, etc.) until a device triggered an event or exceeded a specified wait time.
+
+# Directory management
+
+This section describes functions that directory management often uses, and operations on directories are generally based on directory addresses, as shown in the following image:
+
+![functions that directory management often uses](figures/fs-dir-mg.png)
+
+## Create and Delete Directories
+
+To create a directory, you can use the mkdir() function:
+
+```c
+int mkdir(const char *path, mode_t mode);
+```
+
+|**Parameter**|**Description** |
+|----------|----------------|
+| path | the absolute address of the directory |
+| mode | create a pattern |
+|**Return**|**——** |
+| 0 | create directory successfully |
+| -1 | fail to create directory |
+
+This function is used to create a directory as a folder, the parameter path is the absolute path of the directory, the parameter mode is not enabled in the current version, so just fill in the default parameter 0x777.
+
+Delete a directory using the rmdir() function:
+
+```c
+int rmdir(const char *pathname);
+```
+
+|**Parameter**|**Description** |
+|----------|------------------------|
+| pathname | absolute path to delete the directory |
+|**Return**|**——** |
+| 0 | delete the directory successfully |
+| -1 | fail to delete the directory |
+
+## Open and Close the Directory
+
+Open the directory to use the `opendir()` function:
+
+```c
+DIR* opendir(const char* name);
+```
+
+|**Parameter**|**Description** |
+|----------|-----------------------------------------|
+| name | absolute address of the directory |
+|**Return**|**——** |
+| DIR | open the directory successfully, and return to a pointer to the directory stream |
+| NULL | fail to open |
+
+To close the directory, use the `closedir()` function:
+
+```c
+int closedir(DIR* d);
+```
+
+|**Parameter**|**Description** |
+|----------|--------------|
+| d | directory stream pointer |
+|**Return**|**——** |
+| 0 | directory closed successfully |
+| -1 | directory closing error |
+
+This function is used to close a directory and must be used with the `opendir()` function.
+
+## Read Directory
+
+To read the directory, use the `readdir()` function:
+
+```c
+struct dirent* readdir(DIR *d);
+```
+
+|**Parameter**|**Description** |
+|----------|---------------------------------------|
+| d | directory stream pointer |
+|**Return**|**——** |
+| dirent | read successfully and return to a structure pointer to a directory entry |
+| NULL | read to the end of the directory |
+
+This function is used to read the directory, and the parameter d is the directory stream pointer. In addition, each time a directory is read, the pointer position of the directory stream is automatically recursed by 1 position backward.
+
+## Get the Read Position of the Directory Stream
+
+To get the read location of the directory stream, use the `telldir()` function:
+
+```
+long telldir(DIR *d);
+```
+
+|**Parameter**|**Description** |
+|----------|------------------|
+| d | directory stream pointer |
+|**Return**|**——** |
+| long | read the offset of the position |
+
+The return value of this function records the current position of a directory stream. This return value represents the offset from the beginning of the directory file. You can use this value in the following `seekdir()` to reset the directory to the current position. In other words, the `telldir()` function can be used with the `seekdir()` function to reset the read position of the directory stream to the specified offset.
+
+## Set the Location to Read the Directory Next Time
+
+Set the location to read the directory next time using the `seekdir()` function:
+
+```
+void seekdir(DIR *d, off_t offset);
+```
+
+|**Parameter**|**Description** |
+|----------|----------------------------|
+| d | directory stream pointer |
+| offset | the offset value, displacement from this directory |
+
+This is used to set the read position of the parameter d directory stream, and starts reading from this new position when readdir() is called.
+
+## Reset the Position of Reading Directory to the Beginning
+
+To reset the directory stream's read position to the beginning, use the `rewinddir()` function:
+
+```
+void rewinddir(DIR *d);
+```
+
+|**Parameter**|**Description** |
+|----------|------------|
+| d | directory stream pointer |
+
+This function can be used to set the current read position of the `d` directory stream to the initial position of the directory stream.
+
+# DFS Configuration Options
+
+The specific configuration path of the file system in menuconfig is as follows:
+
+```c
+RT-Thread Components --->
+ Device virtual file system --->
+```
+
+The configuration menu description and corresponding macro definitions are shown in the following table:
+
+|**Configuration Options** |**Corresponding Macro Definition**|**Description** |
+|-------------------------------|-------------------------------|----------------------|
+|[*] Using device virtual file system |RT_USING_DFS |Open DFS virtual file system |
+|[*] Using working directory |DFS_USING_WORKDIR |open a relative path |
+|(2) The maximal number of mounted file system |DFS_FILESYSTEMS_MAX |maximum number of mounted file systems |
+|(2) The maximal number of file system type |DFS_FILESYSTEM_TYPES_MAX |maximum number of supported file systems |
+|(4) The maximal number of opened files | DFS_FD_MAX|maximum number of open files |
+|[ ] Using mount table for file system|RT_USING_DFS_MNTTABLE |open the automatic mount table |
+|[*] Enable elm-chan fatfs |RT_USING_DFS_ELMFAT |open the elm-FatFs file system |
+|[*] Using devfs for device objects |RT_USING_DFS_DEVFS | open the DevFS device file system |
+|[ ] Enable ReadOnly file system on flash |RT_USING_DFS_ROMFS |open the RomFS file system |
+|[ ] Enable RAM file system |RT_USING_DFS_RAMFS |open the RamFS file system |
+|[ ] Enable UFFS file system: Ultra-low-cost Flash File System |RT_USING_DFS_UFFS |open the UFFS file system |
+|[ ] Enable JFFS2 file system |RT_USING_DFS_JFFS2 |open the JFFS2 file system |
+|[ ] Using NFS v3 client file system |RT_USING_DFS_NFS |open the NFS file system |
+
+By default, the RT-Thread operating system does not turn on the relative path function in order to obtain a small memory footprint. When the Support Relative Paths option is not turned on, you should use an absolute directory when working with files and directory interfaces (because there is no currently working directory in the system). If you need to use the current working directory and the relative directory, you can enable the relative path function in the configuration item of the file system.
+
+When the option `[*] Use mount table for file system` is selected, the corresponding macro `RT_USING_DFS_MNTTABLE` will be enabled to turn on the automatic mount table function. The automatic `mount_table[]` is provided by the user in the application code. The user needs to specify the device name, mount path, file system type, read and write flag and private data in the table. After that, the system will traverse the mount table to execute the mount. It should be noted that the mount table must end with `{0}` to judge the end of the table.
+
+The automatic mount table `mount_table []` is shown below, where the five members of `mount_table [0]` are the five parameters of function `dfs_mount ()`. This means that the elm file system is mounted `/` path on the flash 0 device, rwflag is 0, data is 0, `mount_table [1]` is `{0}` as the end to judge the end of the table.
+
+```c
+const struct dfs_mount_tbl mount_table[] =
+{
+ {"flash0", "/", "elm", 0, 0},
+ {0}
+};
+```
+
+## elm-FatFs File System Configuration Option
+
+Elm-FatFs can be further configured after opening the elm-FatFs file system in menuconfig. The configuration menu description and corresponding macro definitions are as follows:
+
+|**Configuration Options** |**Corresponding Macro Definition**|**Description** |
+|---------------------------------|-----------------------------------|-------------------|
+|(437) OEM code page |RT_DFS_ELM_CODE_PAGE |encoding mode |
+|[*] Using RT_DFS_ELM_WORD_ACCESS |RT_DFS_ELM_WORD_ACCESS | |
+|Support long file name (0: LFN disable) ---> |RT_DFS_ELM_USE_LFN |open long file name submenu |
+|(255) Maximal size of file name length |RT_DFS_ELM_MAX_LFN |maximum file name length |
+|(2) Number of volumes (logical drives) to be used. |RT_DFS_ELM_DRIVES |number of devices mounting FatFs |
+|(4096) Maximum sector size to be handled. |RT_DFS_ELM_MAX_SECTOR_SIZE |the sector size of the file system|
+|[ ] Enable sector erase feature |RT_DFS_ELM_USE_ERASE | |
+|[*] Enable the reentrancy (thread safe) of the FatFs module |RT_DFS_ELM_REENTRANT |open reentrant|
+
+### Long File Name
+
+By default, FatFs file naming has the following disadvantages:
+
+- The file name (without suffix) can be up to 8 characters long and the suffix can be up to 3 characters long. The file name and suffix will be truncated when the limit is exceeded.
+- File name does not support case sensitivity (displayed in uppercase).
+
+If you need to support long filenames, you need to turn on the option to support long filenames. The submenu of the long file name is described as follows:
+
+|**Configuration Options** |**Corresponding Macro Definition**|**Description** |
+|----------------------------------|-------------------------|---------------------|
+|( ) 0: LFN disable |RT_DFS_ELM_USE_LFN_0 |close the long file name |
+|( ) 1: LFN with static LFN working buffer|RT_DFS_ELM_USE_LFN_1 |use static buffers to support long file names, and multi-threaded operation of file names will bring re-entry problems |
+|( ) 2: LFN with dynamic LFN working buffer on the stack |RT_DFS_ELM_USE_LFN_2 |long file names are supported by temporary buffers in the stack. Larger demand for stack space. |
+|(X) 3: LFN with dynamic LFN working buffer on the heap |RT_DFS_ELM_USE_LFN_3 |use the heap (malloc request) buffer to store long filenames, it is the safest (default) |
+
+### Encoding Mode
+
+When long file name support is turned on, you can set the encoding mode for the file name. RT-Thread/FatFs uses 437 encoding (American English) by default. If you need to store the Chinese file name, you can use 936 encoding (GBK encoding). The 936 encoding requires a font library of approximately 180KB. If you only use English characters as a file, we recommend using 437 encoding (American English), this will save this 180KB of Flash space.
+
+The file encodings supported by FatFs are as follows:
+
+```c
+/* This option specifies the OEM code page to be used on the target system.
+/ Incorrect setting of the code page can cause a file open failure.
+/
+/ 1 - ASCII (No extended character. Non-LFN cfg. only)
+/ 437 - U.S.
+/ 720 - Arabic
+/ 737 - Greek
+/ 771 - KBL
+/ 775 - Baltic
+/ 850 - Latin 1
+/ 852 - Latin 2
+/ 855 - Cyrillic
+/ 857 - Turkish
+/ 860 - Portuguese
+/ 861 - Icelandic
+/ 862 - Hebrew
+/ 863 - Canadian French
+/ 864 - Arabic
+/ 865 - Nordic
+/ 866 - Russian
+/ 869 - Greek 2
+/ 932 - Japanese (DBCS)
+/ 936 - Simplified Chinese (DBCS)
+/ 949 - Korean (DBCS)
+/ 950 - Traditional Chinese (DBCS)
+*/
+```
+
+### File System Sector Size
+
+Specify the internal sector size of FatFs, which needs to be greater than or equal to the sector size of the actual hardware driver. For example, if a spi flash chip sector is 4096 bytes, the above macro needs to be changed to 4096. Otherwise, when the FatFs reads data from the driver, the array will be out of bounds and the system will crash (the new version gives a warning message when the system is executed) .
+
+Usually Flash device can be set to 4096, and the common TF card and SD card have a sector size of 512.
+
+### Reentrant
+
+FatFs fully considers the situation of multi-threaded safe read and write security. When reading and writing FafFs in multi-threading, in order to avoid the problems caused by re-entry, you need to open the macro above. If the system has only one thread to operate the file system and there is no reentrancy problem, you can turn it off to save resources.
+
+### More Configuration
+
+FatFs itself supports a lot of configuration options and the configuration is very flexible. The following file is a FatFs configuration file that can be modified to customize FatFs.
+
+```c
+components/dfs/filesystems/elmfat/ffconf.h
+```
+
+# DFS Application Example
+
+## FinSH Command
+
+After the file system is successfully mounted, the files and directories can be operated. The commonly used FinSH commands for file system operations are shown in the following table:
+
+|**FinSH Command** |**Description** |
+|--------|----------------------------------|
+| ls | display information about files and directories |
+| cd | enter the specified directory |
+| cp | copy file |
+| rm | delete the file or the directory |
+| mv | move the file or rename it |
+| echo | write the specified content to the specified file, write the file when it exists, and create a new file and write when the file does not exist. |
+| cat | display the contents of the file |
+| pwd | print out the current directory address |
+| mkdir | create a folder |
+| mkfs | formatted the file system |
+
+Use the `ls` command to view the current directory information, and the results are as follows:
+
+```c
+msh />ls # use the `ls` command to view the current directory information
+Directory /: # you can see that the root directory already exists /
+```
+
+Use the `mkdir` command to create a folder, and the results are as follows:
+
+```c
+msh />mkdir rt-thread # create an rt-thread folder
+msh />ls # view directory information as follows
+Directory /:
+rt-thread <DIR>
+```
+
+Use the `echo` command to output the input string to the specified output location. The result is as follows:
+
+```c
+msh />echo "hello rt-thread!!!" # outputs the string to standard output
+hello rt-thread!!!
+msh />echo "hello rt-thread!!!" hello.txt # output the string output to the hello.txt file
+msh />ls
+Directory /:
+rt-thread <DIR>
+hello.txt 18
+msh />
+```
+
+Use the `cat` command to view the contents of the file. The result is as follows:
+
+```c
+msh />cat hello.txt # view the contents of the hello.txt file and output
+hello rt-thread!!!
+```
+
+Use the `rm` command to delete a folder or file. The result is as follows:
+
+```c
+msh />ls # view the information of current directory
+Directory /:
+rt-thread <DIR>
+hello.txt 18
+msh />rm rt-thread # delete the rt-thread folder
+msh />ls
+Directory /:
+hello.txt 18
+msh />rm hello.txt # delete the hello.txt file
+msh />ls
+Directory /:
+msh />
+```
+
+## Read and Write File Examples
+
+Once the file system is working, you can run the application example. In the sample code, you first create a file `text.txt` using the `open()` function and write the string `"RT -Thread Programmer!\n"` in the file using the `write()` function, and then close the file. Use the ` open()` function again to open the `text.txt` file, read the contents and print it out, and close the file finally.
+
+The sample code is as follows:
+
+```c
+#include <rtthread.h>
+#include <dfs_posix.h> /* this header file need to be included when you need to operate the file */
+
+static void readwrite_sample(void)
+{
+ int fd, size;
+ char s[] = "RT-Thread Programmer!", buffer[80];
+
+ rt_kprintf("Write string %s to test.txt.\n", s);
+
+ /* open the ‘/text.txt’ file in create and read-write mode and create the file if it does not exist*/
+ fd = open("/text.txt", O_WRONLY | O_CREAT);
+ if (fd>= 0)
+ {
+ write(fd, s, sizeof(s));
+ close(fd);
+ rt_kprintf("Write done.\n");
+ }
+
+ /* open the ‘/text.txt’ file in read-only mode */
+ fd = open("/text.txt", O_RDONLY);
+ if (fd>= 0)
+ {
+ size = read(fd, buffer, sizeof(buffer));
+ close(fd);
+ rt_kprintf("Read from file test.txt : %s \n", buffer);
+ if (size < 0)
+ return ;
+ }
+ }
+/* export to the msh command list */
+MSH_CMD_EXPORT(readwrite_sample, readwrite sample);
+
+```
+
+## An Example of Changing the File Name
+
+The sample code in this section shows how to modify the file name. The program creates a function `rename_sample()` that manipulates the file and exports it to the msh command list. This function calls the `rename()` function to rename the file named `text.txt` to `text1.txt`. The sample code is as follows:
+
+```c
+#include <rtthread.h>
+#include <dfs_posix.h> /* this header file need to be included when you need to operate the file */
+
+static void rename_sample(void)
+{
+ rt_kprintf("%s => %s", "/text.txt", "/text1.txt");
+
+ if (rename("/text.txt", "/text1.txt") < 0)
+ rt_kprintf("[error!]\n");
+ else
+ rt_kprintf("[ok!]\n");
+}
+/* export to the msh command list */
+MSH_CMD_EXPORT(rename_sample, rename sample);
+```
+
+Run the example in the FinSH console and the results are as follows:
+
+```shell
+msh />echo "hello" text.txt
+msh />ls
+Directory /:
+text.txt 5
+msh />rename_sample
+/text.txt => /text1.txt [ok!]
+msh />ls
+Directory /:
+text1.txt 5
+```
+
+In the example demonstration, we first create a file named `text.txt` using the echo command, and then run the sample code to change the file name of the file `text.txt` to `text1.txt`.
+
+## Get File Status Example
+
+The sample code shows how to get the file status. The program creates a function `stat_sample()` that manipulates the file and exports it to the msh command list. This function calls the `stat()` function to get the file size information of the text.txt file. The sample code is as follows:
+
+```c
+#include <rtthread.h>
+#include <dfs_posix.h> /* this header file need to be included when you need to operate the file */
+
+static void stat_sample(void)
+{
+ int ret;
+ struct stat buf;
+ ret = stat("/text.txt", &buf);
+ if(ret == 0)
+ rt_kprintf("text.txt file size = %d\n", buf.st_size);
+ else
+ rt_kprintf("text.txt file not fonud\n");
+}
+/* export to the msh command list */
+MSH_CMD_EXPORT(stat_sample, show text.txt stat sample);
+```
+
+Run the example in the FinSH console and the results are as follows:
+
+```c
+msh />echo "hello" text.txt
+msh />stat_sample
+text.txt file size = 5
+```
+
+During the example run, the file `text.txt` is first created with the `echo` command, then the sample code is run, and the file size information for the file `text.txt` is printed.
+
+## Create a Directory Example
+
+The sample code in this section shows how to create a directory. The program creates a function file `mkdir_sample()` that manipulates the file and exports it to the msh command list, which calls the `mkdir()` function to create a folder called `dir_test`. The sample code is as follows:
+
+```c
+#include <rtthread.h>
+#include <dfs_posix.h> /* this header file need to be included when you need to operate the file */
+
+static void mkdir_sample(void)
+{
+ int ret;
+
+ /* create a directory */
+ ret = mkdir("/dir_test", 0x777);
+ if (ret < 0)
+ {
+ /* fail to create a directory */
+ rt_kprintf("dir error!\n");
+ }
+ else
+ {
+ /* create a directory successfully */
+ rt_kprintf("mkdir ok!\n");
+ }
+}
+/* export to the msh command list */
+MSH_CMD_EXPORT(mkdir_sample, mkdir sample);
+```
+
+Run the example in the FinSH console and the result is as follows:
+
+```shell
+msh />mkdir_sample
+mkdir ok!
+msh />ls
+Directory /:
+dir_test <DIR> # <DIR> it indicates that the type of the directory is a folder
+```
+
+This example demonstrates creating a folder named `dir_test` in the root directory.
+
+## Read directory Example
+
+The sample code shows how to read the directory. The program creates a function `readdir_sample()` that manipulates the file and exports it to the msh command list. This function calls the `readdir()` function to get the contents of the `dir_test` folder and print it out. The sample code is as follows:
+
+```c
+#include <rtthread.h>
+#include <dfs_posix.h> /* this header file need to be included when you need to operate the file */
+
+static void readdir_sample(void)
+{
+ DIR *dirp;
+ struct dirent *d;
+
+ /* open the / dir_test directory */
+ dirp = opendir("/dir_test");
+ if (dirp == RT_NULL)
+ {
+ rt_kprintf("open directory error!\n");
+ }
+ else
+ {
+ /* read the directory */
+ while ((d = readdir(dirp)) != RT_NULL)
+ {
+ rt_kprintf("found %s\n", d->d_name);
+ }
+
+ /* close the directory */
+ closedir(dirp);
+ }
+}
+/* exports to the msh command list */
+MSH_CMD_EXPORT(readdir_sample, readdir sample);
+```
+
+Run the example in the FinSH console and the result is as follows:
+
+```shell
+msh />ls
+Directory /:
+dir_test <DIR>
+msh />cd dir_test
+msh /dir_test>echo "hello" hello.txt # create a hello.txt file
+msh /dir_test>cd .. # switch to the parent folder
+msh />readdir_sample
+found hello.txt
+```
+
+In this example, first create a hello.txt file under the dir_test folder and exit the dir_test folder. At this point, run the sample program to print out the contents of the dir_test folder.
+
+## An Example of Setting the location of the read directory
+
+The sample code in this section shows how to set the location to read the directory next time. The program creates a function `telldir_sample()` that manipulates the file and exports it to the msh command list. This function first opens the root directory, then reads all the directory information in the root directory and prints the directory information. Meanwhile, use the `telldir()` function to record the location information of the third directory entry. Before reading the directory information in the root directory for the second time, use the `seekdir()` function to set the read location to the address of the third directory entry previously recorded. At this point, read the information in the root directory again, and the directory information is printed out. The sample code is as follows:
+
+```c
+#include <rtthread.h>
+#include <dfs_posix.h> /* this header file need to be included when you need to operate the file */
+
+/* assume that the file operation is done in one thread */
+static void telldir_sample(void)
+{
+ DIR *dirp;
+ int save3 = 0;
+ int cur;
+ int i = 0;
+ struct dirent *dp;
+
+ /* open the root directory */
+ rt_kprintf("the directory is:\n");
+ dirp = opendir("/");
+
+ for (dp = readdir(dirp); dp != RT_NULL; dp = readdir(dirp))
+ {
+ /* save the directory pointer for the third directory entry */
+ i++;
+ if (i == 3)
+ save3 = telldir(dirp);
+
+ rt_kprintf("%s\n", dp->d_name);
+ }
+
+ /* go back to the directory pointer of the third directory entry you just saved */
+ seekdir(dirp, save3);
+
+ /* Check if the current directory pointer is equal to the pointer to the third directory entry that was saved. */
+ cur = telldir(dirp);
+ if (cur != save3)
+ {
+ rt_kprintf("seekdir (d, %ld); telldir (d) == %ld\n", save3, cur);
+ }
+
+ /* start printing from the third directory entry */
+ rt_kprintf("the result of tell_seek_dir is:\n");
+ for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp))
+ {
+ rt_kprintf("%s\n", dp->d_name);
+ }
+
+ /* close the directory */
+ closedir(dirp);
+}
+/* exports to the msh command list */
+MSH_CMD_EXPORT(telldir_sample, telldir sample);
+```
+
+In this demo example, you need to manually create the five folders from `hello_1` to `hello_5` in the root directory with the `mkdir` command, making sure that there is a folder directory under the root directory for running the sample.
+
+Run the example in the FinSH console and the results are as follows:
+
+```shell
+msh />ls
+Directory /:
+hello_1 <DIR>
+hello_2 <DIR>
+hello_3 <DIR>
+hello_4 <DIR>
+hello_5 <DIR>
+msh />telldir_sample
+the directory is:
+hello_1
+hello_2
+hello_3
+hello_4
+hello_5
+the result of tell_seek_dir is:
+hello_3
+hello_4
+hello_5
+```
+
+After running the sample, you can see that the first time you read the root directory information, it starts from the first folder and prints out all the directory information in the root directory. When the directory information is printed for the second time, since the starting position of the reading is set to the position of the third folder by using the `seekdir()` function, the second time when reading the root directory is from the third folder. Start reading until the last folder, only the directory information from `hello_3` to `hello_5` is printed.
+
+# FAQ
+
+## Q: What should I do if I find that the file name or folder name is not displayed properly?
+
+ **A:** Check if long file name support is enabled, DFS feature configuration section.
+
+## Q: What should I do if the file system fails to initialize?
+
+ **A:** Check if the type and number of file systems allowed to be mounted in the file system configuration project are sufficient.
+
+## Q: What should I do if the file system *mkfs* command fails?
+
+ **A:** Check if the storage device exists. If it exists, check to see if the device driver can pass the function test, if it fails, check the driver error. Check if the libc function is enabled.
+
+## Q: What should I do if the file system fails to mount?
+
+**A:**
+
+- Check if the specified mount path exists. The file system can be mounted directly to the root directory ("/"), but if you want to mount it on another path, such as ("/sdcard"). You need to make sure that the ("/sdcard") path exists. Otherwise, you need to create the `sdcard` folder in the root directory before the mount is successful.
+- Check if the file system is created on the storage device. If there is no file system on the storage device, you need to create a file system on the storage using the `mkfs` command.
+
+## Q: What should I do if SFUD cannot detect the Flash specific model?
+
+ **A:**
+
+- Check if the hardware pin settings are wrong.
+- Whether the SPI device is already registered.
+- Whether the SPI device is mounted to the bus.
+- Check the `Using auto probe flash JEDEC SFDP parameter` and the `Using defined supported flash chip information table' under the 'RT-Thread Components → Device Drivers -> Using SPI Bus/Device device drivers -> Using Serial Flash Universal Driver` menu, to see whether the configuration item is selected, if it is not selected then you need to enable these two options.
+- If the storage device is still not recognized with the above option turned on, then issues can be raised in the [SFUD](https://github.com/armink/SFUD) project.
+
+## Q: Why does the benchmark test of the storage device take too long?
+
+**A:**
+
+ - Compare the [benchmark test data](https://github.com/armink/SFUD/blob/master/docs/zh/benchmark.txt) when the `system tick` is 1000 and the length of time required for this test. If the time lag is too large, you can think that the test work is not working properly.
+ - Check the settings of the system tick, because some delay operations will be determined according to the tick time, so you need to set the appropriate `system tick` value according to the system conditions. If the system's `system tick` value is no less than 1000, you will need to use a logic analyzer to check the waveform to determine that the communication rate is normal.
+
+## Q: SPI Flash implements elmfat file system, and how to keep some sectors not used by file system?
+
+ **A:** You can create multiple block devices for the entire storage device using the [partition](https://github.com/RT-Thread-packages/partition) tool package provided by RT-Thread. And block devices can be assigned different functions.
+
+## Q: What should I do if the program gets stuck during the test file system?
+
+ **A:** Try using the debugger or print some necessary debugging information to determine where the program is stuck and ask questions.
+
+## Q: How can I check the problem of the file system step by step?
+
+ **A:** You can step through the problem from the bottom to the top.
+
+- First check if the storage device is successfully registered and the function is normal.
+- Check if a file system is created in the storage device.
+- Check if the specified file system type is registered to the DFS framework, and often check if the allowed file system types and quantities are sufficient.
+- Check if DFS is successfully initialized. The initialization of this step is pure software, so the possibility of error is not high. It should be noted that if component auto-initialization is turned on, there is no need to manually initialize it again.
diff --git a/documentation/6.components/filesystem/figures/elm-fat-mkfs.png b/documentation/6.components/filesystem/figures/elm-fat-mkfs.png
new file mode 100644
index 0000000000..db4621db87
--- /dev/null
+++ b/documentation/6.components/filesystem/figures/elm-fat-mkfs.png
Binary files differ
diff --git a/documentation/6.components/filesystem/figures/fs-dir-mg.png b/documentation/6.components/filesystem/figures/fs-dir-mg.png
new file mode 100644
index 0000000000..d5d82fab66
--- /dev/null
+++ b/documentation/6.components/filesystem/figures/fs-dir-mg.png
Binary files differ
diff --git a/documentation/6.components/filesystem/figures/fs-dir.png b/documentation/6.components/filesystem/figures/fs-dir.png
new file mode 100644
index 0000000000..ecaca5329a
--- /dev/null
+++ b/documentation/6.components/filesystem/figures/fs-dir.png
Binary files differ
diff --git a/documentation/6.components/filesystem/figures/fs-layer.png b/documentation/6.components/filesystem/figures/fs-layer.png
new file mode 100644
index 0000000000..d380192109
--- /dev/null
+++ b/documentation/6.components/filesystem/figures/fs-layer.png
Binary files differ
diff --git a/documentation/6.components/filesystem/figures/fs-mg.png b/documentation/6.components/filesystem/figures/fs-mg.png
new file mode 100644
index 0000000000..11ef254079
--- /dev/null
+++ b/documentation/6.components/filesystem/figures/fs-mg.png
Binary files differ
diff --git a/documentation/6.components/filesystem/figures/fs-reg-block.png b/documentation/6.components/filesystem/figures/fs-reg-block.png
new file mode 100644
index 0000000000..c167e95376
--- /dev/null
+++ b/documentation/6.components/filesystem/figures/fs-reg-block.png
Binary files differ
diff --git a/documentation/6.components/filesystem/figures/fs-reg.png b/documentation/6.components/filesystem/figures/fs-reg.png
new file mode 100644
index 0000000000..d7bf43aca1
--- /dev/null
+++ b/documentation/6.components/filesystem/figures/fs-reg.png
Binary files differ
diff --git a/documentation/6.components/finsh/figures/finsh-hd.png b/documentation/6.components/finsh/figures/finsh-hd.png
new file mode 100644
index 0000000000..c48840ff58
--- /dev/null
+++ b/documentation/6.components/finsh/figures/finsh-hd.png
Binary files differ
diff --git a/documentation/6.components/finsh/figures/finsh-mdk.png b/documentation/6.components/finsh/figures/finsh-mdk.png
new file mode 100644
index 0000000000..1f7bbb8941
--- /dev/null
+++ b/documentation/6.components/finsh/figures/finsh-mdk.png
Binary files differ
diff --git a/documentation/6.components/finsh/figures/finsh-run.png b/documentation/6.components/finsh/figures/finsh-run.png
new file mode 100644
index 0000000000..647068131c
--- /dev/null
+++ b/documentation/6.components/finsh/figures/finsh-run.png
Binary files differ
diff --git a/documentation/6.components/finsh/finsh.md b/documentation/6.components/finsh/finsh.md
new file mode 100644
index 0000000000..e39b56c7e0
--- /dev/null
+++ b/documentation/6.components/finsh/finsh.md
@@ -0,0 +1,562 @@
+@page page_component_finsh FinSH Console
+
+In the early days of computer development, before the advent of graphics systems, there was no mouse or even a keyboard. How did people interact with computers at the time? The earliest computers used a punched note to enter commands into the computer and write the program. Later, with the continuous development of computers, monitors and keyboards became the standard configuration of computers, but the operating system at this time did not support the graphical interface. Computer pioneers developed a software that accepts commands entered by the user, and after interpretation, passes it to The operating system and return the results of the operating system execution to the user. This program wraps around the operating system like a layer of shell, so it's called a shell.
+
+Embedded devices usually need to connect the development board to the PC for communication. Common connections include: serial port, USB, Ethernet, Wi-Fi, etc. A flexible shell should also support working on multiple connection methods. With the shell, the developer can easily get the system running and control the operation of the system through commands. Especially in the debugging phase, with the shell, in addition to being able to locate the problem more quickly, the developer can also use the shell to call the test function, change the parameters of the test function, reduce the number of times the code is downloaded, and shorten the development time of the project.
+
+FinSH is the command line component (shell) of RT-Thread. It is based on the above considerations. FinSH is pronounced [ˈfɪnʃ]. After reading this chapter, we will have a deeper understanding of how FinSH works and how to export your own commands to FinSH.
+
+# Introduction of FinSH
+
+FinSH is the command line component of RT-Thread. It provides a set of operation interfaces for users to call from the command line. It is mainly used to debug or view system information. It can communicate with a PC using serial/Ethernet/USB, etc. The hardware topology is shown below:
+
+![FinSH Hardware connection diagram](figures/finsh-hd.png)
+
+The user inputs a command in the control terminal, and the control terminal transmits the command to the FinSH in the device through the serial port, USB, network, etc., FinSH will read the device input command, parse and automatically scan the internal function table, find the corresponding function name, and execute the function. The response is output, the response is returned through the original path, and the result is displayed on the control terminal.
+
+When using a serial port to connect a device to a control terminal, the execution flow of the FinSH command is as follows:
+
+![FinSH FinSH Command execution flow chart](figures/finsh-run.png)
+
+FinSH supports the rights verification function. After the system is started, the system will perform the rights verification. Only when the rights verification is passed, the FinSH function will be enabled. This improves the security of system input.
+
+FinSH supports auto-completion, and viewing history commands, etc. These functions can be easily accessed through the keys on the keyboard. The keys supported by FinSH are shown in the following table:
+
+|Keys| **Functional Description** |
+|----------|--------------|
+| Tab key | Pressing the Tab key when no characters are entered will print all commands supported by the current system. If you press the Tab key when you have entered some characters, it will find the matching command, and will also complete the file name according to the file system's current directory, and you can continue to input, multiple completions. |
+| ↑↓ key | Scroll up and down the recently entered history command |
+| Backspace key | Delete character |
+| ←→ key | Move the cursor left or right |
+
+FinSH supports two input modes, the traditional command line mode and the C language interpreter mode.
+
+## Traditional Command Line Mode
+
+This mode is also known as msh(module shell). In msh mode, FinSH is implemented in the same way as the traditional shell (dos/bash). For example, you can switch directories to the root directory with the `cd /` command.
+
+MSH can parse commands into parameters and parameters separated by spaces. Its command execution format is as follows:
+
+```
+command [arg1] [arg2] [...]
+```
+
+The command can be either a built-in command in RT-Thread or an executable file.
+
+## C Language Interpreter Mode
+
+This mode is also known as C-Style mode. In C language interpreter mode, FinSH can solve and parse most C language expressions, and use functions like C to access functions and global variables in the system. In addition, it can create variables through the command line. In this mode, the command entered must be similar to the function call in C language, that is, you must carry the `()` symbol. For example, to output all current threads and their status in the system, type `list_thread()` in FinSH to print out the required information. The output of the FinSH command is the return value of this function. For some functions that do not have a return value (void return value), this printout has no meaning.
+
+Initially FinSH only supported C-Style mode. Later, with the development of RT-Thread, C-Style mode is not convenient when running scripts or programs, and it is more convenient to use traditional shell method. In addition, in C-Style mode, FinSH takes up a lot of volume. For these reasons, the msh mode has been added to RT-Thread. The msh mode is small and easy to use. It is recommended that you use the msh mode.
+
+If both modes are enabled in the RT-Thread, they can be dynamically switched. Enter the `exit` in msh mode and press `Enter` to switch to C-Style mode. Enter `msh()` in C-Style mode and press `Enter` to enter msh mode. The commands of the two modes are not common, and the msh command cannot be used in C-Style mode, and vice versa.
+
+# FinSH Built-in Commands
+
+Some FinSH commands are built in by default in RT-Thread. You can print all commands supported by the current system by entering help in FinSH and pressing Enter or directly pressing Tab. The built-in commands in C-Style and msh mode are basically the same, so msh is taken as an example here.
+
+In msh mode, you can list all currently supported commands by pressing the Tab key. The number of default commands is not fixed, and the various components of RT-Thread will output some commands to FinSH. For example, when the DFS component is opened, commands such as `ls`, `cp`, and `cd` are added to FinSH for developers to debug.
+
+The following are all currently supported commands that display RT-Thread kernel status information after pressing the Tab key. The command name is on the left and the description of the command on the right:
+
+```c
+RT-Thread shell commands:
+version - show RT-Thread version information
+list_thread - list thread
+list_sem - list semaphore in system
+list_event - list event in system
+list_mutex - list mutex in system
+list_mailbox - list mail box in system
+list_msgqueue - list message queue in system
+list_timer - list timer in system
+list_device - list device in system
+exit - return to RT-Thread shell mode.
+help - RT-Thread shell help.
+ps - List threads in the system.
+time - Execute command with time.
+free - Show the memory usage in the system.
+```
+
+Here lists the field information returned after entering the common commands, so that the developer can understand the content of the returned information.
+
+## Display Thread Status
+
+Use the `ps` or `list_thread` command to list all thread information in the system, including thread priority, state, maximum stack usage, and more.
+
+```c
+msh />list_thread
+thread pri status sp stack size max used left tick error
+-------- --- ------- ---------- ---------- ------ ---------- ---
+tshell 20 ready 0x00000118 0x00001000 29% 0x00000009 000
+tidle 31 ready 0x0000005c 0x00000200 28% 0x00000005 000
+timer 4 suspend 0x00000078 0x00000400 11% 0x00000009 000
+```
+list_thread Return field description:
+
+|**Field** |**Description** |
+|------------|----------------------------|
+| thread | Thread name |
+| pri | Thread priority |
+| status | The current state of the thread |
+| sp | The current stack position of the thread |
+| stack size | Thread stack size |
+| max used | The maximum stack position used in thread history |
+| left tick | The number of remaining ticks of the thread |
+| error | Thread error code |
+
+## Display Semaphore Status
+
+Use the `list_sem` command to display all semaphore information in the system, including the name of the semaphore, the value of the semaphore, and the number of threads waiting for this semaphore.
+
+```c
+msh />list_sem
+semaphore v suspend thread
+-------- --- --------------
+shrx 000 0
+e0 000 0
+```
+
+list_sem Return field description:
+
+|**Field** | **Description** |
+|----------------|--------------------------|
+| semaphore | Semaphore name |
+| v | The current value of semaphore |
+| suspend thread | The number of threads waiting for this semaphore |
+
+## Display Event Status
+
+Use the `list_event` command to display all event information in the system, including the event name, the value of the event, and the number of threads waiting for this event.
+
+```c
+msh />list_event
+event set suspend thread
+----- ---------- --------------
+```
+
+list_event Return field description:
+
+| Field | **Description** |
+|----------------|----------------------------------|
+| event | Event set name |
+| set | The current event in the event set |
+| suspend thread | The number of threads waiting for an event in this event set |
+
+## Display Mutex Status
+
+Use the `list_mutex` command to display all mutex information in the system, including the mutex name, the owner of the mutex, and the number of nestings the owner holds on the mutex.
+
+```c
+msh />list_mutex
+mutex owner hold suspend thread
+-------- -------- ---- --------------
+fat0 (NULL) 0000 0
+sal_lock (NULL) 0000 0
+```
+
+list_mutex Return field description:
+
+| **Field** | **Description** |
+|----------------|------------------------------------|
+| mutxe | Mutex name |
+| owner | The thread currently holding the mutex |
+| hold | The number of times the holder is nested on this mutex |
+| suspend thread | The number of threads waiting for this mutex |
+
+## Display Mailbox Status
+
+Use the `list_mailbox` command to display all mailbox information in the system, including the mailbox name, the number of messages in the mailbox, and the maximum number of messages the mailbox can hold.
+
+```c
+msh />list_mailbox
+mailbox entry size suspend thread
+-------- ---- ---- --------------
+etxmb 0000 0008 1:etx
+erxmb 0000 0008 1:erx
+```
+
+list_mailbox Return field description:
+
+| Field | **Description** |
+|----------------|----------------------------|
+| mailbox | Mailbox name |
+| entry | The number of messages included in the mailbox |
+| size | The maximum number of messages a mailbox can hold |
+| suspend thread | The number of threads waiting for this mailbox |
+
+## Display Message Queue Status
+
+Use the `list_msgqueue` command to display all message queue information in the system, including the name of the message queue, the number of messages it contains, and the number of threads waiting for this message queue.
+
+```c
+msh />list_msgqueue
+msgqueue entry suspend thread
+-------- ---- --------------
+```
+
+list_msgqueue Return field description:
+
+| Field | **Description** |
+|----------------|----------------------------|
+| msgqueue | Message queue name |
+| entry | The number of messages currently included in the message queue |
+| suspend thread | Number of threads waiting for this message queue |
+
+## Display Memory Pool Status
+
+Use the `list_mempool` command to display all the memory pool information in the system, including the name of the memory pool, the size of the memory pool, and the maximum memory size used.
+
+```c
+msh />list_mempool
+mempool block total free suspend thread
+------- ---- ---- ---- --------------
+signal 0012 0032 0032 0
+```
+
+list_mempool Return field description:
+
+| Field | **Description** |
+|----------------|--------------------|
+| mempool | Memory pool name |
+| block | Memory block size |
+| total | Total memory block |
+| free | Free memory block |
+| suspend thread | The number of threads waiting for this memory pool |
+
+## Display Timer Status
+
+Use the `list_timer` command to display all the timer information in the system, including the name of the timer, whether it is the periodic timer, and the number of beats of the timer timeout.
+
+```c
+msh />list_timer
+timer periodic timeout flag
+-------- ---------- ---------- -----------
+tshell 0x00000000 0x00000000 deactivated
+tidle 0x00000000 0x00000000 deactivated
+timer 0x00000000 0x00000000 deactivated
+```
+
+list_timer Return field description:
+
+| Field | **Description** |
+|----------|--------------------------------|
+| timer | Timer name |
+| periodic | Whether the timer is periodic |
+| timeout | The number of beats when the timer expires |
+| flag | The state of the timer, activated indicates active, and deactivated indicates inactive |
+
+## Display Device Status
+
+Use the `list_device` command to display all device information in the system, including the device name, device type, and the number of times the device was opened.
+
+```c
+msh />list_device
+device type ref count
+------ ----------------- ----------
+e0 Network Interface 0
+uart0 Character Device 2
+```
+
+list_device Return field description:
+
+| Field | Description |
+|-----------|----------------|
+| device | Device name |
+| type | Device type |
+| ref count | The number of times the device was opened |
+
+## Display Dynamic Memory Status
+
+Use the `free` command to display all memory information in the system.
+
+```c
+msh />free
+total memory: 7669836
+used memory : 15240
+maximum allocated memory: 18520
+```
+
+free Return field description:
+
+| Field | Description |
+|--------------------------|------------------|
+| total memory | Total memory size |
+| used memory | Used memory size |
+| maximum allocated memory | Maximum allocated memory |
+
+# Custom FinSH Command
+
+In addition to the commands that come with FinSH, FinSH also provides multiple macro interfaces to export custom commands. The exported commands can be executed directly in FinSH.
+
+## Custom msh Command
+
+The custom msh command can be run in msh mode. To export a command to msh mode, you can use the following macro interface:
+
+```
+MSH_CMD_EXPORT(name, desc);
+```
+
+|**Parameter**|**Description** |
+|----------|----------------|
+| name | The command to export |
+| desc | Description of the export command |
+
+This command can export commands with parameters, or export commands without parameters. When exporting a parameterless command, the input parameter of the function is void. The example is as follows:
+
+```c
+void hello(void)
+{
+ rt_kprintf("hello RT-Thread!\n");
+}
+
+MSH_CMD_EXPORT(hello , say hello to RT-Thread);
+```
+
+When exporting a command with parameters, the function's input parameters are `int argc` and `char**argv`. Argc represents the number of arguments, and argv represents a pointer to a command-line argument string pointer array. An example of exporting a parameter command is as follows:
+
+```c
+static void atcmd(int argc, char**argv)
+{
+ ……
+}
+
+MSH_CMD_EXPORT(atcmd, atcmd sample: atcmd <server|client>);
+```
+
+## Custom C-Style Commands and Variables
+
+Export custom commands to C-Style mode can use the following interface:
+
+```
+FINSH_FUNCTION_EXPORT(name, desc);
+```
+
+|**Parameter**| **Description** |
+|----------|----------------|
+| name | The command to export |
+| desc | Description of the export command |
+
+The following example defines a `hello` function and exports it as a command in C-Style mode:
+
+```c
+void hello(void)
+{
+ rt_kprintf("hello RT-Thread!\n");
+}
+
+FINSH_FUNCTION_EXPORT(hello , say hello to RT-Thread);
+```
+
+In a similar way, you can also export a variable that can be accessed through the following interface:
+
+```
+FINSH_VAR_EXPORT(name, type, desc);
+```
+
+| Parameter | **Description** |
+|----------|----------------|
+| name | The variable to be exported |
+| type | Type of variable |
+| desc | Description of the exported variable |
+
+The following example defines a `dummy` variable and exports it to a variable command in C-Style mode.:
+
+```c
+static int dummy = 0;
+FINSH_VAR_EXPORT(dummy, finsh_type_int, dummy variable for finsh)
+```
+## Custom Command Rename
+
+The function name length of FinSH is limited. It is controlled by the macro definition `FINSH_NAME_MAX` in `finsh.h`. The default is 16 bytes, which means that the FinSH command will not exceed 16 bytes in length. There is a potential problem here: when a function name is longer than FINSH_NAME_MAX, after using FINSH_FUNCTION_EXPORT to export the function to the command table, the full function name is seen in the FinSH symbol table, but a full node execution will result in a *null node* error. This is because although the full function name is displayed, in fact FinSH saves the first 16 bytes as a command. Too many inputs will result in the command not being found correctly. In this case, you can use `FINSH_FUNCTION_EXPORT_ALIAS` to re-export the command name.
+
+```
+FINSH_FUNCTION_EXPORT_ALIAS(name, alias, desc);
+```
+
+| Parameter | Description |
+|----------|-------------------------|
+| name | The command to export |
+| alias | The name that is displayed when exporting to FinSH |
+| desc | Description of the export command |
+
+The command can be exported to msh mode by adding `__cmd_` to the renamed command name. Otherwise, the command will be exported to C-Style mode. The following example defines a `hello` function and renames it to `ho` and exports it to a command in C-Style mode.
+
+```c
+void hello(void)
+{
+ rt_kprintf("hello RT-Thread!\n");
+}
+
+FINSH_FUNCTION_EXPORT_ALIAS(hello , ho, say hello to RT-Thread);
+```
+# FinSH Function Configuration
+
+The FinSH function can be cropped, and the macro configuration options are defined in the rtconfig.h file. The specific configuration items are shown in the following table.
+
+| **Macro Definition** | **Value Type** | Description | Default |
+|-----------------------------------|----------------|------------------------------------------------------------|---------|
+| `#define RT_USING_FINSH` | None | Enable FinSH | on |
+| `#define FINSH_THREAD_NAME` | String | FinSH thread name | "tshell"|
+| `#define FINSH_USING_HISTORY` | None | Turn on historical traceback | on |
+| `#define FINSH_HISTORY_LINES` | Integer type | Number of historical command lines that can be traced back | 5 |
+| `#define FINSH_USING_SYMTAB` | None | Symbol table can be used in FinSH | on |
+| `#define FINSH_USING_DESCRIPTION` | None | Add a description to each FinSH symbol | on |
+| `#define FINSH_USING_MSH` | None | Enable msh mode | on |
+| `#define FINSH_USING_MSH_ONLY` | None | Use only msh mode | on |
+| `#define FINSH_ARG_MAX` | Integer type | Maximum number of input parameters | 10 |
+| `#define FINSH_USING_AUTH` | None | Enable permission verification | off |
+| `#define FINSH_DEFAULT_PASSWORD` | String | Authority verification password | off |
+
+The reference configuration example in rtconfig.h is as follows, and can be configured according to actual functional requirements.
+
+```c
+/* Open FinSH */
+#define RT_USING_FINSH
+
+/* Define the thread name as tshell */
+#define FINSH_THREAD_NAME "tshell"
+
+/* Open history command */
+#define FINSH_USING_HISTORY
+/* Record 5 lines of history commands */
+#define FINSH_HISTORY_LINES 5
+
+/* Enable the use of symbol table */
+#define FINSH_USING_SYMTAB
+/* Turn on description */
+#define FINSH_USING_DESCRIPTION
+
+/* Define FinSH thread priority to 20 */
+#define FINSH_THREAD_PRIORITY 20
+/* Define the stack size of the FinSH thread to be 4KB */
+#define FINSH_THREAD_STACK_SIZE 4096
+/* Define the command character length to 80 bytes */
+#define FINSH_CMD_SIZE 80
+
+/* Open msh function */
+#define FINSH_USING_MSH
+/* Use msh function by default */
+#define FINSH_USING_MSH_DEFAULT
+/* The maximum number of input parameters is 10 */
+#define FINSH_ARG_MAX 10
+```
+
+# FinSH Application Examples
+
+## Examples of msh Command without Arguments
+
+This section demonstrates how to export a custom command to msh. The sample code is as follows, the hello function is created in the code, and the `hello` function can be exported to the FinSH command list via the `MSH_CMD_EXPORT` command.
+
+```c
+#include <rtthread.h>
+
+void hello(void)
+{
+ rt_kprintf("hello RT-Thread!\n");
+}
+
+MSH_CMD_EXPORT(hello , say hello to RT-Thread);
+```
+
+Once the system is up and running, press the tab key in the FinSH console to see the exported command:
+
+```c
+msh />
+RT-Thread shell commands:
+hello - say hello to RT-Thread
+version - show RT-Thread version information
+list_thread - list thread
+……
+```
+
+Run the `hello` command and the results are as follows:
+
+```c
+msh />hello
+hello RT_Thread!
+msh />
+```
+
+## Example of msh Command with Parameters
+
+This section demonstrates how to export a custom command with parameters to FinSH. The sample code is as follows, the `atcmd()` function is created in the code, and the `atcmd()` function can be exported to the msh command list via the MSH_CMD_EXPORT command.
+
+```c
+#include <rtthread.h>
+
+static void atcmd(int argc, char**argv)
+{
+ if (argc < 2)
+ {
+ rt_kprintf("Please input'atcmd <server|client>'\n");
+ return;
+ }
+
+ if (!rt_strcmp(argv[1], "server"))
+ {
+ rt_kprintf("AT server!\n");
+ }
+ else if (!rt_strcmp(argv[1], "client"))
+ {
+ rt_kprintf("AT client!\n");
+ }
+ else
+ {
+ rt_kprintf("Please input'atcmd <server|client>'\n");
+ }
+}
+
+MSH_CMD_EXPORT(atcmd, atcmd sample: atcmd <server|client>);
+```
+
+Once the system is running, press the Tab key in the FinSH console to see the exported command:
+
+```c
+msh />
+RT-Thread shell commands:
+hello - say hello to RT-Thread
+atcmd - atcmd sample: atcmd <server|client>
+version - show RT-Thread version information
+list_thread - list thread
+……
+```
+
+Run the `atcmd` command and the result is as follows:
+
+```c
+msh />atcmd
+Please input 'atcmd <server|client>'
+msh />
+```
+
+Run the `atcmd server` command and the result is as follows:
+
+```c
+msh />atcmd server
+AT server!
+msh />
+```
+
+Run the `atcmd client` command and the result is as follows:
+
+```c
+msh />atcmd client
+AT client!
+msh />
+```
+
+# FinSH Porting
+
+FinSH is written entirely in ANSI C and has excellent portability; it has a small memory footprint, and FinSH will not dynamically request memory if you do not use the functions described in the previous section to dynamically add symbols to FinSH. The FinSH source is located in the `components/finsh` directory. Porting FinSH requires attention to the following aspects:
+
+* FinSH thread:
+
+Each command execution is done in the context of a FinSH thread (that is, a tshell thread). When the RT_USING_FINSH macro is defined, the FinSH thread can be initialized by calling `finsh_system_init()` in the initialization thread. In RT-Thread 1.2.0 and later, you don't have to use the `finsh_set_device(const char* device_name)` function to explicitly specify the device to be used. Instead, the `rt_console_get_device()` function is called automatically to use the console device (The `finsh_set_device(const char* device_name)` must be used in 1.1.x and below to specify the device used by FinSH. The FinSH thread is created in the function `finsh_system_init()` function, which will wait for the rx_sem semaphore.
+
+* FinSH output:
+
+The output of FinSH depends on the output of the system and relies on the `rt_kprintf()` output in RT-Thread. In the startup function `rt_hw_board_init()`, the `rt_console_set_device(const char* name)` function sets the FinSH printout device.
+
+* FinSH input:
+
+After the rin_sem semaphore is obtained, the FinSH thread calls the `rt_device_read()` function to obtain a character from the device (select serial device) and then process it. So the migration of FinSH requires the implementation of the `rt_device_read()` function. The release of the rx_sem semaphore completes the input notification to the FinSH thread by calling the `rx_indicate()` function. The usual process is that when the serial port receive interrupt occurs (that is, the serial port has input character), the interrupt service routine calls the `rx_indicate()` function to notify the FinSH thread that there is input, and then the FinSH thread obtains the serial port input and finally performs the corresponding command processing.
diff --git a/documentation/6.components/network/figures/net-hello.png b/documentation/6.components/network/figures/net-hello.png
new file mode 100644
index 0000000000..aec33b859c
--- /dev/null
+++ b/documentation/6.components/network/figures/net-hello.png
Binary files differ
diff --git a/documentation/6.components/network/figures/net-layer.png b/documentation/6.components/network/figures/net-layer.png
new file mode 100644
index 0000000000..9e896f44cf
--- /dev/null
+++ b/documentation/6.components/network/figures/net-layer.png
Binary files differ
diff --git a/documentation/6.components/network/figures/net-osi.png b/documentation/6.components/network/figures/net-osi.png
new file mode 100644
index 0000000000..aecb790e2d
--- /dev/null
+++ b/documentation/6.components/network/figures/net-osi.png
Binary files differ
diff --git a/documentation/6.components/network/figures/net-recv.png b/documentation/6.components/network/figures/net-recv.png
new file mode 100644
index 0000000000..23461838a3
--- /dev/null
+++ b/documentation/6.components/network/figures/net-recv.png
Binary files differ
diff --git a/documentation/6.components/network/figures/net-send.png b/documentation/6.components/network/figures/net-send.png
new file mode 100644
index 0000000000..aa4777d544
--- /dev/null
+++ b/documentation/6.components/network/figures/net-send.png
Binary files differ
diff --git a/documentation/6.components/network/figures/net-tcp-s.png b/documentation/6.components/network/figures/net-tcp-s.png
new file mode 100644
index 0000000000..5d07186f96
--- /dev/null
+++ b/documentation/6.components/network/figures/net-tcp-s.png
Binary files differ
diff --git a/documentation/6.components/network/figures/net-tcp.png b/documentation/6.components/network/figures/net-tcp.png
new file mode 100644
index 0000000000..c13a25c308
--- /dev/null
+++ b/documentation/6.components/network/figures/net-tcp.png
Binary files differ
diff --git a/documentation/6.components/network/figures/net-udp-client.png b/documentation/6.components/network/figures/net-udp-client.png
new file mode 100644
index 0000000000..c0e916b421
--- /dev/null
+++ b/documentation/6.components/network/figures/net-udp-client.png
Binary files differ
diff --git a/documentation/6.components/network/figures/net-udp-server.png b/documentation/6.components/network/figures/net-udp-server.png
new file mode 100644
index 0000000000..79d1513c2a
--- /dev/null
+++ b/documentation/6.components/network/figures/net-udp-server.png
Binary files differ
diff --git a/documentation/6.components/network/figures/net-udp.png b/documentation/6.components/network/figures/net-udp.png
new file mode 100644
index 0000000000..cea06a21e3
--- /dev/null
+++ b/documentation/6.components/network/figures/net-udp.png
Binary files differ
diff --git a/documentation/6.components/network/network.md b/documentation/6.components/network/network.md
new file mode 100644
index 0000000000..1c20474856
--- /dev/null
+++ b/documentation/6.components/network/network.md
@@ -0,0 +1,779 @@
+@page page_component_network Network Framework
+
+With the popularity of the Internet, people's lives are increasingly dependent on the application of the network. More and more products need to connect to the Internet, and device networking has become a trend. To achieve the connection between the device and the network, you need to follow the TCP/IP protocol, you can run the network protocol stack on the device to connect to the network, or you can use devices (chips with hardware network protocol stack interfaces) to connect to the Internet.
+
+When the device is connected to the network, it is like plugging in the wings. You can use the network to upload data in real time. The user can see the current running status and collected data of the device in a hundred thousand miles, and remotely control the device to complete specific tasks. You can also play online music, make online calls, and act as a LAN storage server through your device.
+
+This chapter will explain the related content of the RT-Thread network framework, and introduce you to the concept, function and usage of the network framework. After reading this chapter, you will be familiar with the concept and implementation principle of the RT-Thread network framework and familiar with network programming using Socket API.
+
+# TCP/IP Introduction to Network Protocols
+
+TCP/IP is short for Transmission Control Protocol/Internet Protocol. It is not a single protocol, but a general term for a protocol family. It includes IP protocol, ICMP protocol, TCP protocol, and http and ftp, pop3, https protocol, etc., which define how electronic devices connect to the Internet and the standards by which data is transferred between them.
+
+## OSI Reference Model
+
+OSI (Open System Interconnect), which is an open system interconnection. Generally referred to as the OSI reference model, it is a network interconnection model studied by the ISO (International Organization for Standardization) in 1985. The architecture standard defines a seven-layer framework for the network interconnection (physical layer, data link layer, network layer, transport layer, session layer, presentation layer, and application layer), that is, the ISO open system interconnection reference model. The first to third layers belong to the lower three layers of the OSI Reference Model and are responsible for creating links for network communication connections; the fourth to seventh layers are the upper four layers of the OSI reference model and is responsible for end-to-end data communication. The capabilities of each layer are further detailed in this framework to achieve interconnectivity, interoperability, and application portability in an open system environment.
+
+## TCP/IP Reference Model
+
+The TCP/IP communication protocol uses a four-layer hierarchical structure, and each layer calls the network provided by its next layer to fulfill its own needs. The four layers are:
+
+* **Application layer**: Different types of network applications have different communication rules, so the application layer protocols are various, such as Simple Mail Transfer Protocol (SMTP), File Transfer Protocol (FTP), and network remote access protocol (Telnet).
+* **Transport layer**: In this layer, it provides data transfer services between nodes, such as Transmission Control Protocol (TCP), User Datagram Protocol (UDP), etc. TCP and UDP add data to the data packet and transmit it to the next layer, this layer is responsible for transmitting data and determining that the data has been delivered and received.
+* **Network layer**: responsible for providing basic data packet transfer functions, so that each packet can reach the destination host (but not check whether it is received correctly), such as Internet Protocol (IP).
+* **Network interface layer**: Management of actual network media, defining how to use actual networks (such as Ethernet, Serial Line, etc.) to transmit data.
+
+## Difference between TCP/IP Reference Model and OSI Reference Model
+
+The following figure shows the TCP/IP reference model and the OSI reference model diagram:
+
+![TCP/IP Reference Model and OSI Reference Model](figures/net-osi.png)
+
+Both the OSI reference model and the TCP/IP reference model are hierarchical, based on the concept of a separate protocol stack. The OSI reference model has 7 layers, while the TCP/IP reference model has only 4 layers, that is, the TCP/IP reference model has no presentation layer and session layer, and the data link layer and physical layer are merged into a network interface layer. However, there is a certain correspondence between the two layers. Due to the complexity of the OSI system and the design prior to implementation, many designs are too ideal and not very convenient for software implementation. Therefore, there are not many systems that fully implement the OSI reference model, and the scope of application is limited. The TCP/IP reference model was first implemented in a computer system. It has a stable implementation on UNIX and Windows platforms, and provides a simple and convenient programming interface (API) on which a wide range of applications are developed. The TCP/IP reference model has become the international standard and industry standard for Internet connectivity.
+
+## IP Address
+
+The IP address refers to the Internet Protocol Address (also translated as the Internet Protocol Address) and is a uniform address format that assigns a logical address to each network and each host on the Internet to mask physical address differences provided by Internet Protocol. The common LAN IP address is 192.168.X.X.
+
+## Subnet Mask
+
+Subnet mask (also called netmask, address mask), which is used to indicate which bits of an IP address identify the subnet where the host is located, and which bits are identified as the bit mask of the host. The subnet mask cannot exist alone, it must be used in conjunction with an IP address. Subnet mask has only one effect, which is to divide an IP address into two parts: network address and host address. The subnet mask is the bit of 1, the IP address is the network address, the subnet mask is the bit of 0, and the IP address is the host address. Taking the IP address 192.168.1.10 and the subnet mask 255.255.255.0 as an example, the first 24 bits of the subnet mask (converting decimal to binary) is 1, so the first 24 bits of the IP address 192.168.1 represent the network address. The remaining 0 is the host address.
+
+## MAC Address
+
+MAC (figures Access Control or Medium Access Control) address, which is translated as media access control, or physical address, hardware address, used to define the location of network devices. In OSI model, the third layer network Layer is responsible for IP address, the second layer data link layer is responsible for the MAC address. A host will have at least one MAC address.
+
+# Introduction to the Network Framework of RT-Thread
+
+In order to support various network protocol stacks, RT-Thread has developed a **SAL** component, the full name of the **Socket abstraction layer**. RT-Thread can seamlessly access various protocol stacks, including several commonly used TCP/IP protocol stack, such as the LwIP protocol stack commonly used in embedded development and the AT Socket protocol stack component developed by RT-Thread, which complete the conversion of data from the network layer to the transport layer.
+
+The main features of the RT-Thread network framework are as follows:
+
+* Support for standard network sockets BSD Socket API, support for poll/select
+* Abstract, unified multiple network protocol stack interfaces
+* Support various physical network cards, network communication module hardware
+* The resource occupancy of SAL socket abstraction layer component is small: ROM 2.8K and RAM 0.6K.
+
+RT-Thread's network framework adopts a layered design with four layers, each layer has different responsibilities. The following figure shows the RT-Thread network framework structure:
+
+![RT-Thread network framework structure](figures/net-layer.png)
+
+The network framework provides a standard BSD Socket interface to user applications. Developers use the BSD Socket interface to operate without worrying about how the underlying network is implemented, and no need to care which network protocol stack the network data passes through. The socket abstraction layer provides the upper application layer. The interfaces are: `accept`, `connect`, `send`, `recv`, etc.
+
+Below the SAL layer is the protocol stack layer. The main protocol stacks supported in the current network framework are as follows:
+
+* **LwIP** is an open source TCP/IP protocol stack implementation that reduces RAM usage while maintaining the main functionality of the TCP/IP protocol, making the LwIP protocol stack ideal for use in embedded systems.
+* **AT Socket** is a component for modules that support AT instructions. The AT command uses a standard serial port for data transmission and reception, and converts complex device communication methods into simple serial port programming, which greatly simplifies the hardware design and software development costs of the product, which makes almost all network modules such as GPRS, 3G/4G, NB-IoT, Bluetooth, WiFi, GPS and other modules are very convenient to access the RT-Thread network framework, develop network applications through the standard BSD Socket method, greatly simplifying the development of upper-layer applications.
+* **Socket CAN** is a way of programming CAN, it is easy to use and easy to program. By accessing the SAL layer, developers can implement Socket CAN programming on RT-Thread.
+
+Below the protocol stack layer is an abstract device layer that is connected to various network protocol stacks by abstracting hardware devices into Ethernet devices or AT devices.
+
+The bottom layer is a variety of network chips or modules (for example: Ethernet chips with built-in protocol stack such as W5500/CH395, WiFi module with AT command, GPRS module, NB-IoT module, etc.). These hardware modules are the carrier that truly performs the network communication function and is responsible for communicating with various physical networks.
+
+In general, the RT-Thread network framework allows developers to only care about and use the standard BSD Socket network interface for network application development, without concern for the underlying specific network protocol stack type and implementation, greatly improving system compatibility and convenience. Developers have completed the development of network-related applications, and have greatly improved the compatibility of RT-Thread in different areas of the Internet of Things.
+
+In addition, based on the network framework, RT-Thread provides a large number of network software packages, which are various network applications based on the SAL layer, such as **Paho MQTT**, **WebClient**, **cJSON**, **netutils**, etc., which can be obtained from the online package management center. These software packages are web application tools. Using them can greatly simplify the development of network applications and shorten the network application development cycle. At present, there are more than a dozen network software packages. The following table lists some of the network software packages currently supported by RT-Thread, and the number of software packages is still increasing.
+
+| **Package Name** | **Description** |
+| ---------------- | ------------------------------------------------------------ |
+| Paho MQTT | Based on Eclipse open source Paho MQTT, it has done a lot of functions and performance optimization, such as: increased automatic reconnection after disconnection, pipe model, support for non-blocking API, support for TLS encrypted transmission, etc. |
+| WebClient | Easy-to-use HTTP client with support for HTTP GET/POST and other common request functions, support for HTTPS, breakpoint retransmission, etc. |
+| mongoose | Embedded Web server network library, similar to Nginx in the embedded world. Licensing is not friendly enough, business needs to be charged |
+| WebTerminal | Access Finsh/MSH Shell packages in the browser or on the mobile |
+| cJSON | Ultra-lightweight JSON parsing library |
+| ljson | Json to struct parsing, output library |
+| ezXML | XML file parsing library, currently does not support parsing XML data |
+| nanopb | Protocol Buffers format data parsing library, Protocol Buffers format takes up less resources than JSON, XML format resources |
+| GAgent | Software package for accessing Gizwits Cloud Platform |
+| Marvell WiFi | Marvell WiFi driver |
+| Wiced WiFi | WiFi driver for Wiced interface |
+| CoAP | Porting libcoap's CoAP communication package |
+| nopoll | Ported open source WebSocket communication package |
+| netutils | A collection of useful network debugging gadgets, including: ping, TFTP, iperf, NetIO, NTP, Telnet, etc. |
+| OneNet | Software for accessing China Mobile OneNet Cloud |
+
+# Network Framework Workflow
+
+Using the RT-Thread network framework, you first need to initialize the SAL, then register various network protocol clusters to ensure that the application can communicate using the socket network socket interface. This section mainly uses LwIP as an example.
+
+## Register the Network Protocol Cluster
+
+First use the `sal_init()` interface to initialize resources such as mutex locks used in the component. The interface looks like this:
+
+```c
+int sal_init(void);
+```
+
+After the SAL is initialized, then use the the `sal_proto_family_register()` interface to register network protocol cluster, for example, the LwIP network protocol cluster is registered to the SAL. The sample code is as follows:
+
+```c
+static const struct proto_family LwIP_inet_family_ops = {
+ "LwIP",
+ AF_INET,
+ AF_INET,
+ inet_create,
+ LwIP_gethostbyname,
+ LwIP_gethostbyname_r,
+ LwIP_freeaddrinfo,
+ LwIP_getaddrinfo,
+};
+
+int LwIP_inet_init(void)
+{
+ sal_proto_family_register(&LwIP_inet_family_ops);
+
+ return 0;
+}
+```
+
+`AF_INET` stands for IPv4 address, for example 127.0.0.1; `AF` is short for "Address Family" and `INET` is short for "Internet".
+
+The `sal_proto_family_register()` interface is defined as follows:
+
+```
+int sal_proto_family_register(const struct proto_family *pf);
+```
+
+|**Parameters**|**Description** |
+|----------|------------------|
+| pf | Protocol cluster structure pointer |
+|**Return**|**——** |
+| 0 | registration success |
+| -1 | registration failed |
+
+## Network Data Receiving Process
+
+After the LwIP is registered to the SAL, the application can send and receive network data through the network socket interface. In LwIP, several main threads are created, and they are `tcpip` thread, `erx` receiving thread and `etx` sending thread. The network data receiving process is as shown in the following picture. The application receives data by calling the standard socket interface `recv()` with blocking mode. When the Ethernet hardware device receives the network data packet, it stores the packet in the receiving buffer, and then sends an email to notify the `erx` thread that the data arrives through the Ethernet interrupt program. The `erx` thread applies for the `pbuf` memory block according to the received data length and put the data into the pbuf's `payload` data, then send the `pbuf` memory block to the `tcpip` thread via mailbox, and the `tcpip` thread returns the data to the application that is blocking the receiving data.
+
+![Data receiving function call flow chart](figures/net-recv.png)
+
+## Network Data Sending Process
+
+The network data sending process is shown in the figure below. When there is data to send, the application calls the standard network socket interface `send()` to hand the data to the `tcpip` thread. The `tcpip` thread sends a message to wake up the `etx` thread. The `etx` thread first determines if the Ethernet is sending data. If data is not being sent, it will put the data to be sent into the send buffer, and then send the data through the Ethernet device. If data is being sent, the `etx` thread suspends itself until the Ethernet device is idle before sending the data out.
+
+![Data sending function call flow chart](figures/net-send.png)
+
+# Network Socket Programming
+
+The application uses Socket (network socket) interface programming to implement network communication functions. Socket is a set of application program interface (API), which shields the communication details of each protocol, so that the application does not need to pay attention to the protocol itself, directly using the interfaces provide by socket to communicate between different hosts interconnected.
+
+## TCP socket Communication Process
+
+TCP(Tranfer Control Protocol) is a connection-oriented protocol to ensure reliable data transmission. Through the TCP protocol transmission, a sequential error-free data stream is obtained. The TCP-based socket programming flow diagram is shown in the following figure. A connection must be established between the sender and the receiver's two sockets in order to communicate on the basis of the TCP protocol. When a socket (usually a server socket) waits for a connection to be established. Another socket can request a connection. Once the two sockets are connected, they can perform two-way data transmission, and both sides can send or receive data. A TCP connection is a reliable connection that guarantees that packets arrive in order, and if a packet loss occurs, the packet is automatically resent.
+
+For example, TCP is equivalent to calling in life. When you call the other party, you must wait for the other party to answer. Only when the other party answers your call can he/she establish a connection with you. The two parties can talk and pass information to each other. Of course, the information passed at this time is reliable, because the other party can't hear what you said and can ask you to repeat the content again. When either party on the call wants to end the call, they will bid farewell to the other party and wait until the other party bids farewell to them before they hang up and end the call.
+
+![TCP-based socket programming flow chart](figures/net-tcp.png)
+
+## UDP socket Communication Process
+
+UDP is short for User Datagram Protocol. It is a connectionless protocol. Each datagram is a separate information, including the complete source address and destination address. It is transmitted to the destination on the network in any possible path. Therefore, whether the destination can be reached, the time to reach the destination, and the correctness of the content cannot be guaranteed. The UDP-based socket programming flow is shown in the following figure.
+
+![UDP-based socket programming flow](figures/net-udp.png)
+
+For example, UDP is equivalent to the walkie-talkie communication in life. After you set up the channel, you can directly say the information you want to express. The data is sent out by the walkie-talkie, but you don't know if your message has been received by others. By the way, unless someone else responds to you with a walkie-talkie. So this method is not reliable.
+
+## Create a Socket
+
+Before communicating, the communicating parties first use the `socket()` interface to create a socket, assigning a socket descriptor and its resources based on the specified address family, data type, and protocol. The interface is as follows:
+
+```c
+int socket(int domain, int type, int protocol);
+```
+
+|**Parameters**|**Description** |
+|----------|--------------------------------------------------|
+| domain | Protocol family |
+| type | Specify the communication type, including values SOCK_STREAM and SOCK_DGRAM. |
+| protocol | Protocol allows to specify a protocol for the socket, which is set to 0 by default. |
+|**Return**|**——** |
+| >=0 | Successful, returns an integer representing the socket descriptor |
+| -1 | Fail |
+
+**Communication types** include SOCK_STREAM and SOCK_DGRAM.
+
+**SOCK_STREAM** indicates connection-oriented TCP data transfer. Data can arrive at another computer without any errors. If it is damaged or lost, it can be resent, but it is relatively slow.
+
+**SOCK_DGRAM** indicates the connectionless UDP data transfer method. The computer only transmits data and does not perform data verification. If the data is damaged during transmission or does not reach another computer, there is no way to remedy it. In other words, if the data is wrong, it is wrong and cannot be retransmitted. Because SOCK_DGRAM does less validation work, it is more efficient than SOCK_STREAM.
+
+The sample code for creating a TCP type socket is as follows:
+
+```c
+ /* Create a socket, type is SOCKET_STREAM,TCP type */
+ if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+ {
+ /* failed to create socket*/
+ rt_kprintf("Socket error\n");
+
+ return;
+ }
+```
+
+## Binding Socket
+
+A binding socket is used to bind a port number and an IP address to a specified socket. When using socket() to create a socket, only the protocol family is given, and no address is assigned. Before the socket receives a connection from another host, it must bind it with an address and port number using bind(). The interface is as follows:
+
+```c
+int bind(int s, const struct sockaddr *name, socklen_t namelen);
+```
+
+|**Parameters**|**Description** |
+|----------|--------------------------------------------|
+| S | Socket descriptor |
+| name | Pointer to the sockaddr structure representing the address to be bound |
+| namelen | Length of sockaddr structure |
+|**Return**|**——** |
+| 0 | Successful |
+| -1 | Fail |
+
+## Establishing a TCP Connection
+
+For server-side programs, after using `bind()` to bind the socket, you also need to use the `listen()` function to make the socket enter the passive listening state, and then call the `accept()` function to respond to the client at any time.
+
+### Listening Socket
+
+The listening socket is used by the TCP server to listen for the specified socket connection. The interface is as follows:
+
+```c
+int listen(int s, int backlog);
+```
+
+|**Parameters**|**Description** |
+|----------|--------------------------------|
+| s | Socket descriptor |
+| backlog | Indicates the maximum number of connections that can be waited at a time |
+|**Return**|**——** |
+| 0 | Successful |
+| -1 | Fail |
+
+### Accept the Connection
+
+When the application listens for connections from other clients, the connection must be initialized with the `accept()` function, which creates a new socket for each connection and removes the connection from the listen queue. The interface is as follows:
+
+```c
+int accept(int s, struct sockaddr *addr, socklen_t *addrlen);
+```
+
+|**Parameters**|**Description** |
+|----------|--------------------------------|
+| s | Socket descriptor |
+| addr | Client device address information |
+| addrlen | Client device address structure length |
+|**Return**|**——** |
+| >=0 | Successful, return the newly created socket descriptor |
+| -1 | Fail |
+
+### Establish Connection
+
+Used by the client to establish a connection with the specified server. The interface is as follows:
+
+```
+int connect(int s, const struct sockaddr *name, socklen_t namelen);
+```
+
+|**Parameters**|**Description** |
+|----------|------------------------|
+| s | Socket descriptor |
+| name | Server address information |
+| namelen | Server address structure length |
+|**Return**|**——** |
+| 0 | Successful |
+| -1 | Fail |
+
+When the client connects to the server, first set the server address and then use the `connect()` function to connect. The sample code is as follows:
+
+```c
+struct sockaddr_in server_addr;
+/* Initialize the pre-connected server address */
+server_addr.sin_family = AF_INET;
+server_addr.sin_port = htons(port);
+server_addr.sin_addr = *((struct in_addr *)host->h_addr);
+rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
+
+/* Connect to the server */
+if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
+{
+ /* Connection failed */
+ closesocket(sock);
+
+ return;
+}
+```
+
+## Data Transmission
+
+TCP and UDP have different data transmission methods. TCP needs to establish a connection before data transmission, use `send()` function for data transmission, use `recv()` function for data reception, and UDP does not need to establish connection. It uses `sendto()` function sends data and receives data using the `recvfrom()` function.
+
+### TCP Data Transmission
+
+After the TCP connection is established, the data is sent using the `send()` function. The interface is as follows:
+
+```c
+int send(int s, const void *dataptr, size_t size, int flags);
+```
+
+|**Parameters**|**Description** |
+|----------|----------------------------|
+| s | Socket descriptor |
+| dataptr | The data pointer to send |
+| size | Length of data sent |
+| flags | Flag, generally 0 |
+|**Return**|**——** |
+| >0 | Successful, return the length of the sent data |
+| <=0 | Failed |
+
+### TCP Data Reception
+
+After the TCP connection is established, use `recv()` to receive the data. The interface is as follows:
+
+```c
+int recv(int s, void *mem, size_t len, int flags);
+```
+
+|**Parameters**|**Description** |
+|----------|----------------------------|
+| s | Socket descriptor |
+| mem | Received data pointer |
+| len | Received data length |
+| flags | Flag, generally 0 |
+|**Return**|**Description** |
+| >0 | Successful, return the length of the received data |
+| =0 | The destination address has been transferred and the connection is closed |
+| <0 | Fail |
+
+### UDP Data transmission
+
+In the case where a connection is not established, you can use the `sendto()` function to send UDP data to the specified destination address, as shown below:
+
+```c
+int sendto(int s, const void *dataptr, size_t size, int flags,
+ const struct sockaddr *to, socklen_t tolen);
+```
+
+|**Parameters**|**Description** |
+|----------|----------------------------|
+| s | Socket descriptor |
+| dataptr | Data pointer sent |
+| size | Length of data sent |
+| flags | Flag, generally 0 |
+| to | Target address structure pointer |
+| tolen | Target address structure length |
+|**Return**|**——** |
+| >0 | Successful, return the length of the sent data |
+| <=0 | Fail |
+
+### UDP Data Reception
+
+To receive UDP data, use the `recvfrom()` function, and the interface is:
+
+```c
+int recvfrom(int s, void *mem, size_t len, int flags,
+ struct sockaddr *from, socklen_t *fromlen);
+```
+
+|**Parameters**|**Description** |
+|----------|----------------------------|
+| s | Socket descriptor |
+| mem | Received data pointer |
+| len | Received data length |
+| flags | Flag, generally 0 |
+| from | Receive address structure pointer |
+| fromlen | Receive address structure length |
+|**Return**|**——** |
+| >0 | Successful, return the length of the received data |
+| 0 | The receiving address has been transferred and the connection is closed |
+| <0 | Fail |
+
+## Close Network Connection
+
+After the network communication is over, you need to close the network connection. There are two ways to use `closesocket()` and `shutdown()`.
+
+The `closesocket()` interface is used to close an existing socket connection, release the socket resource, clear the socket descriptor from memory, and then the socket could not be used again. The connection and cache associated with the socket are also lost the meaning, the TCP protocol will automatically close the connection. The interface is as follows:
+
+```c
+int closesocket(int s);
+```
+
+|**Parameters**|**Description** |
+|----------|--------------|
+| s | Socket descriptor |
+|**Return**|**——** |
+| 0 | Successful |
+| -1 | Fail |
+
+Network connections can also be turned off using the `shutdown()` function. The TCP connection is full-duplex. You can use the `shutdown()` function to implement a half-close. It can close the read or write operation of the connection, or both ends, but it does not release the socket resource. The interface is as follows:
+
+```c
+int shutdown(int s, int how);
+```
+
+|**Parameters**|**Description** |
+|----------|-----------------------------|
+| s | Socket descriptor |
+| how | SHUT_RD closes the receiving end of the connection and no longer receives data. <br />SHUT_WR closes the connected sender and no longer sends data. <br />SHUT_RDWR is closed at both ends. |
+|**Return**|**——** |
+| 0 | Successful |
+| -1 | Fail |
+
+# Network Function Configuration
+
+The main functional configuration options of the network framework are shown in the following table, which can be configured according to different functional requirements:
+
+SAL component configuration options:
+
+|**Macro Definition** |**Value Type**|**Description** |
+|------------------------|--------------|--------------------|
+| RT_USING_SAL | Boolean | Enable SAL |
+| SAL_USING_LWIP | Boolean | Enable LwIP component |
+| SAL_USING_AT | Boolean | Enable the AT component |
+| SAL_USING_POSIX | Boolean | Enable POSIX interface |
+| SAL_PROTO_FAMILIES_NUM | Integer | the maximum number of protocol families supported |
+
+LwIP Configuration options:
+
+|**Macro Definition** |**Value Type**|**Description** |
+|-----------------------------|--------------|----------------------|
+| RT_USING_LWIP | Boolean | Enable LwIP protocol |
+| RT_USING_LWIP_IPV6 | Boolean | Enable IPV6 protocol |
+| RT_LWIP_IGMP | Boolean | Enable the IGMP protocol |
+| RT_LWIP_ICMP | Boolean | Enable the ICMP protocol |
+| RT_LWIP_SNMP | Boolean | Enable the SNMP protocol |
+| RT_LWIP_DNS | Boolean | Enable DHCP function |
+| RT_LWIP_DHCP | Boolean | Enable DHCP function |
+| IP_SOF_BROADCAST | Integer | filtering roadcasting Packets Sended by IP |
+| IP_SOF_BROADCAST_RECV | Integer | filtering roadcasting Packets received by IP |
+| RT_LWIP_IPADDR | String | IP address |
+| RT_LWIP_GWADDR | String | Gateway address |
+| RT_LWIP_MSKADDR | String | Subnet mask |
+| RT_LWIP_UDP | Boolean | Enable UDP protocol |
+| RT_LWIP_TCP | Boolean | Enable TCP protocol |
+| RT_LWIP_RAW | Boolean | Enable RAW API |
+| RT_MEMP_NUM_NETCONN | Integer | Support Numbers of network links |
+| RT_LWIP_PBUF_NUM | Integer | pbuf number of memory blocks |
+| RT_LWIP_RAW_PCB_NUM | Integer | Maximum number of connections for RAW |
+| RT_LWIP_UDP_PCB_NUM | Integer | Maximum number of connections for UDP |
+| RT_LWIP_TCP_PCB_NUM | Integer | Maximum number of connections for TCP |
+| RT_LWIP_TCP_SND_BUF | Integer | TCP send buffer size |
+| RT_LWIP_TCP_WND | Integer | TCP sliding window size |
+| RT_LWIP_TCPTHREAD_PRIORITY | Integer | TCP thread priority |
+| RT_LWIP_TCPTHREAD_MBOX_SIZE | Integer | TCP thread mailbox size |
+| RT_LWIP_TCPTHREAD_STACKSIZE | Integer | TCP thread stack size |
+| RT_LWIP_ETHTHREAD_PRIORITY | Integer | Receive/send thread's priority |
+| RT_LWIP_ETHTHREAD_STACKSIZE | Integer | Receive/send thread's stack size |
+| RT_LwIP_ETHTHREAD_MBOX_SIZE | Integer | Receive/send thread's mailbox size |
+
+# Network Application Example
+
+## View IP Address
+
+In the console, you can use the ifconfig command to check the network status. The IP address is 192.168.12.26, and the FLAGS status is LINK_UP, indicating that the network is configured:
+
+```c
+msh >ifconfig
+network interface: e0 (Default)
+MTU: 1500
+MAC: 00 04 a3 12 34 56
+FLAGS: UP LINK_UP ETHARP BROADCAST IGMP
+ip address: 192.168.12.26
+gw address: 192.168.10.1
+net mask : 255.255.0.0·
+dns server #0: 192.168.10.1
+dns server #1: 223.5.5.5
+```
+
+## Ping Network Test
+
+Use the ping command for network testing:
+
+```c
+msh />ping rt-thread.org
+60 bytes from 116.62.244.242 icmp_seq=0 ttl=49 time=11 ticks
+60 bytes from 116.62.244.242 icmp_seq=1 ttl=49 time=10 ticks
+60 bytes from 116.62.244.242 icmp_seq=2 ttl=49 time=12 ticks
+60 bytes from 116.62.244.242 icmp_seq=3 ttl=49 time=10 ticks
+msh />ping 192.168.10.12
+60 bytes from 192.168.10.12 icmp_seq=0 ttl=64 time=5 ticks
+60 bytes from 192.168.10.12 icmp_seq=1 ttl=64 time=1 ticks
+60 bytes from 192.168.10.12 icmp_seq=2 ttl=64 time=2 ticks
+60 bytes from 192.168.10.12 icmp_seq=3 ttl=64 time=3 ticks
+msh />
+```
+
+Getting the above output indicates that the connection network is successful!
+
+## TCP Client Example
+
+After the network is successfully connected, you can run the network example, first run the TCP client example. This example will open a TCP server on the PC, open a TCP client on the IoT Board, and both parties will communicate on the network.
+
+In the example project, there is already a TCP client program `tcpclient_sample.c`. The function is to implement a TCP client that can receive and display the information sent from the server. If it receives the information starting with 'q' or 'Q', then exit the program directly and close the TCP client. The program exports the tcpclient command to the FinSH console. The command format is `tcpclient URL PORT`, where URL is the server address and PORT is the port number. The sample code is as follows:
+
+```c
+/*
+ * Program list: tcp client
+ *
+ * This is a tcp client routine
+ * Export the tcpclient command to MSH
+ * Command call format: tcpclient URL PORT
+ * URL: server address PORT:: port number
+ * Program function: Receive and display the information sent from the server, and receive the information that starts with 'q' or 'Q' to exit the program.
+*/
+
+#include <rtthread.h>
+#include <sys/socket.h> /* To use BSD socket, you need to include the socket.h header file. */
+#include <netdb.h>
+#include <string.h>
+#include <finsh.h>
+
+#define BUFSZ 1024
+
+static const char send_data[] = "This is TCP Client from RT-Thread."; /* Sending used data */
+void tcpclient(int argc, char**argv)
+{
+ int ret;
+ char *recv_data;
+ struct hostent *host;
+ int sock, bytes_received;
+ struct sockaddr_in server_addr;
+ const char *url;
+ int port;
+
+ /* Received less than 3 parameters */
+ if (argc < 3)
+ {
+ rt_kprintf("Usage: tcpclient URL PORT\n");
+ rt_kprintf("Like: tcpclient 192.168.12.44 5000\n");
+ return ;
+ }
+
+ url = argv[1];
+ port = strtoul(argv[2], 0, 10);
+
+ /* Get the host address through the function entry parameter url (if it is a domain name, it will do domain name resolution) */
+ host = gethostbyname(url);
+
+ /* Allocate buffers for storing received data */
+ recv_data = rt_malloc(BUFSZ);
+ if (recv_data == RT_NULL)
+ {
+ rt_kprintf("No memory\n");
+ return;
+ }
+
+ /* Create a socket of type SOCKET_STREAM, TCP type */
+ if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+ {
+ /* Failed to create socket */
+ rt_kprintf("Socket error\n");
+
+ /* Release receive buffer */
+ rt_free(recv_data);
+ return;
+ }
+
+ /* Initialize the pre-connected server address */
+ server_addr.sin_family = AF_INET;
+ server_addr.sin_port = htons(port);
+ server_addr.sin_addr = *((struct in_addr *)host->h_addr);
+ rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
+
+ /* Connect to the server */
+ if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
+ {
+ /* Connection failed */
+ rt_kprintf("Connect fail!\n");
+ closesocket(sock);
+
+ /* Release receive buffer */
+ rt_free(recv_data);
+ return;
+ }
+
+ while (1)
+ {
+ /* Receive maximum BUFSZ-1 byte data from a sock connection */
+ bytes_received = recv(sock, recv_data, BUFSZ - 1, 0);
+ if (bytes_received < 0)
+ {
+ /* Receive failed, close this connection */
+ closesocket(sock);
+ rt_kprintf("\nreceived error,close the socket.\r\n");
+
+ /* Release receive buffer */
+ rt_free(recv_data);
+ break;
+ }
+ else if (bytes_received == 0)
+ {
+ /* Print the recv function returns a warning message with a value of 0 */
+ rt_kprintf("\nReceived warning,recv function returns 0.\r\n");
+
+ continue;
+ }
+
+ /* Received data, clear the end */
+ recv_data[bytes_received] = '\0';
+
+ if (strncmp(recv_data, "q", 1) == 0 || strncmp(recv_data, "Q", 1) == 0)
+ {
+ /* If the initial letter is q or Q, close this connection */
+ closesocket(sock);
+ rt_kprintf("\n got a'q'or'Q',close the socket.\r\n");
+
+ /* Release receive buffer */
+ rt_free(recv_data);
+ break;
+ }
+ else
+ {
+ /* Display the received data at the control terminal */
+ rt_kprintf("\nReceived data = %s", recv_data);
+ }
+
+ /* Send data to sock connection */
+ ret = send(sock, send_data, strlen(send_data), 0);
+ if (ret < 0)
+ {
+ /* Receive failed, close this connection */
+ closesocket(sock);
+ rt_kprintf("\nsend error,close the socket.\r\n");
+
+ rt_free(recv_data);
+ break;
+ }
+ else if (ret == 0)
+ {
+ /* Print the send function returns a warning message with a value of 0 */
+ rt_kprintf("\n Send warning,send function returns 0.\r\n");
+ }
+ }
+ return;
+}
+MSH_CMD_EXPORT(tcpclient, a tcp client sample);
+```
+
+When running the example, first open a network debugging assistant on your computer and open a TCP server. Select the protocol type as TCP
+Server, fill in the local IP address and port 5000, as shown below.
+
+![Network debugging tool interface](figures/net-tcp-s.png)
+
+Then start the TCP client to connect to the TCP server by entering the following command in the FinSH console:
+
+```C
+msh />tcpclient 192.168.12.45 5000 // Input according to actual situation
+Connect successful
+```
+
+When the console outputs the log message "Connect successful", it indicates that the TCP connection was successfully established. Next, you can perform data communication. In the network debugging tool window, send Hello RT-Thread!, which means that a data is sent from the TCP server to the TCP client, as shown in the following figure:
+
+![网络调试工具界面](figures/net-hello.png)
+
+After receiving the data on the FinSH console, the corresponding log information will be output, you can see:
+
+```c
+msh >tcpclient 192.168.12.130 5000
+Connect successful
+Received data = hello world
+Received data = hello world
+Received data = hello world
+Received data = hello world
+Received data = hello world
+ got a 'q' or 'Q',close the socket.
+msh >
+```
+
+The above information indicates that the TCP client received 5 "hello world" data sent from the server. Finally, the exit command 'q' was received from the TCP server, and the TCP client program exited the operation and returned to the FinSH console.
+
+## UDP Client Example
+
+This is an example of a UDP client. This example will open a UDP server on the PC and open a UDP client on the IoT Board for network communication. A UDP client program has been implemented in the sample project. The function is to send data to the server. The sample code is as follows:
+
+```c
+/*
+ * Program list: udp client
+ *
+ * This is a udp client routine
+ * Export the udpclient command to the msh
+ * Command call format: udpclient URL PORT [COUNT = 10]
+ * URL: Server Address PORT: Port Number COUNT: Optional Parameter Default is 10
+ * Program function: send COUNT datas to the remote end of the service
+*/
+
+#include <rtthread.h>
+#include <sys/socket.h> /* To use BSD socket, you need to include the sockets.h header file. */
+#include <netdb.h>
+#include <string.h>
+#include <finsh.h>
+
+const char send_data[] = "This is UDP Client from RT-Thread.\n"; /* data */
+
+void udpclient(int argc, char**argv)
+{
+ int sock, port, count;
+ struct hostent *host;
+ struct sockaddr_in server_addr;
+ const char *url;
+
+ /* Received less than 3 parameters */
+ if (argc < 3)
+ {
+ rt_kprintf("Usage: udpclient URL PORT [COUNT = 10]\n");
+ rt_kprintf("Like: udpclient 192.168.12.44 5000\n");
+ return ;
+ }
+
+ url = argv[1];
+ port = strtoul(argv[2], 0, 10);
+
+ if (argc> 3)
+ count = strtoul(argv[3], 0, 10);
+ else
+ count = 10;
+
+ /* Get the host address through the function entry parameter url (if it is a domain name, it will do domain name resolution) */
+ host = (struct hostent *) gethostbyname(url);
+
+ /* Create a socket of type SOCK_DGRAM, UDP type */
+ if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
+ {
+ rt_kprintf("Socket error\n");
+ return;
+ }
+
+ /* Initialize the pre-connected server address */
+ server_addr.sin_family = AF_INET;
+ server_addr.sin_port = htons(port);
+ server_addr.sin_addr = *((struct in_addr *)host->h_addr);
+ rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
+
+ /* Send count data in total */
+ while (count)
+ {
+ /* Send data to the remote end of the service */
+ sendto(sock, send_data, strlen(send_data), 0,
+ (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
+
+ /* Thread sleep for a while */
+ rt_thread_delay(50);
+
+ /* Count value minus one */
+ count --;
+ }
+
+ /* Turn off this socket */
+ closesocket(sock);
+}
+```
+
+When running the example, first open a network debugging assistant on your computer and open a UDP server. Select the protocol type as UDP and fill in the local IP address and port 5000, as shown in the figure below.
+
+![网络调试工具界面](figures/net-udp-server.png)
+
+Then you can enter the following command in the FinSH console to send data to the UDP server.
+
+```c
+msh />udpclient 192.168.12.45 1001 // Need to enter according to the real situation
+```
+
+The server will receive 10 messages from This is UDP Client from RT-Thread., as shown below:
+
+![网络调试工具界面](figures/net-udp-client.png)
diff --git a/documentation/6.components/pm/figures/pm_architecture.png b/documentation/6.components/pm/figures/pm_architecture.png
new file mode 100644
index 0000000000..e9e6035fa0
--- /dev/null
+++ b/documentation/6.components/pm/figures/pm_architecture.png
Binary files differ
diff --git a/documentation/6.components/pm/figures/pm_description.png b/documentation/6.components/pm/figures/pm_description.png
new file mode 100644
index 0000000000..509fad5680
--- /dev/null
+++ b/documentation/6.components/pm/figures/pm_description.png
Binary files differ
diff --git a/documentation/6.components/pm/figures/pm_sequence.png b/documentation/6.components/pm/figures/pm_sequence.png
new file mode 100644
index 0000000000..57cd0d2bf6
--- /dev/null
+++ b/documentation/6.components/pm/figures/pm_sequence.png
Binary files differ
diff --git a/documentation/6.components/pm/figures/pm_system.png b/documentation/6.components/pm/figures/pm_system.png
new file mode 100644
index 0000000000..fe224f9ec0
--- /dev/null
+++ b/documentation/6.components/pm/figures/pm_system.png
Binary files differ
diff --git a/documentation/6.components/pm/pm.md b/documentation/6.components/pm/pm.md
new file mode 100644
index 0000000000..c57b9c0f7a
--- /dev/null
+++ b/documentation/6.components/pm/pm.md
@@ -0,0 +1,430 @@
+@page page_component_pm Power Management: PM
+
+The purpose of low power management of embedded system is to reduce system energy consumption as much as possible to prolong the standby time of equipment on the premise of satisfying users'performance requirements. The contradiction between high performance and limited battery energy is most prominent in embedded systems. The combination of hardware low power design and software low power management has become an effective means to solve the contradiction. Nowadays, all kinds of MCUs provide management interfaces in low power consumption more or less. For example, adjusting the frequency of the main control clock, changing the working voltage, adjusting or even closing the bus frequency, closing the working clock of peripheral equipment, etc. With the support of hardware, reasonable software design becomes the key to energy saving. Generally, low power management can be divided into three categories:
+
+- Processor Power Management
+
+ - The main ways of realization are dynamic management of CPU frequency and adjustment of working mode when the system is idle.
+
+- Power management of equipment
+
+ - The main way to achieve this is to shut down individual idle devices
+
+- Power Management of System Platform
+
+ - The main way to realize it is to specific customization of infrequent devices on specific system platforms.
+
+With the rise of the Internet of Things (IoT), the demand for power consumption of products becomes more and more intense. Sensor nodes as data acquisition usually need to work long-term when the battery is powered, and SOC connected to the network also needs fast response function and low power consumption.
+
+In the initial stage of product development, the first consideration is to complete the development of product functions as soon as possible. After the function of the product is gradually improved, it is necessary to add the power management (PM) function. To meet this need of IoT, RT-Thread provides power management components. The idea of power management components is to be as transparent as possible, making it easier for products to add low power functions.
+
+# Introduction of PM Components
+
+RT-Thread's PM components adopt a layered design idea, separating architecture and chip-related parts, and extracting common parts as the core. While providing a common interface to the upper layer, it also makes it easier for the bottom driver to adapt components.
+
+![PM Component Overview](figures/pm_system.png)
+
+## Main Features
+
+The main features of RT-Thread PM components are as follows:
+
+- It manages power consumption based on mode, dynamically adjusts working mode in idle time, and supports multiple levels of sleeping.
+- Transparent to applications, components automatically complete power management at the bottom layer.
+- It supports dynamic frequency conversion in running mode and updates the frequency configuration of equipment automatically according to the mode to ensure normal operation in different running modes.
+- Support equipment power management, automatically manage device suspending and resuming according to the mode, ensure correct suspending and resuming in different sleep mode.
+- Optional sleep time compensation is supported to make OS Tick dependent applications transparent.
+- Provide the device interface to the upper layer. If the devfs component is opened, it can also be accessed through the file system interface.
+
+## Working Principle
+
+The essence of low power consumption is that when the system is idle, the CPU stops working, interrupts or resumes working after the event wakes up. In RTOS, there is usually an IDLE task, which has the lowest priority and remains ready. When the high priority task is not ready, the OS executes the IDLE task. Generally, the CPU executes empty instructions in IDLE tasks without low power processing. The power management component of RT-Thread can effectively reduce the power consumption of the system by managing CPU, clock and equipment in IDLE tasks.
+
+![PM工作原理](figures/pm_description.png)
+
+As shown in the figure above, when the high priority thread runs out or is suspended, the system enters the IDLE thread . After the IDLE thread is executed, it will determine whether the system can go to sleep (to save power). If the system goes to sleep, Some hardware modules will be shut down depending on the chip condition, and OS Tick is also very likely to enter a pause state. At this time, the power management framework will calculate the next timeout point according to the system timer situation, and set a low-power timer, so that the device can wake up at that point, and carry out follow-up work. When the system is awakened (low power timer interrupt or other wake-up interrupt source), the system also needs to know how long it sleeps, and compensate for OS Tick, so that the OS tick value of the system is adjusted to a correct value.
+
+# PM Framework
+
+In RT-Thrad PM components, peripherals or applications vote on the required power consumption mode by voting mechanism. When the system is idle, the appropriate power consumption mode is decided according to the voting number, and the abstract interface is called to control the chip to enter a low power consumption state, so as to reduce the power consumption of the system. When no vote is taken, it is entered in the default mode (usually idle mode). Unlike applications, some peripherals may perform specific operations when they enter a low-power state and take measures to recover when they exit a low-power state, which can be achieved by registering PM devices. By registering PM devices, `suspend` callbacks of registered devices will be triggered before entering a low power state. Developers can perform their own operations in the callbacks. Similarly, `resume` callbacks will be triggered when exiting from a low power state.
+
+![PM Framework](figures/pm_architecture.png)
+
+# Low Power State and Mode
+
+The RT-Thread PM component divides the system into two states: RUN(running state) and Sleep(sleeping state).
+
+Running state controls the frequency of CPU, which is suitable for frequency conversion scenarios. Sleeping state realizes sleeping CPU according to SOC characteristics to reduce power consumption. The two states are controlled independently using different API interfaces.
+
+- **Sleeping state**
+
+Sleeping state is also a low power state in the usual sense. By closing the peripherals and executing the SOC power management interface, the system power consumption is reduced.
+
+The state of sleeping is divided into six patterns, which take the form of pyramids. As the mode increases, the power consumption decreases step by step. The following is the definition of the mode in the sleeping state. Developers can implement the corresponding mode according to the specific SOC, but they need to follow the characteristics of power consumption decreasing step by step.
+
+| Patterns | Level | Description |
+| ---------------------- | ----- | ------------------------------------------------------------ |
+| PM_SLEEP_MODE_NONE | 0 | The system is active without any power reduction. |
+| PM_SLEEP_MODE_IDLE | 1 | The idle mode, which stops CPU and part of the clock when the system is idle. Any event or interrupt can wake up system. |
+| PM_SLEEP_MODE_LIGHT | 2 | Light sleep modes, CPU stops, most clocks and peripherals stop, and time compensation is required after wake-up. |
+| PM_SLEEP_MODE_DEEP | 3 | Deep sleep mode, CPU stops, only a few low power peripheral work, can be awakened by special interrupts |
+| PM_SLEEP_MODE_STANDBY | 4 | Standby mode, CPU stops, device context loss (can be saved to special peripherals), usually reset after wake-up |
+| PM_SLEEP_MODE_SHUTDOWN | 5 | Shutdown mode, lower power consumption than Standby mode, context is usually irrecoverable, reset after wake-up |
+
+>Note: The implementation of power management varies from chip to chip. The above description only gives some recommended scenarios, not all of which need to be implemented. Developers can choose several of them to implement according to their own situation, but they need to follow the principle of higher level and lower power consumption.
+
+- **Running state**
+
+Running state is usually used to change the running frequency of CPU, independent of sleep mode. Current operation status is divided into four levels: high-speed, normal-speed, medium-speed and low-speed, as follows:
+
+| Patterns | Description |
+| ------------------------ | ------------------------------------------------------------ |
+| PM_RUN_MODE_HIGH_SPEED | High-speed mode, suitable for some over-frequency scenarios |
+| PM_RUN_MODE_NORMAL_SPEED | Normal-speed mode, which is the default running state |
+| PM_RUN_MODE_MEDIUM_SPEED | Medium-speed mode, reduce CPU running speed, thereby reducing power consumption |
+| PM_RUN_MODE_LOW_SPEED | Low-speed mode, CPU frequency further reduced |
+
+## Request and release of patterns
+
+In PM components, upper applications can actively participate in power management by requesting and releasing sleep modes. Applications can request different sleep modes according to scenarios and release them after processing. As long as any application or device requests higher-level power mode, it will not switch to a lower mode. Therefore, the requests and releases of sleep mode usually occur in pairs and can be used to protect a certain stage, such as the peripheral DMA transmission process.
+
+## Device Sensitive to Mode Changes
+
+In PM components, switching to a new mode of operation may lead to changes in CPU frequency. If peripherals and CPUs share a part of the clock, the peripheral clock will be affected. When entering the new sleep mode, most clock sources will be stopped. If the peripheral does not support the freezing function of sleep, then the peripheral clock needs to be reconfigured when waking up from sleep. So PM components support PM mode sensitive PM devices. It enables the device to work normally when switching to a new operation mode or a new sleep mode. This function requires the underlying driver to implement the relevant interface and register as a device sensitive to mode changes.
+
+# The calling process
+
+![PM Sequence](figures/pm_sequence.png)
+
+Firstly, the application layer sets the callback function of entering and exiting the dormancy state, and then calls `rt_pm_request` to request the sleeping mode to trigger the sleeping operation. The PM component checks the number of sleeping modes when the system is idle, and gives the recommended mode according to the number of votes. Then the PM component calls `notfiy` to inform the application that it is going to enter the sleep mode, and then suspends the registered PM device and executes the sleep mode implemented by SOC after returning to OK. The system enters the sleep state (if the enabling time is compensated, the low-power timer will be started before the sleep). At this point, the CPU stops working and waits for an event or interrupt to wake up. When the system is awakened, because the global interruption is closed, the system continues to execute from there, gets the sleep time to compensate the OS tick of the system, wakes up the device in turn, and notifies the application to exit from the sleep mode. Such a cycle is completed, exits, and waits for the system to be idle next time.
+
+# Introduction to APIs
+
+## Request Sleep Mode
+
+```c
+void rt_pm_request(uint8_t sleep_mode);
+```
+
+| Parameter | Mode |
+| ---------- | ------------------------ |
+| sleep_mode | Request Sleep mode level |
+
+Sleep_mode takes the following enumeration values:
+
+```c
+enum
+{
+ /* sleep modes */
+ PM_SLEEP_MODE_NONE = 0, /* active state */
+ PM_SLEEP_MODE_IDLE, /* idle mode (default) */
+ PM_SLEEP_MODE_LIGHT, /* Light Sleep Mode */
+ PM_SLEEP_MODE_DEEP, /* Deep Sleep Mode */
+ PM_SLEEP_MODE_STANDBY, /* Standby Mode */
+ PM_SLEEP_MODE_SHUTDOWN, /* Shutdowm Mode */
+ PM_SLEEP_MODE_MAX,
+};
+```
+
+Calling this function adds the corresponding pattern count to 1 and locks the pattern. At this point, if a lower level of power mode is requested, it will not be accessible. Only after releasing (unlocking) the previously requested mode, the system can enter a lower level of power mode; requests to higher power mode are not affected by this. This function needs to be used in conjunction with `rt_pm_release` to protect a certain stage or process.
+
+## Release Sleep Mode
+
+```c
+void rt_pm_release(uint8_t sleep_mode);
+```
+
+| Parameter | Mode |
+| ---------- | ---------------- |
+| sleep_mode | Sleep mode level |
+
+Calling this function decreases the corresponding pattern count by 1, and releases the previously requested pattern in conjunction with `rt_pm_request`.
+
+## Setting up Running Mode
+
+```c
+int rt_pm_run_enter(uint8_t run_mode);
+```
+
+| Parameter | Mode |
+| --------- | ------------------ |
+| run_mode | Running mode level |
+
+`run_mode` can take the following enumeration values:
+
+```c
+enum
+{
+ /* run modes*/
+ PM_RUN_MODE_HIGH_SPEED = 0, /* high speed */
+ PM_RUN_MODE_NORMAL_SPEED, /* Normal speed(default) */
+ PM_RUN_MODE_MEDIUM_SPEED, /* Medium speed */
+ PM_RUN_MODE_LOW_SPEED, /* low speed */
+ PM_RUN_MODE_MAX,
+};
+```
+
+Calling this function changes the CPU's running frequency, thereby reducing the power consumption at runtime. This function only provides levels, and the specific CPU frequency should depend on the actual situation during the migration phase.
+
+## Setting up callback notifications for entering/exiting sleep mode
+
+```c
+void rt_pm_notify_set(void (*notify)(uint8_t event, uint8_t mode, void *data), void *data);
+```
+
+| Parameter | Mode |
+| --------- | ----------------- |
+| notify | callback function |
+| data | Private data |
+
+Evet is the following two enumeration values, identifying entry/exit sleep mode respectively.
+
+```c
+enum
+{
+ RT_PM_ENTER_SLEEP = 0, /* entry sleep mode */
+ RT_PM_EXIT_SLEEP, /* exit sleep mode */
+};
+
+```
+
+# Instruction for Use
+
+## Setting Low Power Level
+
+If the system needs to enter a specified level of low power consumption, it can be achieved by calling rt_pm_request. For example, into deep sleep mode:
+
+```c
+/* Request for Deep Sleep Mode */
+rt_pm_request(PM_SLEEP_MODE_DEEP);
+```
+
+> Note: If higher power consumption modes, such as Light Mode or Idle Mode, are requested elsewhere in the program, then the corresponding mode needs to be released before the deep sleep mode can be entered.
+
+## Protect a stage or process
+
+In special cases, for example, the system is not allowed to enter a lower power mode at a certain stage, which can be protected by rt_pm_request and rt_pm_release. For example, deep sleep mode (which may cause peripherals to stop working) is not allowed during I2C reading data, so the following processing can be done:
+
+```c
+/* Request light sleep mode (I2C peripheral works normally in this mode) */
+rt_pm_request(PM_SLEEP_MODE_LIGHT);
+
+/* Reading Data Procedure */
+
+/* Release this model */
+rt_pm_release(PM_SLEEP_MODE_LIGHT);
+
+```
+
+## Changing CPU Running Frequency
+
+Reducing the running frequency can effectively reduce the power consumption of the system, and the running frequency of the CPU can be changed through the `rt_pm_run_enter` interface. Generally speaking, frequency reduction means that CPU performance decreases and processing speed decreases, which may lead to the increase of task execution time and need to be weighed reasonably.
+
+```c
+/* Enter Medium Speed Mode */
+rt_pm_run_enter(PM_RUN_MODE_MEDIUM_SPEED);
+```
+
+# Migration instructions
+
+Low power management is a very meticulous task. Developers need not only to fully understand the power management of the chip itself, but also to be familiar with the peripheral circuit of the board and deal with it one by one when they enter the low power state, so as to avoid leakage of the peripheral circuit and pull up the overall power consumption.
+
+RT-Thread PM components Abstract each part and provide different OPS interfaces for developers to adapt. The following points need to be paid attention to when they migration:
+
+```c
+/**
+ * low power mode operations
+ */
+struct rt_pm_ops
+{
+ /* Sleep interface for adapting chip-related low power characteristics */
+ void (*sleep)(struct rt_pm *pm, uint8_t mode);
+ /* Run Interface for Frequency Conversion and Voltage Conversion in Running Mode */
+ void (*run)(struct rt_pm *pm, uint8_t mode);
+ /* The following three interfaces are used to start a low-power timer after cardiac arrest to compensate for the OS tick */
+ void (*timer_start)(struct rt_pm *pm, rt_uint32_t timeout);
+ void (*timer_stop)(struct rt_pm *pm);
+ rt_tick_t (*timer_get_tick)(struct rt_pm *pm);
+};
+
+/* The OPS is used to manage the power consumption of peripherals */
+struct rt_device_pm_ops
+{
+ /* Suspending the peripheral before entering sleeping mode and return to non-zero to indicate that the peripheral is not ready and cannot enter */
+ int (*suspend)(const struct rt_device *device, uint8_t mode);
+ /* Resume peripherals after exiting from sleep mode */
+ void (*resume)(const struct rt_device *device, uint8_t mode);
+ /* When the mode changes, notify peripheral processing in the running state */
+ int (*frequency_change)(const struct rt_device *device, uint8_t mode);
+};
+
+/* Register a PM device */
+void rt_pm_device_register(struct rt_device *device, const struct rt_device_pm_ops *ops);
+```
+
+## Power Consumption Characteristics of Chips
+
+```c
+void (*sleep)(struct rt_pm *pm, uint8_t mode);
+```
+
+Each chip has different definitions and management of low power mode. PM component abstracts chip-related characteristics into sleep interface. The interface adapts to low power management related to chips. When entering different `sleep` modes, some hardware-related configurations, storage and other related processing are needed.
+
+## Time Compensation for Sleep Mode
+
+```c
+void (*timer_start)(struct rt_pm *pm, rt_uint32_t timeout);
+void (*timer_stop)(struct rt_pm *pm);
+rt_tick_t (*timer_get_tick)(struct rt_pm *pm);
+```
+
+In some sleep modes (Light Sleep or Deep Sleep), the OS Tick timer in the kernel may be stopped. At this time, it is necessary to start a timer to measure the time of sleep and compensate for the OS Tick after waking up. Time compensated timer must still be able to work properly in this mode and wake up the system, otherwise it is meaningless!
+
+- **timer_start**: Start a low-power timer, and the input parameter is the latest next task readiness time.
+- **timer_get_tick**: Get the sleep time when the system is awakened;
+- **timer_stop**: Used to stop low-power timers after system wake-up.
+
+**Note**: Time compensation for sleep mode needs to be turned on at the initialization stage by setting the bit control of the corresponding mode of timer_mask. For example, if time compensation in Deep Sleep mode needs to be turned on, then after implementing the timer-related OPS interface, the corresponding bit is set at initialization:
+
+```c
+rt_uint8_t timer_mask = 0;
+
+/* Set the bit corresponding to Deep Sleep mode to enable sleep time compensation */
+timer_mask = 1UL << PM_SLEEP_MODE_DEEP;
+
+/* initialize system pm module */
+rt_system_pm_init(&_ops, timer_mask, RT_NULL);
+
+```
+
+## Frequency Conversion in Running Mode
+
+```
+void (*run)(struct rt_pm *pm, uint8_t mode);
+```
+
+The frequency conversion of operation mode is realized by adapting the `run` interface in `rt_pm_ops`, and the appropriate frequency is selected according to the use scenario.
+
+## Power management of peripherals
+
+Power processing of peripherals is an important part of low power management system. When entering some level of sleep mode, it is usually necessary to process some peripherals, such as emptying DMA, closing clock or setting IO to reset state, and recover after quitting sleep.
+
+In this case, PM devices can be registered through rt_pm_device_register interface, suspend and resume callbacks of registered devices will be executed when entering/exiting Sleeping mode, and frequency_change callbacks of devices will also be triggered by frequency changes in Running mode.
+
+A more detailed migration case can be referred to stm32l476-nucleo BSP in the RT-Thread repository.
+
+# MSH Commands
+
+## Request Sleep Mode
+
+The `pm_request` command can be used to request related patterns, using an example as follows:
+
+```c
+msh />pm_request 0
+msh />
+```
+
+The range of parameter values is 0-5, corresponding to the following enumeration values:
+
+```c
+enum
+{
+ /* sleep modes */
+ PM_SLEEP_MODE_NONE = 0, /* active state */
+ PM_SLEEP_MODE_IDLE, /* idle mode (default) */
+ PM_SLEEP_MODE_LIGHT, /* Light Sleep Mode */
+ PM_SLEEP_MODE_DEEP, /* Deep Sleep Mode */
+ PM_SLEEP_MODE_STANDBY, /* Standby Mode */
+ PM_SLEEP_MODE_SHUTDOWN, /* Shutdowm Mode */
+ PM_SLEEP_MODE_MAX,
+};
+```
+
+## Release Sleep Mode
+
+You can use the `pm_release` command to release the sleep mode. The range of parameters is 0-5, and the examples are as follows:
+
+```c
+msh />pm_release 0
+msh />
+```
+
+## Setting up Running Mode
+
+You can use the `pm_run` command to switch the mode of operation with parameters ranging from 0 to 3, as shown in the following example
+
+```c
+msh />pm_run 2
+msh />
+```
+
+The range of parameters is 0 to 3:
+
+```c
+enum
+{
+ /* run modes*/
+ PM_RUN_MODE_HIGH_SPEED = 0,
+ PM_RUN_MODE_NORMAL_SPEED,
+ PM_RUN_MODE_MEDIUM_SPEED,
+ PM_RUN_MODE_LOW_SPEED,
+ PM_RUN_MODE_MAX,
+};
+```
+
+## View mode status
+
+You can use the `pm_dump` command to view the mode state of the PM component, as shown in the following example
+
+```c
+msh >
+msh >pm_dump
+| Power Management Mode | Counter | Timer |
++-----------------------+---------+-------+
+| None Mode | 0 | 0 |
+| Idle Mode | 0 | 0 |
+| LightSleep Mode | 1 | 0 |
+| DeepSleep Mode | 0 | 1 |
+| Standby Mode | 0 | 0 |
+| Shutdown Mode | 0 | 0 |
++-----------------------+---------+-------+
+pm current sleep mode: LightSleep Mode
+pm current run mode: Normal Speed
+msh >
+```
+
+In the pattern list of `pm_dump`, the priority of sleep mode is arranged from high to low.
+
+The `Counter` column identifies the count of requests. The graph shows that the Light Sleep mode is requested once, so the current work is in a slight sleep state.
+
+The `Timer` column identifies whether to turn on sleep time compensation. In the figure, only Deep Sleep mode is used for time compensation.
+
+The bottom part identifies the current sleep mode and running mode level respectively.
+
+# Common problems and debugging methods
+
+- When the system enters the low power mode, the power consumption is too high.
+
+According to the peripheral circuit, check whether the equipment is in a reasonable state to avoid leakage of peripheral equipment.
+
+According to the product's own situation, turn off the peripherals and clocks that are not used during the corresponding sleep mode.
+
+- Unable to enter lower levels of power consumption
+
+Check whether the higher-level power consumption mode is not released. RT-Thread's PM component uses `rt_pm_request` to request dormancy mode. If it is not released after requesting high-power consumption mode, the system will not be able to switch to lower-level power consumption.
+
+For example, after requesting Light Sleep mode, then requesting Deep Sleep mode, the system is still in Light Sleep mode. By calling the interface `rt_pm_request` to release the Light Sleep mode, the system will automatically switch to the Deep Sleep mode.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/documentation/6.components/posix/README.md b/documentation/6.components/posix/README.md
new file mode 100644
index 0000000000..b4618a3dc0
--- /dev/null
+++ b/documentation/6.components/posix/README.md
@@ -0,0 +1,2604 @@
+@page page_component_posix POSIX Interface
+
+# Introduction to Pthreads
+
+POSIX Threads is abbreviated as Pthreads. POSIX is the abbreviation of "Portable Operating System Interface". POSIX is a set of standards established by IEEE Computer Society to improve the compatibility of different operating systems and the portability of applications. Pthreads is a threaded POSIX standard defined in the POSIX.1c, Threads extensions (IEEE Std1003.1c-1995) standard, which defines a set of C programming language types, functions, and constants. Defined in the `pthread.h` header file and a thread library, there are about 100 APIs, all of which have a "`pthread_`" prefix and can be divided into 4 categories:
+
+- **Thread management**: Thread creating, detaching, joining, and setting and querying thread attributes.
+
+- **Mutex**: Abbreviation for "mutual exclusion", which restricts thread access to shared data and protects the integrity of shared data. This includes creating, destroying, locking, and unlocking mutex and some functions for setting or modifying mutex properties.
+
+- **Condition variable**: Communication between threads used to share a mutex. It includes functions such as creation, destruction, waiting condition variables, and sending signal .
+
+- **Read/write locks and barriers**: including the creation, destruction, wait, and related property settings of read-write locks and barriers.
+
+POSIX semaphores are used with Pthreads, but are not part of the Pthreads standard definition and are defined in POSIX.1b, Real-time extensions (IEEE Std1003.1b-1993). Therefore the prefix of the semaphore correlation function is "`sem_`" instead of "`pthread_`".
+
+Message queues, like semaphores, are used with Pthreads and are not part of the Pthreads standard definition and are defined in the IEEE Std 1003.1-2001 standard. The prefix of the message queue related function is "`mq_`".
+
+| Function Prefix | Function Group |
+|----------------------|----------------------|
+| `pthread_ ` | Thread itself and various related functions |
+| `pthread_attr_` | Thread attribute object |
+| `Pthread_mutex_` | Mutex |
+| `pthread_mutexattr_` | Mutex attribute object |
+| `pthread_cond_ ` | Conditional variable |
+| `pthread_condattr_` | Condition variable attribute object |
+| `pthread_rwlock_` | Read-write lock |
+| `pthread_rwlockattr_` | Read-write lock attribute object |
+| `pthread_spin_` | Spin lock |
+| `pthread_barrier_ ` | Barrier |
+| `pthread_barrierattr_` | Barrier attribute object |
+| `sem_` | Semaphore |
+| `mq_ ` | Message queue |
+
+Most Pthreads functions return a value of 0 if they succeed, and an error code contained in the `errno.h` header file if unsuccessful. Many operating systems support Pthreads, such as Linux, MacOSX, Android, and Solaris, so applications written using Pthreads functions are very portable and can be compiled and run directly on many platforms that support Pthreads.
+
+## Use POSIX in RT-Thread
+
+Using the POSIX API interface in RT-Thread includes several parts: libc (for example, newlib), filesystem, pthread, and so on. Need to open the relevant options in rtconfig.h:
+
+``` c
+#define RT_USING_LIBC
+#define RT_USING_DFS
+#define RT_USING_DFS_DEVFS
+#define RT_USING_PTHREADS
+```
+
+RT-Thread implements most of the functions and constants of Pthreads, defined in the pthread.h, mqueue.h, semaphore.h, and sched.h header files according to the POSIX standard. Pthreads is a sublibrary of libc, and Pthreads in RT-Thread are based on the encapsulation of RT-Thread kernel functions, making them POSIX compliant. The Pthreads functions and related functions implemented in RT-Thread are described in detail in the following sections.
+
+# Thread
+
+## Thread Handle
+
+``` c
+typedef rt_thread_t pthread_t;
+```
+
+`Pthread_t` is a redefinition of the `rt_thread_t` type, defined in the `pthread.h` header file. rt_thread_t is the thread handle (or thread identifier) of the RT-Thread and is a pointer to the thread control block. You need to define a variable of type pthread_t before creating a thread. Each thread corresponds to its own thread control block, which is a data structure used by the operating system to control threads. It stores some information about the thread, such as priority, thread name, and thread stack address. Thread control blocks and thread specific information are described in detail in the @ref page_thread_management chapter.
+
+## Create Thread
+
+``` c
+int pthread_create (pthread_t *tid,
+ const pthread_attr_t *attr,
+ void *(*start) (void *), void *arg);
+```
+
+| **Parameter** | **Description** |
+|----------|------------------------------------------------------|
+| tid | Pointer to thread handle (thread identifier), cannot be NULL |
+| attr | Pointer to the thread property, if NULL is used, the default thread property is used |
+| start | Thread entry function address |
+| arg | The argument passed to the thread entry function |
+|**return**| —— |
+| 0 | succeeded |
+| EINVAL | Invalid parameter |
+| ENOMEM | Dynamic allocation of memory failed |
+
+This function creates a pthread thread. This function dynamically allocates the POSIX thread data block and the RT-Thread thread control block, and saves the start address (thread ID) of the thread control block in the memory pointed to by the parameter tid, which can be used to operate in other threads. This thread; and the thread attribute pointed to by attr, the thread entry function pointed to by start, and the entry function parameter arg are stored in the thread data block and the thread control block. If the thread is created successfully, the thread immediately enters the ready state and participates in the scheduling of the system. If the thread creation fails, the resources occupied by the thread are released.
+
+Thread properties and related functions are described in detail in the *Thread Advanced Programming* chapter. In general, the default properties can be used.
+
+> After the pthread thread is created, if the thread needs to be created repeatedly, you need to set the pthread thread to detach mode, or use pthread_join to wait for the created pthread thread to finish.
+
+### Example Code for Creating Thread
+
+The following program initializes two threads, which have a common entry function, but their entry parameters are not the same. Others, they have the same priority and are scheduled for rotation in time slices.
+
+``` c
+#include <pthread.h>
+#include <unistd.h>
+#include <stdio.h>
+
+/* Thread control block */
+static pthread_t tid1;
+static pthread_t tid2;
+
+/* Function return value check */
+static void check_result(char* str,int result)
+{
+ if (0 == result)
+ {
+ printf("%s successfully!\n",str);
+ }
+ else
+ {
+ printf("%s failed! error code is %d\n",str,result);
+ }
+}
+
+/* Thread entry function */
+static void* thread_entry(void* parameter)
+{
+ int count = 0;
+ int no = (int) parameter; /* Obtain the thread's entry parameters */
+
+ while (1)
+ {
+ /* Printout thread count value */
+ printf("thread%d count: %d\n", no, count ++);
+
+ sleep(2); /* Sleep for 2 seconds */
+ }
+}
+
+/* User application portal */
+int rt_application_init()
+{
+ int result;
+
+ /* Create thread 1, the property is the default value, the entry function is thread_entry, and the entry function parameter is 1 */
+ result = pthread_create(&tid1,NULL,thread_entry,(void*)1);
+ check_result("thread1 created", result);
+
+ /* Create thread 2, the property is the default value, the entry function is thread_entry, and the entry function parameter is 2 */
+ result = pthread_create(&tid2,NULL,thread_entry,(void*)2);
+ check_result("thread2 created", result);
+
+ return 0;
+}
+```
+
+## Detach Thread
+
+``` c
+int pthread_detach (pthread_t thread);
+```
+
+| Parameter | Description |
+|------|----------------------|
+| thread | Thread handle (thread identifier) |
+|**return**| —— |
+| 0 | succeeded |
+
+Call this function, If the pthread does not finish running, set the detach state of the thread thread property to detached; when the thread thread has finished, the system will reclaim the resources occupied by the pthread thread.
+
+Usage: The child thread calls `pthread_detach(pthread_self())` (*pthread_self()* returns the thread handle of the currently calling thread), or another thread calls `pthread_detach(thread_id)`. The separation state of the thread attributes will be described in detail later.
+
+> Once the detach state of the thread property is set to detached, the thread cannot be waited by the pthread_join() function or re-set to detached.
+
+### Example Code for Detaching Thread
+
+The following program initializes 2 threads, which have the same priority and are scheduled according to the time slice. Both threads will be set to the detached state. The 2 threads will automatically exit after printing 3 times of information. After exiting, the system will automatically reclaim its resources.
+
+``` c
+#include <pthread.h>
+#include <unistd.h>
+#include <stdio.h>
+
+/* Thread control block */
+static pthread_t tid1;
+static pthread_t tid2;
+
+/* Function return value check */
+static void check_result(char* str,int result)
+{
+ if (0 == result)
+ {
+ printf("%s successfully!\n",str);
+ }
+ else
+ {
+ printf("%s failed! error code is %d\n",str,result);
+ }
+}
+
+/* Thread 1 entry function */
+static void* thread1_entry(void* parameter)
+{
+ int i;
+
+ printf("i'm thread1 and i will detach myself!\n");
+ pthread_detach(pthread_self()); /* Thread 1 detach itself */
+
+ for (i = 0;i < 3;i++) /* Cycle print 3 times */
+ {
+ printf("thread1 run count: %d\n",i);
+ sleep(2); /* Sleep 2 seconds */
+ }
+
+ printf("thread1 exited!\n");
+ return NULL;
+}
+
+/* Thread 2 entry function */
+static void* thread2_entry(void* parameter)
+{
+ int i;
+
+ for (i = 0;i < 3;i++) /* Cycle print 3 times */
+ {
+ printf("thread2 run count: %d\n",i);
+ sleep(2); /* Sleep 2 seconds */
+ }
+
+ printf("thread2 exited!\n");
+ return NULL;
+}
+/* User application portal */
+int rt_application_init()
+{
+ int result;
+
+ /* Create thread 1, property is the default value, separation state is the default value joinable,
+ * The entry function is thread1_entry and the entry function parameter is NULL */
+ result = pthread_create(&tid1,NULL,thread1_entry,NULL);
+ check_result("thread1 created",result);
+
+ /* Create thread 2, the property is the default value, the separation state is the default value joinable,
+ * The entry function is thread2_entry and the entry function parameter is NULL */
+ result = pthread_create(&tid2,NULL,thread2_entry,NULL);
+ check_result("thread2 created",result);
+
+ pthread_detach(tid2); /* detach thread 2 */
+
+ return 0;
+}
+```
+
+## Waiting for Thread to End
+
+``` c
+int pthread_join (pthread_t thread, void**value_ptr);
+```
+
+| Parameter | **Description** |
+|----------|----------------------|
+| thread | Thread handle (thread identifier) |
+| value_ptr | User-defined pointer to store the return value of the waiting thread, which can be obtained by the function pthread_join() |
+|**Return**| —— |
+| 0 | succeeded |
+| EDEADLK | Thread join itself |
+| EINVAL | Join a thread with a detached state |
+| ESRCH | Could not find the thread |
+
+The thread calling this function blocks and waits for the thread with the joinable property to finish running and gets the return value of the thread. The address of the returned value is stored in `value_ptr` and frees the resources held by thread.
+
+The pthread_join() and pthread_detach() functions are similar in that they are used to reclaim the resources occupied by threads after the thread running ends. A thread cannot wait for itself to end. The detached state of the thread thread must be `joinable`, and one thread only corresponds to the `pthread_join()` call. A thread with a split state of joinable will only release the resources it occupies when other threads execute `pthread_join()` on it. So in order to avoid memory leaks, all threads that will end up running, either detached or set to detached, or use pthread_join() to reclaim the resources they consume.
+
+### Example Code for Waiting for the Thread to End
+
+The following program code initializes 2 threads, they have the same priority, and the threads of the same priority are scheduled according to the time slice. The separation status of the 2 thread attributes is the default value joinable, and thread 1 starts running first, and ends after printing 3 times of information. Thread 2 calls pthread_join() to block waiting for thread 1 to end, and reclaims the resources occupied by thread 1, and thread 2 prints the message every 2 seconds.
+
+``` c
+#include <pthread.h>
+#include <unistd.h>
+#include <stdio.h>
+
+/* Thread control block */
+static pthread_t tid1;
+static pthread_t tid2;
+
+/* Function return value check */
+static void check_result(char* str,int result)
+{
+ if (0 == result)
+ {
+ printf("%s successfully!\n",str);
+ }
+ else
+ {
+ printf("%s failed! error code is %d\n",str,result);
+ }
+}
+
+/* Thread 1 entry function */
+static void* thread1_entry(void* parameter)
+{
+ int i;
+
+ for (int i = 0;i < 3;i++) /* Cycle print 3 times */
+ {
+ printf("thread1 run count: %d\n",i);
+ sleep(2); /* Sleep 2 seconds */
+ }
+
+ printf("thread1 exited!\n");
+ return NULL;
+}
+
+/* Thread 2 entry function */
+static void* thread2_entry(void* parameter)
+{
+ int count = 0;
+ void* thread1_return_value;
+
+ /* Blocking waiting thread 1 running end */
+ pthread_join(tid1, NULL);
+
+ /* Thread 2 print information to start output */
+ while(1)
+ {
+ /* Print thread count value output */
+ printf("thread2 run count: %d\n",count ++);
+ sleep(2); /* Sleep 2 seconds */
+ }
+
+ return NULL;
+}
+
+/* User application portal */
+int rt_application_init()
+{
+ int result;
+ /* Create thread 1, property is the default value, separation state is the default value joinable,
+ * The entry function is thread1_entry and the entry function parameter is NULL */
+ result = pthread_create(&tid1,NULL,thread1_entry,NULL);
+ check_result("thread1 created",result);
+
+ /* Create thread 2, the property is the default value, the separation state is the default value joinable,
+ * The entry function is thread2_entry and the entry function parameter is NULL */
+ result = pthread_create(&tid2,NULL,thread2_entry,NULL);
+ check_result("thread2 created",result);
+
+ return 0;
+}
+```
+
+## Exit Thread
+
+``` c
+void pthread_exit(void *value_ptr);
+```
+
+| *Parameter* | **Description** |
+|----------|---------------------------|
+| value_ptr | User-defined pointer to store the return value of the waiting thread, which can be obtained by the function pthread_join() |
+
+Calling this function by the pthread thread terminates execution, just as the process calls the exit() function and returns a pointer to the value returned by the thread. The thread exit is initiated by the thread itself.
+
+> If the split state of the thread is joinable, the resources occupied by the thread will not be released after the thread exits. The pthread_join() function must be called to release the resources occupied by the thread.
+
+### Example Code for Exiting Thread
+
+This program initializes 2 threads, they have the same priority, and the threads of the same priority are scheduled according to the time slice. The separation state of the two thread attributes is the default value joinable, and thread 1 starts running first, sleeps for 2 seconds after printing the information once, and then prints the exit information and then ends the operation. Thread 2 calls pthread_join() to block waiting for thread 1 to end, and reclaims the resources occupied by thread 1, and thread 2 prints the message every 2 seconds.
+
+``` c
+#include <pthread.h>
+#include <unistd.h>
+#include <stdio.h>
+
+/* Thread control block */
+static pthread_t tid1;
+static pthread_t tid2;
+
+/* Function return value check function */
+static void check_result(char* str,int result)
+{
+ if (0 == result)
+ {
+ printf("%s successfully!\n",str);
+ }
+ else
+ {
+ printf("%s failed! error code is %d\n",str,result);
+ }
+}
+
+/* Thread 1 entry function */
+static void* thread1_entry(void* parameter)
+{
+ int count = 0;
+ while(1)
+ {
+ /* Print thread count value output */
+ printf("thread1 run count: %d\n",count ++);
+ sleep(2); /* Sleep 2 seconds */
+ printf("thread1 will exit!\n");
+
+ pthread_exit(0); /* Thread 1 voluntarily quits */
+ }
+}
+
+/* Thread 2 entry function */
+static void* thread2_entry(void* parameter)
+{
+ int count = 0;
+
+ /* The block waits for thread 1 to finish running */
+ pthread_join(tid1,NULL);
+ /* Thread 2 starts outputting print information */
+ while(1)
+ {
+ /* Print thread count value output */
+ printf("thread2 run count: %d\n",count ++);
+ sleep(2); /* Sleep 2 seconds */
+ }
+}
+
+/* User application portal */
+int rt_application_init()
+{
+ int result;
+
+ /* Create thread 1, property is the default value, separation state is the default value joinable,
+ * The entry function is thread1_entry and the entry function parameter is NULL */
+ result = pthread_create(&tid1,NULL,thread1_entry,NULL);
+ check_result("thread1 created",result);
+
+ /* Create thread 2, the property is the default value, the separation state is the default value joinable,
+ * The entry function is thread2_entry and the entry function parameter is NULL */
+ result = pthread_create(&tid2,NULL,thread2_entry,NULL);
+ check_result("thread2 created",result);
+
+ return 0;
+}
+```
+
+# Mutex
+
+Mutexes, also known as mutually exclusive semaphores, are a special binary semaphore. Mutexes are used to ensure the integrity of shared resources. Only one thread can access the shared resource at any time. To access shared resources, the thread must first obtain the mutex. After the access is complete, the mutex must be released. Embedded shared resources include memory, IO, SCI, SPI, etc. If two threads access shared resources at the same time, there may be problems because one thread may use the resource while another thread modifies the shared resource and consider sharing.
+
+There are only two kinds of operations of mutex, locking or unlocking, and only one thread holds a mutex at a time. When a thread holds it, the mutex is latched and its ownership is obtained by this thread. Conversely, when this thread releases it, it unlocks the mutex and loses its ownership. When a thread holds a mutex, other threads will not be able to unlock it or hold it.
+
+The main APIs of the mutex include: calling `pthread_mutex_init()` to initialize a mutex, `pthread_mutex_destroy()` to destroy the mutex, pthread_mutex_lock() to lock the mutex, and `pthread_mutex_unlock()` to unlock the mutex.
+
+The rt-thread operating system implements a priority inheritance algorithm to prevent priority inversion.Priority inheritance is the practice of raising the priority of a low-priority thread that occupies a resource to the same level as the highest-priority thread of all the threads waiting for the resource, then executing, and then returning to the initial setting when the low-priority thread releases the resource.Thus, threads that inherit priority prevent system resources from being preempted by any intermediate priority thread.
+
+For a detailed introduction to priority reversal, please refer to the @ref page_thread_sync Mutex section.
+
+## Mutex Lock Control Block
+
+Each mutex corresponds to a mutex control block that contains some information about the control of the mutex. Before creating a mutex, you must first define a variable of type `pthread_mutex_t`. pthread_mutex_t is a redefinition of pthread_mutex. The pthread_mutex data structure is defined in the pthread.h header file. The data structure is as follows:
+
+``` c
+struct pthread_mutex
+{
+ pthread_mutexattr_t attr; /* Mutex attribute */
+ struct rt_mutex lock; /* RT-Thread Mutex lock control block */
+};
+typedef struct pthread_mutex pthread_mutex_t;
+
+//rt_mutex is a data structure defined in the RT-Thread kernel, defined in the rtdef.h header file. The data structure is as follows:
+
+struct rt_mutex
+{
+ struct rt_ipc_object parent; /* Inherited from the ipc_object class */
+ rt_uint16_t value; /* Mutex value */
+ rt_uint8_t original_priority; /* thread's original priority */
+ rt_uint8_t hold; /* Mutex lock holding count */
+ struct rt_thread *owner; /* Thread that currently has a mutex */
+};
+typedef struct rt_mutex* rt_mutex_t; /* Rt_mutext_t is a pointer to the mutex structure */
+```
+
+## Initialize the Mutex
+
+``` c
+int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
+```
+
+| **Parameter** | **Description** |
+|----------|------------------------------------------------------|
+| mutex | Mutex lock handle, cannot be NULL |
+| attr | Pointer to the mutex attribute, if the pointer is NULL, the default attribute is used. |
+|**return**| —— |
+| 0 | succeeded |
+| EINVAL | Invalid parameter |
+
+This function initializes the mutex `mutex` and sets the mutex property according to the mutex attribute object pointed to by `attr`. After successful initialization, the mutex is unlocked and the thread can obtain it. This function encapsulates the rt_mutex_init() function.
+
+In addition to calling the pthread_mutex_init() function to create a mutex, you can also statically initialize the mutex with the macro PTHREAD_MUTEX_INITIALIZER by: `pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER` (structure constant), which is equivalent to specifying attr to NULL when calling pthread_mutex_init().
+
+The mutex lock properties and related functions are described in detail in the *thread advanced programming* chapter. In general, the default properties can be used.
+
+## Destroy Mutex
+
+``` c
+int pthread_mutex_destroy(pthread_mutex_t *mutex);
+```
+
+| **Parameter** | **Description** |
+|----------|----------------------|
+| mutex | Mutex lock handle, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Mutex is empty or mutex has been destroyed |
+| EBUSY | Mutex is being used |
+
+This function destroys the mutex `mutex`. Mutex is mutable in an uninitialized state after destruction. After destroying the mutex's properties and control block parameters will not be valid, but you can call pthread_mutex_init() to reinitialize the destroyed mutex. However, there is no need to destroy the mutex that is statically initialized with the macro PTHREAD_MUTEX_INITIALIZER.
+
+The mutex can be destroyed when it is determined that the mutex is not locked and no thread is blocked on the mutex.
+
+## Blocking Mode Locks the Mutex
+
+``` c
+int pthread_mutex_lock(pthread_mutex_t *mutex);
+```
+
+| **Parameter** | **Description** |
+|----------|----------------------|
+| mutex | Mutex lock handle, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+| EDEADLK | Mutexes mutex do not call this function repeatedly for a thread with a nested lock |
+
+This function locks the mutex `mutex`, which is a wrapper of the rt_mutex_take() function. If the mutex has not been locked yet, the thread applying for the mutex will successfully lock the mutex. If the mutex has been locked by the current thread and the mutex type is a nested lock, the mutex's holding count is incremented by one, and the current thread will not suspend waiting (deadlock), but the thread must corresponds to the same number of unlocks. If the mutex is held by another thread, the current thread will be blocked until the other thread unlocks the mutex, and the thread waiting for the mutex will acquire the mutex according to the *first in first out* principle. .
+
+## Non-blocking Mode Locks the Mutex
+
+``` c
+int pthread_mutex_trylock(pthread_mutex_t *mutex);
+```
+
+| **Parameter** | **Description** |
+|----------|----------------------|
+| mutex | Mutex lock handle, cannot be NULL |
+|**return**| —— |
+| 0 | succeeded |
+| EINVAL | Invalid parameter |
+| EDEADLK | Mutexes are not nested locks, but threads call this function repeatedly |
+| EBUSY | Mutexes mutex has been locked by other threads |
+
+This function is a non-blocking version of the pthread_mutex_lock() function. The difference is that if the mutex has been locked, the thread will not be blocked, but the error code will be returned immediately.
+
+## Unlock the Mutex
+
+``` c
+int pthread_mutex_unlock(pthread_mutex_t *mutex);
+```
+
+| Parameter | **Description** |
+|----------|----------------------|
+| mutex | Mutex lock handle, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+| EPERM | This function is called repeatedly by a thread when the mutex is not a nested lock |
+| EBUSY | Unlock the mutex held by other threads with the type of error detection lock |
+
+Calling this function to unlock the mutex. This function is a wrapper of the rt_mutex_release() function. When the thread completes the access of the shared resource, it should release the possessed mutex as soon as possible, so that other threads can acquire the mutex in time. Only a thread that already has a mutex can release it, and its holding count is decremented by one each time the mutex is released. When the mutex's holding count is zero (ie, the holding thread has released all holding operations), the mutex becomes available, and the thread waiting on the mutex is placed in a first-in-first-out manner. If the thread's run priority is promoted by the mutex lock, then when the mutex is released, the thread reverts to the priority before holding the mutex.
+
+## Example Code for Mutex Lock
+
+This program will initialize 2 threads, they have the same priority, 2 threads will call the same printer() function to output their own string, the printer() function will output only one character at a time, then sleep for 1 second, call printer The thread of the () function also sleeps. If you do not use a mutex, thread 1 prints a character, and after hibernation, thread 2 is executed, and thread 2 prints a character, so that the thread 1 and thread 2 strings cannot be completely printed, and the printed string is confusing. If a mutex is used to protect the print function printer() shared by 2 threads, thread 1 takes the mutex and executes the printer() print function to print a character, then sleeps for 1 second, which is switched to thread 2 because The nick lock has been locked by thread 1, and thread 2 will block until thread 1 of thread 1 is fully released and the thread 2 is woken up after the mutex is actively released.
+
+``` c
+#include <pthread.h>
+#include <unistd.h>
+#include <stdio.h>
+
+/* Thread control block */
+static pthread_t tid1;
+static pthread_t tid2;
+/* Mutex lock control block */
+static pthread_mutex_t mutex;
+/* Thread-sharing print function */
+static void printer(char* str)
+{
+ while(*str != 0)
+ {
+ putchar(*str); /* Output one character */
+ str++;
+ sleep(1); /* Sleep 1 second */
+ }
+ printf("\n");
+}
+/* Function return value check */
+static void check_result(char* str,int result)
+{
+ if (0 == result)
+ {
+ printf("%s successfully!\n",str);
+ }
+ else
+ {
+ printf("%s failed! error code is %d\n",str,result);
+ }
+}
+/* Thread entry */
+static void* thread1_entry(void* parameter)
+{
+ char* str = "thread1 hello RT-Thread";
+ while (1)
+ {
+ pthread_mutex_lock(&mutex); /* Mutex lock */
+
+ printer(str); /* Access shared print function */
+
+ pthread_mutex_unlock(&mutex); /* Unlock after access is complete */
+
+ sleep(2); /* Sleep 2 seconds */
+ }
+}
+static void* thread2_entry(void* parameter)
+{
+ char* str = "thread2 hi world";
+ while (1)
+ {
+ pthread_mutex_lock(&mutex); /* The mutex locks */
+
+ printer(str); /* Access shared print function */
+
+ pthread_mutex_unlock(&mutex); /* Unlock after access is complete */
+
+ sleep(2); /* Sleep 2 seconds */
+ }
+}
+/* User application portal */
+int rt_application_init()
+{
+ int result;
+ /* Initialize a mutex */
+ pthread_mutex_init(&mutex,NULL);
+
+ /* Create thread 1, the thread entry is thread1_entry, the attribute parameter is NULL, the default value is selected, and the entry parameter is NULL.*/
+ result = pthread_create(&tid1,NULL,thread1_entry,NULL);
+ check_result("thread1 created",result);
+
+ /* Create thread 2, thread entry is thread2_entry, property parameter is NULL select default value, entry parameter is NULL*/
+ result = pthread_create(&tid2,NULL,thread2_entry,NULL);
+ check_result("thread2 created",result);
+
+ return 0;
+}
+```
+
+# Conditional Variable
+
+A condition variable is actually a semaphore used for synchronization between threads. A condition variable is used to block a thread. When a condition is met, a condition is sent to the blocked thread. The blocking thread is woken up. The condition variable needs to be used with the mutex. The mutex is used to protect the shared data.
+
+Condition variables can be used to inform shared data status. For example, if a thread that processes a shared resource queue finds that the queue is empty, then the thread can only wait until one node is added to the queue. After adding, a conditional variable signal is sent to activate the waiting thread.
+
+The main operations of the condition variable include: calling `pthread_cond_init()` to initialize the condition variable, calling `pthread_cond_destroy()` to destroy a condition variable, calling `pthread_cond_wait()` to wait for a condition variable, and calling `pthread_cond_signal()` to send a condition variable.
+
+## Condition Variable Control Block
+
+Each condition variable corresponds to a condition variable control block, including some information about the operation of the condition variable. A `pthread_cond_t` condition variable control block needs to be defined before initializing a condition variable. `pthread_cond_t` is a redefinition of the `pthread_cond` structure type, defined in the pthread.h header file.
+
+``` c
+struct pthread_cond
+{
+ pthread_condattr_t attr; /* Condition variable attribute */
+ struct rt_semaphore sem; /* RT-Thread semaphore control block */
+};
+typedef struct pthread_cond pthread_cond_t;
+
+Rt_semaphore is a data structure defined in the RT-Thread kernel. It is a semaphore control block defined in the rtdef.h header file.
+
+struct rt_semaphore
+{
+ struct rt_ipc_object parent; /* Inherited from the ipc_object class */
+ rt_uint16_t value; /* Semaphore value */
+};
+```
+
+## Initialization Condition Variable
+
+``` c
+int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);
+```
+
+| **Parameter** | **Description** |
+|----|------------------------------------------------|
+| cond | Conditional variable handle, cannot be NULL |
+| attr | Pointer to the condition variable property, if NULL then use the default property value |
+|**return**| —— |
+| 0 | succeeded |
+| EINVAL | Invalid parameter |
+
+This function initializes the `cond` condition variable and sets its properties according to the condition variable property pointed to by `attr` , which is a wrapper of the `rt_sem_init()` function, based on semaphore implementation. The condition variable is not available after successful initialization.
+
+You can also statically initialize a condition variable with the macro PTHREAD_COND_INITIALIZER by: `pthread_cond_t cond = PTHREAD_COND_INITIALIZER` (structural constant), which is equivalent to specifying NULL when calling `pthread_cond_init()`.
+
+Attr General setting NULL use the default value, as described in the thread advanced programming chapter.
+
+## Destroy Condition Variables
+
+``` c
+int pthread_cond_destroy(pthread_cond_t *cond);
+```
+
+| **Parameter** | **Description** |
+|----|------------------------|
+| cond | Conditional variable handle, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+| EPERM | Mutexes are not nested locks, but threads call this function repeatedly |
+| EBUSY | Condition variables are being used |
+
+This function destroys the `cond` condition variable, and the `cond` is uninitialized after destruction. The attribute and control block parameters of the condition variable will not be valid after destruction, but can be reinitialized by calling `pthread_cond_init()` or statically.
+
+Before destroying a condition variable, you need to make sure that no threads are blocked on the condition variable and will not wait to acquire, signal, or broadcast.
+
+## Blocking Mode to Obtain Condition Variables
+
+``` c
+int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
+```
+
+| **Parameter** | **Description** |
+|----------|----------------------------------|
+| cond | Conditional variable handle, cannot be NULL |
+| mutex | Pointer to the mutex control block, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+
+This function gets the `cond` condition variable in blocking mode. The thread needs to lock the mutex before waiting for the condition variable. This function first determines whether the condition variable is available. If it is not available, initializes a condition variable, then unlocks the mutex and then tries to acquire a semaphore when the semaphore's value is greater than zero, it indicates that the semaphore is available, the thread will get the semaphore, and the condition variable will be obtained, and the corresponding semaphore value will be decremented by 1. If the value of the semaphore is equal to zero, indicating that the semaphore is not available, the thread will block until the semaphore is available, after which the mutex will be locked again.
+
+## Specify Blocking Time to Obtain Condition Variables
+
+``` c
+int pthread_cond_timedwait(pthread_cond_t *cond,
+ pthread_mutex_t *mutex,
+ const struct timespec *abstime);
+```
+
+| **Parameter** | **Description** |
+|-------|-------------------------------------------------|
+| cond | Conditional variable handle, cannot be NULL |
+| mutex | Pointer to the mutex control block, cannot be NULL |
+| abstime | The specified wait time in operating system clock tick (OS Tick) |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+| EPERM | Mutexes are not nested locks, but threads call this function repeatedly |
+| ETIMEDOUT | time out |
+
+The only difference between this function and the `pthread_cond_wait()` function is that if the condition variable is not available, the thread will be blocked for the `abstime` duration. After the timeout, the function will directly return the ETIMEDOUT error code and the thread will be woken up to the ready state.
+
+## Send a Conditional Semaphore
+
+``` c
+int pthread_cond_signal(pthread_cond_t *cond);
+```
+
+| **Parameter** | **Description** |
+|----|------------------------|
+| cond | Conditional variable handle, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+
+This function sends a signal and wakes up only one thread waiting for the `cond` condition variable, which encapsulates the rt_sem_release() function, which is to send a semaphore. When the value of the semaphore is equal to zero, and a thread waits for this semaphore, it will wake up the first thread waiting in the queue of the semaphore to get the semaphore. Otherwise the value of the semaphore will be increased by 1.
+
+## Broadcast
+
+``` c
+int pthread_cond_broadcast(pthread_cond_t *cond);
+```
+
+| **Parameter** | **Description** |
+|----|------------------------|
+| cond | Conditional variable handle, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+
+Calling this function will wake up all threads waiting for the `cond` condition variable.
+
+## Example Code for Condition Variable
+
+This example is a producer consumer model with a producer thread and a consumer thread that have the same priority. The producer will produce a number every 2 seconds, put it in the list pointed to by the `head`, and then call pthread_cond_signal() to send signal to the consumer thread to inform the consumer that there is data in the thread list. The consumer thread calls pthread_cond_wait() to wait for the producer thread to send a signal.
+
+``` c
+#include <pthread.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+/* Statically initialize a mutex and a condition variable */
+static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
+
+/* Pointer to the thread control block */
+static pthread_t tid1;
+static pthread_t tid2;
+
+/* Function return value check */
+static void check_result(char* str,int result)
+{
+ if (0 == result)
+ {
+ printf("%s successfully!\n",str);
+ }
+ else
+ {
+ printf("%s failed! error code is %d\n",str,result);
+ }
+}
+
+/* The structure data produced by the producer is stored in the linked list. */
+struct node
+{
+ int n_number;
+ struct node* n_next;
+};
+struct node* head = NULL; /* Link header, is a shared resource */
+
+/* Consumer thread entry function */
+static void* consumer(void* parameter)
+{
+ struct node* p_node = NULL;
+
+ pthread_mutex_lock(&mutex); /* Lock on mutex */
+
+ while (1)
+ {
+ while (head == NULL) /* Determine if there are elements in the list */
+ {
+ pthread_cond_wait(&cond,&mutex); /* Try to get a condition variable */
+ }
+ /*
+ Pthread_cond_wait() will unlock the mutex first, then block in the wait queue until the fetch condition variable is awakened. After being woken up, the thread will lock the mutex again and successfully enter the critical section.
+ */
+
+ p_node = head; /* Obtain resources */
+ head = head->n_next; /* Header pointing to the next resource */
+ /* Printout */
+ printf("consume %d\n",p_node->n_number);
+
+ free(p_node); /* Release the memory occupied by the node after obtaining the resource */
+ }
+ pthread_mutex_unlock(&mutex); /* Release the mutex */
+ return 0;
+}
+/* Producer thread entry function */
+static void* product(void* patameter)
+{
+ int count = 0;
+ struct node *p_node;
+
+ while(1)
+ {
+ /* Dynamically allocate a block of structured memory */
+ p_node = (struct node*)malloc(sizeof(struct node));
+ if (p_node != NULL)
+ {
+ p_node->n_number = count++;
+ pthread_mutex_lock(&mutex); /* To operate on the critical resource head, lock it first */
+
+ p_node->n_next = head;
+ head = p_node; /* Insert data into the list header */
+
+ pthread_mutex_unlock(&mutex); /* Unlock */
+ printf("produce %d\n",p_node->n_number);
+
+ pthread_cond_signal(&cond); /* send a Signal to wake up a thread */
+
+ sleep(2); /* Sleep 2 seconds */
+ }
+ else
+ {
+ printf("product malloc node failed!\n");
+ break;
+ }
+ }
+}
+
+int rt_application_init()
+{
+ int result;
+
+ /* Create a producer thread, the property is the default value, the entry function is product, and the entry function parameter is NULL*/
+ result = pthread_create(&tid1,NULL,product,NULL);
+ check_result("product thread created",result);
+
+ /* Create a consumer thread, the property is the default value, the entry function is consumer, and the entry function parameter is NULL */
+ result = pthread_create(&tid2,NULL,consumer,NULL);
+ check_result("consumer thread created",result);
+
+ return 0;
+}
+```
+
+# Read-write Lock
+
+Read-write locks are also known as multi-reader single-writer locks. The read-write lock divides the visitors of the shared resource into readers and writers. The reader only reads and accesses the shared resources, and the writer needs to write the shared resources. Only one thread can occupy the read-write lock of the write mode at the same time, but there can be multiple threads simultaneously occupying the read-write lock of the read mode. Read-write locks are suitable for reading data structures much more often than writes because read patterns can be shared when locked, and write mode locks are exclusive.
+
+Read-write locks are usually implemented based on mutex locks and condition variables. A thread can lock a read-write lock several times, and it must also have the corresponding number of unlocks.
+
+The main operations of the read-write lock include: calling `pthread_rwlock_init()` to initialize a read-write lock, the write thread calling `pthread_rwlock_wrlock()` to lock the read-write lock, and the read thread calling `pthread_rwlock_rdlock()` to lock the read-write lock , when this read-write lock is not required, calling `pthread_rwlock_destroy()` to destroys the read-write lock.
+
+## Read-write Lock Control Block
+
+Each read-write lock corresponds to a read-write lock control block, including some information about the operation of the read-write lock. `pthread_rwlock_t` is a redefinition of the `pthread_rwlock` data structure, defined in the `pthread.h` header file. Before creating a read-write lock, you need to define a data structure of type `pthread_rwlock_t`.
+
+``` c
+struct pthread_rwlock
+{
+ pthread_rwlockattr_t attr; /* Read-write lock attribute */
+ pthread_mutex_t rw_mutex; /* Mutex lock */
+ pthread_cond_t rw_condreaders; /* Conditional variables for the reader thread to use */
+ pthread_cond_t rw_condwriters; /* Conditional variable for the writer thread to use */
+ int rw_nwaitreaders; /* Reader thread waiting to count */
+ int rw_nwaitwriters; /* Writer thread waiting to count */
+ /* Read-write lock value, value 0: unlocked, value -1: is locked by the writer thread, greater than 0 value: locked by the reader thread */
+ int rw_refcount;
+};
+typedef struct pthread_rwlock pthread_rwlock_t; /* Type redefinition */
+```
+
+## Initialize Read-write Lock
+
+``` c
+int pthread_rwlock_init (pthread_rwlock_t *rwlock,
+ const pthread_rwlockattr_t *attr);
+```
+
+| **Parameter** | **Description** |
+|------|-------------------------------------------|
+| rwlock | Read-write lock handle, cannot be NULL |
+| attr | Pointer to the read-write lock property, RT-Thread does not use this variable |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+
+This function initializes an `rwlock` read-write lock. This function initializes the semaphore and condition variables of the read-write lock control block with default values, and the associated count parameter is initially 0. The read-write lock after initialization is in an unlocked state.
+
+You can also use the macro PTHREAD_RWLOCK_INITIALIZER to statically initialize the read-write lock by: `pthread_rwlock_t mutex = PTHREAD_RWLOCK_INITIALIZER` (structural constant), which is equivalent to specifying `attr` a NULL value when calling pthread_rwlock_init().
+
+`attr` generally sets NULL to the default value, as described in the chapter on advanced threading.
+
+## Destroy Read-write Lock
+
+``` c
+int pthread_rwlock_destroy (pthread_rwlock_t *rwlock);
+```
+
+| **Parameter** | **Description** |
+|------|----------------------|
+| rwlock | Read-write lock handle, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+| EBUSY | The read-write lock is currently being used or has a thread waiting for the read-write lock |
+| EDEADLK | Deadlock |
+
+This function destroys a `rwlock` read-write lock, which destroys the mutex and condition variables in the read-write lock. After the destruction, the properties of the read-write lock and the control block parameters will not be valid, but you can call pthread_rwlock_init() or re-initialize the read-write lock in static mode.
+
+## Read-Lock of Read-Write Lock
+
+### Blocking mode Read-lock the read-write locks
+
+``` c
+int pthread_rwlock_rdlock (pthread_rwlock_t *rwlock);
+```
+
+| **Parameter** | **Description** |
+|------|----------------------|
+| rwlock | Read-write lock handle, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+| EDEADLK | Deadlock |
+
+The reader thread can call this function to read-lock the `rwlock` read-write lock. If the read-write lock is not write-locked and no writer thread is blocked on the read-write lock, the read-write thread will successfully acquire the read-write lock. If the read-write lock has been write-locked, the reader thread will block until the thread that executes the write-lock unlocks the read-write lock.
+
+### Non-blocking Mode Read-lock Read-write Locks
+
+``` c
+int pthread_rwlock_tryrdlock (pthread_rwlock_t *rwlock);
+```
+
+| **Parameter** | **Description** |
+|------|----------------------|
+| rwlock | Read-write lock handle, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+| EBUSY | The read-write lock is currently being used or has a thread waiting for the read-write lock |
+| EDEADLK | Deadlock |
+
+This function differs from the pthread_rwlock_rdlock() function in that if the read-write lock is already write-locked, the reader thread is not blocked, but instead returns an error code EBUSY.
+
+### Specify Blocking Time for the Read-write Lock to be Read-Locked
+
+``` c
+int pthread_rwlock_timedrdlock (pthread_rwlock_t *rwlock,
+ const struct timespec *abstime);
+```
+
+| **Parameter** | **Description** |
+|-------|-------------------------------------------------|
+| rwlock | Read-write lock handle, cannot be NULL |
+| abstime | The specified wait time in operating system clock tick (OS Tick) |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+| ETIMEDOUT | Time out |
+| EDEADLK | Deadlock |
+
+The difference between this function and the pthread_rwlock_rdlock() function is that if the read-write lock has been write-locked, the reader thread will block the specified abstime duration. After the timeout, the function will return the error code ETIMEDOUT and the thread will be woken up to the ready state.
+
+## Write-Lock of Read-Write Lock
+
+### Blocking Mode Write-Locks a Read-write Lock
+
+``` c
+int pthread_rwlock_wrlock (pthread_rwlock_t *rwlock);
+```
+
+| **Parameter** | **Description** |
+|------|----------------------|
+| rwlock | Read-write lock handle, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+| EDEADLK | Deadlock |
+
+The writer thread calls this function to write-lock the `rwlock` read-write lock. A write-lock read-write lock is similar to a mutex, and only one thread can write-lock a read-write lock at a time. If no thread locks the read-write lock, that is, the read-write lock value is 0, the writer thread that calls this function will write-lock the read-write lock, and other threads cannot acquire the read-write lock at this time. If there is already a thread locked the read-write lock, ie the read/write lock value is not 0, then the writer thread will be blocked until the read-write lock is unlocked.
+
+### Non-blocking Mode Write-Lock a Read-write Lock
+
+``` c
+int pthread_rwlock_trywrlock (pthread_rwlock_t *rwlock);
+```
+
+| **Parameter** | **Description** |
+|------|----------------------|
+| rwlock | Read-write lock handle, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+| EBUSY | The read-write lock is currently Write-Locked or there are reader threads blocked on the read-write lock |
+| EDEADLK | Deadlock |
+
+The only difference between this function and the pthread_rwlock_wrlock() function is that if a thread has locked the read-write lock, ie the read-write lock value is not 0, the writer thread that called the function will directly return an error code, and the thread will not be Blocked.
+
+### Specify Blocking Time for the Read-write Lock to be Write-Lock
+
+``` c
+int pthread_rwlock_timedwrlock (pthread_rwlock_t *rwlock,
+ const struct timespec *abstime);
+```
+
+| **Parameter** | **Description** |
+|--------------|---------------------|
+| rwlock abstime | Read-write lock handle, cannot specify the wait time for NULL, the unit is the operating system clock beat (OS Tick) |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+| ETIMEDOUT | Time out |
+| EDEADLK | Deadlock |
+
+The only difference between this function and the pthread_rwlock_wrlock() function is that if a thread locks the read-write lock, that is, the read-write lock value is not 0, the calling thread blocks the specified `abstime` duration. After the timeout, the function returns the error code ETIMEDOUT, and the thread will be woken up to the ready state.
+
+## Unlock the Read-write Lock
+
+``` c
+int pthread_rwlock_unlock (pthread_rwlock_t *rwlock);
+```
+
+| **Parameter** | **Description** |
+|------|----------------------|
+| rwlock | Read-write lock handle, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+| EDEADLK | Deadlock |
+
+This function unlocks the `rwlock` read-write lock. A thread locks the same read-write lock multiple times and must have the same number of unlocks. If multiple threads wait for the read-write lock to lock after unlocking, the system will activate the waiting thread according to the first-in-first-out rule.
+
+## Example Code for Read-write Lock
+
+This program has two reader threads, one reader thread. The two reader threads read-lock the read-write lock first, then sleep for 2 seconds. This time the other reader threads can read-lock the read-write lock, and then read the shared data.
+
+``` c
+#include <pthread.h>
+#include <sched.h>
+#include <stdio.h>
+
+/* Thread control block */
+static pthread_t reader1;
+static pthread_t reader2;
+static pthread_t writer1;
+/* Shared data book */
+static int book = 0;
+/* Read-write lock */
+static pthread_rwlock_t rwlock;
+/* Function result check */
+static void check_result(char* str,int result)
+{
+ if (0 == result)
+ {
+ printf("%s successfully!\n",str);
+ }
+ else
+ {
+ printf("%s failed! error code is %d\n",str,result);
+ }
+}
+/* Thread entry */
+static void* reader1_entry(void* parameter)
+{
+ while (1)
+ {
+
+ pthread_rwlock_rdlock(&rwlock); /* Try to read-lock the read-write lock */
+
+ printf("reader1 read book value is %d\n",book);
+ sleep(2); /* The thread sleeps for 2 seconds, switching to another thread to run */
+
+ pthread_rwlock_unlock(&rwlock); /* Unlock the read-write lock after the thread runs */
+ }
+}
+static void* reader2_entry(void* parameter)
+{
+ while (1)
+ {
+ pthread_rwlock_rdlock(&rwlock); /* Try to read-lock the read-write lock */
+
+ printf("reader2 read book value is %d\n",book);
+ sleep(2); /* The thread sleeps for 2 seconds, switching to another thread to run */
+
+ pthread_rwlock_unlock(&rwlock); /* Unlock the read-write lock after the thread runs */
+ }
+}
+static void* writer1_entry(void* parameter)
+{
+ while (1)
+ {
+ pthread_rwlock_wrlock(&rwlock); /* Try to write-lock the read-write lock */
+
+ book++;
+ printf("writer1 write book value is %d\n",book);
+
+ pthread_rwlock_unlock(&rwlock); /* Unlock the read-write lock */
+
+ sleep(2); /* The thread sleeps for 2 seconds, switching to another thread to run */
+ }
+}
+/* User application portal */
+int rt_application_init()
+{
+ int result;
+ /* Default property initializes read-write lock */
+ pthread_rwlock_init(&rwlock,NULL);
+
+ /* Create a reader1 thread, the thread entry is reader1_entry, the thread attribute is the default value, and the entry parameter is NULL*/
+ result = pthread_create(&reader1,NULL,reader1_entry,NULL);
+ check_result("reader1 created",result);
+
+ /* Create a reader2 thread, the thread entry is reader2_entry, the thread attribute is the default value, and the entry parameter is NULL*/
+ result = pthread_create(&reader2,NULL,reader2_entry,NULL);
+ check_result("reader2 created",result);
+
+ /* Create a writer1 thread, the thread entry is writer1_entry, the thread attribute is, and the entry parameter is NULL*/
+ result = pthread_create(&writer1,NULL,writer1_entry,NULL);
+ check_result("writer1 created",result);
+
+ return 0;
+}
+```
+
+# Barrier
+
+Barriers are a way to synchronize multithreading. Barrier means a barrier or railing that blocks multiple threads that arrive in the same railing until all threads arrived, then remove the railings and let them go at the same time. The thread that arrives first will block, and when all the threads that call the pthread_barrier_wait() function (the number equal to the count specified by the barrier initialization) arrive, the threads will enter the ready state from the blocked state and participate in the system scheduling again.
+
+Barriers are implemented based on condition variables and mutex locks. The main operations include: calling `pthread_barrier_init()` to initialize a barrier, and other threads calling `pthread_barrier_wait()`. After all threads arrived, the thread wakes up to the ready state. Destroy a barrier by calling pthread_barrier_destroy() when the barrier will not be used.
+
+## Barrier Control Block
+
+Before creating a barrier, you need to define a `pthread_barrier_t` barrier control block. `pthread_barrier_t` is a redefinition of the `pthread_barrier` structure type, defined in the pthread.h header file.
+
+``` c
+struct pthread_barrier
+{
+ int count; /* The number of waiting threads specified */
+ pthread_cond_t cond; /* Conditional variable */
+ pthread_mutex_t mutex; /* Mutex lock */
+};
+typedef struct pthread_barrier pthread_barrier_t;
+```
+
+## Create a Barrier
+
+``` c
+int pthread_barrier_init(pthread_barrier_t *barrier,
+ const pthread_barrierattr_t *attr,
+ unsigned count);
+```
+
+| **Parameter** | **Description** |
+|-------|-------------------------------|
+| attr | Pointer to the barrier property, if passing NULL, use the default value. PTHREAD_PROCESS_PRIVATE must be used as a non-NULL value. |
+| barrier | Barrier handle |
+| count | The number of waiting threads specified |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+
+This function creates a `barrier` barrier and initializes the conditional variables and mutex locks of the barrier control block according to the default parameters. The number of waiting threads specified after initialization is `count`, and pthread_barrier_wait() must be called for `count` threads.
+
+attr generally sets NULL to the default value, as described in the chapter on *thread advanced programming*.
+
+## Destruction of Barrier
+
+``` c
+int pthread_barrier_destroy(pthread_barrier_t *barrier);
+```
+
+| **Parameter** | **Description** |
+|-------|--------|
+| barrier | Barrier handle |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+
+This function destroys a barrier. The barrier's properties and control block parameters will not be valid after destruction, but can be reinitialized by calling pthread_barrier_init().
+
+## Wait for Barrier
+
+``` c
+int pthread_barrier_wait(pthread_barrier_t *barrier);
+```
+
+| **Parameter** | **Description** |
+|-------|--------|
+| barrier | Barrier handle |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+
+This function synchronizes the threads waiting in front of the barrier and called by each thread. If the number of queue waiting threads is not 0, count will be decremented by 1. If the count is 0, indicating that all threads have reached the railing. All arriving threads will be woken up and re-entered into the ready state to participate in system scheduling. If count is not 0 after the decrease, it indicates that there is still threads that do not reach the barrier, and the calling thread will block until all threads reach the barrier.
+
+## Example Code for Barrier
+
+This program will create 3 threads, initialize a barrier, and the barrier waits for 3 threads. 3 threads will call pthread_barrier_wait() to wait in front of the barrier. When all 3 threads are arrived, 3 threads will enter the ready state. The output count information is printed every 2 seconds.
+
+``` c
+#include <pthread.h>
+#include <unistd.h>
+#include <stdio.h>
+
+/* Thread control block */
+static pthread_t tid1;
+static pthread_t tid2;
+static pthread_t tid3;
+/* Barrier control block */
+static pthread_barrier_t barrier;
+/* Function return value check function */
+static void check_result(char* str,int result)
+{
+ if (0 == result)
+ {
+ printf("%s successfully!\n",str);
+ }
+ else
+ {
+ printf("%s failed! error code is %d\n",str,result);
+ }
+}
+/* Thread 1 entry function */
+static void* thread1_entry(void* parameter)
+{
+ int count = 0;
+
+ printf("thread1 have arrived the barrier!\n");
+ pthread_barrier_wait(&barrier); /* Reach the barrier and wait for other threads to arrive */
+
+ while (1)
+ {
+ /* Print thread count value output */
+ printf("thread1 count: %d\n",count ++);
+
+ /* Sleep 2 seconds */
+ sleep(2);
+ }
+}
+/* Thread 2 entry function */
+static void* thread2_entry(void* parameter)
+{
+ int count = 0;
+
+ printf("thread2 have arrived the barrier!\n");
+ pthread_barrier_wait(&barrier);
+
+ while (1)
+ {
+ /* Print thread count value */
+ printf("thread2 count: %d\n",count ++);
+
+ /* Sleep 2 seconds */
+ sleep(2);
+ }
+}
+/* Thread 3 entry function */
+static void* thread3_entry(void* parameter)
+{
+ int count = 0;
+
+ printf("thread3 have arrived the barrier!\n");
+ pthread_barrier_wait(&barrier);
+
+ while (1)
+ {
+ /* Print thread count value */
+ printf("thread3 count: %d\n",count ++);
+
+ /* Sleep 2 seconds */
+ sleep(2);
+ }
+}
+/* User application portal */
+int rt_application_init()
+{
+ int result;
+ pthread_barrier_init(&barrier,NULL,3);
+
+ /* Create thread 1, thread entry is thread1_entry, property parameter is set to NULL, select default value, entry parameter is NULL*/
+ result = pthread_create(&tid1,NULL,thread1_entry,NULL);
+ check_result("thread1 created",result);
+
+ /* Create thread 2, thread entry is thread2_entry, property parameter is set to NULL, select default value, entry parameter is NULL*/
+ result = pthread_create(&tid2,NULL,thread2_entry,NULL);
+ check_result("thread2 created",result);
+
+ /* Create thread 3, thread entry is thread3_entry, property parameter is set to NULL Select default value, entry parameter is NULL*/
+ result = pthread_create(&tid3,NULL,thread3_entry,NULL);
+ check_result("thread3 created",result);
+
+}
+```
+
+# Semaphore
+
+Semaphores can be used for communication between processes and processes, or between in-process threads. Each semaphore has a semaphore value that is not less than 0, corresponding to the available amount of semaphore. Call sem_init() or sem_open() to assign an initial value to the semaphore . Call sem_post() to increment the semaphore value by 1. Call sem_wait() to decrement the semaphore value by 1. If the current semaphore is 0, call sem_wait(), the thread will suspended on the wait queue for this semaphore until the semaphore value is greater than 0 and is available.
+
+Depending on the value of the semaphore (representing the number of available resources), POSIX semaphores can be divided into:
+
+- **Binary semaphore**: The value of the semaphore is only 0 and 1, and the initial value is specified as 1. This is the same as a mutex. If the resource is locked, the semaphore value is 0. If the resource is available, the semaphore value is 1. Equivalent to only one key, after the thread gets the key, after completing the access to the shared resource, you need to unlock it, put the key back, and use it for other threads that need this key. The method is the same as the mutex lock. The wait semaphore function must be used in pairs with the send semaphore function. It cannot be used alone.
+
+- **Count semaphore**: The value of the semaphore ranges from 0 to a limit greater than 1 (POSIX indicates that the system's maximum limit is at least 32767). This count indicates the number of available semaphores. At this point, the send semaphore function can be called separately to send the semaphore, which is equivalent to having more than one key, the thread takes a key and consumes one, and the used key does not have to be put back.
+
+POSIX semaphores are also divided into named semaphores and unnamed semaphores:
+
+- A named semaphore: its value is stored in a file and is generally used for inter-process synchronization or mutual exclusion.
+
+- Unnamed semaphore: Its value is stored in memory and is generally used for inter-thread synchronization or mutual exclusion.
+
+The POSIX semaphore of the RT-Thread operating system is mainly based on a package of RT-Thread kernel semaphores, mainly used for communication between threads in the system. It is used in the same way as the semaphore of the RT-Thread kernel.
+
+## Semaphore Control Block
+
+Each semaphore corresponds to a semaphore control block. Before creating a semaphore, you need to define a sem_t semaphore control block. Sem_t is a redefinition of the posix_sem structure type, defined in the semaphore.h header file.
+
+``` c
+struct posix_sem
+{
+ rt_uint16_t refcount;
+ rt_uint8_t unlinked;
+ rt_uint8_t unamed;
+ rt_sem_t sem; /* RT-Thread semaphore */
+ struct posix_sem* next; /* Point to the next semaphore control block */
+};
+typedef struct posix_sem sem_t;
+
+Rt_sem_t is the RT-Thread semaphore control block, defined in the rtdef.h header file.
+
+struct rt_semaphore
+{
+ struct rt_ipc_object parent;/* Inherited from the ipc_object class */
+ rt_uint16_t value; /* Semaphore value */
+};
+/* rt_sem_t is a pointer type to the semaphore structure */
+typedef struct rt_semaphore* rt_sem_t;
+
+```
+
+## Unnamed semaphore
+
+The value of an unnamed semaphore is stored in memory and is generally used for inter-thread synchronization or mutual exclusion. Before using it, you must first call sem_init() to initialize it.
+
+### Initialize the unnamed semaphore
+
+``` c
+int sem_init(sem_t *sem, int pshared, unsigned int value);
+```
+
+| **Parameter** | **Description** |
+|-------|--------------------------------------|
+| sem | Semaphore handle |
+| value | The initial value of the semaphore, indicating the available amount of semaphore resources |
+| pshared | RT-Thread unimplemented parameters |
+|**return**| —— |
+| 0 | Succeeded |
+| -1 | Failed |
+
+This function initializes an unnamed semaphore sem, initializes the semaphore related data structure according to the given or default parameters, and puts the semaphore into the semaphore list. The semaphore value after initialization is the given initial value. This function is a wrapper of the rt_sem_create() function.
+
+### Destroy Unnamed Semaphore
+
+``` c
+int sem_destroy(sem_t *sem);
+```
+
+| **Parameter** | **Description** |
+|----|----------|
+| sem | Semaphore handle |
+|**return**| —— |
+| 0 | Succeeded |
+| -1 | Failed |
+
+This function destroys an unnamed semaphore sem and releases the resources occupied by the semaphore.
+
+## Named Semaphore
+
+A named semaphore whose value is stored in a file and is generally used for inter-process synchronization or mutual exclusion. Two processes can operate on named semaphores of the same name. The well-known semaphore implementation in the RT-Thread operating system is similar to the unnamed semaphore. It is designed for communication between threads and is similar in usage.
+
+### Create or Open a Named Semaphore
+
+``` c
+sem_t *sem_open(const char *name, int oflag, ...);
+```
+
+| **Parameter** | **Description** |
+|----------|----------------|
+| name | Semaphore name |
+| oflag | The way the semaphore is opened |
+|**return**| —— |
+| Semaphore handle | Succeeded |
+| NULL | Failed |
+
+This function creates a new semaphore based on the semaphore name or opens an existing semaphore. The optional values for Oflag are `0`, `O_CREAT` or `O_CREAT|O_EXCL`. If Oflag is set to `O_CREAT` , a new semaphore is created. If Oflag sets to `O_CREAT|O_EXCL`, it returns NULL if the semaphore already exists, and creates a new semaphore if it does not exist. If Oflag is set to 0, a semaphore does not exist and NULL is returned.
+
+### Detach the Named Semaphore
+
+``` c
+int sem_unlink(const char *name);
+```
+
+| **Parameter** | **Description** |
+|----|----------|
+| name | Semaphore name |
+|**return**| —— |
+| 0 | Succeeded |
+| -1 | Failed, semaphore does not exist |
+
+This function looks up the semaphore based on the semaphore name, and marks the semaphore as a detached state if the semaphore is present. Then check the reference count. If the value is 0, the semaphore is deleted immediately. If the value is not 0, it will not be deleted until all threads holding the semaphore close the semaphore.
+
+### Close the Named Semaphore
+
+``` c
+int sem_close(sem_t *sem);
+```
+
+| **Parameter** | **Description** |
+|----|----------|
+| sem | Semaphore handle |
+|**return**| —— |
+| 0 | Succeeded |
+| -1 | Failed |
+
+When a thread terminates,it closes the semaphore it occupies. Whether the thread terminates voluntarily or involuntarily, this closing operation is performed. This is equivalent to a reduction of 1 in the number of semaphores held. If the holding count is zero after subtracting 1 and the semaphore is in separated state, the `sem` semaphore will be deleted and the resources it occupies will be released.
+
+## Obtain Semaphore Value
+
+``` c
+int sem_getvalue(sem_t *sem, int *sval);
+```
+
+| **Parameter** | **Description** |
+|----|---------------------------------|
+| sem | Semaphore handle, cannot be NULL |
+| sval | Save the obtained semaphore value address, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| -1 | Failed |
+
+This function obtains the value of the semaphore and saves it in the memory pointed to by `sval` to know the amount of semaphore resources.
+
+## Blocking Mode to Wait Semaphore
+
+``` c
+int sem_wait(sem_t *sem);
+```
+
+| **Parameter** | **Description** |
+|----|----------------------|
+| sem | Semaphore handle, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| -1 | Failed |
+
+The thread calls this function to get the semaphore, which is a wrapper of the `rt_sem_take(sem,RT_WAITING_FOREVER)` function. If the semaphore value is greater than zero, the semaphore is available, the thread gets the semaphore, and the semaphore value is decremented by one. If the semaphore value is equal to 0, indicating that the semaphore is not available, the thread is blocked and entering the suspended state and queued in a first-in, first-out manner until the semaphore is available.
+
+## Non-blocking Mode to Wait Semaphore
+
+``` c
+int sem_trywait(sem_t *sem);
+```
+
+| **Parameter** | **Description** |
+|----|----------------------|
+| sem | Semaphore handle, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| -1 | Failed |
+
+This function is a non-blocking version of the sem_wait() function and is a wrapper of the `rt_sem_take(sem,0)` function. When the semaphore is not available, the thread does not block, but returns directly.
+
+## Specify the Blocking Time Waiting for the Semaphore
+
+``` c
+int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
+```
+
+| **Parameter** | **Description** |
+|------------|-------------------------------------------------|
+| sem | Semaphore handle, cannot be NULL |
+| abs_timeout | The specified wait time in operating system clock tick (OS Tick) |
+|**return**| —— |
+| 0 | Succeeded |
+| -1 | Failed |
+
+The difference between this function and `the sem_wait()` function is that if the semaphore is not available, the thread will block the duration of `abs_timeout`. After the timeout, the function returns -1, and the thread will be awakened from the blocking state to the ready state.
+
+## Send Semaphore
+
+``` c
+int sem_post(sem_t *sem);
+```
+
+| **Parameter** | **Description** |
+|----|----------------------|
+| sem | Semaphore handle, cannot be NULL |
+|**return**| —— |
+| 0 | Succeeded |
+| -1 | Failed |
+
+This function will release a sem semaphore, which is a wrapper of the rt_sem_release() function. If the thread queue waiting for the semaphore is not empty, indicating that there are threads waiting for the semaphore, the first thread waiting for the semaphore will switch from the suspended state to the ready state, waiting for system scheduling. If no thread is waiting for the semaphore, the semaphore value will be incremented by one.
+
+## Example Code for Unnamed Semaphore
+
+A typical case of semaphore usage is the producer consumer model. A producer thread and a consumer thread operate on the same block of memory, the producer fills the shared memory, and the consumer reads the data from the shared memory.
+
+This program creates 2 threads, 2 semaphores, one semaphore indicates that the shared data is empty, one semaphore indicates that the shared data is not empty, and a mutex is used to protect the shared resource. After the producer thread produces the data, it will send a `full_sem` semaphore to the consumer, informing the consumer that the thread has data available, and waiting for the `empty_sem` semaphore sent by the consumer thread after 2 seconds of sleep. The consumer thread processes the shared data after the `full_sem` sent by the producer, and sends an `empty_sem` semaphore to the producer thread after processing. The program will continue to loop like this.
+
+``` c
+#include <pthread.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <semaphore.h>
+
+/* Statically initialize a mutex to protect shared resources */
+static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+/* 2 semaphore control blocks, one for resource empty signals and one for resource full signals */
+static sem_t empty_sem,full_sem;
+
+/* Pointer to the thread control block */
+static pthread_t tid1;
+static pthread_t tid2;
+
+/* Function return value check */
+static void check_result(char* str,int result)
+{
+ if (0 == result)
+ {
+ printf("%s successfully!\n",str);
+ }
+ else
+ {
+ printf("%s failed! error code is %d\n",str,result);
+ }
+}
+
+/* The structure data produced by the producer is stored in the linked list. */
+struct node
+{
+ int n_number;
+ struct node* n_next;
+};
+struct node* head = NULL; /* Link header, a shared resource */
+
+/* Consumer thread entry function */
+static void* consumer(void* parameter)
+{
+ struct node* p_node = NULL;
+
+ while (1)
+ {
+ sem_wait(&full_sem);
+ pthread_mutex_lock(&mutex); /* Lock mutex */
+
+ while (head != NULL) /* Determine if there are elements in the list */
+ {
+ p_node = head; /* Obtain resources */
+ head = head->n_next; /* Header pointing to the next resource */
+ /* Print */
+ printf("consume %d\n",p_node->n_number);
+
+ free(p_node); /* Release the memory occupied by the node after getting the resource */
+ }
+
+ pthread_mutex_unlock(&mutex); /* The critical section data operation is completed, and the mutex is released. */
+
+ sem_post(&empty_sem); /* Send a null semaphore to the producer */
+ }
+}
+/* Producer thread entry function */
+static void* product(void* patameter)
+{
+ int count = 0;
+ struct node *p_node;
+
+ while(1)
+ {
+ /* Dynamically allocate a block of structured memory */
+ p_node = (struct node*)malloc(sizeof(struct node));
+ if (p_node != NULL)
+ {
+ p_node->n_number = count++;
+ pthread_mutex_lock(&mutex); /* To operate on the critical resource head, lock it first */
+
+ p_node->n_next = head;
+ head = p_node; /* Insert data into the list header */
+
+ pthread_mutex_unlock(&mutex); /* Unlock */
+ printf("produce %d\n",p_node->n_number);
+
+ sem_post(&full_sem); /* Send a full semaphore to the consumer */
+ }
+ else
+ {
+ printf("product malloc node failed!\n");
+ break;
+ }
+ sleep(2); /* Sleep 2 seconds */
+ sem_wait(&empty_sem); /* Wait for consumers to send empty semapho */
+ }
+}
+
+int rt_application_init()
+{
+ int result;
+
+ sem_init(&empty_sem,NULL,0);
+ sem_init(&full_sem,NULL,0);
+ /* Create a producer thread, the property is the default value, the entry function is product, and the entry function parameter is NULL*/
+ result = pthread_create(&tid1,NULL,product,NULL);
+ check_result("product thread created",result);
+
+ /* Create a consumer thread, the property is the default value, the entry function is consumer, and the entry function parameter is NULL */
+ result = pthread_create(&tid2,NULL,consumer,NULL);
+ check_result("consumer thread created",result);
+
+ return 0;
+}
+```
+
+# Message Queue
+
+Message Queuing is another commonly used inter-thread communication method that accepts messages of unfixed length from threads or interrupt service routines and caches the messages in their own memory space. Other threads can also read the corresponding message from the message queue, and when the message queue is empty, the reader thread can be suspended. When a new message arrives, the suspended thread will be woken up to receive and process the message.
+
+The main operations of the message queue include: creating or opening by the function `mq_open()`, calling `mq_send()` to send a message to the message queue, calling `mq_receive()` to get a message from the message queue, and when the message queue is not in use, you can call `mq_unlink()` to delete message queue.
+
+POSIX message queue is mainly used for inter-process communication. The POSIX message queue of RT-Thread operating system is mainly based on a package of RT-Thread kernel message queue, mainly used for communication between threads in the system. It is used in the same way as the message queue of the RT-Thread kernel.
+
+## Message Queue Control Block
+
+Each message queue corresponds to a message queue control block. Before creating a message queue, you need to define a message queue control block. The message queue control block is defined in the mqueue.h header file.
+
+``` c
+struct mqdes
+{
+ rt_uint16_t refcount; /* Reference count */
+ rt_uint16_t unlinked; /* Separation status of the message queue, a value of 1 indicates that the message queue has been separated */
+ rt_mq_t mq; /* RT-Thread message queue control block */
+ struct mqdes* next; /* Point to the next message queue control block */
+};
+typedef struct mqdes* mqd_t; /* Message queue control block pointer type redefinition */
+```
+
+## Create or Open a Message Queue
+
+``` c
+mqd_t mq_open(const char *name, int oflag, ...);
+```
+
+| **Parameter** | **Description** |
+|----------|----------------|
+| name | Message queue name |
+| oflag | Message queue open mode |
+|**return**| —— |
+| Message queue handle | Succeeded |
+| NULL | Failed |
+
+This function creates a new message queue or opens an existing message queue based on the name of the message queue. The optional values for Oflag are `0`, `O_CREAT` or `O_CREAT\|O_EXCL`. If Oflag is set to `O_CREAT` then a new message queue is created. If Oflag sets `O_CREAT\|O_EXCL`, it returns NULL if the message queue already exists, and creates a new message queue if it does not exist. If Oflag is set to `0`, the message queue does not exist and returns NULL.
+
+## Detach Message Queue
+
+``` c
+int mq_unlink(const char *name);
+```
+
+| **Parameter** | **Description** |
+|----|------------|
+| name | Message queue name |
+|**return**| —— |
+| 0 | Succeeded |
+| -1 | Failed |
+
+This function finds the message queue based on the message queue name name. If found, it sets the message queue to a detached state. If the hold count is 0, the message queue is deleted and the resources occupied by the message queue are released.
+
+## Close the Message Queue
+
+``` c
+int mq_close(mqd_t mqdes);
+```
+
+| **Parameter** | **Description** |
+|----------|------------|
+| mqdes | Message queue handle |
+|**return**| —— |
+| 0 | Succeeded |
+| -1 | Failed |
+
+When a thread terminates,it closes the message queue it occupies. Whether the thread terminates voluntarily or involuntarily, this closure is performed. This is equivalent to the message queue holding count minus 1. If the holding count is 0 after the minus 1 and the message queue is in the separated state, the `mqdes` message queue will be deleted and released the resources it occupies.
+
+## Block Mode to Send a Message
+
+``` c
+int mq_send(mqd_t mqdes,
+ const char *msg_ptr,
+ size_t msg_len,
+ unsigned msg_prio);
+```
+
+| **Parameter** | **Description** |
+|---------|----------------------------------|
+| mqdes | Message queue handle, cannot be NULL |
+| sg_ptr | Pointer to the message to be sent, cannot be NULL |
+| msg_len | The length of the message sent |
+| msg_prio | RT-Thread unimplemented this parameter |
+|**return**| —— |
+| 0 | Succeeded |
+| -1 | Failed |
+
+This function is used to send a message to the `mqdes` message queue, which is a wrapper of the rt_mq_send() function. This function adds the message pointed to by `msg_ptr` to the `mqdes` message queue, and the length of the message sent `msg_len` must be less than or equal to the maximum message length set when the message queue is created.
+
+If the message queue is full, that is, the number of messages in the message queue is equal to the maximum number of messages, the thread that sent the message or the interrupt program will receive an error code (-RT_EFULL).
+
+## Specify Blocking Time to Send a Message
+
+``` c
+int mq_timedsend(mqd_t mqdes,
+ const char *msg_ptr,
+ size_t msg_len,
+ unsigned msg_prio,
+ const struct timespec *abs_timeout);
+```
+
+| **Parameter** | **Description** |
+|------------|-------------------------------------------------|
+| mqdes | Message queue handle, cannot be NULL |
+| msg_ptr | Pointer to the message to be sent, cannot be NULL |
+| msg_len | The length of the message sent |
+| msg_prio | RT-Thread unimplemented parameters |
+| abs_timeout | The specified wait time in operating system clock tick (OS Tick) |
+|**Parameter**| —— |
+| 0 | Succeeded |
+| -1 | Failed |
+
+Currently RT-Thread does not support sending messages with the specified blocking time, but the function interface has been implemented, which is equivalent to calling mq_send().
+
+## Blocking Mode to Receive Message
+
+``` c
+ssize_t mq_receive(mqd_t mqdes,
+ char *msg_ptr,
+ size_t msg_len,
+ unsigned *msg_prio);
+```
+
+| **Parameter** | **Description** |
+|---------|----------------------------------|
+| mqdes | Message queue handle, cannot be NULL |
+| msg_ptr | Pointer to the message to be sent, cannot be NULL |
+| msg_len | The length of the message sent |
+| msg_prio | RT-Thread unimplemented parameters |
+|**return**| —— |
+| Message length | Succeeded |
+| -1 | Failed |
+
+This function removes the oldest message from the `mqdes` message queue and puts the message in the memory pointed to by `msg_ptr`. If the message queue is empty, the thread that called the mq_receive() function will block until the message in the message queue is available.
+
+## Specify Blocking Time to Receive Message
+
+``` c
+ssize_t mq_timedreceive(mqd_t mqdes,
+ char *msg_ptr,
+ size_t msg_len,
+ unsigned *msg_prio,
+ const struct timespec *abs_timeout);
+```
+
+| **Parameter** | **Description** |
+|------------|-------------------------------------------------|
+| mqdes | Message queue handle, cannot be NULL |
+| msg_ptr | Pointer to the message to be sent, cannot be NULL |
+| msg_len | The length of the message sent |
+| msg_prio | RT-Thread unimplemented parameters |
+| abs_timeout | The specified wait time in operating system clock tick (OS Tick) |
+|**return**| —— |
+| Message length | Succeeded |
+| -1 | Failed |
+
+The difference between this function and the mq_receive() function is that if the message queue is empty, the thread will block the `abs_timeout` duration. After the timeout, the function will return `-1`, and the thread will be awakened from the blocking state to the ready state.
+
+## Example Code for Message Queue
+
+This program creates 3 threads, thread2 accepts messages from the message queue, and thread2 and thread3 send messages to the message queue.
+
+``` c
+#include <mqueue.h>
+#include <stdio.h>
+
+/* Thread control block */
+static pthread_t tid1;
+static pthread_t tid2;
+static pthread_t tid3;
+/* Message queue handle */
+static mqd_t mqueue;
+
+/* Function return value check function */
+static void check_result(char* str,int result)
+{
+ if (0 == result)
+ {
+ printf("%s successfully!\n",str);
+ }
+ else
+ {
+ printf("%s failed! error code is %d\n",str,result);
+ }
+}
+/* Thread 1 entry function */
+static void* thread1_entry(void* parameter)
+{
+ char buf[128];
+ int result;
+
+ while (1)
+ {
+ /* Receive messages from the message queue */
+ result = mq_receive(mqueue, &buf[0], sizeof(buf), 0);
+ if (result != -1)
+ {
+ /* Output content */
+ printf("thread1 recv [%s]\n", buf);
+ }
+
+ /* Sleep 1 second */
+ // sleep(1);
+ }
+}
+/* Thread 2 entry function */
+static void* thread2_entry(void* parameter)
+{
+ int i, result;
+ char buf[] = "message2 No.x";
+
+ while (1)
+ {
+ for (i = 0; i < 10; i++)
+ {
+ buf[sizeof(buf) - 2] = '0' + i;
+
+ printf("thread2 send [%s]\n", buf);
+ /* Send a message to the message queue */
+ result = mq_send(mqueue, &buf[0], sizeof(buf), 0);
+ if (result == -1)
+ {
+ /* Message queue full, delayed 1s */
+ printf("thread2:message queue is full, delay 1s\n");
+ sleep(1);
+ }
+ }
+
+ /* Sleep 2 seconds */
+ sleep(2);
+ }
+}
+/* Thread 3 entry function */
+static void* thread3_entry(void* parameter)
+{
+ int i, result;
+ char buf[] = "message3 No.x";
+
+ while (1)
+ {
+ for (i = 0; i < 10; i++)
+ {
+ buf[sizeof(buf) - 2] = '0' + i;
+
+ printf("thread3 send [%s]\n", buf);
+ /* Send messages to the message queue */
+ result = mq_send(mqueue, &buf[0], sizeof(buf), 0);
+ if (result == -1)
+ {
+ /* Message queue full, delayed 1s */
+ printf("thread3:message queue is full, delay 1s\n");
+ sleep(1);
+ }
+ }
+
+ /* Sleep 2 seconds */
+ sleep(2);
+ }
+}
+/* User application portal */
+int rt_application_init()
+{
+ int result;
+ struct mq_attr mqstat;
+ int oflag = O_CREAT|O_RDWR;
+#define MSG_SIZE 128
+#define MAX_MSG 128
+ memset(&mqstat, 0, sizeof(mqstat));
+ mqstat.mq_maxmsg = MAX_MSG;
+ mqstat.mq_msgsize = MSG_SIZE;
+ mqstat.mq_flags = 0;
+ mqueue = mq_open("mqueue1",O_CREAT,0777,&mqstat);
+
+ /* Create thread 1, thread entry is thread1_entry, property parameter is set to NULL, select default value, entry parameter is NULL*/
+ result = pthread_create(&tid1,NULL,thread1_entry,NULL);
+ check_result("thread1 created",result);
+
+ /* Create thread 2, thread entry is thread2_entry, property parameter is set to NULL, select default value, entry parameter is NULL*/
+ result = pthread_create(&tid2,NULL,thread2_entry,NULL);
+ check_result("thread2 created",result);
+
+ /* Create thread 3, thread entry is thread3_entry, property parameter is set to NULL Select default value, entry parameter is NULL*/
+ result = pthread_create(&tid3,NULL,thread3_entry,NULL);
+ check_result("thread3 created",result);
+
+
+ return 0;
+}
+```
+
+# Thread Advanced Programming
+
+This section provides a detailed introduction to some of the rarely used property objects and related functions.
+
+The thread attributes implemented by RT-Thread include thread stack size, thread priority, thread separation status, and thread scheduling policy. `pthread_create()` must initialize the property object before using the property object. APIs such as setting thread properties should be called before the thread is created. Changes of thread attributes do not affect the threads that have been created.
+
+The thread attribute structure `pthread_attr_t` is defined in the pthread.h header file. The thread attribute structure is as follows:
+
+``` c
+/* pthread_attr_t Type redefinition */
+typedef struct pthread_attr pthread_attr_t;
+/* Thread attribute structure */
+struct pthread_attr
+{
+ void* stack_base; /* Thread stack address */
+ rt_uint32_t stack_size; /* Thread stack size */
+ rt_uint8_t priority; /* Thread priority */
+ rt_uint8_t detachstate; /* Thread detached state */
+ rt_uint8_t policy; /* Thread scheduling policy */
+ rt_uint8_t inheritsched; /* Thread inheritance */
+};
+```
+
+## Thread Property Initialization and Deinitialization
+
+The thread property initialization and deinitialization functions are as follows:
+
+``` c
+int pthread_attr_init(pthread_attr_t *attr);
+int pthread_attr_destroy(pthread_attr_t *attr);
+```
+
+| **Parameter** | **Description** |
+|----|------------------|
+| attr | Pointer to the thread property |
+|**return**| —— |
+| 0 | Succeeded |
+
+Using the pthread_attr_init() function initializes the thread attribute structure `attr` with the default value, which is equivalent to setting the parameter to NULL when calling the thread initialization function. You need to define a `pthread_attr_t` attribute object before use. This function must be called before the pthread_create() function.
+
+The pthread_attr_destroy() function deinitializes the property pointed to by `attr` and can then reinitialize this property object by calling the pthread_attr_init() function again.
+
+## Thread Detached State
+
+Setting or getting the separation state of a thread is as follows. By default, the thread is non-separated.
+
+``` c
+int pthread_attr_setdetachstate(pthread_attr_t *attr, int state);
+int pthread_attr_getdetachstate(pthread_attr_t const *attr, int *state);
+```
+
+| **Parameter** | **Description** |
+|----------|-------------------|
+| attr | Pointer to the thread property |
+| state | Thread detached state |
+|**return**| —— |
+| 0 | Succeeded |
+
+The thread separation state property value state can be `PTHREAD_CREATE_JOINABL` (non-detached) and `THREAD_CREATE_DETACHED` (detached).
+
+The detached state of a thread determines how a thread reclaims the resources it occupies after the end of its run. There are two types of thread separation: joinable or detached. When the thread is created, you should call pthread_join() or pthread_detach() to reclaim the resources occupied by the thread after it finishes running. If the thread's detached state is joinable, other threads can call the pthread_join() function to wait for the thread to finish and get the thread return value, and then reclaim the resources occupied by the thread. A thread with a detached state cannot be joined by another thread. Immediately after the end of its operation, the system resources are released.
+
+## Thread Scheduling Policy
+
+Setting \ Obtaining thread scheduling policy function is as follows:
+
+``` c
+int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy);
+int pthread_attr_getschedpolicy(pthread_attr_t const *attr, int *policy);
+```
+
+Only the function interface is implemented. The default different priorities are based on priority scheduling, and the same priority time slice polling scheduling
+
+## Thread Scheduling Parameter
+
+Set / Obtain the thread's priority function as follows:
+
+``` c
+int pthread_attr_setschedparam(pthread_attr_t *attr,
+ struct sched_param const *param);
+int pthread_attr_getschedparam(pthread_attr_t const *attr,
+ struct sched_param *param);
+```
+
+| **Parameter** | **Description** |
+|----------|------------------|
+| attr | Pointer to the thread property |
+| param | Pointer to the dispatch parameter |
+|**return**| —— |
+| 0 | Succeeded |
+
+The `pthread_attr_setschedparam()` function sets the priority of the thread. Use `param` to set the thread priority.
+
+**Parameter** : The `struct sched_param` is defined in sched.h and has the following structure:
+
+``` c
+struct sched_param
+{
+ int sched_priority; /* Thread priority */
+};
+```
+
+The member `sched_paraority` of the `sched_param` controls the priority value of the thread.
+
+## Thread Stack Size
+
+Set / Obtain the stack size of a thread is as follows:
+
+``` c
+int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stack_size);
+int pthread_attr_getstacksize(pthread_attr_t const *attr, size_t *stack_size);
+```
+
+| **Parameter** | **Description** |
+|-----------|------------------|
+| attr | Pointer to the thread property |
+| stack_size | Thread stack size |
+|**return**| —— |
+| 0 | Succeeded |
+
+The `pthread_attr_setstacksize()` function sets the stack size in bytes. Stack space address alignment is required on most systems (for example, the ARM architecture needs to be aligned to a 4-byte address).
+
+## Thread Stack Size and Address
+
+Set / Obtain the stack address and stack size of a thread is as follows:
+
+``` c
+int pthread_attr_setstack(pthread_attr_t *attr,
+ void *stack_base,
+ size_t stack_size);
+int pthread_attr_getstack(pthread_attr_t const *attr,
+ void**stack_base,
+ size_t *stack_size);
+```
+
+| **Parameter** | **Description** |
+|-----------|------------------|
+| attr | Pointer to the thread property |
+| stack_size | Thread stack size |
+| stack_base | Thread stack address |
+|**return**| —— |
+| 0 | Succeeded |
+
+## Thread Attribute Related Function
+
+The function that sets / obtains the scope of the thread is as follows:
+
+``` c
+int pthread_attr_setscope(pthread_attr_t *attr, int scope);
+int pthread_attr_getscope(pthread_attr_t const *attr);
+```
+
+| **Parameter** | **Description** |
+|-----------|------------------|
+| attr | Pointer to the thread property |
+| scope | Thread scope |
+|**return**| —— |
+| 0 | scope is PTHREAD_SCOPE_SYSTEM |
+| EOPNOTSUPP | scope is PTHREAD_SCOPE_PROCESS |
+| EINVAL | scope is PTHREAD_SCOPE_SYSTEM |
+
+## Example Code for Thread Property
+
+This program will initialize 2 threads, they have a common entry function, but their entry parameters are not the same. The first thread created will use the provided `attr` thread attribute, and the other thread will use the system default attribute. Thread priority is a very important parameter, so this program will modify the first created thread to have a priority of 8, and the system default priority of 24.
+
+``` c
+#include <pthread.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <sched.h>
+
+/* Thread control block */
+static pthread_t tid1;
+static pthread_t tid2;
+
+/* Function return value check */
+static void check_result(char* str,int result)
+{
+ if (0 == result)
+ {
+ printf("%s successfully!\n",str);
+ }
+ else
+ {
+ printf("%s failed! error code is %d\n",str,result);
+ }
+}
+/* Thread entry function */
+static void* thread_entry(void* parameter)
+{
+ int count = 0;
+ int no = (int) parameter; /* Obtain the thread's entry parameters */
+
+ while (1)
+ {
+ /* Printout thread count value */
+ printf("thread%d count: %d\n", no, count ++);
+
+ sleep(2); /* Sleep 2 seconds */
+ }
+}
+
+/* User application portal */
+int rt_application_init()
+{
+ int result;
+ pthread_attr_t attr; /* Thread attribute */
+ struct sched_param prio; /* Thread priority */
+
+ prio.sched_priority = 8; /* Priority is set to 8 */
+ pthread_attr_init(&attr); /* Initialize the property with default values first */
+ pthread_attr_setschedparam(&attr,&prio); /* Modify the priority corresponding to the attribute */
+
+ /* Create thread 1, attribute is attr, entry function is thread_entry, and the entry function parameter is 1 */
+ result = pthread_create(&tid1,&attr,thread_entry,(void*)1);
+ check_result("thread1 created",result);
+
+ /* Create thread 2, the property is the default value, the entry function is thread_entry, and the entry function parameter is 2 */
+ result = pthread_create(&tid2,NULL,thread_entry,(void*)2);
+ check_result("thread2 created",result);
+
+ return 0;
+}
+```
+
+## Thread Cancellation
+
+Cancellation is a mechanism that allows one thread to end other threads. A thread can send a cancel request to another thread. Depending on the settings, the target thread may ignore it and may end immediately or postpone it until the next cancellation point.
+
+### Send Cancellation Request
+
+The cancellation request can be sent using the following function:
+
+``` c
+int pthread_cancel(pthread_t thread);
+```
+
+| **Parameter** | **Description** |
+|------|--------|
+| thread | Thread handle |
+|**return**| —— |
+| 0 | Succeeded |
+
+This function sends a cancel request to the `thread` thread. Whether the thread will respond to the cancellation request and when it responds depends on the state and type of thread cancellation.
+
+### Set Cancel Status
+
+The cancellation request can be set using the following function:
+
+``` c
+int pthread_setcancelstate(int state, int *oldstate);
+```
+
+| **Parameter** | **Description** |
+|--------|-------------------------------|
+| state | There are two values: <br />`PTHREAD_CANCEL_ENABLE`: Cancel enable. <br />`PTHREAD_CANCEL_DISABLE`: Cancel disabled (default value when thread is created). |
+| oldstate | Save the original cancellation status |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | state is not PTHREAD_CANCEL_ENABLE or PTHREAD_CANCEL_DISABLE |
+
+This function sets the cancel state and is called by the thread itself. Canceling the enabled thread will react to the cancel request, and canceling the disabled thread will not react to the cancel request.
+
+### Set Cancellation Type
+
+You can use the following function to set the cancellation type, which is called by the thread itself:
+
+``` c
+int pthread_setcanceltype(int type, int *oldtype);
+```
+
+| **Parameter** | **Description** |
+|-------|---------------------------------|
+| type | There are 2 values: <br />`PTHREAD_CANCEL_DEFFERED`: After the thread receives the cancellation request, it will continue to run to the next cancellation point and then end. (Default value when thread is created) .<br />`PTHREAD_CANCEL_ASYNCHRONOUS`: The thread ends immediately. |
+| oldtype | Save the original cancellation type |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | state is neither PTHREAD_CANCEL_DEFFERED nor PTHREAD_CANCEL_ASYNCHRONOUS |
+
+### Set Cancellation Point
+
+The cancellation point can be set using the following function:
+
+``` c
+void pthread_testcancel(void);
+```
+
+This function creates a cancellation point where the thread is called. Called primarily by a thread that does not contain a cancellation point, it can respond to a cancellation request. This function does not work if pthread_testcancel() is called while the cancel state is disabled.
+
+### Cancellation Point
+
+The cancellation point is where the thread ends when it accepts the cancellation request. According to the POSIX standard, system calls that cause blocking, such as pthread_join(), pthread_testcancel(), pthread_cond_wait(), pthread_cond_timedwait(), and sem_wait(), are cancellation points.
+
+All cancellation points included in RT-Thread are as follows:
+
+- mq_receive()
+
+- mq_send()
+
+- mq_timedreceive()
+
+- mq_timedsend()
+
+- msgrcv()
+
+- msgsnd()
+
+- msync()
+
+- pthread_cond_timedwait()
+
+- pthread_cond_wait()
+
+- pthread_join()
+
+- pthread_testcancel()
+
+- sem_timedwait()
+
+- sem_wait()
+
+- pthread_rwlock_rdlock()
+
+- pthread_rwlock_timedrdlock()
+
+- pthread_rwlock_timedwrlock()
+
+- pthread_rwlock_wrlock()
+
+### Example Code for Thread Cancel
+
+This program creates 2 threads. After thread2 starts running, it sleeps for 8 seconds. Thread1 sets its own cancel state and type, and then prints the run count information in an infinite loop. After thread2 wakes up, it sends a cancel request to thread1, and thread1 ends the run immediately after receiving the cancel request.
+
+``` c
+#include <pthread.h>
+#include <unistd.h>
+#include <stdio.h>
+
+/* Thread control block */
+static pthread_t tid1;
+static pthread_t tid2;
+
+/* Function return value check */
+static void check_result(char* str,int result)
+{
+ if (0 == result)
+ {
+ printf("%s successfully!\n",str);
+ }
+ else
+ {
+ printf("%s failed! error code is %d\n",str,result);
+ }
+}
+/* Thread 1 entry function */
+static void* thread1_entry(void* parameter)
+{
+ int count = 0;
+ /* Set the cancel state of thread 1 to be enabled. The cancel type is terminated immediately after the thread receives the cancel point. */
+ pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
+ pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
+
+ while(1)
+ {
+ /* Print thread count value output */
+ printf("thread1 run count: %d\n",count ++);
+ sleep(2); /* Sleep 2 seconds */
+ }
+}
+/* Thread 2 entry function */
+static void* thread2_entry(void* parameter)
+{
+ int count = 0;
+ sleep(8);
+ /* Send a cancel request to thread 1 */
+ pthread_cancel(tid1);
+ /* Waiting for thread 1 to finish in blocking mode */
+ pthread_join(tid1,NULL);
+ printf("thread1 exited!\n");
+ /* Thread 2 print information to start output */
+ while(1)
+ {
+ /* Print thread count value output */
+ printf("thread2 run count: %d\n",count ++);
+ sleep(2); /* Sleep 2 seconds */
+ }
+}
+/* User application portal */
+int rt_application_init()
+{
+ int result;
+ /* Create thread 1, the property is the default value, the separation state is the default value joinable, the entry function is thread1_entry, and the entry function parameter is NULL */
+ result = pthread_create(&tid1,NULL,thread1_entry,NULL);
+ check_result("thread1 created",result);
+
+ /* Create thread 2, the property is the default value, the separation state is the default value joinable, the entry function is thread2_entry, and the entry function parameter is NULL */
+ result = pthread_create(&tid2,NULL,thread2_entry,NULL);
+ check_result("thread2 created",result);
+
+ return 0;
+}
+```
+
+## One-time Initialization
+
+It can be initialized once using the following function:
+
+``` c
+int pthread_once(pthread_once_t * once_control, void (*init_routine) (void));
+```
+
+| **Parameter** | **Description** |
+|-------------|--------|
+| once_control | Control variable |
+| init_routine | Execute function |
+|**return**| —— |
+| 0 | Succeeded |
+
+Sometimes we need to initialize some variables only once. If we do multiple initialization procedures, it will get an error. In traditional sequential programming, one-time initialization is often managed by using Boolean variables. The control variable is statically initialized to 0, and any code that relies on initialization can test the variable. If the variable value is still 0, it can be initialized and then set the variable to 1. Codes that are checked later will skip initialization.
+
+## Clean up after the Thread Ends
+
+The thread cleanup function interface:
+
+``` c
+void pthread_cleanup_pop(int execute);
+void pthread_cleanup_push(void (*routine)(void*), void *arg);
+```
+
+| **Parameter** | **Description** |
+|-------|-----------------------------|
+| execute | 0 or 1, determin whether to execute the cleanup function |
+| routine | Pointer to the cleanup function |
+| arg | The parameter passed to the cleanup function |
+
+pthread_cleanup_push() puts the specified cleanup `routine` into the thread's cleanup function list. pthread_cleanup_pop() takes the first function from the header of the cleanup function list. If `execute` is a non-zero value, then this function is executed.
+
+## Other Thread Related Functions
+
+### Determine if two Threads are Equal
+
+``` c
+int pthread_equal (pthread_t t1, pthread_t t2);
+```
+
+| **Parameter** | **Description** |
+|----------|--------|
+| pthread_t | Thread handle |
+|**return**| —— |
+| 0 | Not equal |
+| 1 | Equal |
+
+### Obtain Thread Handle
+
+``` c
+pthread_t pthread_self (void);
+```
+pthread_self() returns the handle of the calling thread.
+
+### Get the Maximum and Minimum Priority
+
+``` c
+int sched_get_priority_min(int policy);
+int sched_get_priority_max(int policy);
+```
+
+| **Parameter** | **Description** |
+|------|---------------------------------|
+| policy | 2 values are optional: SCHED_FIFO, SCHED_RR |
+
+sched_get_priority_min() returns a value of 0, with the highest priority in RT-Thread and sched_get_priority_max() with the lowest priority.
+
+## Mutex Attribute
+
+The mutex properties implemented by RT-Thread include the mutex type and the mutex scope.
+
+### Mutex Lock Attribute Initialization and Deinitialization
+
+``` c
+int pthread_mutexattr_init(pthread_mutexattr_t *attr);
+int pthread_mutexattr_destroy(pthread_mutexattr_t *attr);
+```
+
+| **Parameter** | **Description** |
+|----|------------------------|
+| attr | Pointer to the mutex attribute object |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+
+The pthread_mutexattr_init() function initializes the property object pointed to by `attr` with the default value, which is equivalent to setting the property parameter to NULL when calling the pthread_mutex_init() function.
+
+The pthread_mutexattr_destroy() function will initialize the property object pointed to by `attr` and can be reinitialized by calling the pthread_mutexattr_init() function.
+
+### Mutex Lock Scope
+
+``` c
+int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared);
+int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared);
+```
+
+| **Parameter** | **Description** |
+|-------|--------------------|
+| type | Mutex type |
+| pshared | There are 2 optional values: <br />`PTHREAD_PROCESS_PRIVATE`: The default value, used to synchronize only threads in the process. `PTHREAD_PROCESS_SHARED`: Used to synchronize threads in this process and other processes. |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+
+### Mutex Type
+
+``` c
+int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);
+int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type);
+```
+
+| **Parameter** | **Description** |
+|----|------------------------|
+| type | Mutex type |
+| attr | Pointer to the mutex attribute object |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+
+The type of mutex determines how a thread behaves when it acquires a mutex. RT-Thread implements three mutex types:
+
+- **PTHREAD_MUTEX_NORMAL**: Normal lock. When a thread is locked, the remaining threads requesting the lock will form a wait queue, and after unlocking, the lock will be acquired in the first-in first-out manner. If a thread attempts to regain the mutex without first releasing the mutex, it does not generate a deadlock, but instead returns an error code, just like the error checking lock.
+
+- **PTHREAD_MUTEX_RECURSIVE**: Nested locks that allow a thread to successfully acquire the same lock multiple times, requiring the same number of unlocks to release the mutex.
+
+- **PTHREAD_MUTEX_ERRORCHECK**: Error checking lock, if a thread tries to regain the mutex without first releasing the mutex, an error is returned. This ensures that deadlocks do not occur when multiple locks are not allowed.
+
+## Condition Variable Attribute
+
+Use the default value PTHREAD_PROCESS_PRIVATE to initialize the condition variable attribute attr to use the following function:
+
+``` c
+int pthread_condattr_init(pthread_condattr_t *attr);
+```
+
+| **Parameter** | **Description** |
+|----|--------------------------|
+| attr | Pointer to a condition variable property object |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+
+### Obtain Condition Variable Scope
+
+``` c
+int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared);
+```
+
+| **Parameter** | **Description** |
+|----|--------------------------|
+| attr | Pointer to a condition variable property object |
+|**return**| —— |
+| 0 | Succeeded |
+| EINVAL | Invalid parameter |
+
+## Read-write Lock Attribute
+
+### Initialize Property
+
+``` c
+int pthread_rwlockattr_init (pthread_rwlockattr_t *attr);
+```
+
+| **Parameter** | **Description** |
+|----|--------------------|
+| attr | Pointer to the read-write lock property |
+|**return**| —— |
+| 0 | Succeeded |
+|-1 | Invalid parameter |
+
+This function initializes the read-write lock attribute `attr` with the default value PTHREAD_PROCESS_PRIVATE.
+
+### Obtain Scope
+
+``` c
+int pthread_rwlockattr_getpshared (const pthread_rwlockattr_t *attr, int *pshared);
+```
+
+| **Parameter** | **Description** |
+|-------|--------------------------|
+| attr | Pointer to the read-write lock property |
+| pshared | Pointer to the scope of the read-write lock |
+|**return**| —— |
+| 0 | Succeeded |
+|-1 | Invalid parameter |
+
+The memory pointed to by pshared is saved as PTHREAD_PROCESS_PRIVATE.
+
+## Barrier Attribute
+
+### Initialize Property
+
+``` c
+int pthread_barrierattr_init(pthread_barrierattr_t *attr);
+```
+
+| **Parameter** | **Description** |
+|----|------------------|
+| attr | Pointer to the barrier property |
+|**return**| —— |
+| 0 | Succeeded |
+|-1 | Invalid parameter |
+
+The modified function initializes the barrier attribute `attr` with the default value PTHREAD_PROCESS_PRIVATE.
+
+### Obtain Scope
+
+``` c
+int pthread_barrierattr_getpshared(const pthread_barrierattr_t *attr, int *pshared);
+```
+
+| **Parameter** | **Description** |
+|-------|-----------------------------|
+| attr | Pointer to the barrier property |
+| pshared | Pointer to save barrier scope data |
+|**return**| —— |
+| 0 | Succeeded |
+|-1 | Invalid parameter |
+
+## Message Queue Property
+
+The message queue attribute control block is as follows:
+
+``` c
+struct mq_attr
+{
+ long mq_flags; /* Message queue flag to indicate whether to block */
+ long mq_maxmsg; /* Message queue maximum number of messages */
+ long mq_msgsize; /* The maximum number of bytes per message in the message queue */
+ long mq_curmsgs; /* Message queue current message number */
+};
+```
+### Obtain Attribute
+``` c
+int mq_getattr(mqd_t mqdes, struct mq_attr *mqstat);
+```
+
+| **Parameter** | **Description** |
+|------|------------------------|
+| mqdes | Pointer to the message queue control block |
+| mqstat | Pointer to save the get data |
+|**return**| —— |
+| 0 | Succeeded |
+|-1 | Invalid parameter |
diff --git a/documentation/6.components/sal/figures/sal_frame.jpg b/documentation/6.components/sal/figures/sal_frame.jpg
new file mode 100644
index 0000000000..0fb9299544
--- /dev/null
+++ b/documentation/6.components/sal/figures/sal_frame.jpg
Binary files differ
diff --git a/documentation/6.components/sal/sal.md b/documentation/6.components/sal/sal.md
new file mode 100644
index 0000000000..8169d73c27
--- /dev/null
+++ b/documentation/6.components/sal/sal.md
@@ -0,0 +1,825 @@
+@page page_component_sal Socket Abstraction Layer: SAL
+
+# SAL Introduction
+
+In order to adapt to more network protocol stack types and avoid the system's dependence on a single network protocol stack, the RT-Thread system provides a SAL (Socket Abstraction Layer) components that implement different network protocol stacks or network implementations. The abstraction of the interface provides a set of standard BSD Socket APIs to the upper layer, so that developers only need to care about and use the network interface provided by the network application layer, without concern for the underlying specific network protocol stack type and implementation, which greatly improves the system's compatibility makes it easy for developers to complete protocol stack adaptation and network-related development. Main features of the SAL component are as follows:
+
+- Abstract and unified multiple network protocol stack interfaces;;
+- Provide Socket-level TLS encrypted transport feature;
+- Support standard BSD Socket APIs;
+- Unified FD management for easy operation of network functions using read/write poll/select;
+
+## SAL Network Framework
+
+The SAL network framework of RT-Thread is mainly shown in the following structure:
+
+![SAL 网络框架图](figures/sal_frame.jpg)
+
+The top layer is the network's application layer, provides a set of standard BSD Socket APIs, such as `socket`, `connect` and other functions, for most of the system network development applications.
+
+The second part is the virtual file system layer. In the RT-Thread system, the DFS file system program can implement different file system operations using standard interface functions.The network socket interface also supports the file system structure. The network socket descriptor created when using the network socket interface is uniformly managed by the file system. Therefore, the network socket descriptor can also use the standard file operation interface.The interfaces provided for the upper application layer are: `read`, `write`, `close`, `poll`/`select`, and so on.
+
+The third part is the socket abstraction layer, through which RT-thread system can adapt to different network protocol stacks in the lower layer and provide unified network programming interface in the upper layer to facilitate access of different protocol stacks. The socket abstraction layer provides interfaces for the upper application layer, such as `accept`, `connect`, `send`, `recv`, etc.
+
+The fourth part is the protocol stack layer, which includes several commonly used TCP/IP protocol stacks, such as lwIP, a light TCP/IP protocol stack commonly used in embedded development, and AT Socket network function implementation developed by rt-thread. These protocol stacks or network functions directly contact the hardware to complete the transformation of data from the network layer to the transmission layer.
+
+The network application layer of RT-thread provides interfaces mainly based on the standard BSD Socket API, which ensures that programs can be written on PC, debugged, and then ported to the RT-thread operating system.
+
+## Working Principles
+
+The working principle of SAL component is mainly divided into the following three parts:
+
+- Unified abstract functions of multi-protocol stack access and interface functions;
+- SAL TLS encryption transmission function;
+
+### Multi-Protocol Stack Access and Unified Abstract Function Of Interface Function
+
+For different protocol stacks or network function implementations, the names of network interfaces may be different. Take the `connect` connection function as an example. The interface name in the lwIP protocol stack is `lwip_connect`, and the interface name in the AT Socket network implementation is `at_connect`. The SAL component provides abstraction and unification of the interface of different protocol stacks or networks. When the socket is created, the component **judges the protocol stack or network function used by judging the incoming protocol domain type**, and completes the RT-Thread.
+
+Currently, the protocol stack or network implementation types supported by the SAL component are: **lwIP protocol stack**, **AT Socket protocol stack**, **WIZnet hardware TCP/IP protocol stack**.
+
+```c
+int socket(int domain, int type, int protocol);
+```
+
+The above is the definition of the socket creation function in the standard BSD Socket API. The `domain` indicates that the protocol domain is also called the protocol domain. It is used to determine which protocol stack or network implementation to use. The domain type used by the AT Socket protocol stack is **AF_AT**, lwIP protocol stack uses protocol domain type **AF_INET**, etc., WIZnet protocol stack uses protocol domain type **AF_WIZ**.
+
+For different software packages, the protocol domain type passed to the socket may be fixed and will not change depending on how the SAL component is accessed. **In order to dynamically adapt access to different protocol stacks or network implementations**, the SAL component provides two protocol domain type matching methods for each protocol stack or network implementation: **Primary protocol domain type and secondary protocol domain type**. When socket is created, it first determines whether the incoming protocol domain type has the supported primary protocol type. If it is, it uses the corresponding protocol stack or network implementation, if not, determine whether the subprotocol cluster type supports. The current system support protocol domain types are as follows:
+
+1. lwIP Protocol stack: family = AF_INET、sec_family = AF_INET
+
+2. AT Socket Protocol stack: family = AF_AT、sec_family = AF_INET
+
+3. WIZnet hardware TCP/IP Protocol stack: family = AF_WIZ、sec_family = AF_INET
+
+
+
+The main function of the SAL component is to unify the underlying BSD Socket API interface. The following takes the `connect` function call flow as an example to illustrate the SAL component function call method:
+
+- `connect`: The abstract BSD Socket API provided by the SAL component for unified FD management;
+- `sal_connect`: The `connect` implementation function in the SAL component that is used to call the `operation` function registered by the underlying stack.。
+- `lwip_connect`: The layer `connect` connection function provided by the underlying protocol stack is registered in the SAL component when the NIC is initialized, and the final call operation function。
+
+```c
+/* SAL component provides BSD Socket APIs for the application layer */
+int connect(int s, const struct sockaddr *name, socklen_t namelen)
+{
+ /* Get the SAL socket descriptor */
+ int socket = dfs_net_getsocket(s);
+
+ /* Execute the sal_connect function with a SAL socket descriptor*/
+ return sal_connect(socket, name, namelen);
+}
+
+/* SAL component abstract function interface implementation */
+int sal_connect(int socket, const struct sockaddr *name, socklen_t namelen)
+{
+ struct sal_socket *sock;
+ struct sal_proto_family *pf;
+ int ret;
+
+ /* Check if the SAL socket structure is normal */
+ SAL_SOCKET_OBJ_GET(sock, socket);
+
+ /* Check if the current socket network connection status is normal. */
+ SAL_NETDEV_IS_COMMONICABLE(sock->netdev);
+ /* Check if the underlying operation function corresponding to the current socket is normal. */
+ SAL_NETDEV_SOCKETOPS_VALID(sock->netdev, pf, connect);
+
+ /* The connect operation function that performs the underlying registration */
+ ret = pf->skt_ops->connect((int) sock->user_data, name, namelen);
+#ifdef SAL_USING_TLS
+ if (ret >= 0 && SAL_SOCKOPS_PROTO_TLS_VALID(sock, connect))
+ {
+ if (proto_tls->ops->connect(sock->user_data_tls) < 0)
+ {
+ return -1;
+ }
+ return ret;
+ }
+#endif
+ return ret;
+}
+
+/* The underlying connect function of the lwIP protocol stack function */
+int lwip_connect(int socket, const struct sockaddr *name, socklen_t namelen)
+{
+ ...
+}
+```
+
+### SAL TLS Encrypted Transmission Function
+
+**1. SAL TLS Feature**
+
+In the transmission of protocol data such as TCP and UDP, since the data packet is plaintext, it is likely to be intercepted and parsed by others, which has a great impact on the secure transmission of information. In order to solve such problems, users generally need to add the SSL/TLS protocol between the application layer and the transport layer.
+
+TLS (Transport Layer Security) is a protocol based on the transport layer TCP protocol. Its predecessor is SSL (Secure Socket Layer). Its main function is to encrypt the application layer message asymmetrically and then transmit it by TCP protocol, so as to achieve secure data encryption interaction.
+
+Currently used TLS methods: **MbedTLS, OpenSSL, s2n**, etc., but for different encryption methods, you need to use their specified encryption interface and process for encryption, the migration of some application layer protocols is more complicated. Therefore, the SAL TLS function is generated, the main function is to **provide TLS-encrypted transmission characteristics at the Socket level, abstract multiple TLS processing methods, and provide a unified interface for completing TLS data interaction**.
+
+**2. How to use the SAL TLS feature**
+
+The process is as follows:
+
+- Configure to enable any network protocol stack support (such as lwIP protocol stack);
+
+- Configure to enable the MbedTLS package (currently only supports MbedTLS type encryption);
+
+- Configure to enable SAL_TLS support (as shown in the configuration options section below);
+
+After the configuration is complete, as long as the `protocol` type passed in the socket creation uses **PROTOCOL_TLS** or **PROTOCOL_DTLS **, the standard BSD Socket API interface can be used to complete the establishment of the TLS connection and the data transmission and reception. The sample code is as follows:
+
+```c
+#include <stdio.h>
+#include <string.h>
+
+#include <rtthread.h>
+#include <sys/socket.h>
+#include <netdb.h>
+
+/* RT-Thread offical website,supporting TLS function */
+#define SAL_TLS_HOST "www.rt-thread.org"
+#define SAL_TLS_PORT 443
+#define SAL_TLS_BUFSZ 1024
+
+static const char *send_data = "GET /download/rt-thread.txt HTTP/1.1\r\n"
+ "Host: www.rt-thread.org\r\n"
+ "User-Agent: rtthread/4.0.1 rtt\r\n\r\n";
+
+void sal_tls_test(void)
+{
+ int ret, i;
+ char *recv_data;
+ struct hostent *host;
+ int sock = -1, bytes_received;
+ struct sockaddr_in server_addr;
+
+ /* Get the host address through the function entry parameter url (if it is a domain name, it will do domain name resolution) */
+ host = gethostbyname(SAL_TLS_HOST);
+
+ recv_data = rt_calloc(1, SAL_TLS_BUFSZ);
+ if (recv_data == RT_NULL)
+ {
+ rt_kprintf("No memory\n");
+ return;
+ }
+
+ /* Create a socket of type SOCKET_STREAM, TCP protocol, TLS type */
+ if ((sock = socket(AF_INET, SOCK_STREAM, PROTOCOL_TLS)) < 0)
+ {
+ rt_kprintf("Socket error\n");
+ goto __exit;
+ }
+
+ /* Initialize the server address */
+ server_addr.sin_family = AF_INET;
+ server_addr.sin_port = htons(SAL_TLS_PORT);
+ server_addr.sin_addr = *((struct in_addr *)host->h_addr);
+ rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
+
+ if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) < 0)
+ {
+ rt_kprintf("Connect fail!\n");
+ goto __exit;
+ }
+
+ /* Send data to the socket connection */
+ ret = send(sock, send_data, strlen(send_data), 0);
+ if (ret <= 0)
+ {
+ rt_kprintf("send error,close the socket.\n");
+ goto __exit;
+ }
+
+ /* Receive and print the response data, using encrypted data transmission */
+ bytes_received = recv(sock, recv_data, SAL_TLS_BUFSZ - 1, 0);
+ if (bytes_received <= 0)
+ {
+ rt_kprintf("received error,close the socket.\n");
+ goto __exit;
+ }
+
+ rt_kprintf("recv data:\n");
+ for (i = 0; i < bytes_received; i++)
+ {
+ rt_kprintf("%c", recv_data[i]);
+ }
+
+__exit:
+ if (recv_data)
+ rt_free(recv_data);
+
+ if (sock >= 0)
+ closesocket(sock);
+}
+
+#ifdef FINSH_USING_MSH
+#include <finsh.h>
+MSH_CMD_EXPORT(sal_tls_test, SAL TLS function test);
+#endif /* FINSH_USING_MSH */
+```
+
+## Configuration Options
+
+When we use the SAL component we need to define the following macro definition in rtconfig.h:
+
+| **Macro definition** | **Description** |
+|--------------------------------|--------------------------------|
+| RT_USING_SAL | Enable the SAL function |
+| SAL_USING_LWIP | Enable lwIP stack support |
+| SAL_USING_AT | Enable AT Socket protocol stack support |
+| SAL_USING_TLS | Enable SAL TLS feature support |
+| SAL_USING_POSIX | Enable POSIX file system related function support, such as read, write, select/poll, etc. |
+
+Currently, the SAL abstraction layer supports the lwIP protocol stack, the AT Socket protocol stack, and the WIZnet hardware TCP/IP protocol stack. To enable SAL in the system, at least one protocol stack support is required.
+
+The above configuration options can be added directly to the `rtconfig.h` file or added by the component package management tool Env configuration option. The specific configuration path in the Env tool is as follows:
+
+```c
+RT-Thread Components --->
+ Network --->
+ Socket abstraction layer --->
+ [*] Enable socket abstraction layer
+ protocol stack implement --->
+ [ ] Support lwIP stack
+ [ ] Support AT Commands stack
+ [ ] Support MbedTLS protocol
+ [*] Enable BSD socket operated by file system API
+```
+
+After the configuration is complete, you can use the `scons` command to regenerate the function and complete the addition of the SAL component.
+
+# Initialization
+
+配置开启 SAL 选项之后,需要在启动时对它进行初始化,开启 SAL 功能,如果程序中已经使用了组件自动初始化,则不再需要额外进行单独的初始化,否则需要在初始化任务中调用如下函数:
+
+```c
+int sal_init(void);
+```
+
+The initialization function is mainly for initializing the SAL component, supporting the component to repeatedly initialize the judgment, and completing the initialization of the resource such as the mutex used in the component. There is no new thread created in the SAL component, which means that the SAL component resource is very small. Currently, the **SAL component resource is occupied by ROM 2.8K and RAM 0.6K**.
+
+
+# BSD Socket API Introduction
+
+The SAL component abstracts the standard BSD Socket API interface. The following is an introduction to common network interfaces:
+
+## Create a Socket (socket)
+
+``` c
+int socket(int domain, int type, int protocol);
+```
+
+| **Parameter** | **Description** |
+|--------|-------------------------------------|
+| domain | protocol domain type |
+| type | protocol type |
+| protocol | Transport layer protocol for actual use |
+| **back** | -- |
+| >=0 | Success, an integer representing the socket descriptor will be returned |
+| -1 | Fail |
+
+This function is used to assign a socket descriptor and the resources it USES based on the specified address family, data type, and protocol.
+
+**domain ( protocol domain type ):**
+
+- AF_INET: IPv4
+- AF_INET6: IPv6
+
+**type ( protocol type ):**
+
+- SOCK_STREAM:Stream socket
+- SOCK_DGRAM: Datagram socket
+- SOCK_RAW: Raw socket
+
+## Bind Socket (bind)
+
+```c
+int bind(int s, const struct sockaddr *name, socklen_t namelen);
+```
+
+| **P**arameter | **Description** |
+|---------|---------------------------------------------|
+| s | socket descriptor |
+| name | a pointer to the sockaddr structure representing the address to bind to |
+| namelen | length of sockaddr structure |
+| **back** | -- |
+| 0 | success |
+| -1 | fail |
+
+This function is used to bind the port number and IP address to the specified socket。
+
+SAL components depend on the `netdev` components, when using ` bind () ` function, can get IP address information through the netdev nic name, is used to create Socket bound to the specified object of network interface card. The following example completes the process of binding the IP address of the network interface card and connecting to the server through the name of the incoming network interface card:
+
+```c
+#include <rtthread.h>
+#include <arpa/inet.h>
+#include <netdev.h>
+
+#define SERVER_HOST "192.168.1.123"
+#define SERVER_PORT 1234
+
+static int bing_test(int argc, char **argv)
+{
+ struct sockaddr_in client_addr;
+ struct sockaddr_in server_addr;
+ struct netdev *netdev = RT_NULL;
+ int sockfd = -1;
+
+ if (argc != 2)
+ {
+ rt_kprintf("bind_test [netdev_name] --bind network interface device by name.\n");
+ return -RT_ERROR;
+ }
+
+ /* Get the netdev network interface card object by name */
+ netdev = netdev_get_by_name(argv[1]);
+ if (netdev == RT_NULL)
+ {
+ rt_kprintf("get network interface device(%s) failed.\n", argv[1]);
+ return -RT_ERROR;
+ }
+
+ if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
+ {
+ rt_kprintf("Socket create failed.\n");
+ return -RT_ERROR;
+ }
+
+ /* Initializes the client address to bind to */
+ client_addr.sin_family = AF_INET;
+ client_addr.sin_port = htons(8080);
+ /* Gets the IP address information in the network interface card object */
+ client_addr.sin_addr.s_addr = netdev->ip_addr.addr;
+ rt_memset(&(client_addr.sin_zero), 0, sizeof(client_addr.sin_zero));
+
+ if (bind(sockfd, (struct sockaddr *)&client_addr, sizeof(struct sockaddr)) < 0)
+ {
+ rt_kprintf("socket bind failed.\n");
+ closesocket(sockfd);
+ return -RT_ERROR;
+ }
+ rt_kprintf("socket bind network interface device(%s) success!\n", netdev->name);
+
+ /* Initializes the server address for the pre-connection */
+ server_addr.sin_family = AF_INET;
+ server_addr.sin_port = htons(SERVER_PORT);
+ server_addr.sin_addr.s_addr = inet_addr(SERVER_HOST);
+ rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
+
+ /* Connect to the server */
+ if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) < 0)
+ {
+ rt_kprintf("socket connect failed!\n");
+ closesocket(sockfd);
+ return -RT_ERROR;
+ }
+ else
+ {
+ rt_kprintf("socket connect success!\n");
+ }
+
+ /* Close the connection */
+ closesocket(sockfd);
+ return RT_EOK;
+}
+
+#ifdef FINSH_USING_MSH
+#include <finsh.h>
+MSH_CMD_EXPORT(bing_test, bind network interface device test);
+#endif /* FINSH_USING_MSH */
+```
+
+## Listen Socket (listen)
+
+```c
+int listen(int s, int backlog);
+```
+
+| **Parameter** | **Description** |
+|-------|-------------------------------|
+| s | socket descriptor |
+| backlog | represents the maximum number of connections that can wait at a time |
+| **back** | -- |
+| 0 | success |
+| -1 | fail |
+
+This function is used by the TCP server to listen for a specified socket connection。
+
+## Accept Connection (accept)
+
+```c
+int accept(int s, struct sockaddr *addr, socklen_t *addrlen);
+```
+
+| **Parameter** | **Descrption** |
+|-------|-------------------------------|
+| s | socket descriptor |
+| addr | represents the maximum number of connections that can wait at a time |
+| addrlen | length of client device address structure |
+| **back** | -- |
+| 0 | success, return the newly created socket descriptor |
+| -1 | fail |
+
+When the application listens for connections from other hosts, the connection is initialized with the `accept()` function, and `accept()` creates a new socket for each connection and removes the connection from the listen queue.
+
+## Establish Connection (connect)
+
+```c
+int connect(int s, const struct sockaddr *name, socklen_t namelen);
+```
+
+| **Parameter** | **Description** |
+|-------|-------------------------------|
+| s | socket descriptor |
+| name | server address information |
+| namelen | server address structure length |
+| **back** | -- |
+| 0 | successful, return the newly created socket descriptor |
+| -1 | fail |
+
+This function is used to establish a connection to the specified socket.
+
+## Send TCP Data (send)
+
+```c
+int send(int s, const void *dataptr, size_t size, int flags);
+```
+
+| **Parameter** | **Description** |
+|-------|---------------------------|
+| s | socket descriptor |
+| dataptr | sent data pointer |
+| size | length of sent data |
+| flags | flags, usually 0 |
+| **back** | -- |
+| >0 | success, the length of the sent data is returned |
+| <=0 | Fail |
+
+This function is commonly used to send data over a TCP connection。
+
+## Receive TCP Data (recv)
+
+```c
+int recv(int s, void *mem, size_t len, int flags);
+```
+
+| **Parameter** | **Description** |
+|-----|---------------------------|
+| s | socket descriptor |
+| mem | received data pointer |
+| len | length of received data |
+| flags | flags, usually 0 |
+| **back** | -- |
+| >0 | success, the length of the received data will be returned |
+| =0 | the destination address has been transmitted and the connection is closed |
+| <0 | fail |
+
+This function is used to receive data over a TCP connection。
+
+## Send UDP Data (sendto)
+
+```c
+int sendto(int s, const void *dataptr, size_t size, int flags, const struct sockaddr *to, socklen_t tolen);
+```
+
+| **Parameter** | **Description** |
+|-------|---------------------------|
+| s | socket descriptor |
+| dataptr | sent data pointer |
+| size | length of sent data |
+| flags | flags, usually 0 |
+| to | target address structure pointer |
+| tolen | length of the target address structure |
+| **return** | -- |
+| >0 | success, the length of the received data will be returned |
+| <=0 | fail |
+
+This function is used for UDP connections to send data。
+
+## Receive UDP Data (recvfrom)
+
+```c
+int recvfrom(int s, void *mem, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen);
+```
+
+| **Parameter** | **Description** |
+|-------|---------------------------|
+| s | socket descriptor |
+| mem | received data pointer |
+| len | length of data received |
+| flags | flags, usually 0 |
+| from | received address structure pointer |
+| fromlen | length of received address structure |
+| **back** | -- |
+| >0 | success, return the length of the received data |
+| =0 | the receiving address has been transferred and the connection is closed |
+| <0 | fail |
+
+This function is used to receive data on a UDP connection。
+
+## Close Socket (closesocket)
+
+```c
+int closesocket(int s);
+```
+
+| **Parameter** | **Description** |
+|----|-------------|
+| s | Socket descriptor |
+| **back** | -- |
+| 0 | success |
+| -1 | fail |
+
+This function is used to close the connection and release the resource.。
+
+## Shutdown The Socket By Setting(shutdown)
+
+```c
+int shutdown(int s, int how);
+```
+
+| **Parameter** | **Descrption** |
+|----|-----------------|
+| s | socket descriptor |
+| how | socket control |
+| **back** | -- |
+| 0 | fail |
+| -1 | success |
+
+This function provides more permissions to control the closing process of the socket.。
+
+**How ( socket control ):**
+
+- 0: Stop receiving current data and reject future data reception;
+- 1: Stop sending data and discard unsent data;
+- 2: Stop receiving and sending data。
+
+## Set Socket Options(setsockopt)
+
+```c
+int setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen);
+```
+
+| **Parameter** | **Description** |
+|-------|-----------------------|
+| s | socket descriptor |
+| level | protocol stack configuration options |
+| optname | option name to be set |
+| optval | set the buffer address of the option value |
+| optlen | set the buffer length of the option value |
+| **back** | -- |
+| =0 | success |
+| <0 | fail |
+
+This function is used to set the socket mode and modify the socket configuration options.。
+
+**level ( protocol stack configuration options ):**
+
+- SOL_SOCKET:Socket layer
+- IPPROTO_TCP:TCP layer
+- IPPROTO_IP:IP layer
+
+**optname ( Option name to be set ):**
+
+- SO_KEEPALIVE:Set keep alive options
+- SO_RCVTIMEO:Set socket data reception timeout
+- SO_SNDTIMEO:Set socket data sending timeout
+
+## Get Socket Options(getsockopt)
+
+```c
+int getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen);
+```
+
+| **Parameter** | **Description** |
+|-------|---------------------------|
+| s | socket descriptor |
+| level | protocol stack configuration options |
+| optname | option name to be set |
+| optval | get the buffer address of the option value |
+| optlen | get the buffer length address of the option value |
+| **back** | -- |
+| =0 | success |
+| <0 | fail |
+
+This function is used to get the socket configuration options。
+
+## Get Remote Address Information (getpeername)
+
+```c
+int getpeername(int s, struct sockaddr *name, socklen_t *namelen);
+```
+
+| **Parameter** | **Description** |
+|-------|-------------------------|
+| s | socket descriptor |
+| name | received address structure pointer |
+| namelen | length of received address structure |
+| **back** | -- |
+| =0 | success |
+| <0 | fail |
+
+This function is used to get the remote address information associated with the socket。
+
+## Get Local Address Information (getsockname)
+
+```c
+int getsockname(int s, struct sockaddr *name, socklen_t *namelen);
+```
+
+| **Parameter** | **Description** |
+|-------|-------------------------|
+| s | Socket descriptor |
+| name | received address structure pointer |
+| namelen | length of received address structure |
+| **back** | -- |
+| =0 | success |
+| <0 | fail |
+
+This function is used to get local socket address information。
+
+## Configure Socket Parameters (ioctlsocket))
+
+```c
+int ioctlsocket(int s, long cmd, void *arg);
+```
+
+| **Parameter** | **Description** |
+|-----|-----------------|
+| s | socket descriptor |
+| cmd | socket operation command |
+| arg | operation command's parameters |
+| **back** | -- |
+| =0 | success |
+| <0 | fail |
+
+This function sets the socket control mode。
+
+**The CMD supports following commands**
+
+- FIONBIO: Turns on or off the socket's non-blocking mode. Arg parameter 1 is open non-blocking and 0 is closed non-blocking.
+
+# Network Protocol Stack Access
+
+Access to the network protocol stack or network function implementation is mainly to initialize and register the protocol cluster structure, and add it to the protocol cluster list in SAL component. The protocol cluster structure is defined as follows:
+
+```c
+/* network interface socket opreations */
+struct sal_socket_ops
+{
+ int (*socket) (int domain, int type, int protocol);
+ int (*closesocket)(int s);
+ int (*bind) (int s, const struct sockaddr *name, socklen_t namelen);
+ int (*listen) (int s, int backlog);
+ int (*connect) (int s, const struct sockaddr *name, socklen_t namelen);
+ int (*accept) (int s, struct sockaddr *addr, socklen_t *addrlen);
+ int (*sendto) (int s, const void *data, size_t size, int flags, const struct sockaddr *to, socklen_t tolen);
+ int (*recvfrom) (int s, void *mem, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen);
+ int (*getsockopt) (int s, int level, int optname, void *optval, socklen_t *optlen);
+ int (*setsockopt) (int s, int level, int optname, const void *optval, socklen_t optlen);
+ int (*shutdown) (int s, int how);
+ int (*getpeername)(int s, struct sockaddr *name, socklen_t *namelen);
+ int (*getsockname)(int s, struct sockaddr *name, socklen_t *namelen);
+ int (*ioctlsocket)(int s, long cmd, void *arg);
+#ifdef SAL_USING_POSIX
+ int (*poll) (struct dfs_file *file, struct rt_pollreq *req);
+#endif
+};
+
+/* sal network database name resolving */
+struct sal_netdb_ops
+{
+ struct hostent* (*gethostbyname) (const char *name);
+ int (*gethostbyname_r)(const char *name, struct hostent *ret, char *buf, size_t buflen, struct hostent **result, int *h_errnop);
+ int (*getaddrinfo) (const char *nodename, const char *servname, const struct addrinfo *hints, struct addrinfo **res);
+ void (*freeaddrinfo) (struct addrinfo *ai);
+};
+
+/* Protocol domain structure definition */
+struct sal_proto_family
+{
+ int family; /* primary protocol families type */
+ int sec_family; /* secondary protocol families type */
+ const struct sal_socket_ops *skt_ops; /* socket opreations */
+ const struct sal_netdb_ops *netdb_ops; /* network database opreations */
+};
+
+```
+
+- `family`: Each protocol stack supports the main protocol cluster types, such as AF_INET for lwIP, AF_AT Socket, and AF_WIZ for WIZnet。
+- `sec_family`:The type of sub-protocol domain supported by each protocol stack, used to support a single protocol stack or network implementation, that matches other types of protocol cluster types in the package。
+- `skt_ops`: Define socket related functions, such as connect, send, recv, etc., each protocol cluster has a different set of implementation。
+- `netdb_ops`:Define non-socket-related execution functions, such as `gethostbyname`, `getaddrinfo`, `freeaddrinfo`, etc. Each protocol cluster has a different set of implementations。
+
+The following is the access registration process implemented by AT Socket network. Developers can refer to other protocol stacks or network implementations for access:
+
+```c
+#include <rtthread.h>
+#include <netdb.h>
+#include <sal_low_lvl.h> /* SAL component structure holds the header file */
+#include <at_socket.h> /* AT Socket related header file */
+#include <af_inet.h>
+
+#include <netdev.h> /*network interface card function related header file */
+
+#ifdef SAL_USING_POSIX
+#include <dfs_poll.h> /* Poll function related header file */
+#endif
+
+#ifdef SAL_USING_AT
+
+/* A custom poll execution function that handles the events received in the poll */
+static int at_poll(struct dfs_file *file, struct rt_pollreq *req)
+{
+ int mask = 0;
+ struct at_socket *sock;
+ struct socket *sal_sock;
+
+ sal_sock = sal_get_socket((int) file->data);
+ if(!sal_sock)
+ {
+ return -1;
+ }
+
+ sock = at_get_socket((int)sal_sock->user_data);
+ if (sock != NULL)
+ {
+ rt_base_t level;
+
+ rt_poll_add(&sock->wait_head, req);
+
+ level = rt_hw_interrupt_disable();
+ if (sock->rcvevent)
+ {
+ mask |= POLLIN;
+ }
+ if (sock->sendevent)
+ {
+ mask |= POLLOUT;
+ }
+ if (sock->errevent)
+ {
+ mask |= POLLERR;
+ }
+ rt_hw_interrupt_enable(level);
+ }
+
+ return mask;
+}
+#endif
+
+/* Define and assign socket execution functions, and the SAL component calls the underlying function of the registration when it executes relevant functions */
+static const struct proto_ops at_inet_stream_ops =
+{
+ at_socket,
+ at_closesocket,
+ at_bind,
+ NULL,
+ at_connect,
+ NULL,
+ at_sendto,
+ at_recvfrom,
+ at_getsockopt,
+ at_setsockopt,
+ at_shutdown,
+ NULL,
+ NULL,
+ NULL,
+
+#ifdef SAL_USING_POSIX
+ at_poll,
+#else
+ NULL,
+#endif /* SAL_USING_POSIX */
+};
+
+static const struct sal_netdb_ops at_netdb_ops =
+{
+ at_gethostbyname,
+ NULL,
+ at_getaddrinfo,
+ at_freeaddrinfo,
+};
+
+/* define and assign AT Socket protocol domain structure */
+static const struct sal_proto_family at_inet_family =
+{
+ AF_AT,
+ AF_INET,
+ &at_socket_ops,
+ &at_netdb_ops,
+};
+
+/* Used to set the protocol domain information in the network interface card device */
+int sal_at_netdev_set_pf_info(struct netdev *netdev)
+{
+ RT_ASSERT(netdev);
+
+ netdev->sal_user_data = (void *) &at_inet_family;
+ return 0;
+}
+
+#endif /* SAL_USING_AT */
+```
diff --git a/documentation/6.components/ulog/figures/ulog_async_vs_sync.png b/documentation/6.components/ulog/figures/ulog_async_vs_sync.png
new file mode 100644
index 0000000000..39d651fa13
--- /dev/null
+++ b/documentation/6.components/ulog/figures/ulog_async_vs_sync.png
Binary files differ
diff --git a/documentation/6.components/ulog/figures/ulog_example.png b/documentation/6.components/ulog/figures/ulog_example.png
new file mode 100644
index 0000000000..7d4d5b945f
--- /dev/null
+++ b/documentation/6.components/ulog/figures/ulog_example.png
Binary files differ
diff --git a/documentation/6.components/ulog/figures/ulog_example_all_format.png b/documentation/6.components/ulog/figures/ulog_example_all_format.png
new file mode 100644
index 0000000000..70dbb240ed
--- /dev/null
+++ b/documentation/6.components/ulog/figures/ulog_example_all_format.png
Binary files differ
diff --git a/documentation/6.components/ulog/figures/ulog_example_async.png b/documentation/6.components/ulog/figures/ulog_example_async.png
new file mode 100644
index 0000000000..43fd13ecdd
--- /dev/null
+++ b/documentation/6.components/ulog/figures/ulog_example_async.png
Binary files differ
diff --git a/documentation/6.components/ulog/figures/ulog_example_filter20.png b/documentation/6.components/ulog/figures/ulog_example_filter20.png
new file mode 100644
index 0000000000..42c61980dc
--- /dev/null
+++ b/documentation/6.components/ulog/figures/ulog_example_filter20.png
Binary files differ
diff --git a/documentation/6.components/ulog/figures/ulog_example_filter30.png b/documentation/6.components/ulog/figures/ulog_example_filter30.png
new file mode 100644
index 0000000000..daccd700f2
--- /dev/null
+++ b/documentation/6.components/ulog/figures/ulog_example_filter30.png
Binary files differ
diff --git a/documentation/6.components/ulog/figures/ulog_example_filter40.png b/documentation/6.components/ulog/figures/ulog_example_filter40.png
new file mode 100644
index 0000000000..b5d5f245c9
--- /dev/null
+++ b/documentation/6.components/ulog/figures/ulog_example_filter40.png
Binary files differ
diff --git a/documentation/6.components/ulog/figures/ulog_example_hexdump.png b/documentation/6.components/ulog/figures/ulog_example_hexdump.png
new file mode 100644
index 0000000000..1d14f050f3
--- /dev/null
+++ b/documentation/6.components/ulog/figures/ulog_example_hexdump.png
Binary files differ
diff --git a/documentation/6.components/ulog/figures/ulog_example_syslog.png b/documentation/6.components/ulog/figures/ulog_example_syslog.png
new file mode 100644
index 0000000000..996cde3a17
--- /dev/null
+++ b/documentation/6.components/ulog/figures/ulog_example_syslog.png
Binary files differ
diff --git a/documentation/6.components/ulog/figures/ulog_framework.png b/documentation/6.components/ulog/figures/ulog_framework.png
new file mode 100644
index 0000000000..bc01eb4101
--- /dev/null
+++ b/documentation/6.components/ulog/figures/ulog_framework.png
Binary files differ
diff --git a/documentation/6.components/ulog/figures/ulog_framework_backend.png b/documentation/6.components/ulog/figures/ulog_framework_backend.png
new file mode 100644
index 0000000000..5df4c71cc1
--- /dev/null
+++ b/documentation/6.components/ulog/figures/ulog_framework_backend.png
Binary files differ
diff --git a/documentation/6.components/ulog/figures/ulog_menuconfig_async.png b/documentation/6.components/ulog/figures/ulog_menuconfig_async.png
new file mode 100644
index 0000000000..7e5f591829
--- /dev/null
+++ b/documentation/6.components/ulog/figures/ulog_menuconfig_async.png
Binary files differ
diff --git a/documentation/6.components/ulog/figures/ulog_menuconfig_format.png b/documentation/6.components/ulog/figures/ulog_menuconfig_format.png
new file mode 100644
index 0000000000..63bf46019e
--- /dev/null
+++ b/documentation/6.components/ulog/figures/ulog_menuconfig_format.png
Binary files differ
diff --git a/documentation/6.components/ulog/figures/ulog_syslog_format.png b/documentation/6.components/ulog/figures/ulog_syslog_format.png
new file mode 100644
index 0000000000..69b17b71db
--- /dev/null
+++ b/documentation/6.components/ulog/figures/ulog_syslog_format.png
Binary files differ
diff --git a/documentation/6.components/ulog/ulog.md b/documentation/6.components/ulog/ulog.md
new file mode 100644
index 0000000000..f840fba419
--- /dev/null
+++ b/documentation/6.components/ulog/ulog.md
@@ -0,0 +1,800 @@
+@page page_component_ulog Ulog Log
+
+# Ulog Introduction
+
+**Log definition**:The log is to output the status, process and other information of the software to different media (for example: file, console, display, etc.), display and save. Provide reference for software traceability, performance analysis, system monitoring, fault warning and other functions during software debugging and maintenance. It can be said that the use of logs consumes at least 80% of the software life cycle.
+
+**The importance of the log**:For the operating system, because the complexity of the software is very large, single-step debugging is not suitable in some scenarios, the log component is almost standard part on the operating system. A sophisticated logging system can also make the debugging of the operating system more effective.
+
+**The origin of ulog**: RT-Thread has always lacked a small, useful log component, and the birth of ulog complements this short board. It will be open sourced as a basic component of RT-Thread, allowing our developers to use a simple and easy-to-use logging system to improve development efficiency.
+
+Ulog is a very simple and easy to use C/C++ log component. The first letter u stands for μ, which means micro. It can achieve the lowest **ROM<1K, RAM<0.2K** resource usage. Ulog is not only small in size, but also has very comprehensive functions. Its design concept refers to another C/C++ open source log library: EasyLogger (referred to as elog), and has made many improvements in terms of functions and performance. The main features are as follows:
+
+* The backend of the log output is diversified and can support, for example, serial port, network, file, flash memory and other backend forms.
+
+* The log output is designed to be thread-safe and supports asynchronous output mode.
+
+* The logging system is highly reliable and is still available in complex environments such as interrupted ISRs and Hardfault.
+
+* The log supports runtime/compilation time to set the output level.
+
+* The log content supports global filtering by keyword and label.
+
+* The APIs and log formats are compatible with linux syslog.
+
+* Support for dumping debug data to the log in hex format.
+
+* Compatible with `rtdbg` (RTT's early log header file) and EasyLogger's log output API.
+
+## Ulog Architecture
+
+The following figure shows the ulog log component architecture diagram:
+
+![ulog architecture](figures/ulog_framework.png)
+
+* **Front end**:This layer is the closest layer to the application, and provides users with two types of API interfaces, `syslog` and `LOG_X`, which are convenient for users to use in different scenarios.
+
+* **Core**:The main work of the middle core layer is to format and filter the logs passed by the upper layer, and then generate log frames, and finally output them to the lowest-end back-end devices through different output modules.
+
+* **Back end**:After receiving the log frames sent from the core layer, the logs are output to the registered log backend devices, such as files, consoles, log servers, and so on.
+
+## Configuration Options
+
+The path to configure ulog using menuconfig in the ENV tool is as follows:
+
+```c
+ RT-Thread Components → Utilities → Enable ulog
+```
+
+ The ulog configuration options are described below. In general, the default configuration is used:
+
+```c
+[*] Enable ulog /* Enable ulog */
+ The static output log level./* Select a static log output level. After the selection is completed, the log level lower than the set level (here specifically the log using the LOG_X API) will not be compiled into the ROM. */
+[ ] Enable ISR log. /* Enable interrupted ISR log, ie log output API can also be used in ISR */
+[*] Enable assert check. /* Enable assertion checks. If fter disabled, the asserted log will not be compiled into ROM */
+(128) The log's max width. /* The maximum length of the log. Since ulog's logging API is in units of rows, this length also represents the maximum length of a row of logs. */
+[ ] Enable async output mode. /* Enable asynchronous log output mode. When this mode is turned on, the log will not be output to the backend immediately, but will be cached first, and then handed to the log output thread (for example: idle thread) to output. */
+ log format ---> /* Configure the format of the log, such as time information, color information, thread information, whether to support floating point, etc. */
+[*] Enable console backend. /* Enable the console as a backend. After enabling, the log can be output to the console serial port. It is recommended to keep it on. */
+[ ] Enable runtime log filter. /* Enable the runtime log filter, which is dynamic filtering. After enabling, the log will support dynamic filtering when the system is running, by means of tags, keywords, and so on. */
+```
+
+**The configuration log format option description is as follows:**
+
+```c
+[ ] Enable float number support. It will using more thread stack. /* Supporting floating-point variables (traditional rtdbg/rt_kprintf does not support floating-point logs) */
+ [*] Enable color log. /* Colored log */
+ [*] Enable time information. /* Time information */
+ [ ] Enable timestamp format for time. /* Including timestamp */
+ [*] Enable level information. /* Level information */
+ [*] Enable tag information. /* Label Information */
+ [ ] Enable thread information. /* Thread information */
+```
+
+## Log Level
+
+The log level represents the importance of the log, from high to low in ulog, with the following log levels:
+
+| Level | Name | Description |
+| ------------ | ---- | ----------------------- |
+| LOG_LVL_ASSERT | assertion | Unhandled and fatal errors occurred, so that the system could not continue to run. These are assertion logs. |
+| LOG_LVL_ERROR | error | The log that is output when a serious, **unrepairable** error occurs is an error level log. |
+| LOG_LVL_WARNING | warning | These warning logs are output when there are some less important errors with **repairability**. |
+| LOG_LVL_INFO | information | A log of important prompt information that is viewed by the upper-level user of the module, for example, initialization success, current working status, and so on. This level of log is generally **retained** during mass production. |
+| LOG_LVL_DBG | debug | The debug log that is viewed by the developer of this module. This level of log is generally **closed** during mass production. |
+
+The log level in ulog also has the following classification:
+
+* **Static and dynamic levels**:Classify according to whether the log can be modified during the run phase. The dynamic level that can be modified during the run phase can only be called static level in the **compilation phase**. Logs that are lower than the static level (here specifically the logs using the `LOG_X` API) will not be compiled into the ROM and will not be output or displayed. The dynamic level can control logs that their level are higher than or equal to the static level. Logs that are lower than the dynamic level are filtered out when ulog is running.
+
+* **Global level and module level**:Classification by scope. Each file (module) can also be set to a separate log level in ulog. The global level scope is larger than the module level, that is, the module level can only control module logs higher than or equal to the global level.
+
+As can be seen from the above classification, the output level of the log can be set in the following four aspects of ulog:
+
+* **Global static **log level:Configured in menuconfig, corresponding to the `ULOG_OUTPUT_LVL` macro.
+
+* **Global Dynamics** log level:Use the `void ulog_global_filter_lvl_set(rt_uint32_t level)` function to set it.
+
+* **Module static** log level:The `LOG_LVL` macro is defined in the module (file), similar to the way the log tag macro `LOG_TAG` is defined.
+
+* **Module dynamics** log level:Use the `int ulog_tag_lvl_filter_set(const char *tag, rt_uint32_t level)` function to set it.
+
+Their scope of action is:**Global Static**>**Global Dynamics**>**Module Static**>**Module Dynamic**.
+
+## Log Label
+
+Due to the increasing log output, in order to avoid the log being outputted indiscriminately, it is necessary to use a tag to classify each log. The definition of the label is in the form of **modular**, for example: Wi-Fi components include device driver (wifi_driver), device management (wifi_mgnt) and other modules, Wi-Fi component internal module can use `wifi.driver`, `wifi.mgnt` is used as a label to perform classified output of logs.
+
+The tag attribute of each log can also be output and displayed. At the same time, ulog can also set the output level of each tag (module) corresponding to the log. The log of the current unimportant module can be selectively closed, which not only reduces ROM resources, but also helps developers filter irrelevant logs.
+
+See the `rt-thread\examples\ulog_example.c` ulog routine file with the `LOG_TAG` macro defined at the top of the file:
+
+```c
+#define LOG_TAG "example" // The label corresponding to this module. When not defined, default: NO_TAG
+#define LOG_LVL LOG_LVL_DBG // The log output level corresponding to this module. When not defined, default: debug level
+#include <ulog.h> // this header file Must be under LOG_TAG and LOG_LVL
+```
+
+Note that the definition log tag must be above `#include <ulog.h>`, otherwise the default `NO_TAG` will be used (not recommended to define these macros in the header file).
+
+The scope of the log tag is the current source file, and the project source code will usually be classified according to the module. Therefore, when defining a label, you can specify the module name and sub-module name as the label name. This is not only clear and intuitive when the log output is displayed, but also facilitates subsequent dynamic adjustment of the level or filtering by label.
+
+# Log Initialization
+
+## Initialization
+
+```c
+int ulog_init(void)
+```
+
+| **Return** | **Description** |
+| :----- | :----- |
+|>=0 | Succeeded |
+|-5 | Failed, insufficient memory |
+
+This function must be called to complete ulog initialization before using ulog. This function will also be called automatically if component auto-initialization is turned on.
+
+## Deinitialization
+
+```c
+void ulog_deinit(void)
+```
+
+This deinit release resource can be executed when ulog is no longer used.
+
+# Log Output API
+
+Ulog mainly has two log output macro APIs, which are defined in the source code as follows:
+
+```c
+#define LOG_E(...) ulog_e(LOG_TAG, __VA_ARGS__)
+#define LOG_W(...) ulog_w(LOG_TAG, __VA_ARGS__)
+#define LOG_I(...) ulog_i(LOG_TAG, __VA_ARGS__)
+#define LOG_D(...) ulog_d(LOG_TAG, __VA_ARGS__)
+#define LOG_RAW(...) ulog_raw(__VA_ARGS__)
+#define LOG_HEX(name, width, buf, size) ulog_hex(name, width, buf, size)
+```
+
+* The macro `LOG_X(...)`:`X` corresponds to the first letter of the different levels. The parameter `...` is the log content, and the format is the same as printf. This method is preferred because on the one hand, because its API format is simple, only one log information is entered, and the static log level filtering by module is also supported.
+
+* The macro `ulog_x(LOG_TAG, __VA_ARGS__)`: `x ` corresponds to a different level of shorthand. The parameter `LOG_TAG` is the log label, the parameter `...` is the log content, and the format is the same as printf. This API is useful when you use different tag output logs in one file.
+
+| **API** |**Description** |
+|-------------------------|--------------------------|
+| LOG_E(...)| Error level log |
+| LOG_W(...) | Error level log |
+| LOG_I(...) | Prompt level log |
+| LOG_D(...)| Debug level log |
+| LOG_RAW(...) | Output raw log |
+| LOG_HEX(name, width, buf, size)| Output hexadecimal format data to the log |
+
+API such as ` LOG_X` and `ulog_x` , the output are formatted logs. When you need to output logs without any format, you can use `LOG_RAW` or `ulog_raw()`. E.g:
+
+```c
+LOG_RAW("\r");
+ulog_raw("\033[2A");
+```
+
+You can use `LOG_HEX()` or `ulog_hex` to dump data into the log in hexadecimal hex format. The function parameters and descriptions are as follows:
+
+| **Parameter** | **Description** |
+| ---- | -------------------------- |
+| tag | Log label |
+| width | The width (number) of a line of hex content |
+| buf | Data content to be output |
+| size | Data size |
+
+The `hexdump` log is DEBUG level, supports runtime level filtering. The tag corresponding to the hexdump log supports tag filtering during runtime.
+
+Ulog also provides the assertion API: `ASSERT(expression)`. When the assertion is triggered, the system will stop running, and `ulog_flush()` will be executed internally, and all log backends will execute flush. If asynchronous mode is turned on, all logs in the buffer will also be flushed. An example of the use of assertions is as follows:
+
+```c
+void show_string(const char *str)
+{
+ ASSERT(str);
+ ...
+}
+```
+
+# ULog Usage Example
+
+## Example
+
+The following is a description of the ulog routine. Open `rt-thread\examples\ulog_example.c` and you can see that there are labels and static priorities defined at the top.
+
+```c
+#define LOG_TAG "example"
+#define LOG_LVL LOG_LVL_DBG
+#include <ulog.h>
+```
+
+The `LOG_X` API is used in the `void ulog_example(void)` function, which is roughly as follows:
+
+```c
+/* output different level log by LOG_X API */
+LOG_D("LOG_D(%d): RT-Thread is an open source IoT operating system from China.", count);
+LOG_I("LOG_I(%d): RT-Thread is an open source IoT operating system from China.", count);
+LOG_W("LOG_W(%d): RT-Thread is an open source IoT operating system from China.", count);
+LOG_E("LOG_E(%d): RT-Thread is an open source IoT operating system from China.", count);
+```
+
+These log output APIs support the printf format and will automatically wrap lines at the end of the log.
+
+The following will show the effect of the ulog routine on qemu:
+
+- Copy `rt-thread\examples\ulog_example.c` to the `rt-thread\bsp\qemu-vexpress-a9\applications` folder.
+- Go to the `rt-thread\bsp\qemu-vexpress-a9` directory in Env
+- After determining that the configuration of ulog has been executed before, execute the `scons` command and wait for the compilation to complete.
+- Run `qemu.bat` to open RT-Thread's qemu simulator
+- Enter the `ulog_example` command to see the results of the ulog routine. The effect is as follows.
+
+![ulog routine](figures/ulog_example.png)
+
+You can see that each log is displayed in rows, and different levels of logs have different colors. At the top of the log is the tick of the current system, with the log level and label displayed in the middle, and the specific log content at the end. These log formats and configuration instructions are also highlighted later in this article.
+
+## Used in Interrupt ISR
+
+Many times you need to output a log in the interrupt ISR, but the ISR may interrupt the thread that is doing the log output. To ensure that the interrupt log and the thread log do not interfere with each other, special handling must be performed for the interrupt condition.
+
+Ulog has integrated interrupt log function, but it is not enabled by default. Open the `Enable ISR log` option when using it. The API of the log is the same as that used in the thread, for example:
+
+```c
+#define LOG_TAG "driver.timer"
+#define LOG_LVL LOG_LVL_DBG
+#include <ulog.h>
+
+void Timer2_Handler(void)
+{
+ /* enter interrupt */
+ rt_interrupt_enter();
+
+ LOG_D("I'm in timer2 ISR");
+
+ /* leave interrupt */
+ rt_interrupt_leave();
+}
+
+```
+
+Here are the different strategies for interrupt logging in ulog in synchronous mode and asynchronous mode:
+
+**In synchronous mode**:If the thread is interrupted when the log is being output at this time, and there is a log to be output in the interrupt, it will be directly output to the console, and output to other backends is not supported;
+
+**In asynchronous mode**:If the above situation occurs, the log in the interrupt will be put into the buffer first, and finally sent to the log output thread for processing together with the thread log.
+
+## Set the Log Format
+
+The log format supported by ulog can be configured in menuconfig, located in `RT-Thread Components` → `Utilities` → `ulog` → `log format`. The specific configuration is as follows:
+
+![ulog format configuration](figures/ulog_menuconfig_format.png)
+
+They can be configured separately: floating-point number support (traditional rtdbg/rt_kprintf does not support floating-point logs), colored logs, time information (including timestamps), level information, tag information, thread information. Below we will **select all of these options**, save and recompile and run the ulog routine again in qemu to see the actual effect:
+
+![ulog routine (all formats)](figures/ulog_example_all_format.png)
+
+It can be seen that the time information has been changed from the tick value of the system to the timestamp information compared to the first run routine, and the thread information has also been output.
+
+## Hexdump Output Using
+
+Hexdump is also a more common function when logging output. hexdump can output a piece of data in hex format. The corresponding API is: `void ulog_hexdump(const char *tag, rt_size_t width, rt_uint8_t *buf, rt_size_t size)` , see below the specific use method and operation effect:
+
+```c
+/* Define an array of 128 bytes in length */
+uint8_t i, buf[128];
+/* Fill the array with numbers */
+for (i = 0; i < sizeof(buf); i++)
+{
+ buf[i] = i;
+}
+/* Dumps the data in the array in hex format with a width of 16 */
+ulog_hexdump("buf_dump_test", 16, buf, sizeof(buf));
+```
+
+You can copy the above code into the ulog routine, and then look at the actual running results:
+
+![ulog routine (hexdump)](figures/ulog_example_hexdump.png)
+
+It can be seen that the middle is the hexadecimal information of the buf data, and the rightmost is the character information corresponding to each data.
+
+# Log Advanced Features
+
+After understanding the introduction of the log in the previous section, the basic functions of ulog can be mastered. In order to let everyone better use ulog, this application note will focus on the advanced features of ulog and some experience and skills in log debugging. After learning these advanced uses, developers can also greatly improve the efficiency of log debugging.
+
+It also introduces the advanced mode of ulog: syslog mode, which is fully compatible with the Linux syslog from the front-end API to the log format, greatly facilitating the migration of software from Linux.
+
+## Log Backend
+
+![Ulog framework](figures/ulog_framework_backend.png)
+
+Speaking of the backend, let's review the ulog's framework. As can be seen from the above figure, ulog is a design with front and back ends separated, and there is no dependence on the front and back ends. And the backends that are supported are diversified, no matter what kind of backends, as long as they are implemented, they can be registered.
+
+Currently ulog has integrated the console backend, the traditional device that outputs `rt_kprintf` print logs. Ulog also supports the Flash backend, which seamlessly integrates with EasyFlash. See its package for details.([Click to view](https://github.com/armink-rtt-pkgs/ulog_easyflash_be))。Later ulog will also increase the implementation of backends such as file backends and network backends. Of course, if there are special needs, users can also implement the backend themselves.
+
+### Register Backend Device
+
+```c
+rt_err_t ulog_backend_register(ulog_backend_t backend, const char *name, rt_bool_t support_color)
+```
+
+| **Parameter** | **Description** |
+| :----- | :----- |
+|backend | Backend device handle |
+|name| Backend device name |
+|support_color| Whether it supports color logs |
+|**return**|-- |
+|>=0 | Succeeded |
+
+This function is used to register the backend device into the ulog, ensuring that the function members in the backend device structure are set before registration.
+
+### Logout Backend Device
+
+```c
+rt_err_t ulog_backend_unregister(ulog_backend_t backend);
+```
+
+| **Parameter** | **Description** |
+| :----- | :----- |
+|backend | Backend device handle |
+|**return**|-- |
+|>=0 | Succeeded |
+
+This function is used to unregister a backend device that has already been registered.
+
+### Backend Implementation and Registration Examples
+
+The console backend is taken as an example to briefly introduce the implementation method and registration method of the backend.
+
+Open the `rt-thread/components/utilities/ulog/backend/console_be.c` file and you can see the following:
+
+```c
+#include <rthw.h>
+#include <ulog.h>
+
+/* Defining console backend devices */
+static struct ulog_backend console;
+/* Console backend output function */
+void ulog_console_backend_output(struct ulog_backend *backend, rt_uint32_t level, const char *tag, rt_bool_t is_raw, const char *log, size_t len)
+{
+ ...
+ /* Output log to the console */
+ ...
+}
+/* Console backend initialization */
+int ulog_console_backend_init(void)
+{
+ /* Set output function */
+ console.output = ulog_console_backend_output;
+ /* Registration backend */
+ ulog_backend_register(&console, "console", RT_TRUE);
+
+ return 0;
+}
+INIT_COMPONENT_EXPORT(ulog_console_backend_init);
+```
+
+Through the above code, it can be seen that the implementation of the console backend is very simple. Here, the `output` function of the backend device is implemented, and the backend is registered in the ulog, and then the log of ulog is output to the console.
+
+If you want to implement a more complex back-end device, you need to understand the back-end device structure, as follows:
+
+```c
+struct ulog_backend
+{
+ char name[RT_NAME_MAX];
+ rt_bool_t support_color;
+ void (*init) (struct ulog_backend *backend);
+ void (*output)(struct ulog_backend *backend, rt_uint32_t level, const char *tag, rt_bool_t is_raw, const char *log, size_t len);
+ void (*flush) (struct ulog_backend *backend);
+ void (*deinit)(struct ulog_backend *backend);
+ rt_slist_t list;
+};
+```
+
+From the perspective of this structure, the requirements for implementing the backend device are as follows:
+
+* `The name` and `support_color` properties can be passed in through the `ulog_backend_register()` function.
+
+* `output` is the back-end specific output function, and all backends must implement the interface.
+
+* `init`/`deinit` is optional, `init` is called at `register`, and `deinit` is called at `ulog_deinit`.
+
+* `flush` is also optional, and some internal output cached backends need to implement this interface. For example, some file systems with RAM cache. The flush of the backend is usually called by `ulog_flush` in the case of an exception such as assertion or hardfault.
+
+## Asynchronous Log
+
+In ulog, the default output mode is synchronous mode, and in many scenarios users may also need asynchronous mode. When the user calls the log output API, the log is cached in the buffer, and the thread dedicated to the log output takes out the log and outputs it to the back end.
+
+Asynchronous mode and synchronous mode are the same for the user, there is no difference in the use of the log API, because ulog will distinguish between the underlying processing. The difference between the two works is as follows:
+
+![ulog asynchronous VS synchronization](figures/ulog_async_vs_sync.png)
+
+The advantages and disadvantages of asynchronous mode are as follows:
+
+**Advantage**:
+
+* First, the log output will not block the current thread, and some backend output rates are low, so using the synchronous output mode may affect the timing of the current thread. The asynchronous mode does not have this problem.
+
+* Secondly, since each thread that uses the log omits the action of the backend output, the stack overhead of these threads may also be reduced, and from this perspective, the resource consumption of the entire system can also be reduced.
+
+* Interrupt logs in synchronous mode can only be output to the console backend, while in asynchronous mode interrupt logs can be output to all backends.
+
+**Disadvantage**:First, the asynchronous mode requires a log buffer. Furthermore, the output of the asynchronous log needs to be completed by a special thread, such as an idle thread or a user-defined thread, which is slightly more complicated to use. The overall sense of asynchronous mode resource occupancy will be higher than the synchronous mode.
+
+### Configuration Option
+
+Use menuconfig in the Env tool to enter the ulog configuration options:
+
+```c
+ RT-Thread Components → Utilities → Enable ulog
+```
+
+The asynchronous mode related configuration options are described as follows:
+
+```c
+[*] Enable async output mode. /* Enable asynchronous mode */
+(2048) The async output buffer size. /* Asynchronous buffer size, default is 2048*/
+[*] Enable async output by thread. /* Whether to enable the asynchronous log output thread in ulog, the thread will wait for log notification when it runs, and then output the log to all backends. This option is turned on by default, and can be turned off if you want to modify it to another thread, such as an idle thread. */
+(1024) The async output thread stack size. /* Asynchronous output thread stack size, default is 1024 */
+(30) The async output thread stack priority./* The priority of the asynchronous output thread, the default is 30*/
+```
+
+When using the idle thread output, the implementation is simple, just call `rt_thread_idle_sethook(ulog_async_output)` at the application layer, but there are some limitations.
+
+* The idle thread stack size needs to be adjusted based on actual backend usage.
+
+* Because thread suspend operations are not allowed inside idle threads, backends such as Flash and networking may not be available based on idle threads.
+
+### Use Example
+
+Save the asynchronous output option configuration and copy `rt-thread\examples\ulog_example.c` to the `rt-thread\bsp\qemu-vexpress-a9\applications` folder.
+
+Execute the `scons` command and wait for the compilation to complete. Run `qemu.bat` to open the qemu emulator for RT-Thread.
+Enter the `ulog_example` command to see the results of the ulog routine. The approximate effect is as follows:
+
+![ulog asynchronous routine](figures/ulog_example_async.png)
+
+If you look carefully, you can see that after the asynchronous mode is turned on, the time information of these logs that are very close in code is almost the same. However, in synchronous mode, the log is output using the user thread. Since the log output takes a certain amount of time, there is a certain interval between each log. It also fully shows that the asynchronous log output is very efficient, and it takes almost no time for the caller.
+
+## Log Dynamic Filter
+
+In the previous section, some static filtering functions have been introduced. Static filtering has its advantages such as saving resources, but in many cases, users need to dynamically adjust the filtering mode of the log while the software is running. This allows the dynamic filter function of ulog to be used. To use the dynamic filter feature, turn on the `Enable runtime log filter.` option in menuconfig, which is **turned off by default**.
+
+There are four types of dynamic filtering supported by ulog, and there are corresponding API functions and Finsh/MSH commands, which will be introduced one by one.
+
+### Filter by Module Level
+
+```c
+int ulog_tag_lvl_filter_set(const char *tag, rt_uint32_t level)
+```
+
+| **Parameter** | **Description** |
+| ------- | ------------------------------ |
+| tag | Log label |
+| level | Set log level |
+|**return**|-- |
+| >=0 | Succeeded |
+| -5 | Failed, not enough memory |
+
+* Command format: `ulog_tag_lvl <tag> <level>`
+
+The **module** referred to here represents a class of log code with the same tag attributes. Sometimes it is necessary to dynamically modify the log output level of a module at runtime.
+
+The parameter log `level` can take the following values:
+
+|**Level** |**Name** |
+| --------------------- | ---------------- |
+| LOG_LVL_ASSERT | Assertion |
+| LOG_LVL_ERROR | Error |
+| LOG_LVL_WARNING | Warning |
+| LOG_LVL_INFO | Information |
+| LOG_LVL_DBG | Debug |
+| LOG_FILTER_LVL_SILENT | Silent (stop output) |
+| LOG_FILTER_LVL_ALL | All |
+
+An example of a function call and command is as follows:
+
+| Function | Function Call | Execute an order |
+| ---------------- | ------------------------------ | ------------------ |
+| Close all logs of `wifi` module | `ulog_tag_lvl_filter_set("wifi", LOG_FILTER_LVL_SILENT);` | `ulog_tag_lvl wifi 0` |
+| Open all logs of `wifi` module | `ulog_tag_lvl_filter_set("wifi", LOG_FILTER_LVL_ALL);` | `ulog_tag_lvl wifi 7` |
+| Set the `wifi` module log level to warning | `ulog_tag_lvl_filter_set("wifi", LOG_LVL_WARNING);` | `ulog_tag_lvl wifi 4` |
+
+### Global Filtering by Label
+
+```c
+void ulog_global_filter_tag_set(const char *tag)
+```
+
+| **Parameter** | **Description** |
+| :--- | :------------- |
+| tag | Set filter label |
+
+* The command format: `ulog_tag [tag]`, when the tag is empty, the label filtering is canceled.
+
+This filtering method can perform label filtering on all logs, and only the **log containing the label information** is allowed to output.
+
+For example: there are 3 kinds of tags for `wifi.driver`, `wifi.mgnt`, `audio.driver`. When setting the filter tag to `wifi`, only the tags are `wifi.driver` and `wifi.mgnt. The log of ` will be output. Similarly, when the filter tag is set to `driver`, only logs with tags `wifi.driver` and `audio.driver` will be output. Examples of function calls and commands for common functions are as follows:
+
+| Function | Function Call | Execute an Order |
+| -------------| -------------------- | ---------- |
+| Set the filter tag to `wifi` | `ulog_global_filter_tag_set("wifi");` | `ulog_tag wifi` |
+| Set the filter tag to `driver` | `ulog_global_filter_tag_set("driver");` | `ulog_tag driver` |
+| Cancel label filtering | `ulog_global_filter_tag_set("");` | `ulog_tag` |
+
+### Global Filtering by Level
+
+```c
+void ulog_global_filter_lvl_set(rt_uint32_t level)
+```
+
+| **Parameter** | **Description** |
+| ---- | -------------------|
+| level | Set log level |
+
+* Command format: `ulog_lvl <level>` , level Refer to the following table:
+
+| **Value** | **Description** |
+| :------------ | :--------------- |
+| 0 | assertion |
+| 3 | error |
+| 4 | warning |
+| 6 | information |
+| 7 | debug |
+
+After setting the global filter level by function or command, the log below **setting level** will stop output. Examples of function calls and commands for common functions are as follows:
+
+| Function | Function Call | Execute an order |
+| ----------| ------------------------------ | ------- |
+| Close all logs | `ulog_global_filter_lvl_set(LOG_FILTER_LVL_SILENT);` | `ulog_lvl 0` |
+| Open all logs | `ulog_global_filter_lvl_set(LOG_FILTER_LVL_ALL);` | `ulog_lvl 7` |
+| Set the log level to warning | `ulog_global_filter_lvl_set(LOG_LVL_WARNING);` | `ulog_lvl 4` |
+
+### Global Filtering by Keyword
+
+```c
+void ulog_global_filter_kw_set(const char *keyword)
+```
+
+| **Parameter** | **Description** |
+| :------ | :--------------- |
+| keyword | Set filter keywords |
+
+* The command format: `ulog_kw [keyword]`, when the keyword is empty, the keyword filtering is canceled.
+
+This filtering method can filter all the logs by keyword, and the log **containing the keyword information** is allowed to output. Examples of function calls and commands for common functions are as follows:
+
+| Function | Function Call | Execute an order |
+| -------------- | ------------------- | --------- |
+| Set the filter keyword to `wifi` | `ulog_global_filter_kw_set("wifi");` | `ulog_kw wifi` |
+| Clear filter keywords | `ulog_global_filter_kw_set("");` | `ulog_kw` |
+
+### View Filter Information
+
+After setting the filter parameters, if you want to view the current filter information, you can enter the `ulog_filter` command. The approximate effect is as follows:
+
+```c
+msh />ulog_filter
+--------------------------------------
+ulog global filter:
+level : Debug
+tag : NULL
+keyword : NULL
+--------------------------------------
+ulog tag's level filter:
+wifi : Warning
+audio.driver : Error
+msh />
+```
+
+> Filter parameters are also supported storing in Flash and also support boot autoload configuration. If you need this feature, please see the instructions for the **ulog_easyflash** package.([Click to check](https://github.com/armink-rtt-pkgs/ulog_easyflash_be))
+
+### Use Example
+
+Still executing in qemu BSP, first open dynamic filter in menuconfig, then save the configuration and compile and run the routine. After the log output is about **20** times, the corresponding filter code in ulog_example.c will be executed:
+
+```c
+if (count == 20)
+{
+ /* Set the global filer level is INFO. All of DEBUG log will stop output */
+ ulog_global_filter_lvl_set(LOG_LVL_INFO);
+ /* Set the test tag's level filter's level is ERROR. The DEBUG, INFO, WARNING log will stop output. */
+ ulog_tag_lvl_filter_set("test", LOG_LVL_ERROR);
+}
+...
+```
+
+At this point, the global filter level is set to the INFO level, so you can no longer see logs lower than the INFO level. At the same time, the log output level of the `test` tag is set to ERROR, and the log lower than ERROR in the `test` tag is also stopped. In each log, there is a count value of the current log output count. The effect of the comparison is as follows:
+
+![ulog filter routine 20](figures/ulog_example_filter20.png)
+
+After the log output is about **30** times, the following filter code corresponding to ulog_example.c is executed:
+
+```c
+...
+else if (count == 30)
+{
+ /* Set the example tag's level filter's level is LOG_FILTER_LVL_SILENT, the log enter silent mode. */
+ ulog_tag_lvl_filter_set("example", LOG_FILTER_LVL_SILENT);
+ /* Set the test tag's level filter's level is WARNING. The DEBUG, INFO log will stop output. */
+ ulog_tag_lvl_filter_set("test", LOG_LVL_WARNING);
+}
+...
+```
+
+At this point, the filter of the `example` module has been added, and all the logs of this module are stopped, so the module log will not be visible next. At the same time, reduce the log output level of the `test` tag to WARING. At this point, you can only see the WARING and ERROR level logs of the `test` tag. The effect is as follows:
+
+![ulog filter routine 30](figures/ulog_example_filter30.png)
+
+After the log output is about **40** times, the following filter code corresponding to ulog_example.c is executed:
+
+```c
+...
+else if (count == 40)
+{
+ /* Set the test tag's level filter's level is LOG_FILTER_LVL_ALL. All level log will resume output. */
+ ulog_tag_lvl_filter_set("test", LOG_FILTER_LVL_ALL);
+ /* Set the global filer level is LOG_FILTER_LVL_ALL. All level log will resume output */
+ ulog_global_filter_lvl_set(LOG_FILTER_LVL_ALL);
+}
+```
+
+At this time, the log output level of the `test` module is adjusted to `LOG_FILTER_LVL_ALL`, that is, the log of any level of the module is no longer filtered. At the same time, the global filter level is set to `LOG_FILTER_LVL_ALL`, so all the logs of the `test` module will resume output. The effect is as follows:
+
+![ulog filter routine 40](figures/ulog_example_filter40.png)
+
+## Usage when the System is Abnormal
+
+Since the asynchronous mode of ulog has a caching mechanism, the registered backend may also have a cache inside. If there are error conditions such as hardfault and assertion in the system, but there are still logs in the cache that are not output, which may cause the log to be lost. It is impossible to find the cause of the exception.
+
+For this scenario, ulog provides a unified log flush function: `void ulog_flush(void)`. When an exception occurs, when the exception information log is output, the function is called at the same time to ensure that the remaining logs in the cache can also be output to the back end.
+
+The following is an example of RT-Thread assertion and CmBacktrace:
+
+### Assertion
+
+RT-Thread assertions support assertion callbacks. We define an assertion hook function similar to the following, and then set it to the system via the `rt_assert_set_hook(rtt_user_assert_hook);` function.
+
+```c
+static void rtt_user_assert_hook(const char* ex, const char* func, rt_size_t line)
+{
+ rt_enter_critical();
+
+ ulog_output(LOG_LVL_ASSERT, "rtt", RT_TRUE, "(%s) has assert failed at %s:%ld.", ex, func, line);
+ /* flush all log */
+ ulog_flush();
+ while(1);
+}
+```
+
+### CmBacktrace
+
+CmBacktrace is a fault diagnosis library for ARM Cortex-M series MCUs. It also has a corresponding RT-Thread package, and the latest version of the package has been adapted for ulog. The adaptation code is located in `cmb_cfg.h` :
+
+```c
+...
+/* print line, must config by user */
+#include <rtthread.h>
+#ifndef RT_USING_ULOG
+#define cmb_println(...) rt_kprintf(__VA_ARGS__);rt_kprintf("\r\n")
+#else
+#include <ulog.h>
+#define cmb_println(...) ulog_e("cmb", __VA_ARGS__);ulog_flush()
+#endif /* RT_USING_ULOG */
+...
+```
+
+It can be seen that when ulog is enabled, each log output of CmBacktrace will use the error level, and `ulog_flush` will be executed at the same time, and the user does not need to make any modifications.
+
+## Syslog Mode
+
+On Unix-like operating systems, syslog is widely used in system logs. The common backends of syslog are files and networks. The syslog logs can be recorded in local files or sent over the network to the server that receives the syslog.
+
+Ulog provides support for the syslog mode, not only the front-end API is exactly the same as the syslog API, but the log format is also RFC compliant. However, it should be noted that after the syslog mode is enabled, the log output format of the entire ulog will be in syslog format regardless of which log output API is used.
+
+To use the syslog configuration you need to enable the `Enable syslog format log and API.` option.
+
+### Log Format
+
+![ulog syslog format](figures/ulog_syslog_format.png)
+
+As shown in the figure above, the ulog syslog log format is divided into the following four parts:
+
+| Format | **Description** |
+| ---- | --------------------- |
+| PRI | The PRI part consists of a number enclosed in angle brackets. This number contains the Facility and Severity information, which is made by Facility multiplying 8 and then adding Severity. Facility and Severity are passed in by the syslog function. For details, see syslog.h. |
+| Header | The Header part is mainly a timestamp indicating the time of the current log; |
+| TAG | The current log label can be passed in via the `openlog` function. If not specified, `rtt` will be used as the default label. |
+| Content | The specific content of the log |
+
+### Instruction
+
+The syslog option needs to be enabled in menuconfig before use. The main commonly used APIs are:
+
+* Open syslog:`void openlog(const char *ident, int option, int facility)`
+
+* Output syslog log:`void syslog(int priority, const char *format, ...)`
+
+> Hint: Calling `openlog` is optional. If you do not call `openlog`, the openlog is automatically called when syslog is called for the first time.
+
+
+syslog() is very simple to use. The input format is the same as the printf function. There are also syslog routines in ulog_example.c that work as follows in qemu:
+
+![ulog syslog routine](figures/ulog_example_syslog.png)
+
+## Migrate from *rt_dbg.h* or elog to ulog
+
+If the two types of log components were used in the project before, when ulog is to be used, it will involve how to make the previous code also support ulog. The following will focus on the migration process.
+
+### Migrate from rt_dbg.h
+
+Currently rtdbg has completed **seamless docking** ulog. After ulog is turned on, the code of rtdbg in the old project can be used to complete the log output without any modification.
+
+### Migrate from Elog(EasyLogger)
+
+If you are not sure that a source code file is running on a target platform that will use ulog, then it is recommended to add the following changes to the file:
+
+```c
+#ifdef RT_USING_ULOG
+#include <ulog.h>
+#else
+#include <elog.h>
+#endif /* RT_USING_ULOG */
+```
+
+If you explicitly only use the ulog component, then simply change the header file reference from `elog.h` to `ulog .h`, and no other code needs to be changed.
+
+## Log Usage Tip
+
+With the logging tool, if it is used improperly, it will also cause the log to be abused, and the log information cannot be highlighted. Here we will focus on sharing some tips on the use of the log component to make the log information more intuitive. The main concerns are:
+
+### Rational Use of Label Classification
+
+Reasonably use the label function. For each module code before the use of the log, first clear the module, sub-module name. This also allows the logs to be categorized at the very beginning and ready for later log filtering.
+
+### Rational Use of Log Levels
+
+When you first use the log library, you will often encounter warnings and errors. The logs cannot be distinguished. The information cannot be distinguished from the debug logs, which makes the log level selection inappropriate. Some important logs may not be visible, and unimportant logs are full of problems. Therefore, be sure to read the log level section carefully before using it. For each level, there are clear standards.
+
+### Avoid Repetitive and Redundant Logs
+
+In some cases, repeated or cyclic execution of code occurs, and the same, similar log problems are output multiple times. Such a log not only takes up a lot of system resources, but also affects the developer's positioning of the problem. Therefore, in this case, it is recommended to add special processing for repetitive logs, such as: let the upper layer output some business-related logs, the bottom layer only returns the specific result status; the same log at the same time point, can increase to deal with the re-processing, only output once and so on when the error state has not changed.
+
+### Open More Log Formats
+
+The timestamp and thread information are not turned on in the default log format of ulog. These two log messages are useful on RTOS. They can help developers to understand the running time and time difference of each log, and clearly see which thread is executing the current code. So if conditions permit, it is still recommended to open.
+
+### Close Unimportant Logs
+
+Ulog provides log switch and filtering functions in various dimensions, which can completely control the refinement. Therefore, if you debug a function module, you can properly close the log output of other unrelated modules, so that you can focus on the current debugging on the module.
+
+# Common Problems
+
+## Q: The log code has been executed, but there is no output.
+
+ **A:** Refer to the Log Levels section for the log level classification and check the log filtering parameters. There is also the possibility of accidentally closing the console backend and re-opening `Enable console backend`.
+
+## Q: After ulog is turned on, the system crashes, for example: thread stack overflow.
+
+ **A:** Ulog will occupy more part of the thread stack space than the previous rtdbg or `rt_kprintf` printout function. If floating-point printing support is enabled, it is recommended because it uses the internal memory of libc with a large amount of `vsnprintf`. Reserve more than 250 bytes. If the timestamp function is turned on, the stack recommends a reserve of 100 bytes.
+
+## Q: The end of the log content is missing.
+
+ **A:** This is because the log content exceeds the maximum width of the set log. Check the `The log's max width` option and increase it to the appropriate size.
+
+## Q: After turning on the timestamp, why can't I see the millisecond time?
+
+ **A:** This is because ulog currently only supports millisecond timestamps when the software emulation RTC state is turned on. To display, just turn on the RT-Thread software to simulate the RTC function.
+
+## Q: Define LOG_TAG and LOG_LVL before each include ulog header file, can it be simplified?
+
+**A:** If `LOG_TAG` is not defined, the `NO_TAG` tag will be used by default, so the output log will be easily misunderstood. Therefore the tag macro is not recommended to be omitted.
+
+If `LOG_LVL` is not defined, the debug level is used by default. If the module is in the development stage, this process can be omitted, but if the module code is stable, it is recommended to define the macro and modify the level to information level.
+
+## Q: Warning when running:Warning: There is no enough buffer for saving async log, please increase the ULOG_ASYNC_OUTPUT_BUF_SIZE option。
+
+**A:** When this prompt is encountered, it indicates that the buffer in the asynchronous mode has overflowed, which will cause some of the log to be lost. Increasing the ULOG_ASYNC_OUTPUT_BUF_SIZE option can solve the problem.
+
+## Q: Compile time prompt:The idle thread stack size must more than 384 when using async output by idle (ULOG_ASYNC_OUTPUT_BY_IDLE)。
+
+**A:** When using an idle thread as the output thread, the stack size of the idle thread needs to be increased, depending on the specific backend device. For example, when the console being a backend, the idle thread must be at least 384 bytes.
diff --git a/documentation/6.components/utest/figures/UtestAppStruct-1.png b/documentation/6.components/utest/figures/UtestAppStruct-1.png
new file mode 100644
index 0000000000..1925cbe767
--- /dev/null
+++ b/documentation/6.components/utest/figures/UtestAppStruct-1.png
Binary files differ
diff --git a/documentation/6.components/utest/figures/UtestRunLogShow.png b/documentation/6.components/utest/figures/UtestRunLogShow.png
new file mode 100644
index 0000000000..0de5e47c03
--- /dev/null
+++ b/documentation/6.components/utest/figures/UtestRunLogShow.png
Binary files differ
diff --git a/documentation/6.components/utest/figures/testcase-runflowchart.jpg b/documentation/6.components/utest/figures/testcase-runflowchart.jpg
new file mode 100644
index 0000000000..76117ac2c1
--- /dev/null
+++ b/documentation/6.components/utest/figures/testcase-runflowchart.jpg
Binary files differ
diff --git a/documentation/6.components/utest/utest.md b/documentation/6.components/utest/utest.md
new file mode 100644
index 0000000000..9580fcb2b7
--- /dev/null
+++ b/documentation/6.components/utest/utest.md
@@ -0,0 +1,274 @@
+@page page_component_utest utest Framework
+
+# utest Introduction
+
+utest (unit test) is a unit testing framework developed by RT-Thread. The original intention of designing utest is to make it easier for RT-Thread developers to write test programs using a unified framework interface for unit testing, coverage testing, and integration testing.
+
+## Test Case Definition
+
+A test case (tc) is a single test performed to achieve a specific test objective. It is a specification that includes test input, execution conditions, test procedures, and expected results. It is a infinite loop with clear end conditions and test results.
+
+The utest (unit test) framework defines user-written test programs as **test cases**, and a test case contains only one *testcase* function (similar to the main function), which can contain multiple *test unit* functions.
+
+The test code for a function, specifically through the API provided by the utest framework, is a test case.
+
+## Test Unit Definition
+
+The test unit is a test point subdivided by the function to be tested. Each test point can be the smallest measurable unit of the function to be tested. Of course, different classification methods will subdivide different test units.
+
+## utest Application Block Diagram
+
+![utest Application Block Diagram](./figures/UtestAppStruct-1.png)
+
+As shown in the figure above, the test case is designed based on the service interface provided by the test framework utest, which supports compiling multiple test cases together for testing. In addition, as you can see from the figure, a test case corresponds to a unique *testcase* function, and multiple test units are included in *testcase*.
+
+# utest API
+
+To enable uniform test case code, the test framework utest provides a common API interface for test case writing.
+
+## Macros of assertion
+
+> NOTE:
+> Here assert only records the number of passes and failures, it does not generate assertions or terminates program execution. Its function is not equivalent to RT_ASSERT.
+
+
+| assert Macro | Description |
+| :------ | :------ |
+| uassert_true(value) | If the value is true then the test passes, otherwise the test fails. |
+| uassert_false(value) | If the value is false then the test passes, otherwise the test fails. |
+| uassert_null(value) | If the Value is null then the test passes, otherwise the test fails |
+| uassert_not_null(value)| If the value is a non-null value, the test passes, otherwise the test fails. |
+| uassert_int_equal(a, b)| If the values of a and b are equal, the test passes, otherwise the test fails. |
+| uassert_int_not_equal(a, b)| If the values of a and b are not equal, the test passes, otherwise the test fails. |
+| uassert_str_equal(a, b) | If the string a and the string b are the same, the test passes, otherwise the test fails. |
+| uassert_str_not_equal(a, b)| If the string a and the string b are not the same, the test passes, otherwise the test fails. |
+| uassert_in_range(value, min, max) | If the value is in the range of min and max, the test passes, otherwise the test fails. |
+| uassert_not_in_range(value, min, max)| If the value is not in the range of min and max, the test passes, otherwise the test fails. |
+
+## Macros for Running Test Units
+
+```c
+UTEST_UNIT_RUN(test_unit_func)
+```
+
+In the test case, the specified test unit function `test_unit_func` is executed using the `UTEST_UNIT_RUN` macro. The test unit must be executed using the `UTEST_UNIT_RUN` macro.
+
+## Macros for Exporting Test Cases
+
+```c
+UTEST_TC_EXPORT(testcase, name, init, cleanup, timeout)
+```
+
+| Parameters | Description |
+| :----- | :------ |
+| testcase | Test case main-bearing function (**specifies** using a function called *static void testcase(void)* |
+| name | Test case name (uniqueness). Specifies the naming format for connecting relative names of test cases relative to `testcases directory` with `.` |
+| init | the initialization function before Test case startup |
+| cleanup | Cleanup function after the end of the test case |
+| timeout | Test case expected test time (in seconds) |
+
+**Test case naming requirements:**
+
+Test cases need to be named in the prescribed format. Specifies the naming format for the connection of the current test case relative to the `testcases directory ` linked with `.` . The name contains the file name of the current test case file (the file name except the suffix name).
+
+**Test case naming example:**
+
+Assuming that there is a `testcases\components\filesystem\dfs\dfs_api_tc.c` test case file in the test case `testcases` directory, the test case name in the `dfs_api_tc.c` is named `components.filesystem.dfs.dfs_api_tc`.
+
+## Test Case LOG Output Interface
+
+The utest framework relies on the *ulog log module* for log output and the log output level in the utest framework. So just add `#include "utest.h"` to the test case to use all level interfaces (LOG_D/LOG_I/LOG_E) of the ulog log module.
+
+In addition, the utest framework adds an additional log control interface as follows:
+
+```c
+#define UTEST_LOG_ALL (1u)
+#define UTEST_LOG_ASSERT (2u)
+
+void utest_log_lv_set(rt_uint8_t lv);
+```
+
+Users can use the `utest_log_lv_set` interface to control the log output level in test cases. The `UTEST_LOG_ALL` configuration outputs all logs, and the `UTEST_LOG_ASSERT` configuration only outputs logs after the failure of uassert.
+
+# Configuration Enable
+
+Using the utest framework requires the following configuration in the ENV tool using menuconfig:
+
+```c
+RT-Thread Kernel --->
+ Kernel Device Object --->
+ (256) the buffer size for console log printf /* The minimum buffer required by the utest log */
+RT-Thread Components --->
+ Utilities --->
+ -*- Enable utest (RT-Thread test framework) /* Enable utest framework */
+ (4096) The utest thread stack size /* Set the utest thread stack (required for -thread mode) */
+ (20) The utest thread priority /* Set utest thread priority (required for -thread mode) */
+```
+
+# Application Paradigm
+
+The utest framework and related APIs were introduced earlier. The basic test case code structure is described here.
+
+The code blocks necessary for the test case file are as follows:
+
+```c
+/*
+ * Copyright (c) 2006-2019, RT-Thread Development Team
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Change Logs:
+ * Date Author Notes
+ * 2019-01-16 MurphyZhao the first version
+ */
+
+#include <rtthread.h>
+#include "utest.h"
+
+static void test_xxx(void)
+{
+ uassert_true(1);
+}
+
+static rt_err_t utest_tc_init(void)
+{
+ return RT_EOK;
+}
+
+static rt_err_t utest_tc_cleanup(void)
+{
+ return RT_EOK;
+}
+
+static void testcase(void)
+{
+ UTEST_UNIT_RUN(test_xxx);
+}
+UTEST_TC_EXPORT(testcase, "components.utilities.utest.sample.sample_tc", utest_tc_init, utest_tc_cleanup, 10);
+```
+
+A basic test case must contain the following:
+
+- File comment header (Copyright)
+
+ The test case file must contain a file comment header containing `Copyright`, time, author, and description information.
+
+- utest_tc_init(void)
+
+ The initialization function before the test run is generally used to initialize the environment required for the test.
+
+- utest_tc_cleanup(void)
+
+ The cleanup function after the test is used to clean up the resources (such as memory, threads, semaphores, etc.) applied during the test.
+
+- testcase(void)
+
+ The mainly function of testcase, a test case implementation can only contain one testcase function (similar to the main function). Usually this function is only used to run the test unit execution function `UTEST_UNIT_RUN`.
+
+ A testcase can contain multiple test units, each of which is executed by `UTEST_UNIT_RUN`.
+
+- UTEST_UNIT_RUN
+
+ Test unit execution function.
+
+- test_xxx(void)
+
+ Test implementation of each functional unit. The user determines the function name and function implementation based on the requirements.
+
+- uassert_true
+
+ The assertion macro used to determine the test result (this assertion macro does not terminate the program run). Test cases must use the `uassert_xxx` macro to determine the test results, otherwise the test framework does not know if the test passed.
+
+ After all the `uassert_xxx` macros have been passed, the entire test case is passed.
+
+- UTEST_TC_EXPORT
+
+ Export the test case testcase function to the test framework.
+
+# Requirements for running test cases
+
+The test framework utest exports all test cases to the `UtestTcTab` code segment. The `UtestTcTab` section is not required to be defined in the link script in the IAR and MDK compilers, but it needs to be explicitly set in the link script when GCC is compiled.
+
+Therefore, in order for test cases to be compiled and run under GCC, the `UtestTcTab` code segment must be defined in the *link script* of GCC.
+
+In the `.text` of the GCC link script, add the definition of the `UtestTcTab` section in the following format:
+
+```c
+/* section information for utest */
+. = ALIGN(4);
+__rt_utest_tc_tab_start = .;
+KEEP(*(UtestTcTab))
+__rt_utest_tc_tab_end = .;
+```
+
+# Running Test Cases
+
+The test framework provides the following commands to make it easy for users to run test cases on the RT-Thread MSH command line. The commands are as follows:
+
+***utest_list* command**
+
+Lists the test cases supported by the current system, including the name of the test case and the time required for the test. This command has no parameters.
+
+***utest_run* command**
+
+Test case execution command, the format of the command is as follows:
+
+```c
+utest_run [-thread or -help] [testcase name] [loop num]
+```
+
+| utest_run Command Parameters | Description |
+| :---- | :----- |
+| -thread | Run the test framework in threaded mode |
+| -help | Print help information |
+| testcase name | Specify the test case name. Using the wildcard `*` is supported, specifying front byte of the test case name is supported. |
+| loop num | the number of iterations of test cases |
+
+**Example of test command usage:**
+
+```c
+msh />utest_list
+[14875] I/utest: Commands list :
+[14879] I/utest: [testcase name]:components.filesystem.dfs.dfs_api_tc; [run timeout]:30
+[14889] I/utest: [testcase name]:components.filesystem.posix.posix_api_tc; [run timeout]:30
+[14899] I/utest: [testcase name]:packages.iot.netutils.iperf.iperf_tc; [run timeout]:30
+msh />
+msh />utest_run components.filesystem.dfs.dfs_api_tc
+[83706] I/utest: [==========] [ utest ] started
+[83712] I/utest: [----------] [ testcase ] (components.filesystem.dfs.dfs_api_tc) started
+[83721] I/testcase: in testcase func...
+[84615] D/utest: [ OK ] [ unit ] (test_mkfs:26) is passed
+[84624] D/testcase: dfs mount rst: 0
+[84628] D/utest: [ OK ] [ unit ] (test_dfs_mount:35) is passed
+[84639] D/utest: [ OK ] [ unit ] (test_dfs_open:40) is passed
+[84762] D/utest: [ OK ] [ unit ] (test_dfs_write:74) is passed
+[84770] D/utest: [ OK ] [ unit ] (test_dfs_read:113) is passed
+[85116] D/utest: [ OK ] [ unit ] (test_dfs_close:118) is passed
+[85123] I/utest: [ PASSED ] [ result ] testcase (components.filesystem.dfs.dfs_api_tc)
+[85133] I/utest: [----------] [ testcase ] (components.filesystem.dfs.dfs_api_tc) finished
+[85143] I/utest: [==========] [ utest ] finished
+msh />
+```
+
+## Test result analysis
+
+![utest log display](./figures/UtestRunLogShow.png)
+
+As shown in the figure above, the log of the test case run is divided into four columns from left to right, which are `(1) log header information`, `(2) result bar`, `(3) property bar`, and `(4) detail information display bar`. The test case test result (PASSED or FAILED) is identified in the log using the `result` attribute.
+
+# Test Case Run Process
+
+![Test Case Run Process](./figures/testcase-runflowchart.jpg)
+
+From the above flow chart you can get the following:
+
+* The utest framework is a sequential execution of all **test units** in the *testcase* function
+* Assert of the previous UTEST_UNIT_RUN macro has occurred, and all subsequent UTEST_UNIT_RUN will skip execution.
+
+# NOTE
+
+- Determine whether the link script has the `UtestTcTab` section added before compiling with GCC.
+- Make sure `RT-Thread Kernel -> Kernel Device Object -> (256) the buffer size for console log printf` is at least 256 bytes before compiling.
+- The resources (threads, semaphores, timers, memory, etc.) created in the test case need to be released before the test ends.
+- A test case implementation can only export a test body function (testcase function) using `UTEST_TC_EXPORT`
+- Write a `README.md` document for the your test case to guide the user through configuring the test environment.