lwip.rst 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. lwIP
  2. ====
  3. :link_to_translation:`zh_CN:[中文]`
  4. ESP-IDF uses the open source `lwIP lightweight TCP/IP stack`_. The ESP-IDF version of lwIP (`esp-lwip`_) has some modifications and additions compared to the upstream project.
  5. Supported APIs
  6. --------------
  7. ESP-IDF supports the following lwIP TCP/IP stack functions:
  8. - `BSD Sockets API`_
  9. - `Netconn API`_ is enabled but not officially supported for ESP-IDF applications
  10. Adapted APIs
  11. ^^^^^^^^^^^^
  12. .. warning::
  13. When using any lwIP API other than the `BSD Sockets API`_, please make sure that the API is thread-safe. To check if a given API call is thread-safe, enable the :ref:`CONFIG_LWIP_CHECK_THREAD_SAFETY` configuration option and run the application. This enables lwIP to assert the correct access of the TCP/IP core functionality. If the API is not accessed or locked properly from the appropriate `lwIP FreeRTOS Task`_, the execution will be aborted. The general recommendation is to use the :doc:`/api-reference/network/esp_netif` component to interact with lwIP.
  14. Some common lwIP app APIs are supported indirectly by ESP-IDF:
  15. - Dynamic Host Configuration Protocol (DHCP) Server & Client are supported indirectly via the :doc:`/api-reference/network/esp_netif` functionality.
  16. - Simple Network Time Protocol (SNTP) is also supported via the :doc:`/api-reference/network/esp_netif`, or directly via the :component_file:`lwip/include/apps/esp_sntp.h` functions, which also provide thread-safe API to :component_file:`lwip/lwip/src/include/lwip/apps/sntp.h` functions, see also :ref:`system-time-sntp-sync`.
  17. - ICMP Ping is supported using a variation on the lwIP ping API, see :doc:`/api-reference/protocols/icmp_echo`.
  18. - ICMPv6 Ping, supported by lwIP's ICMPv6 Echo API, is used to test IPv6 network connectivity. For more information, see :example:`protocols/sockets/icmpv6_ping`.
  19. - NetBIOS lookup is available using the standard lwIP API. :example:`protocols/http_server/restful_server` has the option to demonstrate using NetBIOS to look up a host on the LAN.
  20. - mDNS uses a different implementation to the lwIP default mDNS, see :doc:`/api-reference/protocols/mdns`. But lwIP can look up mDNS hosts using standard APIs such as ``gethostbyname()`` and the convention ``hostname.local``, provided the :ref:`CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES` setting is enabled.
  21. - The PPP implementation in lwIP can be used to create PPPoS (PPP over serial) interface in ESP-IDF. Please refer to the documentation of the :doc:`/api-reference/network/esp_netif` component to create and configure a PPP network interface, by means of the ``ESP_NETIF_DEFAULT_PPP()`` macro defined in :component_file:`esp_netif/include/esp_netif_defaults.h`. Additional runtime settings are provided via :component_file:`esp_netif/include/esp_netif_ppp.h`. PPPoS interfaces are typically used to interact with NBIoT/GSM/LTE modems. More application-level friendly API is supported by the `esp_modem <https://components.espressif.com/component/espressif/esp_modem>`_ library, which uses this PPP lwIP module behind the scenes.
  22. BSD Sockets API
  23. ---------------
  24. The BSD Sockets API is a common cross-platform TCP/IP sockets API that originated in the Berkeley Standard Distribution of UNIX but is now standardized in a section of the POSIX specification. BSD Sockets are sometimes called POSIX Sockets or Berkeley Sockets.
  25. As implemented in ESP-IDF, lwIP supports all of the common usages of the BSD Sockets API.
  26. References
  27. ^^^^^^^^^^
  28. A wide range of BSD Sockets reference materials are available, including:
  29. - `Single UNIX Specification - BSD Sockets page <https://pubs.opengroup.org/onlinepubs/007908799/xnsix.html>`_
  30. - `Berkeley Sockets - Wikipedia page <https://en.wikipedia.org/wiki/Berkeley_sockets>`_
  31. Examples
  32. ^^^^^^^^
  33. A number of ESP-IDF examples show how to use the BSD Sockets APIs:
  34. - :example:`protocols/sockets/tcp_server`
  35. - :example:`protocols/sockets/tcp_client`
  36. - :example:`protocols/sockets/udp_server`
  37. - :example:`protocols/sockets/udp_client`
  38. - :example:`protocols/sockets/udp_multicast`
  39. - :example:`protocols/http_request`: this simplified example uses a TCP socket to send an HTTP request, but :doc:`/api-reference/protocols/esp_http_client` is a much better option for sending HTTP requests
  40. Supported Functions
  41. ^^^^^^^^^^^^^^^^^^^
  42. The following BSD socket API functions are supported. For full details, see :component_file:`lwip/lwip/src/include/lwip/sockets.h`.
  43. - ``socket()``
  44. - ``bind()``
  45. - ``accept()``
  46. - ``shutdown()``
  47. - ``getpeername()``
  48. - ``getsockopt()`` & ``setsockopt()``: see `Socket Options`_
  49. - ``close()``: via :doc:`/api-reference/storage/vfs`
  50. - ``read()``, ``readv()``, ``write()``, ``writev()``: via :doc:`/api-reference/storage/vfs`
  51. - ``recv()``, ``recvmsg()``, ``recvfrom()``
  52. - ``send()``, ``sendmsg()``, ``sendto()``
  53. - ``select()``: via :doc:`/api-reference/storage/vfs`
  54. - ``poll()`` : on ESP-IDF, ``poll()`` is implemented by calling ``select()`` internally, so using ``select()`` directly is recommended, if a choice of methods is available
  55. - ``fcntl()``: see `fcntl()`_
  56. Non-standard functions:
  57. - ``ioctl()``: see `ioctl()`_
  58. .. note::
  59. Some lwIP application sample code uses prefixed versions of BSD APIs, e.g., ``lwip_socket()``, instead of the standard ``socket()``. Both forms can be used with ESP-IDF, but using standard names is recommended.
  60. Socket Error Handling
  61. ^^^^^^^^^^^^^^^^^^^^^
  62. BSD Socket error handling code is very important for robust socket applications. Normally, socket error handling involves the following aspects:
  63. - Detecting the error
  64. - Getting the error reason code
  65. - Handling the error according to the reason code
  66. In lwIP, we have two different scenarios for handling socket errors:
  67. - Socket API returns an error. For more information, see `Socket API Errors`_.
  68. - ``select(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset, struct timeval *timeout)`` has an exception descriptor indicating that the socket has an error. For more information, see `select() Errors`_.
  69. Socket API Errors
  70. +++++++++++++++++
  71. **Error detection**
  72. - We can know that the socket API fails according to its return value.
  73. **Get the error reason code**
  74. - When socket API fails, the return value does not contain the failure reason and the application can get the error reason code by accessing ``errno``. Different values indicate different meanings. For more information, see `Socket Error Reason Code`_.
  75. Example:
  76. .. code-block::
  77. int err;
  78. int sockfd;
  79. if (sockfd = socket(AF_INET,SOCK_STREAM,0) < 0) {
  80. // the error code is obtained from errno
  81. err = errno;
  82. return err;
  83. }
  84. ``select()`` Errors
  85. +++++++++++++++++++
  86. **Error detection**
  87. - Socket error when ``select()`` has exception descriptor.
  88. **Get the error reason code**
  89. - If the ``select()`` indicates that the socket fails, we can not get the error reason code by accessing ``errno``, instead we should call ``getsockopt()`` to get the failure reason code. Since ``select()`` has exception descriptor, the error code is not given to ``errno``.
  90. .. note::
  91. The ``getsockopt()`` function has the following prototype: ``int getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen)``. Its purpose is to get the current value of the option of any type, any state socket, and store the result in ``optval``. For example, when you get the error code on a socket, you can get it by ``getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &err, &optlen)``.
  92. Example:
  93. .. code-block::
  94. int err;
  95. if (select(sockfd + 1, NULL, NULL, &exfds, &tval) <= 0) {
  96. err = errno;
  97. return err;
  98. } else {
  99. if (FD_ISSET(sockfd, &exfds)) {
  100. // select() exception set using getsockopt()
  101. int optlen = sizeof(int);
  102. getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &err, &optlen);
  103. return err;
  104. }
  105. }
  106. Socket Error Reason Code
  107. ++++++++++++++++++++++++
  108. Below is a list of common error codes. For a more detailed list of standard POSIX/C error codes, please see `newlib errno.h <https://github.com/espressif/newlib-esp32/blob/master/newlib/libc/include/sys/errno.h>`_ and the platform-specific extensions :component_file:`newlib/platform_include/errno.h`.
  109. .. list-table::
  110. :header-rows: 1
  111. :widths: 50 50
  112. :align: center
  113. * - Error code
  114. - Description
  115. * - ECONNREFUSED
  116. - Connection refused
  117. * - EADDRINUSE
  118. - Address already in use
  119. * - ECONNABORTED
  120. - Software caused connection abort
  121. * - ENETUNREACH
  122. - Network is unreachable
  123. * - ENETDOWN
  124. - Network interface is not configured
  125. * - ETIMEDOUT
  126. - Connection timed out
  127. * - EHOSTDOWN
  128. - Host is down
  129. * - EHOSTUNREACH
  130. - Host is unreachable
  131. * - EINPROGRESS
  132. - Connection already in progress
  133. * - EALREADY
  134. - Socket already connected
  135. * - EDESTADDRREQ
  136. - Destination address required
  137. * - EPROTONOSUPPORT
  138. - Unknown protocol
  139. Socket Options
  140. ^^^^^^^^^^^^^^
  141. The ``getsockopt()`` and ``setsockopt()`` functions allow getting and setting per-socket options respectively.
  142. Not all standard socket options are supported by lwIP in ESP-IDF. The following socket options are supported:
  143. Common Options
  144. ++++++++++++++
  145. Used with level argument ``SOL_SOCKET``.
  146. - ``SO_REUSEADDR``: available if :ref:`CONFIG_LWIP_SO_REUSE` is set, whose behavior can be customized by setting :ref:`CONFIG_LWIP_SO_REUSE_RXTOALL`
  147. - ``SO_KEEPALIVE``
  148. - ``SO_BROADCAST``
  149. - ``SO_ACCEPTCONN``
  150. - ``SO_RCVBUF``: available if :ref:`CONFIG_LWIP_SO_RCVBUF` is set
  151. - ``SO_SNDTIMEO`` / ``SO_RCVTIMEO``
  152. - ``SO_ERROR``: only used with ``select()``, see `Socket Error Handling`_
  153. - ``SO_TYPE``
  154. - ``SO_NO_CHECK``: for UDP sockets only
  155. IP Options
  156. ++++++++++
  157. Used with level argument ``IPPROTO_IP``.
  158. - ``IP_TOS``
  159. - ``IP_TTL``
  160. - ``IP_PKTINFO``: available if :ref:`CONFIG_LWIP_NETBUF_RECVINFO` is set
  161. For multicast UDP sockets:
  162. - ``IP_MULTICAST_IF``
  163. - ``IP_MULTICAST_LOOP``
  164. - ``IP_MULTICAST_TTL``
  165. - ``IP_ADD_MEMBERSHIP``
  166. - ``IP_DROP_MEMBERSHIP``
  167. TCP Options
  168. +++++++++++
  169. TCP sockets only. Used with level argument ``IPPROTO_TCP``.
  170. - ``TCP_NODELAY``
  171. Options relating to TCP keepalive probes:
  172. - ``TCP_KEEPALIVE``: int value, TCP keepalive period in milliseconds
  173. - ``TCP_KEEPIDLE``: same as ``TCP_KEEPALIVE``, but the value is in seconds
  174. - ``TCP_KEEPINTVL``: int value, the interval between keepalive probes in seconds
  175. - ``TCP_KEEPCNT``: int value, number of keepalive probes before timing out
  176. IPv6 Options
  177. ++++++++++++
  178. IPv6 sockets only. Used with level argument ``IPPROTO_IPV6``.
  179. - ``IPV6_CHECKSUM``
  180. - ``IPV6_V6ONLY``
  181. For multicast IPv6 UDP sockets:
  182. - ``IPV6_JOIN_GROUP`` / ``IPV6_ADD_MEMBERSHIP``
  183. - ``IPV6_LEAVE_GROUP`` / ``IPV6_DROP_MEMBERSHIP``
  184. - ``IPV6_MULTICAST_IF``
  185. - ``IPV6_MULTICAST_HOPS``
  186. - ``IPV6_MULTICAST_LOOP``
  187. ``fcntl()``
  188. ^^^^^^^^^^^
  189. The ``fcntl()`` function is a standard API for manipulating options related to a file descriptor. In ESP-IDF, the :doc:`/api-reference/storage/vfs` layer is used to implement this function.
  190. When the file descriptor is a socket, only the following ``fcntl()`` values are supported:
  191. - ``O_NONBLOCK`` to set or clear non-blocking I/O mode. Also supports ``O_NDELAY``, which is identical to ``O_NONBLOCK``.
  192. - ``O_RDONLY``, ``O_WRONLY``, ``O_RDWR`` flags for different read or write modes. These flags can only be read using ``F_GETFL``, and cannot be set using ``F_SETFL``. A TCP socket returns a different mode depending on whether the connection has been closed at either end or is still open at both ends. UDP sockets always return ``O_RDWR``.
  193. ``ioctl()``
  194. ^^^^^^^^^^^
  195. The ``ioctl()`` function provides a semi-standard way to access some internal features of the TCP/IP stack. In ESP-IDF, the :doc:`/api-reference/storage/vfs` layer is used to implement this function.
  196. When the file descriptor is a socket, only the following ``ioctl()`` values are supported:
  197. - ``FIONREAD`` returns the number of bytes of the pending data already received in the socket's network buffer.
  198. - ``FIONBIO`` is an alternative way to set/clear non-blocking I/O status for a socket, equivalent to ``fcntl(fd, F_SETFL, O_NONBLOCK, ...)``.
  199. Netconn API
  200. -----------
  201. lwIP supports two lower-level APIs as well as the BSD Sockets API: the Netconn API and the Raw API.
  202. The lwIP Raw API is designed for single-threaded devices and is not supported in ESP-IDF.
  203. The Netconn API is used to implement the BSD Sockets API inside lwIP, and it can also be called directly from ESP-IDF apps. This API has lower resource usage than the BSD Sockets API. In particular, it can send and receive data without firstly copying it into internal lwIP buffers.
  204. .. important::
  205. Espressif does not test the Netconn API in ESP-IDF. As such, this functionality is **enabled but not supported**. Some functionality may only work correctly when used from the BSD Sockets API.
  206. For more information about the Netconn API, consult `lwip/lwip/src/include/lwip/api.h <http://www.nongnu.org/lwip/2_0_x/api_8h.html>`_ and `part of the **unofficial** lwIP Application Developers Manual <https://lwip.fandom.com/wiki/Netconn_API>`_.
  207. lwIP FreeRTOS Task
  208. ------------------
  209. lwIP creates a dedicated TCP/IP FreeRTOS task to handle socket API requests from other tasks.
  210. A number of configuration items are available to modify the task and the queues (mailboxes) used to send data to/from the TCP/IP task:
  211. - :ref:`CONFIG_LWIP_TCPIP_RECVMBOX_SIZE`
  212. - :ref:`CONFIG_LWIP_TCPIP_TASK_STACK_SIZE`
  213. - :ref:`CONFIG_LWIP_TCPIP_TASK_AFFINITY`
  214. IPv6 Support
  215. ------------
  216. Both IPv4 and IPv6 are supported in a dual-stack configuration and are enabled by default. Both IPv6 and IPv4 may be disabled separately if they are not needed, see :ref:`lwip-ram-usage`.
  217. IPv6 support is limited to **Stateless Autoconfiguration** only. **Stateful configuration** is not supported in ESP-IDF, nor in upstream lwIP.
  218. IPv6 Address configuration is defined by means of these protocols or services:
  219. - **SLAAC** IPv6 Stateless Address Autoconfiguration (RFC-2462)
  220. - **DHCPv6** Dynamic Host Configuration Protocol for IPv6 (RFC-8415)
  221. None of these two types of address configuration is enabled by default, so the device uses only Link Local addresses or statically-defined addresses.
  222. .. _lwip-ivp6-autoconfig:
  223. Stateless Autoconfiguration Process
  224. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  225. To enable address autoconfiguration using the Router Advertisement protocol, please enable:
  226. - :ref:`CONFIG_LWIP_IPV6_AUTOCONFIG`
  227. This configuration option enables IPv6 autoconfiguration for all network interfaces, which differs from the upstream lwIP behavior, where the autoconfiguration needs to be explicitly enabled for each ``netif`` with ``netif->ip6_autoconfig_enabled=1``.
  228. .. _lwip-ivp6-dhcp6:
  229. DHCPv6
  230. ^^^^^^
  231. DHCPv6 in lwIP is very simple and supports only stateless configuration. It could be enabled using:
  232. - :ref:`CONFIG_LWIP_IPV6_DHCP6`
  233. Since the DHCPv6 works only in its stateless configuration, the :ref:`lwip-ivp6-autoconfig` has to be enabled as well via :ref:`CONFIG_LWIP_IPV6_AUTOCONFIG`.
  234. Moreover, the DHCPv6 needs to be explicitly enabled from the application code using:
  235. .. code-block::
  236. dhcp6_enable_stateless(netif);
  237. DNS Servers in IPv6 Autoconfiguration
  238. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  239. In order to autoconfigure DNS server(s), especially in IPv6-only networks, we have these two options:
  240. - Recursive Domain Name System (DNS): this belongs to the Neighbor Discovery Protocol (NDP) and uses :ref:`lwip-ivp6-autoconfig`.
  241. The number of servers must be set :ref:`CONFIG_LWIP_IPV6_RDNSS_MAX_DNS_SERVERS`, this option is disabled by default, i.e., set to 0.
  242. - DHCPv6 stateless configuration, uses :ref:`lwip-ivp6-dhcp6` to configure DNS servers. Note that this configuration assumes IPv6 Router Advertisement Flags (RFC-5175) to be set to
  243. - Managed Address Configuration Flag = 0
  244. - Other Configuration Flag = 1
  245. ESP-lwIP Custom Modifications
  246. -----------------------------
  247. Additions
  248. ^^^^^^^^^
  249. The following code is added, which is not present in the upstream lwIP release:
  250. Thread-Safe Sockets
  251. +++++++++++++++++++
  252. It is possible to ``close()`` a socket from a different thread than the one that created it. The ``close()`` call blocks, until any function calls currently using that socket from other tasks have returned.
  253. It is, however, not possible to delete a task while it is actively waiting on ``select()`` or ``poll()`` APIs. It is always necessary that these APIs exit before destroying the task, as this might corrupt internal structures and cause subsequent crashes of the lwIP. These APIs allocate globally referenced callback pointers on the stack so that when the task gets destroyed before unrolling the stack, the lwIP could still hold pointers to the deleted stack.
  254. On-Demand Timers
  255. ++++++++++++++++
  256. lwIP IGMP and MLD6 feature both initialize a timer in order to trigger timeout events at certain times.
  257. The default lwIP implementation is to have these timers enabled all the time, even if no timeout events are active. This increases CPU usage and power consumption when using automatic Light-sleep mode. ``ESP-lwIP`` default behavior is to set each timer ``on demand``, so it is only enabled when an event is pending.
  258. To return to the default lwIP behavior, which is always-on timers, disable :ref:`CONFIG_LWIP_TIMERS_ONDEMAND`.
  259. lwIP Timers API
  260. +++++++++++++++
  261. When not using Wi-Fi, the lwIP timer can be turned off via the API to reduce power consumption.
  262. The following API functions are supported. For full details, see :component_file:`lwip/lwip/src/include/lwip/timeouts.h`.
  263. - ``sys_timeouts_init()``
  264. - ``sys_timeouts_deinit()``
  265. Additional Socket Options
  266. +++++++++++++++++++++++++
  267. - Some standard IPV4 and IPV6 multicast socket options are implemented, see `Socket Options`_.
  268. - Possible to set IPV6-only UDP and TCP sockets with ``IPV6_V6ONLY`` socket option, while normal lwIP is TCP-only.
  269. IP Layer Features
  270. +++++++++++++++++
  271. - IPV4-source-based routing implementation is different
  272. - IPV4-mapped IPV6 addresses are supported
  273. Customized lwIP Hooks
  274. +++++++++++++++++++++
  275. The original lwIP supports implementing custom compile-time modifications via ``LWIP_HOOK_FILENAME``. This file is already used by the ESP-IDF port layer, but ESP-IDF users could still include and implement any custom additions via a header file defined by the macro ``ESP_IDF_LWIP_HOOK_FILENAME``. Here is an example of adding a custom hook file to the build process, and the hook is called ``my_hook.h``, located in the project's ``main`` folder:
  276. .. code-block:: cmake
  277. idf_component_get_property(lwip lwip COMPONENT_LIB)
  278. target_compile_options(${lwip} PRIVATE "-I${PROJECT_DIR}/main")
  279. target_compile_definitions(${lwip} PRIVATE "-DESP_IDF_LWIP_HOOK_FILENAME=\"my_hook.h\"")
  280. Limitations
  281. ^^^^^^^^^^^
  282. Calling ``send()`` or ``sendto()`` repeatedly on a UDP socket may eventually fail with ``errno`` equal to ``ENOMEM``. This failure occurs due to the limitations of buffer sizes in the lower-layer network interface drivers. If all driver transmit buffers are full, the UDP transmission will fail. For applications that transmit a high volume of UDP datagrams and aim to avoid any dropped datagrams by the sender, it is advisable to implement error code checking and employ a retransmission mechanism with a short delay.
  283. .. only:: esp32
  284. Increasing the number of TX buffers in the :ref:`Wi-Fi <CONFIG_ESP_WIFI_TX_BUFFER>` or :ref:`Ethernet <CONFIG_ETH_DMA_TX_BUFFER_NUM>` project configuration as applicable may also help.
  285. .. only:: not esp32 and SOC_WIFI_SUPPORTED
  286. Increasing the number of TX buffers in the :ref:`Wi-Fi <CONFIG_ESP_WIFI_TX_BUFFER>` project configuration may also help.
  287. .. _lwip-performance:
  288. Performance Optimization
  289. ------------------------
  290. TCP/IP performance is a complex subject, and performance can be optimized toward multiple goals. The default settings of ESP-IDF are tuned for a compromise between throughput, latency, and moderate memory usage.
  291. Maximum Throughput
  292. ^^^^^^^^^^^^^^^^^^
  293. Espressif tests ESP-IDF TCP/IP throughput using the :example:`wifi/iperf` example in an RF-sealed enclosure.
  294. The :example_file:`wifi/iperf/sdkconfig.defaults` file for the iperf example contains settings known to maximize TCP/IP throughput, usually at the expense of higher RAM usage. To get maximum TCP/IP throughput in an application at the expense of other factors, it is suggested to apply settings from this file into the project sdkconfig.
  295. .. important::
  296. Suggest applying changes a few at a time and checking the performance each time with a particular application workload.
  297. - If a lot of tasks are competing for CPU time on the system, consider that the lwIP task has configurable CPU affinity (:ref:`CONFIG_LWIP_TCPIP_TASK_AFFINITY`) and runs at fixed priority (18, ``ESP_TASK_TCPIP_PRIO``). To optimize CPU utilization, consider assigning competing tasks to different cores or adjusting their priorities to lower values. For additional details on built-in task priorities, please refer to :ref:`built-in-task-priorities`.
  298. - If using ``select()`` function with socket arguments only, disabling :ref:`CONFIG_VFS_SUPPORT_SELECT` will make ``select()`` calls faster.
  299. - If there is enough free IRAM, select :ref:`CONFIG_LWIP_IRAM_OPTIMIZATION` and :ref:`CONFIG_LWIP_EXTRA_IRAM_OPTIMIZATION` to improve TX/RX throughput.
  300. .. only:: SOC_WIFI_SUPPORTED
  301. If using a Wi-Fi network interface, please also refer to :ref:`wifi-buffer-usage`.
  302. Minimum Latency
  303. ^^^^^^^^^^^^^^^
  304. Except for increasing buffer sizes, most changes that increase throughput also decrease latency by reducing the amount of CPU time spent in lwIP functions.
  305. - For TCP sockets, lwIP supports setting the standard ``TCP_NODELAY`` flag to disable Nagle's algorithm.
  306. .. _lwip-ram-usage:
  307. Minimum RAM Usage
  308. ^^^^^^^^^^^^^^^^^
  309. Most lwIP RAM usage is on-demand, as RAM is allocated from the heap as needed. Therefore, changing lwIP settings to reduce RAM usage may not change RAM usage at idle, but can change it at peak.
  310. - Reducing :ref:`CONFIG_LWIP_MAX_SOCKETS` reduces the maximum number of sockets in the system. This also causes TCP sockets in the ``WAIT_CLOSE`` state to be closed and recycled more rapidly when needed to open a new socket, further reducing peak RAM usage.
  311. - Reducing :ref:`CONFIG_LWIP_TCPIP_RECVMBOX_SIZE`, :ref:`CONFIG_LWIP_TCP_RECVMBOX_SIZE` and :ref:`CONFIG_LWIP_UDP_RECVMBOX_SIZE` reduce RAM usage at the expense of throughput, depending on usage.
  312. - Reducing :ref:`CONFIG_LWIP_TCP_MSL` and :ref:`CONFIG_LWIP_TCP_FIN_WAIT_TIMEOUT` reduces the maximum segment lifetime in the system. This also causes TCP sockets in the ``TIME_WAIT`` and ``FIN_WAIT_2`` states to be closed and recycled more rapidly.
  313. - Disabling :ref:`CONFIG_LWIP_IPV6` can save about 39 KB for firmware size and 2 KB RAM when the system is powered up and 7 KB RAM when the TCP/IP stack is running. If there is no requirement for supporting IPV6, it can be disabled to save flash and RAM footprint.
  314. - Disabling :ref:`CONFIG_LWIP_IPV4` can save about 26 KB of firmware size and 600 B RAM on power up and 6 KB RAM when the TCP/IP stack is running. If the local network supports IPv6-only configuration, IPv4 can be disabled to save flash and RAM footprint.
  315. .. only:: SOC_WIFI_SUPPORTED
  316. If using Wi-Fi, please also refer to :ref:`wifi-buffer-usage`.
  317. Peak Buffer Usage
  318. +++++++++++++++++
  319. The peak heap memory that lwIP consumes is the **theoretically-maximum memory** that the lwIP driver consumes. Generally, the peak heap memory that lwIP consumes depends on:
  320. - the memory required to create a UDP connection: ``lwip_udp_conn``
  321. - the memory required to create a TCP connection: ``lwip_tcp_conn``
  322. - the number of UDP connections that the application has: ``lwip_udp_con_num``
  323. - the number of TCP connections that the application has: ``lwip_tcp_con_num``
  324. - the TCP TX window size: ``lwip_tcp_tx_win_size``
  325. - the TCP RX window size: ``lwip_tcp_rx_win_size``
  326. **So, the peak heap memory that the lwIP consumes can be calculated with the following formula:**
  327. lwip_dynamic_peek_memory = (lwip_udp_con_num * lwip_udp_conn) + (lwip_tcp_con_num * (lwip_tcp_tx_win_size + lwip_tcp_rx_win_size + lwip_tcp_conn))
  328. Some TCP-based applications need only one TCP connection. However, they may choose to close this TCP connection and create a new one when an error occurs (e.g., a sending failure). This may result in multiple TCP connections existing in the system simultaneously, because it may take a long time for a TCP connection to close, according to the TCP state machine, refer to RFC793.
  329. .. _lwIP lightweight TCP/IP stack: https://savannah.nongnu.org/projects/lwip/
  330. .. _esp-lwip: https://github.com/espressif/esp-lwip