rawapi.txt 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. Raw TCP/IP interface for lwIP
  2. Authors: Adam Dunkels, Leon Woestenberg, Christiaan Simons
  3. lwIP provides three Application Program's Interfaces (APIs) for programs
  4. to use for communication with the TCP/IP code:
  5. * low-level "core" / "callback" or "raw" API.
  6. * higher-level "sequential" API.
  7. * BSD-style socket API.
  8. The sequential API provides a way for ordinary, sequential, programs
  9. to use the lwIP stack. It is quite similar to the BSD socket API. The
  10. model of execution is based on the blocking open-read-write-close
  11. paradigm. Since the TCP/IP stack is event based by nature, the TCP/IP
  12. code and the application program must reside in different execution
  13. contexts (threads).
  14. The socket API is a compatibility API for existing applications,
  15. currently it is built on top of the sequential API. It is meant to
  16. provide all functions needed to run socket API applications running
  17. on other platforms (e.g. unix / windows etc.). However, due to limitations
  18. in the specification of this API, there might be incompatibilities
  19. that require small modifications of existing programs.
  20. ** Threading
  21. lwIP started targeting single-threaded environments. When adding multi-
  22. threading support, instead of making the core thread-safe, another
  23. approach was chosen: there is one main thread running the lwIP core
  24. (also known as the "tcpip_thread"). The raw API may only be used from
  25. this thread! Application threads using the sequential- or socket API
  26. communicate with this main thread through message passing.
  27. As such, the list of functions that may be called from
  28. other threads or an ISR is very limited! Only functions
  29. from these API header files are thread-safe:
  30. - api.h
  31. - netbuf.h
  32. - netdb.h
  33. - netifapi.h
  34. - sockets.h
  35. - sys.h
  36. Additionaly, memory (de-)allocation functions may be
  37. called from multiple threads (not ISR!) with NO_SYS=0
  38. since they are protected by SYS_LIGHTWEIGHT_PROT and/or
  39. semaphores.
  40. Only since 1.3.0, if SYS_LIGHTWEIGHT_PROT is set to 1
  41. and LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT is set to 1,
  42. pbuf_free() may also be called from another thread or
  43. an ISR (since only then, mem_free - for PBUF_RAM - may
  44. be called from an ISR: otherwise, the HEAP is only
  45. protected by semaphores).
  46. ** The remainder of this document discusses the "raw" API. **
  47. The raw TCP/IP interface allows the application program to integrate
  48. better with the TCP/IP code. Program execution is event based by
  49. having callback functions being called from within the TCP/IP
  50. code. The TCP/IP code and the application program both run in the same
  51. thread. The sequential API has a much higher overhead and is not very
  52. well suited for small systems since it forces a multithreaded paradigm
  53. on the application.
  54. The raw TCP/IP interface is not only faster in terms of code execution
  55. time but is also less memory intensive. The drawback is that program
  56. development is somewhat harder and application programs written for
  57. the raw TCP/IP interface are more difficult to understand. Still, this
  58. is the preferred way of writing applications that should be small in
  59. code size and memory usage.
  60. Both APIs can be used simultaneously by different application
  61. programs. In fact, the sequential API is implemented as an application
  62. program using the raw TCP/IP interface.
  63. --- Callbacks
  64. Program execution is driven by callbacks. Each callback is an ordinary
  65. C function that is called from within the TCP/IP code. Every callback
  66. function is passed the current TCP or UDP connection state as an
  67. argument. Also, in order to be able to keep program specific state,
  68. the callback functions are called with a program specified argument
  69. that is independent of the TCP/IP state.
  70. The function for setting the application connection state is:
  71. - void tcp_arg(struct tcp_pcb *pcb, void *arg)
  72. Specifies the program specific state that should be passed to all
  73. other callback functions. The "pcb" argument is the current TCP
  74. connection control block, and the "arg" argument is the argument
  75. that will be passed to the callbacks.
  76. --- TCP connection setup
  77. The functions used for setting up connections is similar to that of
  78. the sequential API and of the BSD socket API. A new TCP connection
  79. identifier (i.e., a protocol control block - PCB) is created with the
  80. tcp_new() function. This PCB can then be either set to listen for new
  81. incoming connections or be explicitly connected to another host.
  82. - struct tcp_pcb *tcp_new(void)
  83. Creates a new connection identifier (PCB). If memory is not
  84. available for creating the new pcb, NULL is returned.
  85. - err_t tcp_bind(struct tcp_pcb *pcb, ip_addr_t *ipaddr,
  86. u16_t port)
  87. Binds the pcb to a local IP address and port number. The IP address
  88. can be specified as IP_ADDR_ANY in order to bind the connection to
  89. all local IP addresses.
  90. If another connection is bound to the same port, the function will
  91. return ERR_USE, otherwise ERR_OK is returned.
  92. - struct tcp_pcb *tcp_listen(struct tcp_pcb *pcb)
  93. Commands a pcb to start listening for incoming connections. When an
  94. incoming connection is accepted, the function specified with the
  95. tcp_accept() function will be called. The pcb will have to be bound
  96. to a local port with the tcp_bind() function.
  97. The tcp_listen() function returns a new connection identifier, and
  98. the one passed as an argument to the function will be
  99. deallocated. The reason for this behavior is that less memory is
  100. needed for a connection that is listening, so tcp_listen() will
  101. reclaim the memory needed for the original connection and allocate a
  102. new smaller memory block for the listening connection.
  103. tcp_listen() may return NULL if no memory was available for the
  104. listening connection. If so, the memory associated with the pcb
  105. passed as an argument to tcp_listen() will not be deallocated.
  106. - struct tcp_pcb *tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
  107. Same as tcp_listen, but limits the number of outstanding connections
  108. in the listen queue to the value specified by the backlog argument.
  109. To use it, your need to set TCP_LISTEN_BACKLOG=1 in your lwipopts.h.
  110. - void tcp_accepted(struct tcp_pcb *pcb)
  111. Inform lwIP that an incoming connection has been accepted. This would
  112. usually be called from the accept callback. This allows lwIP to perform
  113. housekeeping tasks, such as allowing further incoming connections to be
  114. queued in the listen backlog.
  115. ATTENTION: the PCB passed in must be the listening pcb, not the pcb passed
  116. into the accept callback!
  117. - void tcp_accept(struct tcp_pcb *pcb,
  118. err_t (* accept)(void *arg, struct tcp_pcb *newpcb,
  119. err_t err))
  120. Specified the callback function that should be called when a new
  121. connection arrives on a listening connection.
  122. - err_t tcp_connect(struct tcp_pcb *pcb, ip_addr_t *ipaddr,
  123. u16_t port, err_t (* connected)(void *arg,
  124. struct tcp_pcb *tpcb,
  125. err_t err));
  126. Sets up the pcb to connect to the remote host and sends the
  127. initial SYN segment which opens the connection.
  128. The tcp_connect() function returns immediately; it does not wait for
  129. the connection to be properly setup. Instead, it will call the
  130. function specified as the fourth argument (the "connected" argument)
  131. when the connection is established. If the connection could not be
  132. properly established, either because the other host refused the
  133. connection or because the other host didn't answer, the "err"
  134. callback function of this pcb (registered with tcp_err, see below)
  135. will be called.
  136. The tcp_connect() function can return ERR_MEM if no memory is
  137. available for enqueueing the SYN segment. If the SYN indeed was
  138. enqueued successfully, the tcp_connect() function returns ERR_OK.
  139. --- Sending TCP data
  140. TCP data is sent by enqueueing the data with a call to
  141. tcp_write(). When the data is successfully transmitted to the remote
  142. host, the application will be notified with a call to a specified
  143. callback function.
  144. - err_t tcp_write(struct tcp_pcb *pcb, const void *dataptr, u16_t len,
  145. u8_t apiflags)
  146. Enqueues the data pointed to by the argument dataptr. The length of
  147. the data is passed as the len parameter. The apiflags can be one or more of:
  148. - TCP_WRITE_FLAG_COPY: indicates whether the new memory should be allocated
  149. for the data to be copied into. If this flag is not given, no new memory
  150. should be allocated and the data should only be referenced by pointer. This
  151. also means that the memory behind dataptr must not change until the data is
  152. ACKed by the remote host
  153. - TCP_WRITE_FLAG_MORE: indicates that more data follows. If this is given,
  154. the PSH flag is set in the last segment created by this call to tcp_write.
  155. If this flag is given, the PSH flag is not set.
  156. The tcp_write() function will fail and return ERR_MEM if the length
  157. of the data exceeds the current send buffer size or if the length of
  158. the queue of outgoing segment is larger than the upper limit defined
  159. in lwipopts.h. The number of bytes available in the output queue can
  160. be retrieved with the tcp_sndbuf() function.
  161. The proper way to use this function is to call the function with at
  162. most tcp_sndbuf() bytes of data. If the function returns ERR_MEM,
  163. the application should wait until some of the currently enqueued
  164. data has been successfully received by the other host and try again.
  165. - void tcp_sent(struct tcp_pcb *pcb,
  166. err_t (* sent)(void *arg, struct tcp_pcb *tpcb,
  167. u16_t len))
  168. Specifies the callback function that should be called when data has
  169. successfully been received (i.e., acknowledged) by the remote
  170. host. The len argument passed to the callback function gives the
  171. amount bytes that was acknowledged by the last acknowledgment.
  172. --- Receiving TCP data
  173. TCP data reception is callback based - an application specified
  174. callback function is called when new data arrives. When the
  175. application has taken the data, it has to call the tcp_recved()
  176. function to indicate that TCP can advertise increase the receive
  177. window.
  178. - void tcp_recv(struct tcp_pcb *pcb,
  179. err_t (* recv)(void *arg, struct tcp_pcb *tpcb,
  180. struct pbuf *p, err_t err))
  181. Sets the callback function that will be called when new data
  182. arrives. The callback function will be passed a NULL pbuf to
  183. indicate that the remote host has closed the connection. If
  184. there are no errors and the callback function is to return
  185. ERR_OK, then it must free the pbuf. Otherwise, it must not
  186. free the pbuf so that lwIP core code can store it.
  187. - void tcp_recved(struct tcp_pcb *pcb, u16_t len)
  188. Must be called when the application has received the data. The len
  189. argument indicates the length of the received data.
  190. --- Application polling
  191. When a connection is idle (i.e., no data is either transmitted or
  192. received), lwIP will repeatedly poll the application by calling a
  193. specified callback function. This can be used either as a watchdog
  194. timer for killing connections that have stayed idle for too long, or
  195. as a method of waiting for memory to become available. For instance,
  196. if a call to tcp_write() has failed because memory wasn't available,
  197. the application may use the polling functionality to call tcp_write()
  198. again when the connection has been idle for a while.
  199. - void tcp_poll(struct tcp_pcb *pcb,
  200. err_t (* poll)(void *arg, struct tcp_pcb *tpcb),
  201. u8_t interval)
  202. Specifies the polling interval and the callback function that should
  203. be called to poll the application. The interval is specified in
  204. number of TCP coarse grained timer shots, which typically occurs
  205. twice a second. An interval of 10 means that the application would
  206. be polled every 5 seconds.
  207. --- Closing and aborting connections
  208. - err_t tcp_close(struct tcp_pcb *pcb)
  209. Closes the connection. The function may return ERR_MEM if no memory
  210. was available for closing the connection. If so, the application
  211. should wait and try again either by using the acknowledgment
  212. callback or the polling functionality. If the close succeeds, the
  213. function returns ERR_OK.
  214. The pcb is deallocated by the TCP code after a call to tcp_close().
  215. - void tcp_abort(struct tcp_pcb *pcb)
  216. Aborts the connection by sending a RST (reset) segment to the remote
  217. host. The pcb is deallocated. This function never fails.
  218. ATTENTION: When calling this from one of the TCP callbacks, make
  219. sure you always return ERR_ABRT (and never return ERR_ABRT otherwise
  220. or you will risk accessing deallocated memory or memory leaks!
  221. If a connection is aborted because of an error, the application is
  222. alerted of this event by the err callback. Errors that might abort a
  223. connection are when there is a shortage of memory. The callback
  224. function to be called is set using the tcp_err() function.
  225. - void tcp_err(struct tcp_pcb *pcb, void (* err)(void *arg,
  226. err_t err))
  227. The error callback function does not get the pcb passed to it as a
  228. parameter since the pcb may already have been deallocated.
  229. --- Lower layer TCP interface
  230. TCP provides a simple interface to the lower layers of the
  231. system. During system initialization, the function tcp_init() has
  232. to be called before any other TCP function is called. When the system
  233. is running, the two timer functions tcp_fasttmr() and tcp_slowtmr()
  234. must be called with regular intervals. The tcp_fasttmr() should be
  235. called every TCP_FAST_INTERVAL milliseconds (defined in tcp.h) and
  236. tcp_slowtmr() should be called every TCP_SLOW_INTERVAL milliseconds.
  237. --- UDP interface
  238. The UDP interface is similar to that of TCP, but due to the lower
  239. level of complexity of UDP, the interface is significantly simpler.
  240. - struct udp_pcb *udp_new(void)
  241. Creates a new UDP pcb which can be used for UDP communication. The
  242. pcb is not active until it has either been bound to a local address
  243. or connected to a remote address.
  244. - void udp_remove(struct udp_pcb *pcb)
  245. Removes and deallocates the pcb.
  246. - err_t udp_bind(struct udp_pcb *pcb, ip_addr_t *ipaddr,
  247. u16_t port)
  248. Binds the pcb to a local address. The IP-address argument "ipaddr"
  249. can be IP_ADDR_ANY to indicate that it should listen to any local IP
  250. address. The function currently always return ERR_OK.
  251. - err_t udp_connect(struct udp_pcb *pcb, ip_addr_t *ipaddr,
  252. u16_t port)
  253. Sets the remote end of the pcb. This function does not generate any
  254. network traffic, but only set the remote address of the pcb.
  255. - err_t udp_disconnect(struct udp_pcb *pcb)
  256. Remove the remote end of the pcb. This function does not generate
  257. any network traffic, but only removes the remote address of the pcb.
  258. - err_t udp_send(struct udp_pcb *pcb, struct pbuf *p)
  259. Sends the pbuf p. The pbuf is not deallocated.
  260. - void udp_recv(struct udp_pcb *pcb,
  261. void (* recv)(void *arg, struct udp_pcb *upcb,
  262. struct pbuf *p,
  263. ip_addr_t *addr,
  264. u16_t port),
  265. void *recv_arg)
  266. Specifies a callback function that should be called when a UDP
  267. datagram is received.
  268. --- System initalization
  269. A truly complete and generic sequence for initializing the lwip stack
  270. cannot be given because it depends on the build configuration (lwipopts.h)
  271. and additional initializations for your runtime environment (e.g. timers).
  272. We can give you some idea on how to proceed when using the raw API.
  273. We assume a configuration using a single Ethernet netif and the
  274. UDP and TCP transport layers, IPv4 and the DHCP client.
  275. Call these functions in the order of appearance:
  276. - stats_init()
  277. Clears the structure where runtime statistics are gathered.
  278. - sys_init()
  279. Not of much use since we set the NO_SYS 1 option in lwipopts.h,
  280. to be called for easy configuration changes.
  281. - mem_init()
  282. Initializes the dynamic memory heap defined by MEM_SIZE.
  283. - memp_init()
  284. Initializes the memory pools defined by MEMP_NUM_x.
  285. - pbuf_init()
  286. Initializes the pbuf memory pool defined by PBUF_POOL_SIZE.
  287. - etharp_init()
  288. Initializes the ARP table and queue.
  289. Note: you must call etharp_tmr at a ARP_TMR_INTERVAL (5 seconds) regular interval
  290. after this initialization.
  291. - ip_init()
  292. Doesn't do much, it should be called to handle future changes.
  293. - udp_init()
  294. Clears the UDP PCB list.
  295. - tcp_init()
  296. Clears the TCP PCB list and clears some internal TCP timers.
  297. Note: you must call tcp_fasttmr() and tcp_slowtmr() at the
  298. predefined regular intervals after this initialization.
  299. - netif_add(struct netif *netif, ip_addr_t *ipaddr,
  300. ip_addr_t *netmask, ip_addr_t *gw,
  301. void *state, err_t (* init)(struct netif *netif),
  302. err_t (* input)(struct pbuf *p, struct netif *netif))
  303. Adds your network interface to the netif_list. Allocate a struct
  304. netif and pass a pointer to this structure as the first argument.
  305. Give pointers to cleared ip_addr structures when using DHCP,
  306. or fill them with sane numbers otherwise. The state pointer may be NULL.
  307. The init function pointer must point to a initialization function for
  308. your ethernet netif interface. The following code illustrates it's use.
  309. err_t netif_if_init(struct netif *netif)
  310. {
  311. u8_t i;
  312. for(i = 0; i < ETHARP_HWADDR_LEN; i++) netif->hwaddr[i] = some_eth_addr[i];
  313. init_my_eth_device();
  314. return ERR_OK;
  315. }
  316. For ethernet drivers, the input function pointer must point to the lwip
  317. function ethernet_input() declared in "netif/etharp.h". Other drivers
  318. must use ip_input() declared in "lwip/ip.h".
  319. - netif_set_default(struct netif *netif)
  320. Registers the default network interface.
  321. - netif_set_up(struct netif *netif)
  322. When the netif is fully configured this function must be called.
  323. - dhcp_start(struct netif *netif)
  324. Creates a new DHCP client for this interface on the first call.
  325. Note: you must call dhcp_fine_tmr() and dhcp_coarse_tmr() at
  326. the predefined regular intervals after starting the client.
  327. You can peek in the netif->dhcp struct for the actual DHCP status.
  328. --- Optimalization hints
  329. The first thing you want to optimize is the lwip_standard_checksum()
  330. routine from src/core/inet.c. You can override this standard
  331. function with the #define LWIP_CHKSUM <your_checksum_routine>.
  332. There are C examples given in inet.c or you might want to
  333. craft an assembly function for this. RFC1071 is a good
  334. introduction to this subject.
  335. Other significant improvements can be made by supplying
  336. assembly or inline replacements for htons() and htonl()
  337. if you're using a little-endian architecture.
  338. #define LWIP_PLATFORM_BYTESWAP 1
  339. #define LWIP_PLATFORM_HTONS(x) <your_htons>
  340. #define LWIP_PLATFORM_HTONL(x) <your_htonl>
  341. Check your network interface driver if it reads at
  342. a higher speed than the maximum wire-speed. If the
  343. hardware isn't serviced frequently and fast enough
  344. buffer overflows are likely to occur.
  345. E.g. when using the cs8900 driver, call cs8900if_service(ethif)
  346. as frequently as possible. When using an RTOS let the cs8900 interrupt
  347. wake a high priority task that services your driver using a binary
  348. semaphore or event flag. Some drivers might allow additional tuning
  349. to match your application and network.
  350. For a production release it is recommended to set LWIP_STATS to 0.
  351. Note that speed performance isn't influenced much by simply setting
  352. high values to the memory options.
  353. For more optimization hints take a look at the lwIP wiki.
  354. --- Zero-copy MACs
  355. To achieve zero-copy on transmit, the data passed to the raw API must
  356. remain unchanged until sent. Because the send- (or write-)functions return
  357. when the packets have been enqueued for sending, data must be kept stable
  358. after that, too.
  359. This implies that PBUF_RAM/PBUF_POOL pbufs passed to raw-API send functions
  360. must *not* be reused by the application unless their ref-count is 1.
  361. For no-copy pbufs (PBUF_ROM/PBUF_REF), data must be kept unchanged, too,
  362. but the stack/driver will/must copy PBUF_REF'ed data when enqueueing, while
  363. PBUF_ROM-pbufs are just enqueued (as ROM-data is expected to never change).
  364. Also, data passed to tcp_write without the copy-flag must not be changed!
  365. Therefore, be careful which type of PBUF you use and if you copy TCP data
  366. or not!