uip-doc.txt 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. /**
  2. \mainpage The uIP TCP/IP stack
  3. \author Adam Dunkels, http://www.sics.se/~adam/
  4. The uIP TCP/IP stack is intended to make it possible to communicate
  5. using the TCP/IP protocol suite even on small 8-bit
  6. micro-controllers. Despite being small and simple, uIP do not require
  7. their peers to have complex, full-size stacks, but can communicate
  8. with peers running a similarly light-weight stack. The code size is on
  9. the order of a few kilobytes and RAM usage can be configured to be as
  10. low as a few hundred bytes.
  11. uIP can be found at the uIP web page: http://www.sics.se/~adam/uip/
  12. \sa \ref apps "Application programs"
  13. \sa \ref uipopt "Compile-time configuration options"
  14. \sa \ref uipconffunc "Run-time configuration functions"
  15. \sa \ref uipinit "Initialization functions"
  16. \sa \ref uipdevfunc "Device driver interface" and
  17. \ref uipdrivervars "variables used by device drivers"
  18. \sa \ref uipappfunc "uIP functions called from application programs"
  19. (see below) and the \ref psock "protosockets API" and their underlying
  20. \ref pt "protothreads"
  21. \section uIPIntroduction Introduction
  22. With the success of the Internet, the TCP/IP protocol suite has become
  23. a global standard for communication. TCP/IP is the underlying protocol
  24. used for web page transfers, e-mail transmissions, file transfers, and
  25. peer-to-peer networking over the Internet. For embedded systems, being
  26. able to run native TCP/IP makes it possible to connect the system
  27. directly to an intranet or even the global Internet. Embedded devices
  28. with full TCP/IP support will be first-class network citizens, thus
  29. being able to fully communicate with other hosts in the network.
  30. Traditional TCP/IP implementations have required far too much
  31. resources both in terms of code size and memory usage to be useful in
  32. small 8 or 16-bit systems. Code size of a few hundred kilobytes and
  33. RAM requirements of several hundreds of kilobytes have made it
  34. impossible to fit the full TCP/IP stack into systems with a few tens
  35. of kilobytes of RAM and room for less than 100 kilobytes of
  36. code.
  37. The uIP implementation is designed to have only the absolute minimal
  38. set of features needed for a full TCP/IP stack. It can only handle a
  39. single network interface and contains the IP, ICMP, UDP and TCP
  40. protocols. uIP is written in the C programming language.
  41. Many other TCP/IP implementations for small systems assume that the
  42. embedded device always will communicate with a full-scale TCP/IP
  43. implementation running on a workstation-class machine. Under this
  44. assumption, it is possible to remove certain TCP/IP mechanisms that
  45. are very rarely used in such situations. Many of those mechanisms are
  46. essential, however, if the embedded device is to communicate with
  47. another equally limited device, e.g., when running distributed
  48. peer-to-peer services and protocols. uIP is designed to be RFC
  49. compliant in order to let the embedded devices to act as first-class
  50. network citizens. The uIP TCP/IP implementation that is not tailored
  51. for any specific application.
  52. \section tcpip TCP/IP Communication
  53. The full TCP/IP suite consists of numerous protocols, ranging from low
  54. level protocols such as ARP which translates IP addresses to MAC
  55. addresses, to application level protocols such as SMTP that is used to
  56. transfer e-mail. The uIP is mostly concerned with the TCP and IP
  57. protocols and upper layer protocols will be referred to as "the
  58. application". Lower layer protocols are often implemented in hardware
  59. or firmware and will be referred to as "the network device" that are
  60. controlled by the network device driver.
  61. TCP provides a reliable byte stream to the upper layer protocols. It
  62. breaks the byte stream into appropriately sized segments and each
  63. segment is sent in its own IP packet. The IP packets are sent out on
  64. the network by the network device driver. If the destination is not on
  65. the physically connected network, the IP packet is forwarded onto
  66. another network by a router that is situated between the two
  67. networks. If the maximum packet size of the other network is smaller
  68. than the size of the IP packet, the packet is fragmented into smaller
  69. packets by the router. If possible, the size of the TCP segments are
  70. chosen so that fragmentation is minimized. The final recipient of the
  71. packet will have to reassemble any fragmented IP packets before they
  72. can be passed to higher layers.
  73. The formal requirements for the protocols in the TCP/IP stack is
  74. specified in a number of RFC documents published by the Internet
  75. Engineering Task Force, IETF. Each of the protocols in the stack is
  76. defined in one more RFC documents and RFC1122 collects
  77. all requirements and updates the previous RFCs.
  78. The RFC1122 requirements can be divided into two categories; those
  79. that deal with the host to host communication and those that deal with
  80. communication between the application and the networking stack. An
  81. example of the first kind is "A TCP MUST be able to receive a TCP
  82. option in any segment" and an example of the second kind is "There
  83. MUST be a mechanism for reporting soft TCP error conditions to the
  84. application." A TCP/IP implementation that violates requirements of
  85. the first kind may not be able to communicate with other TCP/IP
  86. implementations and may even lead to network failures. Violation of
  87. the second kind of requirements will only affect the communication
  88. within the system and will not affect host-to-host communication.
  89. In uIP, all RFC requirements that affect host-to-host communication
  90. are implemented. However, in order to reduce code size, we have
  91. removed certain mechanisms in the interface between the application
  92. and the stack, such as the soft error reporting mechanism and
  93. dynamically configurable type-of-service bits for TCP
  94. connections. Since there are only very few applications that make use
  95. of those features they can be removed without loss of generality.
  96. \section mainloop Main Control Loop
  97. The uIP stack can be run either as a task in a multitasking system, or
  98. as the main program in a singletasking system. In both cases, the main
  99. control loop does two things repeatedly:
  100. - Check if a packet has arrived from the network.
  101. - Check if a periodic timeout has occurred.
  102. If a packet has arrived, the input handler function, uip_input(),
  103. should be invoked by the main control loop. The input handler function
  104. will never block, but will return at once. When it returns, the stack
  105. or the application for which the incoming packet was intended may have
  106. produced one or more reply packets which should be sent out. If so,
  107. the network device driver should be called to send out these packets.
  108. Periodic timeouts are used to drive TCP mechanisms that depend on
  109. timers, such as delayed acknowledgments, retransmissions and
  110. round-trip time estimations. When the main control loop infers that
  111. the periodic timer should fire, it should invoke the timer handler
  112. function uip_periodic(). Because the TCP/IP stack may perform
  113. retransmissions when dealing with a timer event, the network device
  114. driver should called to send out the packets that may have been produced.
  115. \section arch Architecture Specific Functions
  116. uIP requires a few functions to be implemented specifically for the
  117. architecture on which uIP is intended to run. These functions should
  118. be hand-tuned for the particular architecture, but generic C
  119. implementations are given as part of the uIP distribution.
  120. \subsection checksums Checksum Calculation
  121. The TCP and IP protocols implement a checksum that covers the data and
  122. header portions of the TCP and IP packets. Since the calculation of
  123. this checksum is made over all bytes in every packet being sent and
  124. received it is important that the function that calculates the
  125. checksum is efficient. Most often, this means that the checksum
  126. calculation must be fine-tuned for the particular architecture on
  127. which the uIP stack runs.
  128. While uIP includes a generic checksum function, it also leaves it open
  129. for an architecture specific implementation of the two functions
  130. uip_ipchksum() and uip_tcpchksum(). The checksum calculations in those
  131. functions can be written in highly optimized assembler rather than
  132. generic C code.
  133. \subsection longarith 32-bit Arithmetic
  134. The TCP protocol uses 32-bit sequence numbers, and a TCP
  135. implementation will have to do a number of 32-bit additions as part of
  136. the normal protocol processing. Since 32-bit arithmetic is not
  137. natively available on many of the platforms for which uIP is intended,
  138. uIP leaves the 32-bit additions to be implemented by the architecture
  139. specific module and does not make use of any 32-bit arithmetic in the
  140. main code base.
  141. While uIP implements a generic 32-bit addition, there is support for
  142. having an architecture specific implementation of the uip_add32()
  143. function.
  144. \section memory Memory Management
  145. In the architectures for which uIP is intended, RAM is the most
  146. scarce resource. With only a few kilobytes of RAM available for the
  147. TCP/IP stack to use, mechanisms used in traditional TCP/IP cannot be
  148. directly applied.
  149. The uIP stack does not use explicit dynamic memory
  150. allocation. Instead, it uses a single global buffer for holding
  151. packets and has a fixed table for holding connection state. The global
  152. packet buffer is large enough to contain one packet of maximum
  153. size. When a packet arrives from the network, the device driver places
  154. it in the global buffer and calls the TCP/IP stack. If the packet
  155. contains data, the TCP/IP stack will notify the corresponding
  156. application. Because the data in the buffer will be overwritten by the
  157. next incoming packet, the application will either have to act
  158. immediately on the data or copy the data into a secondary buffer for
  159. later processing. The packet buffer will not be overwritten by new
  160. packets before the application has processed the data. Packets that
  161. arrive when the application is processing the data must be queued,
  162. either by the network device or by the device driver. Most single-chip
  163. Ethernet controllers have on-chip buffers that are large enough to
  164. contain at least 4 maximum sized Ethernet frames. Devices that are
  165. handled by the processor, such as RS-232 ports, can copy incoming
  166. bytes to a separate buffer during application processing. If the
  167. buffers are full, the incoming packet is dropped. This will cause
  168. performance degradation, but only when multiple connections are
  169. running in parallel. This is because uIP advertises a very small
  170. receiver window, which means that only a single TCP segment will be in
  171. the network per connection.
  172. In uIP, the same global packet buffer that is used for incoming
  173. packets is also used for the TCP/IP headers of outgoing data. If the
  174. application sends dynamic data, it may use the parts of the global
  175. packet buffer that are not used for headers as a temporary storage
  176. buffer. To send the data, the application passes a pointer to the data
  177. as well as the length of the data to the stack. The TCP/IP headers are
  178. written into the global buffer and once the headers have been
  179. produced, the device driver sends the headers and the application data
  180. out on the network. The data is not queued for
  181. retransmissions. Instead, the application will have to reproduce the
  182. data if a retransmission is necessary.
  183. The total amount of memory usage for uIP depends heavily on the
  184. applications of the particular device in which the implementations are
  185. to be run. The memory configuration determines both the amount of
  186. traffic the system should be able to handle and the maximum amount of
  187. simultaneous connections. A device that will be sending large e-mails
  188. while at the same time running a web server with highly dynamic web
  189. pages and multiple simultaneous clients, will require more RAM than a
  190. simple Telnet server. It is possible to run the uIP implementation
  191. with as little as 200 bytes of RAM, but such a configuration will
  192. provide extremely low throughput and will only allow a small number of
  193. simultaneous connections.
  194. \section api Application Program Interface (API)
  195. The Application Program Interface (API) defines the way the
  196. application program interacts with the TCP/IP stack. The most commonly
  197. used API for TCP/IP is the BSD socket API which is used in most Unix
  198. systems and has heavily influenced the Microsoft Windows WinSock
  199. API. Because the socket API uses stop-and-wait semantics, it requires
  200. support from an underlying multitasking operating system. Since the
  201. overhead of task management, context switching and allocation of stack
  202. space for the tasks might be too high in the intended uIP target
  203. architectures, the BSD socket interface is not suitable for our
  204. purposes.
  205. uIP provides two APIs to programmers: protosockets, a BSD socket-like
  206. API without the overhead of full multi-threading, and a "raw"
  207. event-based API that is nore low-level than protosockets but uses less
  208. memory.
  209. \sa \ref psock
  210. \sa \ref pt
  211. \subsection rawapi The uIP raw API
  212. The "raw" uIP API uses an event driven interface where the application is
  213. invoked in response to certain events. An application running on top
  214. of uIP is implemented as a C function that is called by uIP in
  215. response to certain events. uIP calls the application when data is
  216. received, when data has been successfully delivered to the other end
  217. of the connection, when a new connection has been set up, or when data
  218. has to be retransmitted. The application is also periodically polled
  219. for new data. The application program provides only one callback
  220. function; it is up to the application to deal with mapping different
  221. network services to different ports and connections. Because the
  222. application is able to act on incoming data and connection requests as
  223. soon as the TCP/IP stack receives the packet, low response times can
  224. be achieved even in low-end systems.
  225. uIP is different from other TCP/IP stacks in that it requires help
  226. from the application when doing retransmissions. Other TCP/IP stacks
  227. buffer the transmitted data in memory until the data is known to be
  228. successfully delivered to the remote end of the connection. If the
  229. data needs to be retransmitted, the stack takes care of the
  230. retransmission without notifying the application. With this approach,
  231. the data has to be buffered in memory while waiting for an
  232. acknowledgment even if the application might be able to quickly
  233. regenerate the data if a retransmission has to be made.
  234. In order to reduce memory usage, uIP utilizes the fact that the
  235. application may be able to regenerate sent data and lets the
  236. application take part in retransmissions. uIP does not keep track of
  237. packet contents after they have been sent by the device driver, and
  238. uIP requires that the application takes an active part in performing
  239. the retransmission. When uIP decides that a segment should be
  240. retransmitted, it calls the application with a flag set indicating
  241. that a retransmission is required. The application checks the
  242. retransmission flag and produces the same data that was previously
  243. sent. From the application's standpoint, performing a retransmission
  244. is not different from how the data originally was sent. Therefore the
  245. application can be written in such a way that the same code is used
  246. both for sending data and retransmitting data. Also, it is important
  247. to note that even though the actual retransmission operation is
  248. carried out by the application, it is the responsibility of the stack
  249. to know when the retransmission should be made. Thus the complexity of
  250. the application does not necessarily increase because it takes an
  251. active part in doing retransmissions.
  252. \subsubsection appevents Application Events
  253. The application must be implemented as a C function, UIP_APPCALL(),
  254. that uIP calls whenever an event occurs. Each event has a corresponding
  255. test function that is used to distinguish between different
  256. events. The functions are implemented as C macros that will evaluate
  257. to either zero or non-zero. Note that certain events can happen in
  258. conjunction with each other (i.e., new data can arrive at the same
  259. time as data is acknowledged).
  260. \subsubsection connstate The Connection Pointer
  261. When the application is called by uIP, the global variable uip_conn is
  262. set to point to the uip_conn structure for the connection that
  263. currently is handled, and is called the "current connection". The
  264. fields in the uip_conn structure for the current connection can be
  265. used, e.g., to distinguish between different services, or to check to
  266. which IP address the connection is connected. One typical use would be
  267. to inspect the uip_conn->lport (the local TCP port number) to decide
  268. which service the connection should provide. For instance, an
  269. application might decide to act as an HTTP server if the value of
  270. uip_conn->lport is equal to 80 and act as a TELNET server if the value
  271. is 23.
  272. \subsubsection recvdata Receiving Data
  273. If the uIP test function uip_newdata() is non-zero, the remote host of
  274. the connection has sent new data. The uip_appdata pointer point to the
  275. actual data. The size of the data is obtained through the uIP function
  276. uip_datalen(). The data is not buffered by uIP, but will be
  277. overwritten after the application function returns, and the
  278. application will therefor have to either act directly on the incoming
  279. data, or by itself copy the incoming data into a buffer for later
  280. processing.
  281. \subsubsection senddata Sending Data
  282. When sending data, uIP adjusts the length of the data sent by the
  283. application according to the available buffer space and the current
  284. TCP window advertised by the receiver. The amount of buffer space is
  285. dictated by the memory configuration. It is therefore possible that
  286. all data sent from the application does not arrive at the receiver,
  287. and the application may use the uip_mss() function to see how much
  288. data that actually will be sent by the stack.
  289. The application sends data by using the uIP function uip_send(). The
  290. uip_send() function takes two arguments; a pointer to the data to be
  291. sent and the length of the data. If the application needs RAM space
  292. for producing the actual data that should be sent, the packet buffer
  293. (pointed to by the uip_appdata pointer) can be used for this purpose.
  294. The application can send only one chunk of data at a time on a
  295. connection and it is not possible to call uip_send() more than once
  296. per application invocation; only the data from the last call will be
  297. sent.
  298. \subsubsection rexmitdata Retransmitting Data
  299. Retransmissions are driven by the periodic TCP timer. Every time the
  300. periodic timer is invoked, the retransmission timer for each
  301. connection is decremented. If the timer reaches zero, a retransmission
  302. should be made. As uIP does not keep track of packet contents after they have
  303. been sent by the device driver, uIP requires that the
  304. application takes an active part in performing the
  305. retransmission. When uIP decides that a segment should be
  306. retransmitted, the application function is called with the
  307. uip_rexmit() flag set, indicating that a retransmission is
  308. required.
  309. The application must check the uip_rexmit() flag and produce the same
  310. data that was previously sent. From the application's standpoint,
  311. performing a retransmission is not different from how the data
  312. originally was sent. Therefor, the application can be written in such
  313. a way that the same code is used both for sending data and
  314. retransmitting data. Also, it is important to note that even though
  315. the actual retransmission operation is carried out by the application,
  316. it is the responsibility of the stack to know when the retransmission
  317. should be made. Thus the complexity of the application does not
  318. necessarily increase because it takes an active part in doing
  319. retransmissions.
  320. \subsubsection closing Closing Connections
  321. The application closes the current connection by calling the
  322. uip_close() during an application call. This will cause the connection
  323. to be cleanly closed. In order to indicate a fatal error, the
  324. application might want to abort the connection and does so by calling
  325. the uip_abort() function.
  326. If the connection has been closed by the remote end, the test function
  327. uip_closed() is true. The application may then do any necessary
  328. cleanups.
  329. \subsubsection errors Reporting Errors
  330. There are two fatal errors that can happen to a connection, either
  331. that the connection was aborted by the remote host, or that the
  332. connection retransmitted the last data too many times and has been
  333. aborted. uIP reports this by calling the application function. The
  334. application can use the two test functions uip_aborted() and
  335. uip_timedout() to test for those error conditions.
  336. \subsubsection polling Polling
  337. When a connection is idle, uIP polls the application every time the
  338. periodic timer fires. The application uses the test function
  339. uip_poll() to check if it is being polled by uIP.
  340. The polling event has two purposes. The first is to let the
  341. application periodically know that a connection is idle, which allows
  342. the application to close connections that have been idle for too
  343. long. The other purpose is to let the application send new data that
  344. has been produced. The application can only send data when invoked by
  345. uIP, and therefore the poll event is the only way to send data on an
  346. otherwise idle connection.
  347. \subsubsection listen Listening Ports
  348. uIP maintains a list of listening TCP ports. A new port is opened for
  349. listening with the uip_listen() function. When a connection request
  350. arrives on a listening port, uIP creates a new connection and calls
  351. the application function. The test function uip_connected() is true if
  352. the application was invoked because a new connection was created.
  353. The application can check the lport field in the uip_conn structure to
  354. check to which port the new connection was connected.
  355. \subsubsection connect Opening Connections
  356. New connections can be opened from within
  357. uIP by the function uip_connect(). This function
  358. allocates a new connection and sets a flag in the connection state
  359. which will open a TCP connection to the specified IP address and port
  360. the next time the connection is polled by uIP. The uip_connect()
  361. function returns
  362. a pointer to the uip_conn structure for the new
  363. connection. If there are no free connection slots, the function
  364. returns NULL.
  365. The function uip_ipaddr() may be used to pack an IP address into the
  366. two element 16-bit array used by uIP to represent IP addresses.
  367. Two examples of usage are shown below. The first example shows how to
  368. open a connection to TCP port 8080 of the remote end of the current
  369. connection. If there are not enough TCP connection slots to allow a
  370. new connection to be opened, the uip_connect() function returns NULL
  371. and the current connection is aborted by uip_abort().
  372. \code
  373. void connect_example1_app(void) {
  374. if(uip_connect(uip_conn->ripaddr, HTONS(8080)) == NULL) {
  375. uip_abort();
  376. }
  377. }
  378. \endcode
  379. The second example shows how to open a new connection to a specific IP
  380. address. No error checks are made in this example.
  381. \code
  382. void connect_example2(void) {
  383. u16_t ipaddr[2];
  384. uip_ipaddr(ipaddr, 192,168,0,1);
  385. uip_connect(ipaddr, HTONS(8080));
  386. }
  387. \endcode
  388. \section examples Examples
  389. This section presents a number of very simple uIP applications. The
  390. uIP code distribution contains several more complex applications.
  391. \subsection example1 A Very Simple Application
  392. This first example shows a very simple application. The application
  393. listens for incoming connections on port 1234. When a connection has
  394. been established, the application replies to all data sent to it by
  395. saying "ok"
  396. The implementation of this application is shown below. The application
  397. is initialized with the function called example1_init() and the uIP
  398. callback function is called example1_app(). For this application, the
  399. configuration variable UIP_APPCALL should be defined to be
  400. example1_app().
  401. \code
  402. void example1_init(void) {
  403. uip_listen(HTONS(1234));
  404. }
  405. void example1_app(void) {
  406. if(uip_newdata() || uip_rexmit()) {
  407. uip_send("ok\n", 3);
  408. }
  409. }
  410. \endcode
  411. The initialization function calls the uIP function uip_listen() to
  412. register a listening port. The actual application function
  413. example1_app() uses the test functions uip_newdata() and uip_rexmit()
  414. to determine why it was called. If the application was called because
  415. the remote end has sent it data, it responds with an "ok". If the
  416. application function was called because data was lost in the network
  417. and has to be retransmitted, it also sends an "ok". Note that this
  418. example actually shows a complete uIP application. It is not required
  419. for an application to deal with all types of events such as
  420. uip_connected() or uip_timedout().
  421. \subsection example2 A More Advanced Application
  422. This second example is slightly more advanced than the previous one,
  423. and shows how the application state field in the uip_conn structure is
  424. used.
  425. This application is similar to the first application in that it
  426. listens to a port for incoming connections and responds to data sent
  427. to it with a single "ok". The big difference is that this application
  428. prints out a welcoming "Welcome!" message when the connection has been
  429. established.
  430. This seemingly small change of operation makes a big difference in how
  431. the application is implemented. The reason for the increase in
  432. complexity is that if data should be lost in the network, the
  433. application must know what data to retransmit. If the "Welcome!"
  434. message was lost, the application must retransmit the welcome and if
  435. one of the "ok" messages is lost, the application must send a new
  436. "ok".
  437. The application knows that as long as the "Welcome!" message has not
  438. been acknowledged by the remote host, it might have been dropped in
  439. the network. But once the remote host has sent an acknowledgment
  440. back, the application can be sure that the welcome has been received
  441. and knows that any lost data must be an "ok" message. Thus the
  442. application can be in either of two states: either in the WELCOME-SENT
  443. state where the "Welcome!" has been sent but not acknowledged, or in
  444. the WELCOME-ACKED state where the "Welcome!" has been acknowledged.
  445. When a remote host connects to the application, the application sends
  446. the "Welcome!" message and sets it's state to WELCOME-SENT. When the
  447. welcome message is acknowledged, the application moves to the
  448. WELCOME-ACKED state. If the application receives any new data from the
  449. remote host, it responds by sending an "ok" back.
  450. If the application is requested to retransmit the last message, it
  451. looks at in which state the application is. If the application is in
  452. the WELCOME-SENT state, it sends a "Welcome!" message since it
  453. knows that the previous welcome message hasn't been acknowledged. If
  454. the application is in the WELCOME-ACKED state, it knows that the last
  455. message was an "ok" message and sends such a message.
  456. The implementation of this application is seen below. This
  457. configuration settings for the application is follows after its
  458. implementation.
  459. \code
  460. struct example2_state {
  461. enum {WELCOME_SENT, WELCOME_ACKED} state;
  462. };
  463. void example2_init(void) {
  464. uip_listen(HTONS(2345));
  465. }
  466. void example2_app(void) {
  467. struct example2_state *s;
  468. s = (struct example2_state *)uip_conn->appstate;
  469. if(uip_connected()) {
  470. s->state = WELCOME_SENT;
  471. uip_send("Welcome!\n", 9);
  472. return;
  473. }
  474. if(uip_acked() && s->state == WELCOME_SENT) {
  475. s->state = WELCOME_ACKED;
  476. }
  477. if(uip_newdata()) {
  478. uip_send("ok\n", 3);
  479. }
  480. if(uip_rexmit()) {
  481. switch(s->state) {
  482. case WELCOME_SENT:
  483. uip_send("Welcome!\n", 9);
  484. break;
  485. case WELCOME_ACKED:
  486. uip_send("ok\n", 3);
  487. break;
  488. }
  489. }
  490. }
  491. \endcode
  492. The configuration for the application:
  493. \code
  494. #define UIP_APPCALL example2_app
  495. #define UIP_APPSTATE_SIZE sizeof(struct example2_state)
  496. \endcode
  497. \subsection example3 Differentiating Between Applications
  498. If the system should run multiple applications, one technique to
  499. differentiate between them is to use the TCP port number of either the
  500. remote end or the local end of the connection. The example below shows
  501. how the two examples above can be combined into one application.
  502. \code
  503. void example3_init(void) {
  504. example1_init();
  505. example2_init();
  506. }
  507. void example3_app(void) {
  508. switch(uip_conn->lport) {
  509. case HTONS(1234):
  510. example1_app();
  511. break;
  512. case HTONS(2345):
  513. example2_app();
  514. break;
  515. }
  516. }
  517. \endcode
  518. \subsection example4 Utilizing TCP Flow Control
  519. This example shows a simple application that connects to a host, sends
  520. an HTTP request for a file and downloads it to a slow device such a
  521. disk drive. This shows how to use the flow control functions of uIP.
  522. \code
  523. void example4_init(void) {
  524. u16_t ipaddr[2];
  525. uip_ipaddr(ipaddr, 192,168,0,1);
  526. uip_connect(ipaddr, HTONS(80));
  527. }
  528. void example4_app(void) {
  529. if(uip_connected() || uip_rexmit()) {
  530. uip_send("GET /file HTTP/1.0\r\nServer:192.186.0.1\r\n\r\n",
  531. 48);
  532. return;
  533. }
  534. if(uip_newdata()) {
  535. device_enqueue(uip_appdata, uip_datalen());
  536. if(device_queue_full()) {
  537. uip_stop();
  538. }
  539. }
  540. if(uip_poll() && uip_stopped()) {
  541. if(!device_queue_full()) {
  542. uip_restart();
  543. }
  544. }
  545. }
  546. \endcode
  547. When the connection has been established, an HTTP request is sent to
  548. the server. Since this is the only data that is sent, the application
  549. knows that if it needs to retransmit any data, it is that request that
  550. should be retransmitted. It is therefore possible to combine these two
  551. events as is done in the example.
  552. When the application receives new data from the remote host, it sends
  553. this data to the device by using the function device_enqueue(). It is
  554. important to note that this example assumes that this function copies
  555. the data into its own buffers. The data in the uip_appdata buffer will
  556. be overwritten by the next incoming packet.
  557. If the device's queue is full, the application stops the data from the
  558. remote host by calling the uIP function uip_stop(). The application
  559. can then be sure that it will not receive any new data until
  560. uip_restart() is called. The application polling event is used to
  561. check if the device's queue is no longer full and if so, the data flow
  562. is restarted with uip_restart().
  563. \subsection example5 A Simple Web Server
  564. This example shows a very simple file server application that listens
  565. to two ports and uses the port number to determine which file to
  566. send. If the files are properly formatted, this simple application can
  567. be used as a web server with static pages. The implementation follows.
  568. \code
  569. struct example5_state {
  570. char *dataptr;
  571. unsigned int dataleft;
  572. };
  573. void example5_init(void) {
  574. uip_listen(HTONS(80));
  575. uip_listen(HTONS(81));
  576. }
  577. void example5_app(void) {
  578. struct example5_state *s;
  579. s = (struct example5_state)uip_conn->appstate;
  580. if(uip_connected()) {
  581. switch(uip_conn->lport) {
  582. case HTONS(80):
  583. s->dataptr = data_port_80;
  584. s->dataleft = datalen_port_80;
  585. break;
  586. case HTONS(81):
  587. s->dataptr = data_port_81;
  588. s->dataleft = datalen_port_81;
  589. break;
  590. }
  591. uip_send(s->dataptr, s->dataleft);
  592. return;
  593. }
  594. if(uip_acked()) {
  595. if(s->dataleft < uip_mss()) {
  596. uip_close();
  597. return;
  598. }
  599. s->dataptr += uip_conn->len;
  600. s->dataleft -= uip_conn->len;
  601. uip_send(s->dataptr, s->dataleft);
  602. }
  603. }
  604. \endcode
  605. The application state consists of a pointer to the data that should be
  606. sent and the size of the data that is left to send. When a remote host
  607. connects to the application, the local port number is used to
  608. determine which file to send. The first chunk of data is sent using
  609. uip_send(). uIP makes sure that no more than MSS bytes of data is
  610. actually sent, even though s->dataleft may be larger than the MSS.
  611. The application is driven by incoming acknowledgments. When data has
  612. been acknowledged, new data can be sent. If there is no more data to
  613. send, the connection is closed using uip_close().
  614. \subsection example6 Structured Application Program Design
  615. When writing larger programs using uIP it is useful to be able to
  616. utilize the uIP API in a structured way. The following example
  617. provides a structured design that has showed itself to be useful for
  618. writing larger protocol implementations than the previous examples
  619. showed here. The program is divided into an uIP event handler function
  620. that calls seven application handler functions that process new data,
  621. act on acknowledged data, send new data, deal with connection
  622. establishment or closure events and handle errors. The functions are
  623. called newdata(), acked(), senddata(), connected(), closed(),
  624. aborted(), and timedout(), and needs to be written specifically for
  625. the protocol that is being implemented.
  626. The uIP event handler function is shown below.
  627. \code
  628. void example6_app(void) {
  629. if(uip_aborted()) {
  630. aborted();
  631. }
  632. if(uip_timedout()) {
  633. timedout();
  634. }
  635. if(uip_closed()) {
  636. closed();
  637. }
  638. if(uip_connected()) {
  639. connected();
  640. }
  641. if(uip_acked()) {
  642. acked();
  643. }
  644. if(uip_newdata()) {
  645. newdata();
  646. }
  647. if(uip_rexmit() ||
  648. uip_newdata() ||
  649. uip_acked() ||
  650. uip_connected() ||
  651. uip_poll()) {
  652. senddata();
  653. }
  654. }
  655. \endcode
  656. The function starts with dealing with any error conditions that might
  657. have happened by checking if uip_aborted() or uip_timedout() are
  658. true. If so, the appropriate error function is called. Also, if the
  659. connection has been closed, the closed() function is called to the it
  660. deal with the event.
  661. Next, the function checks if the connection has just been established
  662. by checking if uip_connected() is true. The connected() function is
  663. called and is supposed to do whatever needs to be done when the
  664. connection is established, such as intializing the application state
  665. for the connection. Since it may be the case that data should be sent
  666. out, the senddata() function is called to deal with the outgoing data.
  667. The following very simple application serves as an example of how the
  668. application handler functions might look. This application simply
  669. waits for any data to arrive on the connection, and responds to the
  670. data by sending out the message "Hello world!". To illustrate how to
  671. develop an application state machine, this message is sent in two
  672. parts, first the "Hello" part and then the "world!" part.
  673. \code
  674. #define STATE_WAITING 0
  675. #define STATE_HELLO 1
  676. #define STATE_WORLD 2
  677. struct example6_state {
  678. u8_t state;
  679. char *textptr;
  680. int textlen;
  681. };
  682. static void aborted(void) {}
  683. static void timedout(void) {}
  684. static void closed(void) {}
  685. static void connected(void) {
  686. struct example6_state *s = (struct example6_state *)uip_conn->appstate;
  687. s->state = STATE_WAITING;
  688. s->textlen = 0;
  689. }
  690. static void newdata(void) {
  691. struct example6_state *s = (struct example6_state *)uip_conn->appstate;
  692. if(s->state == STATE_WAITING) {
  693. s->state = STATE_HELLO;
  694. s->textptr = "Hello ";
  695. s->textlen = 6;
  696. }
  697. }
  698. static void acked(void) {
  699. struct example6_state *s = (struct example6_state *)uip_conn->appstate;
  700. s->textlen -= uip_conn->len;
  701. s->textptr += uip_conn->len;
  702. if(s->textlen == 0) {
  703. switch(s->state) {
  704. case STATE_HELLO:
  705. s->state = STATE_WORLD;
  706. s->textptr = "world!\n";
  707. s->textlen = 7;
  708. break;
  709. case STATE_WORLD:
  710. uip_close();
  711. break;
  712. }
  713. }
  714. }
  715. static void senddata(void) {
  716. struct example6_state *s = (struct example6_state *)uip_conn->appstate;
  717. if(s->textlen > 0) {
  718. uip_send(s->textptr, s->textlen);
  719. }
  720. }
  721. \endcode
  722. The application state consists of a "state" variable, a "textptr"
  723. pointer to a text message and the "textlen" length of the text
  724. message. The "state" variable can be either "STATE_WAITING", meaning
  725. that the application is waiting for data to arrive from the network,
  726. "STATE_HELLO", in which the application is sending the "Hello" part of
  727. the message, or "STATE_WORLD", in which the application is sending the
  728. "world!" message.
  729. The application does not handle errors or connection closing events,
  730. and therefore the aborted(), timedout() and closed() functions are
  731. implemented as empty functions.
  732. The connected() function will be called when a connection has been
  733. established, and in this case sets the "state" variable to be
  734. "STATE_WAITING" and the "textlen" variable to be zero, indicating that
  735. there is no message to be sent out.
  736. When new data arrives from the network, the newdata() function will be
  737. called by the event handler function. The newdata() function will
  738. check if the connection is in the "STATE_WAITING" state, and if so
  739. switches to the "STATE_HELLO" state and registers a 6 byte long "Hello
  740. " message with the connection. This message will later be sent out by
  741. the senddata() function.
  742. The acked() function is called whenever data that previously was sent
  743. has been acknowleged by the receiving host. This acked() function
  744. first reduces the amount of data that is left to send, by subtracting
  745. the length of the previously sent data (obtained from "uip_conn->len")
  746. from the "textlen" variable, and also adjusts the "textptr" pointer
  747. accordingly. It then checks if the "textlen" variable now is zero,
  748. which indicates that all data now has been successfully received, and
  749. if so changes application state. If the application was in the
  750. "STATE_HELLO" state, it switches state to "STATE_WORLD" and sets up a
  751. 7 byte "world!\n" message to be sent. If the application was in the
  752. "STATE_WORLD" state, it closes the connection.
  753. Finally, the senddata() function takes care of actually sending the
  754. data that is to be sent. It is called by the event handler function
  755. when new data has been received, when data has been acknowledged, when
  756. a new connection has been established, when the connection is polled
  757. because of inactivity, or when a retransmission should be made. The
  758. purpose of the senddata() function is to optionally format the data
  759. that is to be sent, and to call the uip_send() function to actually
  760. send out the data. In this particular example, the function simply
  761. calls uip_send() with the appropriate arguments if data is to be sent,
  762. after checking if data should be sent out or not as indicated by the
  763. "textlen" variable.
  764. It is important to note that the senddata() function never should
  765. affect the application state; this should only be done in the acked()
  766. and newdata() functions.
  767. \section protoimpl Protocol Implementations
  768. The protocols in the TCP/IP protocol suite are designed in a layered
  769. fashion where each protocol performs a specific function and the
  770. interactions between the protocol layers are strictly defined. While
  771. the layered approach is a good way to design protocols, it is not
  772. always the best way to implement them. In uIP, the protocol
  773. implementations are tightly coupled in order to save code space.
  774. This section gives detailed information on the specific protocol
  775. implementations in uIP.
  776. \subsection ip IP --- Internet Protocol
  777. When incoming packets are processed by uIP, the IP layer is the first
  778. protocol that examines the packet. The IP layer does a few simple
  779. checks such as if the destination IP address of the incoming packet
  780. matches any of the local IP address and verifies the IP header
  781. checksum. Since there are no IP options that are strictly required and
  782. because they are very uncommon, any IP options in received packets are
  783. dropped.
  784. \subsubsection ipreass IP Fragment Reassembly
  785. IP fragment reassembly is implemented using a separate buffer that
  786. holds the packet to be reassembled. An incoming fragment is copied
  787. into the right place in the buffer and a bit map is used to keep track
  788. of which fragments have been received. Because the first byte of an IP
  789. fragment is aligned on an 8-byte boundary, the bit map requires a
  790. small amount of memory. When all fragments have been reassembled, the
  791. resulting IP packet is passed to the transport layer. If all fragments
  792. have not been received within a specified time frame, the packet is
  793. dropped.
  794. The current implementation only has a single buffer for holding
  795. packets to be reassembled, and therefore does not support simultaneous
  796. reassembly of more than one packet. Since fragmented packets are
  797. uncommon, this ought to be a reasonable decision. Extending the
  798. implementation to support multiple buffers would be straightforward,
  799. however.
  800. \subsubsection ipbroadcast Broadcasts and Multicasts
  801. IP has the ability to broadcast and multicast packets on the local
  802. network. Such packets are addressed to special broadcast and multicast
  803. addresses. Broadcast is used heavily in many UDP based protocols such
  804. as the Microsoft Windows file-sharing SMB protocol. Multicast is
  805. primarily used in protocols used for multimedia distribution such as
  806. RTP. TCP is a point-to-point protocol and does not use broadcast or
  807. multicast packets. uIP current supports broadcast packets as well as
  808. sending multicast packets. Joining multicast groups (IGMP) and
  809. receiving non-local multicast packets is not currently supported.
  810. \subsection icmp ICMP --- Internet Control Message Protocol
  811. The ICMP protocol is used for reporting soft error conditions and for
  812. querying host parameters. Its main use is, however, the echo mechanism
  813. which is used by the "ping" program.
  814. The ICMP implementation in uIP is very simple as itis restricted to
  815. only implement ICMP echo messages. Replies to echo messages are
  816. constructed by simply swapping the source and destination IP addresses
  817. of incoming echo requests and rewriting the ICMP header with the
  818. Echo-Reply message type. The ICMP checksum is adjusted using standard
  819. techniques (see RFC1624).
  820. Since only the ICMP echo message is implemented, there is no support
  821. for Path MTU discovery or ICMP redirect messages. Neither of these is
  822. strictly required for interoperability; they are performance
  823. enhancement mechanisms.
  824. \subsection tcp TCP --- Transmission Control Protocol
  825. The TCP implementation in uIP is driven by incoming packets and timer
  826. events. Incoming packets are parsed by TCP and if the packet contains
  827. data that is to be delivered to the application, the application is
  828. invoked by the means of the application function call. If the incoming
  829. packet acknowledges previously sent data, the connection state is
  830. updated and the application is informed, allowing it to send out new
  831. data.
  832. \subsubsection listeb Listening Connections
  833. TCP allows a connection to listen for incoming connection requests. In
  834. uIP, a listening connection is identified by the 16-bit port number
  835. and incoming connection requests are checked against the list of
  836. listening connections. This list of listening connections is dynamic
  837. and can be altered by the applications in the system.
  838. \subsubsection slidingwindow Sliding Window
  839. Most TCP implementations use a sliding window mechanism for sending
  840. data. Multiple data segments are sent in succession without waiting
  841. for an acknowledgment for each segment.
  842. The sliding window algorithm uses a lot of 32-bit operations and
  843. because 32-bit arithmetic is fairly expensive on most 8-bit CPUs, uIP
  844. does not implement it. Also, uIP does not buffer sent packets and a
  845. sliding window implementation that does not buffer sent packets will have
  846. to be supported by a complex application layer. Instead, uIP allows
  847. only a single TCP segment per connection to be unacknowledged at any
  848. given time.
  849. It is important to note that even though most TCP implementations use
  850. the sliding window algorithm, it is not required by the TCP
  851. specifications. Removing the sliding window mechanism does not affect
  852. interoperability in any way.
  853. \subsubsection rttest Round-Trip Time Estimation
  854. TCP continuously estimates the current Round-Trip Time (RTT) of every
  855. active connection in order to find a suitable value for the
  856. retransmission time-out.
  857. The RTT estimation in uIP is implemented using TCP's periodic
  858. timer. Each time the periodic timer fires, it increments a counter for
  859. each connection that has unacknowledged data in the network. When an
  860. acknowledgment is received, the current value of the counter is used
  861. as a sample of the RTT. The sample is used together with Van
  862. Jacobson's standard TCP RTT estimation function to calculate an
  863. estimate of the RTT. Karn's algorithm is used to ensure that
  864. retransmissions do not skew the estimates.
  865. \subsubsection rexmit Retransmissions
  866. Retransmissions are driven by the periodic TCP timer. Every time the
  867. periodic timer is invoked, the retransmission timer for each
  868. connection is decremented. If the timer reaches zero, a retransmission
  869. should be made.
  870. As uIP does not keep track of packet contents after they have
  871. been sent by the device driver, uIP requires that the
  872. application takes an active part in performing the
  873. retransmission. When uIP decides that a segment should be
  874. retransmitted, it calls the application with a flag set indicating
  875. that a retransmission is required. The application checks the
  876. retransmission flag and produces the same data that was previously
  877. sent. From the application's standpoint, performing a retransmission
  878. is not different from how the data originally was sent. Therefore the
  879. application can be written in such a way that the same code is used
  880. both for sending data and retransmitting data. Also, it is important
  881. to note that even though the actual retransmission operation is
  882. carried out by the application, it is the responsibility of the stack
  883. to know when the retransmission should be made. Thus the complexity of
  884. the application does not necessarily increase because it takes an
  885. active part in doing retransmissions.
  886. \subsubsection flowcontrol Flow Control
  887. The purpose of TCP's flow control mechanisms is to allow communication
  888. between hosts with wildly varying memory dimensions. In each TCP
  889. segment, the sender of the segment indicates its available buffer
  890. space. A TCP sender must not send more data than the buffer space
  891. indicated by the receiver.
  892. In uIP, the application cannot send more data than the receiving host
  893. can buffer. And application cannot send more data than the amount of
  894. bytes it is allowed to send by the receiving host. If the remote host
  895. cannot accept any data at all, the stack initiates the zero window
  896. probing mechanism.
  897. \subsubsection congestioncontrol Congestion Control
  898. The congestion control mechanisms limit the number of simultaneous TCP
  899. segments in the network. The algorithms used for congestion control
  900. are designed to be simple to implement and require only a few lines of
  901. code.
  902. Since uIP only handles one in-flight TCP segment per connection,
  903. the amount of simultaneous segments cannot be further limited, thus
  904. the congestion control mechanisms are not needed.
  905. \subsubsection urgdata Urgent Data
  906. TCP's urgent data mechanism provides an application-to-application
  907. notification mechanism, which can be used by an application to mark
  908. parts of the data stream as being more urgent than the normal
  909. stream. It is up to the receiving application to interpret the meaning
  910. of the urgent data.
  911. In many TCP implementations, including the BSD implementation, the
  912. urgent data feature increases the complexity of the implementation
  913. because it requires an asynchronous notification mechanism in an
  914. otherwise synchronous API. As uIP already use an asynchronous event
  915. based API, the implementation of the urgent data feature does not lead
  916. to increased complexity.
  917. \section performance Performance
  918. In TCP/IP implementations for high-end systems, processing time is
  919. dominated by the checksum calculation loop, the operation of copying
  920. packet data and context switching. Operating systems for high-end
  921. systems often have multiple protection domains for protecting kernel
  922. data from user processes and user processes from each other. Because
  923. the TCP/IP stack is run in the kernel, data has to be copied between
  924. the kernel space and the address space of the user processes and a
  925. context switch has to be performed once the data has been
  926. copied. Performance can be enhanced by combining the copy operation
  927. with the checksum calculation. Because high-end systems usually have
  928. numerous active connections, packet demultiplexing is also an
  929. expensive operation.
  930. A small embedded device does not have the necessary processing power
  931. to have multiple protection domains and the power to run a
  932. multitasking operating system. Therefore there is no need to copy
  933. data between the TCP/IP stack and the application program. With an
  934. event based API there is no context switch between the TCP/IP stack
  935. and the applications.
  936. In such limited systems, the TCP/IP processing overhead is dominated
  937. by the copying of packet data from the network device to host memory,
  938. and checksum calculation. Apart from the checksum calculation and
  939. copying, the TCP processing done for an incoming packet involves only
  940. updating a few counters and flags before handing the data over to the
  941. application. Thus an estimate of the CPU overhead of our TCP/IP
  942. implementations can be obtained by calculating the amount of CPU
  943. cycles needed for the checksum calculation and copying of a maximum
  944. sized packet.
  945. \subsection delack The Impact of Delayed Acknowledgments
  946. Most TCP receivers implement the delayed acknowledgment algorithm for
  947. reducing the number of pure acknowledgment packets sent. A TCP
  948. receiver using this algorithm will only send acknowledgments for every
  949. other received segment. If no segment is received within a specific
  950. time-frame, an acknowledgment is sent. The time-frame can be as high
  951. as 500 ms but typically is 200 ms.
  952. A TCP sender such as uIP that only handles a single outstanding TCP
  953. segment will interact poorly with the delayed acknowledgment
  954. algorithm. Because the receiver only receives a single segment at a
  955. time, it will wait as much as 500 ms before an acknowledgment is
  956. sent. This means that the maximum possible throughput is severely
  957. limited by the 500 ms idle time.
  958. Thus the maximum throughput equation when sending data from uIP will
  959. be $p = s / (t + t_d)$ where $s$ is the segment size and $t_d$ is the
  960. delayed acknowledgment timeout, which typically is between 200 and
  961. 500 ms. With a segment size of 1000 bytes, a round-trip time of 40 ms
  962. and a delayed acknowledgment timeout of 200 ms, the maximum
  963. throughput will be 4166 bytes per second. With the delayed acknowledgment
  964. algorithm disabled at the receiver, the maximum throughput would be
  965. 25000 bytes per second.
  966. It should be noted, however, that since small systems running uIP are
  967. not very likely to have large amounts of data to send, the delayed
  968. acknowledgmen t throughput degradation of uIP need not be very
  969. severe. Small amounts of data sent by such a system will not span more
  970. than a single TCP segment, and would therefore not be affected by the
  971. throughput degradation anyway.
  972. The maximum throughput when uIP acts as a receiver is not affected by
  973. the delayed acknowledgment throughput degradation.
  974. */
  975. /** @} */