You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tcp.c 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494
  1. #include <string.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <assert.h>
  5. #include <errno.h>
  6. #include <byteswap.h>
  7. #include <ipxe/timer.h>
  8. #include <ipxe/iobuf.h>
  9. #include <ipxe/malloc.h>
  10. #include <ipxe/init.h>
  11. #include <ipxe/retry.h>
  12. #include <ipxe/refcnt.h>
  13. #include <ipxe/pending.h>
  14. #include <ipxe/xfer.h>
  15. #include <ipxe/open.h>
  16. #include <ipxe/uri.h>
  17. #include <ipxe/netdevice.h>
  18. #include <ipxe/profile.h>
  19. #include <ipxe/process.h>
  20. #include <ipxe/tcpip.h>
  21. #include <ipxe/tcp.h>
  22. /** @file
  23. *
  24. * TCP protocol
  25. *
  26. */
  27. FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
  28. /** A TCP connection */
  29. struct tcp_connection {
  30. /** Reference counter */
  31. struct refcnt refcnt;
  32. /** List of TCP connections */
  33. struct list_head list;
  34. /** Flags */
  35. unsigned int flags;
  36. /** Data transfer interface */
  37. struct interface xfer;
  38. /** Remote socket address */
  39. struct sockaddr_tcpip peer;
  40. /** Local port */
  41. unsigned int local_port;
  42. /** Maximum segment size */
  43. size_t mss;
  44. /** Current TCP state */
  45. unsigned int tcp_state;
  46. /** Previous TCP state
  47. *
  48. * Maintained only for debug messages
  49. */
  50. unsigned int prev_tcp_state;
  51. /** Current sequence number
  52. *
  53. * Equivalent to SND.UNA in RFC 793 terminology.
  54. */
  55. uint32_t snd_seq;
  56. /** Unacknowledged sequence count
  57. *
  58. * Equivalent to (SND.NXT-SND.UNA) in RFC 793 terminology.
  59. */
  60. uint32_t snd_sent;
  61. /** Send window
  62. *
  63. * Equivalent to SND.WND in RFC 793 terminology
  64. */
  65. uint32_t snd_win;
  66. /** Current acknowledgement number
  67. *
  68. * Equivalent to RCV.NXT in RFC 793 terminology.
  69. */
  70. uint32_t rcv_ack;
  71. /** Receive window
  72. *
  73. * Equivalent to RCV.WND in RFC 793 terminology.
  74. */
  75. uint32_t rcv_win;
  76. /** Received timestamp value
  77. *
  78. * Updated when a packet is received; copied to ts_recent when
  79. * the window is advanced.
  80. */
  81. uint32_t ts_val;
  82. /** Most recent received timestamp that advanced the window
  83. *
  84. * Equivalent to TS.Recent in RFC 1323 terminology.
  85. */
  86. uint32_t ts_recent;
  87. /** Send window scale
  88. *
  89. * Equivalent to Snd.Wind.Scale in RFC 1323 terminology
  90. */
  91. uint8_t snd_win_scale;
  92. /** Receive window scale
  93. *
  94. * Equivalent to Rcv.Wind.Scale in RFC 1323 terminology
  95. */
  96. uint8_t rcv_win_scale;
  97. /** Maximum receive window */
  98. uint32_t max_rcv_win;
  99. /** Transmit queue */
  100. struct list_head tx_queue;
  101. /** Receive queue */
  102. struct list_head rx_queue;
  103. /** Transmission process */
  104. struct process process;
  105. /** Retransmission timer */
  106. struct retry_timer timer;
  107. /** Shutdown (TIME_WAIT) timer */
  108. struct retry_timer wait;
  109. /** Pending operations for SYN and FIN */
  110. struct pending_operation pending_flags;
  111. /** Pending operations for transmit queue */
  112. struct pending_operation pending_data;
  113. };
  114. /** TCP flags */
  115. enum tcp_flags {
  116. /** TCP data transfer interface has been closed */
  117. TCP_XFER_CLOSED = 0x0001,
  118. /** TCP timestamps are enabled */
  119. TCP_TS_ENABLED = 0x0002,
  120. /** TCP acknowledgement is pending */
  121. TCP_ACK_PENDING = 0x0004,
  122. };
  123. /** TCP internal header
  124. *
  125. * This is the header that replaces the TCP header for packets
  126. * enqueued on the receive queue.
  127. */
  128. struct tcp_rx_queued_header {
  129. /** SEQ value, in host-endian order
  130. *
  131. * This represents the SEQ value at the time the packet is
  132. * enqueued, and so excludes the SYN, if present.
  133. */
  134. uint32_t seq;
  135. /** Flags
  136. *
  137. * Only FIN is valid within this flags byte; all other flags
  138. * have already been processed by the time the packet is
  139. * enqueued.
  140. */
  141. uint8_t flags;
  142. /** Reserved */
  143. uint8_t reserved[3];
  144. };
  145. /**
  146. * List of registered TCP connections
  147. */
  148. static LIST_HEAD ( tcp_conns );
  149. /** Transmit profiler */
  150. static struct profiler tcp_tx_profiler __profiler = { .name = "tcp.tx" };
  151. /** Receive profiler */
  152. static struct profiler tcp_rx_profiler __profiler = { .name = "tcp.rx" };
  153. /** Data transfer profiler */
  154. static struct profiler tcp_xfer_profiler __profiler = { .name = "tcp.xfer" };
  155. /* Forward declarations */
  156. static struct process_descriptor tcp_process_desc;
  157. static struct interface_descriptor tcp_xfer_desc;
  158. static void tcp_expired ( struct retry_timer *timer, int over );
  159. static void tcp_wait_expired ( struct retry_timer *timer, int over );
  160. static struct tcp_connection * tcp_demux ( unsigned int local_port );
  161. static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
  162. uint32_t win );
  163. /**
  164. * Name TCP state
  165. *
  166. * @v state TCP state
  167. * @ret name Name of TCP state
  168. */
  169. static inline __attribute__ (( always_inline )) const char *
  170. tcp_state ( int state ) {
  171. switch ( state ) {
  172. case TCP_CLOSED: return "CLOSED";
  173. case TCP_LISTEN: return "LISTEN";
  174. case TCP_SYN_SENT: return "SYN_SENT";
  175. case TCP_SYN_RCVD: return "SYN_RCVD";
  176. case TCP_ESTABLISHED: return "ESTABLISHED";
  177. case TCP_FIN_WAIT_1: return "FIN_WAIT_1";
  178. case TCP_FIN_WAIT_2: return "FIN_WAIT_2";
  179. case TCP_CLOSING_OR_LAST_ACK: return "CLOSING/LAST_ACK";
  180. case TCP_TIME_WAIT: return "TIME_WAIT";
  181. case TCP_CLOSE_WAIT: return "CLOSE_WAIT";
  182. default: return "INVALID";
  183. }
  184. }
  185. /**
  186. * Dump TCP state transition
  187. *
  188. * @v tcp TCP connection
  189. */
  190. static inline __attribute__ (( always_inline )) void
  191. tcp_dump_state ( struct tcp_connection *tcp ) {
  192. if ( tcp->tcp_state != tcp->prev_tcp_state ) {
  193. DBGC ( tcp, "TCP %p transitioned from %s to %s\n", tcp,
  194. tcp_state ( tcp->prev_tcp_state ),
  195. tcp_state ( tcp->tcp_state ) );
  196. }
  197. tcp->prev_tcp_state = tcp->tcp_state;
  198. }
  199. /**
  200. * Dump TCP flags
  201. *
  202. * @v flags TCP flags
  203. */
  204. static inline __attribute__ (( always_inline )) void
  205. tcp_dump_flags ( struct tcp_connection *tcp, unsigned int flags ) {
  206. if ( flags & TCP_RST )
  207. DBGC2 ( tcp, " RST" );
  208. if ( flags & TCP_SYN )
  209. DBGC2 ( tcp, " SYN" );
  210. if ( flags & TCP_PSH )
  211. DBGC2 ( tcp, " PSH" );
  212. if ( flags & TCP_FIN )
  213. DBGC2 ( tcp, " FIN" );
  214. if ( flags & TCP_ACK )
  215. DBGC2 ( tcp, " ACK" );
  216. }
  217. /***************************************************************************
  218. *
  219. * Open and close
  220. *
  221. ***************************************************************************
  222. */
  223. /**
  224. * Check if local TCP port is available
  225. *
  226. * @v port Local port number
  227. * @ret port Local port number, or negative error
  228. */
  229. static int tcp_port_available ( int port ) {
  230. return ( tcp_demux ( port ) ? -EADDRINUSE : port );
  231. }
  232. /**
  233. * Open a TCP connection
  234. *
  235. * @v xfer Data transfer interface
  236. * @v peer Peer socket address
  237. * @v local Local socket address, or NULL
  238. * @ret rc Return status code
  239. */
  240. static int tcp_open ( struct interface *xfer, struct sockaddr *peer,
  241. struct sockaddr *local ) {
  242. struct sockaddr_tcpip *st_peer = ( struct sockaddr_tcpip * ) peer;
  243. struct sockaddr_tcpip *st_local = ( struct sockaddr_tcpip * ) local;
  244. struct tcp_connection *tcp;
  245. size_t mtu;
  246. int port;
  247. int rc;
  248. /* Allocate and initialise structure */
  249. tcp = zalloc ( sizeof ( *tcp ) );
  250. if ( ! tcp )
  251. return -ENOMEM;
  252. DBGC ( tcp, "TCP %p allocated\n", tcp );
  253. ref_init ( &tcp->refcnt, NULL );
  254. intf_init ( &tcp->xfer, &tcp_xfer_desc, &tcp->refcnt );
  255. process_init_stopped ( &tcp->process, &tcp_process_desc, &tcp->refcnt );
  256. timer_init ( &tcp->timer, tcp_expired, &tcp->refcnt );
  257. timer_init ( &tcp->wait, tcp_wait_expired, &tcp->refcnt );
  258. tcp->prev_tcp_state = TCP_CLOSED;
  259. tcp->tcp_state = TCP_STATE_SENT ( TCP_SYN );
  260. tcp_dump_state ( tcp );
  261. tcp->snd_seq = random();
  262. tcp->max_rcv_win = TCP_MAX_WINDOW_SIZE;
  263. INIT_LIST_HEAD ( &tcp->tx_queue );
  264. INIT_LIST_HEAD ( &tcp->rx_queue );
  265. memcpy ( &tcp->peer, st_peer, sizeof ( tcp->peer ) );
  266. /* Calculate MSS */
  267. mtu = tcpip_mtu ( &tcp->peer );
  268. if ( ! mtu ) {
  269. DBGC ( tcp, "TCP %p has no route to %s\n",
  270. tcp, sock_ntoa ( peer ) );
  271. rc = -ENETUNREACH;
  272. goto err;
  273. }
  274. tcp->mss = ( mtu - sizeof ( struct tcp_header ) );
  275. /* Bind to local port */
  276. port = tcpip_bind ( st_local, tcp_port_available );
  277. if ( port < 0 ) {
  278. rc = port;
  279. DBGC ( tcp, "TCP %p could not bind: %s\n",
  280. tcp, strerror ( rc ) );
  281. goto err;
  282. }
  283. tcp->local_port = port;
  284. DBGC ( tcp, "TCP %p bound to port %d\n", tcp, tcp->local_port );
  285. /* Start timer to initiate SYN */
  286. start_timer_nodelay ( &tcp->timer );
  287. /* Add a pending operation for the SYN */
  288. pending_get ( &tcp->pending_flags );
  289. /* Attach parent interface, transfer reference to connection
  290. * list and return
  291. */
  292. intf_plug_plug ( &tcp->xfer, xfer );
  293. list_add ( &tcp->list, &tcp_conns );
  294. return 0;
  295. err:
  296. ref_put ( &tcp->refcnt );
  297. return rc;
  298. }
  299. /**
  300. * Close TCP connection
  301. *
  302. * @v tcp TCP connection
  303. * @v rc Reason for close
  304. *
  305. * Closes the data transfer interface. If the TCP state machine is in
  306. * a suitable state, the connection will be deleted.
  307. */
  308. static void tcp_close ( struct tcp_connection *tcp, int rc ) {
  309. struct io_buffer *iobuf;
  310. struct io_buffer *tmp;
  311. /* Close data transfer interface */
  312. intf_shutdown ( &tcp->xfer, rc );
  313. tcp->flags |= TCP_XFER_CLOSED;
  314. /* If we are in CLOSED, or have otherwise not yet received a
  315. * SYN (i.e. we are in LISTEN or SYN_SENT), just delete the
  316. * connection.
  317. */
  318. if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
  319. /* Transition to CLOSED for the sake of debugging messages */
  320. tcp->tcp_state = TCP_CLOSED;
  321. tcp_dump_state ( tcp );
  322. /* Free any unprocessed I/O buffers */
  323. list_for_each_entry_safe ( iobuf, tmp, &tcp->rx_queue, list ) {
  324. list_del ( &iobuf->list );
  325. free_iob ( iobuf );
  326. }
  327. /* Free any unsent I/O buffers */
  328. list_for_each_entry_safe ( iobuf, tmp, &tcp->tx_queue, list ) {
  329. list_del ( &iobuf->list );
  330. free_iob ( iobuf );
  331. pending_put ( &tcp->pending_data );
  332. }
  333. assert ( ! is_pending ( &tcp->pending_data ) );
  334. /* Remove pending operations for SYN and FIN, if applicable */
  335. pending_put ( &tcp->pending_flags );
  336. pending_put ( &tcp->pending_flags );
  337. /* Remove from list and drop reference */
  338. process_del ( &tcp->process );
  339. stop_timer ( &tcp->timer );
  340. stop_timer ( &tcp->wait );
  341. list_del ( &tcp->list );
  342. ref_put ( &tcp->refcnt );
  343. DBGC ( tcp, "TCP %p connection deleted\n", tcp );
  344. return;
  345. }
  346. /* If we have not had our SYN acknowledged (i.e. we are in
  347. * SYN_RCVD), pretend that it has been acknowledged so that we
  348. * can send a FIN without breaking things.
  349. */
  350. if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
  351. tcp_rx_ack ( tcp, ( tcp->snd_seq + 1 ), 0 );
  352. /* If we have no data remaining to send, start sending FIN */
  353. if ( list_empty ( &tcp->tx_queue ) &&
  354. ! ( tcp->tcp_state & TCP_STATE_SENT ( TCP_FIN ) ) ) {
  355. tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
  356. tcp_dump_state ( tcp );
  357. /* Add a pending operation for the FIN */
  358. pending_get ( &tcp->pending_flags );
  359. }
  360. }
  361. /***************************************************************************
  362. *
  363. * Transmit data path
  364. *
  365. ***************************************************************************
  366. */
  367. /**
  368. * Calculate transmission window
  369. *
  370. * @v tcp TCP connection
  371. * @ret len Maximum length that can be sent in a single packet
  372. */
  373. static size_t tcp_xmit_win ( struct tcp_connection *tcp ) {
  374. size_t len;
  375. /* Not ready if we're not in a suitable connection state */
  376. if ( ! TCP_CAN_SEND_DATA ( tcp->tcp_state ) )
  377. return 0;
  378. /* Length is the minimum of the receiver's window and the path MTU */
  379. len = tcp->snd_win;
  380. if ( len > TCP_PATH_MTU )
  381. len = TCP_PATH_MTU;
  382. return len;
  383. }
  384. /**
  385. * Check data-transfer flow control window
  386. *
  387. * @v tcp TCP connection
  388. * @ret len Length of window
  389. */
  390. static size_t tcp_xfer_window ( struct tcp_connection *tcp ) {
  391. /* Not ready if data queue is non-empty. This imposes a limit
  392. * of only one unACKed packet in the TX queue at any time; we
  393. * do this to conserve memory usage.
  394. */
  395. if ( ! list_empty ( &tcp->tx_queue ) )
  396. return 0;
  397. /* Return TCP window length */
  398. return tcp_xmit_win ( tcp );
  399. }
  400. /**
  401. * Process TCP transmit queue
  402. *
  403. * @v tcp TCP connection
  404. * @v max_len Maximum length to process
  405. * @v dest I/O buffer to fill with data, or NULL
  406. * @v remove Remove data from queue
  407. * @ret len Length of data processed
  408. *
  409. * This processes at most @c max_len bytes from the TCP connection's
  410. * transmit queue. Data will be copied into the @c dest I/O buffer
  411. * (if provided) and, if @c remove is true, removed from the transmit
  412. * queue.
  413. */
  414. static size_t tcp_process_tx_queue ( struct tcp_connection *tcp, size_t max_len,
  415. struct io_buffer *dest, int remove ) {
  416. struct io_buffer *iobuf;
  417. struct io_buffer *tmp;
  418. size_t frag_len;
  419. size_t len = 0;
  420. list_for_each_entry_safe ( iobuf, tmp, &tcp->tx_queue, list ) {
  421. frag_len = iob_len ( iobuf );
  422. if ( frag_len > max_len )
  423. frag_len = max_len;
  424. if ( dest ) {
  425. memcpy ( iob_put ( dest, frag_len ), iobuf->data,
  426. frag_len );
  427. }
  428. if ( remove ) {
  429. iob_pull ( iobuf, frag_len );
  430. if ( ! iob_len ( iobuf ) ) {
  431. list_del ( &iobuf->list );
  432. free_iob ( iobuf );
  433. pending_put ( &tcp->pending_data );
  434. }
  435. }
  436. len += frag_len;
  437. max_len -= frag_len;
  438. }
  439. return len;
  440. }
  441. /**
  442. * Transmit any outstanding data
  443. *
  444. * @v tcp TCP connection
  445. *
  446. * Transmits any outstanding data on the connection.
  447. *
  448. * Note that even if an error is returned, the retransmission timer
  449. * will have been started if necessary, and so the stack will
  450. * eventually attempt to retransmit the failed packet.
  451. */
  452. static void tcp_xmit ( struct tcp_connection *tcp ) {
  453. struct io_buffer *iobuf;
  454. struct tcp_header *tcphdr;
  455. struct tcp_mss_option *mssopt;
  456. struct tcp_window_scale_padded_option *wsopt;
  457. struct tcp_timestamp_padded_option *tsopt;
  458. void *payload;
  459. unsigned int flags;
  460. size_t len = 0;
  461. uint32_t seq_len;
  462. uint32_t app_win;
  463. uint32_t max_rcv_win;
  464. uint32_t max_representable_win;
  465. int rc;
  466. /* Start profiling */
  467. profile_start ( &tcp_tx_profiler );
  468. /* If retransmission timer is already running, do nothing */
  469. if ( timer_running ( &tcp->timer ) )
  470. return;
  471. /* Calculate both the actual (payload) and sequence space
  472. * lengths that we wish to transmit.
  473. */
  474. if ( TCP_CAN_SEND_DATA ( tcp->tcp_state ) ) {
  475. len = tcp_process_tx_queue ( tcp, tcp_xmit_win ( tcp ),
  476. NULL, 0 );
  477. }
  478. seq_len = len;
  479. flags = TCP_FLAGS_SENDING ( tcp->tcp_state );
  480. if ( flags & ( TCP_SYN | TCP_FIN ) ) {
  481. /* SYN or FIN consume one byte, and we can never send both */
  482. assert ( ! ( ( flags & TCP_SYN ) && ( flags & TCP_FIN ) ) );
  483. seq_len++;
  484. }
  485. tcp->snd_sent = seq_len;
  486. /* If we have nothing to transmit, stop now */
  487. if ( ( seq_len == 0 ) && ! ( tcp->flags & TCP_ACK_PENDING ) )
  488. return;
  489. /* If we are transmitting anything that requires
  490. * acknowledgement (i.e. consumes sequence space), start the
  491. * retransmission timer. Do this before attempting to
  492. * allocate the I/O buffer, in case allocation itself fails.
  493. */
  494. if ( seq_len )
  495. start_timer ( &tcp->timer );
  496. /* Allocate I/O buffer */
  497. iobuf = alloc_iob ( len + TCP_MAX_HEADER_LEN );
  498. if ( ! iobuf ) {
  499. DBGC ( tcp, "TCP %p could not allocate iobuf for %08x..%08x "
  500. "%08x\n", tcp, tcp->snd_seq, ( tcp->snd_seq + seq_len ),
  501. tcp->rcv_ack );
  502. return;
  503. }
  504. iob_reserve ( iobuf, TCP_MAX_HEADER_LEN );
  505. /* Fill data payload from transmit queue */
  506. tcp_process_tx_queue ( tcp, len, iobuf, 0 );
  507. /* Expand receive window if possible */
  508. max_rcv_win = tcp->max_rcv_win;
  509. app_win = xfer_window ( &tcp->xfer );
  510. if ( max_rcv_win > app_win )
  511. max_rcv_win = app_win;
  512. max_representable_win = ( 0xffff << tcp->rcv_win_scale );
  513. if ( max_rcv_win > max_representable_win )
  514. max_rcv_win = max_representable_win;
  515. max_rcv_win &= ~0x03; /* Keep everything dword-aligned */
  516. if ( tcp->rcv_win < max_rcv_win )
  517. tcp->rcv_win = max_rcv_win;
  518. /* Fill up the TCP header */
  519. payload = iobuf->data;
  520. if ( flags & TCP_SYN ) {
  521. mssopt = iob_push ( iobuf, sizeof ( *mssopt ) );
  522. mssopt->kind = TCP_OPTION_MSS;
  523. mssopt->length = sizeof ( *mssopt );
  524. mssopt->mss = htons ( tcp->mss );
  525. wsopt = iob_push ( iobuf, sizeof ( *wsopt ) );
  526. wsopt->nop = TCP_OPTION_NOP;
  527. wsopt->wsopt.kind = TCP_OPTION_WS;
  528. wsopt->wsopt.length = sizeof ( wsopt->wsopt );
  529. wsopt->wsopt.scale = TCP_RX_WINDOW_SCALE;
  530. }
  531. if ( ( flags & TCP_SYN ) || ( tcp->flags & TCP_TS_ENABLED ) ) {
  532. tsopt = iob_push ( iobuf, sizeof ( *tsopt ) );
  533. memset ( tsopt->nop, TCP_OPTION_NOP, sizeof ( tsopt->nop ) );
  534. tsopt->tsopt.kind = TCP_OPTION_TS;
  535. tsopt->tsopt.length = sizeof ( tsopt->tsopt );
  536. tsopt->tsopt.tsval = htonl ( currticks() );
  537. tsopt->tsopt.tsecr = htonl ( tcp->ts_recent );
  538. }
  539. if ( len != 0 )
  540. flags |= TCP_PSH;
  541. tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
  542. memset ( tcphdr, 0, sizeof ( *tcphdr ) );
  543. tcphdr->src = htons ( tcp->local_port );
  544. tcphdr->dest = tcp->peer.st_port;
  545. tcphdr->seq = htonl ( tcp->snd_seq );
  546. tcphdr->ack = htonl ( tcp->rcv_ack );
  547. tcphdr->hlen = ( ( payload - iobuf->data ) << 2 );
  548. tcphdr->flags = flags;
  549. tcphdr->win = htons ( tcp->rcv_win >> tcp->rcv_win_scale );
  550. tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
  551. /* Dump header */
  552. DBGC2 ( tcp, "TCP %p TX %d->%d %08x..%08x %08x %4zd",
  553. tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
  554. ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) + seq_len ),
  555. ntohl ( tcphdr->ack ), len );
  556. tcp_dump_flags ( tcp, tcphdr->flags );
  557. DBGC2 ( tcp, "\n" );
  558. /* Transmit packet */
  559. if ( ( rc = tcpip_tx ( iobuf, &tcp_protocol, NULL, &tcp->peer, NULL,
  560. &tcphdr->csum ) ) != 0 ) {
  561. DBGC ( tcp, "TCP %p could not transmit %08x..%08x %08x: %s\n",
  562. tcp, tcp->snd_seq, ( tcp->snd_seq + tcp->snd_sent ),
  563. tcp->rcv_ack, strerror ( rc ) );
  564. return;
  565. }
  566. /* Clear ACK-pending flag */
  567. tcp->flags &= ~TCP_ACK_PENDING;
  568. profile_stop ( &tcp_tx_profiler );
  569. }
  570. /** TCP process descriptor */
  571. static struct process_descriptor tcp_process_desc =
  572. PROC_DESC_ONCE ( struct tcp_connection, process, tcp_xmit );
  573. /**
  574. * Retransmission timer expired
  575. *
  576. * @v timer Retransmission timer
  577. * @v over Failure indicator
  578. */
  579. static void tcp_expired ( struct retry_timer *timer, int over ) {
  580. struct tcp_connection *tcp =
  581. container_of ( timer, struct tcp_connection, timer );
  582. DBGC ( tcp, "TCP %p timer %s in %s for %08x..%08x %08x\n", tcp,
  583. ( over ? "expired" : "fired" ), tcp_state ( tcp->tcp_state ),
  584. tcp->snd_seq, ( tcp->snd_seq + tcp->snd_sent ), tcp->rcv_ack );
  585. assert ( ( tcp->tcp_state == TCP_SYN_SENT ) ||
  586. ( tcp->tcp_state == TCP_SYN_RCVD ) ||
  587. ( tcp->tcp_state == TCP_ESTABLISHED ) ||
  588. ( tcp->tcp_state == TCP_FIN_WAIT_1 ) ||
  589. ( tcp->tcp_state == TCP_CLOSE_WAIT ) ||
  590. ( tcp->tcp_state == TCP_CLOSING_OR_LAST_ACK ) );
  591. if ( over ) {
  592. /* If we have finally timed out and given up,
  593. * terminate the connection
  594. */
  595. tcp->tcp_state = TCP_CLOSED;
  596. tcp_dump_state ( tcp );
  597. tcp_close ( tcp, -ETIMEDOUT );
  598. } else {
  599. /* Otherwise, retransmit the packet */
  600. tcp_xmit ( tcp );
  601. }
  602. }
  603. /**
  604. * Shutdown timer expired
  605. *
  606. * @v timer Shutdown timer
  607. * @v over Failure indicator
  608. */
  609. static void tcp_wait_expired ( struct retry_timer *timer, int over __unused ) {
  610. struct tcp_connection *tcp =
  611. container_of ( timer, struct tcp_connection, wait );
  612. assert ( tcp->tcp_state == TCP_TIME_WAIT );
  613. DBGC ( tcp, "TCP %p wait complete in %s for %08x..%08x %08x\n", tcp,
  614. tcp_state ( tcp->tcp_state ), tcp->snd_seq,
  615. ( tcp->snd_seq + tcp->snd_sent ), tcp->rcv_ack );
  616. tcp->tcp_state = TCP_CLOSED;
  617. tcp_dump_state ( tcp );
  618. tcp_close ( tcp, 0 );
  619. }
  620. /**
  621. * Send RST response to incoming packet
  622. *
  623. * @v in_tcphdr TCP header of incoming packet
  624. * @ret rc Return status code
  625. */
  626. static int tcp_xmit_reset ( struct tcp_connection *tcp,
  627. struct sockaddr_tcpip *st_dest,
  628. struct tcp_header *in_tcphdr ) {
  629. struct io_buffer *iobuf;
  630. struct tcp_header *tcphdr;
  631. int rc;
  632. /* Allocate space for dataless TX buffer */
  633. iobuf = alloc_iob ( TCP_MAX_HEADER_LEN );
  634. if ( ! iobuf ) {
  635. DBGC ( tcp, "TCP %p could not allocate iobuf for RST "
  636. "%08x..%08x %08x\n", tcp, ntohl ( in_tcphdr->ack ),
  637. ntohl ( in_tcphdr->ack ), ntohl ( in_tcphdr->seq ) );
  638. return -ENOMEM;
  639. }
  640. iob_reserve ( iobuf, TCP_MAX_HEADER_LEN );
  641. /* Construct RST response */
  642. tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
  643. memset ( tcphdr, 0, sizeof ( *tcphdr ) );
  644. tcphdr->src = in_tcphdr->dest;
  645. tcphdr->dest = in_tcphdr->src;
  646. tcphdr->seq = in_tcphdr->ack;
  647. tcphdr->ack = in_tcphdr->seq;
  648. tcphdr->hlen = ( ( sizeof ( *tcphdr ) / 4 ) << 4 );
  649. tcphdr->flags = ( TCP_RST | TCP_ACK );
  650. tcphdr->win = htons ( 0 );
  651. tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
  652. /* Dump header */
  653. DBGC2 ( tcp, "TCP %p TX %d->%d %08x..%08x %08x %4d",
  654. tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
  655. ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) ),
  656. ntohl ( tcphdr->ack ), 0 );
  657. tcp_dump_flags ( tcp, tcphdr->flags );
  658. DBGC2 ( tcp, "\n" );
  659. /* Transmit packet */
  660. if ( ( rc = tcpip_tx ( iobuf, &tcp_protocol, NULL, st_dest,
  661. NULL, &tcphdr->csum ) ) != 0 ) {
  662. DBGC ( tcp, "TCP %p could not transmit RST %08x..%08x %08x: "
  663. "%s\n", tcp, ntohl ( in_tcphdr->ack ),
  664. ntohl ( in_tcphdr->ack ), ntohl ( in_tcphdr->seq ),
  665. strerror ( rc ) );
  666. return rc;
  667. }
  668. return 0;
  669. }
  670. /***************************************************************************
  671. *
  672. * Receive data path
  673. *
  674. ***************************************************************************
  675. */
  676. /**
  677. * Identify TCP connection by local port number
  678. *
  679. * @v local_port Local port
  680. * @ret tcp TCP connection, or NULL
  681. */
  682. static struct tcp_connection * tcp_demux ( unsigned int local_port ) {
  683. struct tcp_connection *tcp;
  684. list_for_each_entry ( tcp, &tcp_conns, list ) {
  685. if ( tcp->local_port == local_port )
  686. return tcp;
  687. }
  688. return NULL;
  689. }
  690. /**
  691. * Parse TCP received options
  692. *
  693. * @v tcp TCP connection
  694. * @v data Raw options data
  695. * @v len Raw options length
  696. * @v options Options structure to fill in
  697. */
  698. static void tcp_rx_opts ( struct tcp_connection *tcp, const void *data,
  699. size_t len, struct tcp_options *options ) {
  700. const void *end = ( data + len );
  701. const struct tcp_option *option;
  702. unsigned int kind;
  703. memset ( options, 0, sizeof ( *options ) );
  704. while ( data < end ) {
  705. option = data;
  706. kind = option->kind;
  707. if ( kind == TCP_OPTION_END )
  708. return;
  709. if ( kind == TCP_OPTION_NOP ) {
  710. data++;
  711. continue;
  712. }
  713. switch ( kind ) {
  714. case TCP_OPTION_MSS:
  715. options->mssopt = data;
  716. break;
  717. case TCP_OPTION_WS:
  718. options->wsopt = data;
  719. break;
  720. case TCP_OPTION_TS:
  721. options->tsopt = data;
  722. break;
  723. default:
  724. DBGC ( tcp, "TCP %p received unknown option %d\n",
  725. tcp, kind );
  726. break;
  727. }
  728. data += option->length;
  729. }
  730. }
  731. /**
  732. * Consume received sequence space
  733. *
  734. * @v tcp TCP connection
  735. * @v seq_len Sequence space length to consume
  736. */
  737. static void tcp_rx_seq ( struct tcp_connection *tcp, uint32_t seq_len ) {
  738. /* Sanity check */
  739. assert ( seq_len > 0 );
  740. /* Update acknowledgement number */
  741. tcp->rcv_ack += seq_len;
  742. /* Update window */
  743. if ( tcp->rcv_win > seq_len ) {
  744. tcp->rcv_win -= seq_len;
  745. } else {
  746. tcp->rcv_win = 0;
  747. }
  748. /* Update timestamp */
  749. tcp->ts_recent = tcp->ts_val;
  750. /* Mark ACK as pending */
  751. tcp->flags |= TCP_ACK_PENDING;
  752. }
  753. /**
  754. * Handle TCP received SYN
  755. *
  756. * @v tcp TCP connection
  757. * @v seq SEQ value (in host-endian order)
  758. * @v options TCP options
  759. * @ret rc Return status code
  760. */
  761. static int tcp_rx_syn ( struct tcp_connection *tcp, uint32_t seq,
  762. struct tcp_options *options ) {
  763. /* Synchronise sequence numbers on first SYN */
  764. if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
  765. tcp->rcv_ack = seq;
  766. if ( options->tsopt )
  767. tcp->flags |= TCP_TS_ENABLED;
  768. if ( options->wsopt ) {
  769. tcp->snd_win_scale = options->wsopt->scale;
  770. tcp->rcv_win_scale = TCP_RX_WINDOW_SCALE;
  771. }
  772. }
  773. /* Ignore duplicate SYN */
  774. if ( seq != tcp->rcv_ack )
  775. return 0;
  776. /* Acknowledge SYN */
  777. tcp_rx_seq ( tcp, 1 );
  778. /* Mark SYN as received and start sending ACKs with each packet */
  779. tcp->tcp_state |= ( TCP_STATE_SENT ( TCP_ACK ) |
  780. TCP_STATE_RCVD ( TCP_SYN ) );
  781. return 0;
  782. }
  783. /**
  784. * Handle TCP received ACK
  785. *
  786. * @v tcp TCP connection
  787. * @v ack ACK value (in host-endian order)
  788. * @v win WIN value (in host-endian order)
  789. * @ret rc Return status code
  790. */
  791. static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
  792. uint32_t win ) {
  793. uint32_t ack_len = ( ack - tcp->snd_seq );
  794. size_t len;
  795. unsigned int acked_flags;
  796. /* Check for out-of-range or old duplicate ACKs */
  797. if ( ack_len > tcp->snd_sent ) {
  798. DBGC ( tcp, "TCP %p received ACK for %08x..%08x, "
  799. "sent only %08x..%08x\n", tcp, tcp->snd_seq,
  800. ( tcp->snd_seq + ack_len ), tcp->snd_seq,
  801. ( tcp->snd_seq + tcp->snd_sent ) );
  802. if ( TCP_HAS_BEEN_ESTABLISHED ( tcp->tcp_state ) ) {
  803. /* Just ignore what might be old duplicate ACKs */
  804. return 0;
  805. } else {
  806. /* Send RST if an out-of-range ACK is received
  807. * on a not-yet-established connection, as per
  808. * RFC 793.
  809. */
  810. return -EINVAL;
  811. }
  812. }
  813. /* Update window size */
  814. tcp->snd_win = win;
  815. /* Ignore ACKs that don't actually acknowledge any new data.
  816. * (In particular, do not stop the retransmission timer; this
  817. * avoids creating a sorceror's apprentice syndrome when a
  818. * duplicate ACK is received and we still have data in our
  819. * transmit queue.)
  820. */
  821. if ( ack_len == 0 )
  822. return 0;
  823. /* Stop the retransmission timer */
  824. stop_timer ( &tcp->timer );
  825. /* Determine acknowledged flags and data length */
  826. len = ack_len;
  827. acked_flags = ( TCP_FLAGS_SENDING ( tcp->tcp_state ) &
  828. ( TCP_SYN | TCP_FIN ) );
  829. if ( acked_flags ) {
  830. len--;
  831. pending_put ( &tcp->pending_flags );
  832. }
  833. /* Update SEQ and sent counters */
  834. tcp->snd_seq = ack;
  835. tcp->snd_sent = 0;
  836. /* Remove any acknowledged data from transmit queue */
  837. tcp_process_tx_queue ( tcp, len, NULL, 1 );
  838. /* Mark SYN/FIN as acknowledged if applicable. */
  839. if ( acked_flags )
  840. tcp->tcp_state |= TCP_STATE_ACKED ( acked_flags );
  841. /* Start sending FIN if we've had all possible data ACKed */
  842. if ( list_empty ( &tcp->tx_queue ) &&
  843. ( tcp->flags & TCP_XFER_CLOSED ) &&
  844. ! ( tcp->tcp_state & TCP_STATE_SENT ( TCP_FIN ) ) ) {
  845. tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
  846. pending_get ( &tcp->pending_flags );
  847. }
  848. return 0;
  849. }
  850. /**
  851. * Handle TCP received data
  852. *
  853. * @v tcp TCP connection
  854. * @v seq SEQ value (in host-endian order)
  855. * @v iobuf I/O buffer
  856. * @ret rc Return status code
  857. *
  858. * This function takes ownership of the I/O buffer.
  859. */
  860. static int tcp_rx_data ( struct tcp_connection *tcp, uint32_t seq,
  861. struct io_buffer *iobuf ) {
  862. uint32_t already_rcvd;
  863. uint32_t len;
  864. int rc;
  865. /* Ignore duplicate or out-of-order data */
  866. already_rcvd = ( tcp->rcv_ack - seq );
  867. len = iob_len ( iobuf );
  868. if ( already_rcvd >= len ) {
  869. free_iob ( iobuf );
  870. return 0;
  871. }
  872. iob_pull ( iobuf, already_rcvd );
  873. len -= already_rcvd;
  874. /* Acknowledge new data */
  875. tcp_rx_seq ( tcp, len );
  876. /* Deliver data to application */
  877. profile_start ( &tcp_xfer_profiler );
  878. if ( ( rc = xfer_deliver_iob ( &tcp->xfer, iobuf ) ) != 0 ) {
  879. DBGC ( tcp, "TCP %p could not deliver %08x..%08x: %s\n",
  880. tcp, seq, ( seq + len ), strerror ( rc ) );
  881. return rc;
  882. }
  883. profile_stop ( &tcp_xfer_profiler );
  884. return 0;
  885. }
  886. /**
  887. * Handle TCP received FIN
  888. *
  889. * @v tcp TCP connection
  890. * @v seq SEQ value (in host-endian order)
  891. * @ret rc Return status code
  892. */
  893. static int tcp_rx_fin ( struct tcp_connection *tcp, uint32_t seq ) {
  894. /* Ignore duplicate or out-of-order FIN */
  895. if ( seq != tcp->rcv_ack )
  896. return 0;
  897. /* Acknowledge FIN */
  898. tcp_rx_seq ( tcp, 1 );
  899. /* Mark FIN as received */
  900. tcp->tcp_state |= TCP_STATE_RCVD ( TCP_FIN );
  901. /* Close connection */
  902. tcp_close ( tcp, 0 );
  903. return 0;
  904. }
  905. /**
  906. * Handle TCP received RST
  907. *
  908. * @v tcp TCP connection
  909. * @v seq SEQ value (in host-endian order)
  910. * @ret rc Return status code
  911. */
  912. static int tcp_rx_rst ( struct tcp_connection *tcp, uint32_t seq ) {
  913. /* Accept RST only if it falls within the window. If we have
  914. * not yet received a SYN, then we have no window to test
  915. * against, so fall back to checking that our SYN has been
  916. * ACKed.
  917. */
  918. if ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) {
  919. if ( ! tcp_in_window ( seq, tcp->rcv_ack, tcp->rcv_win ) )
  920. return 0;
  921. } else {
  922. if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
  923. return 0;
  924. }
  925. /* Abort connection */
  926. tcp->tcp_state = TCP_CLOSED;
  927. tcp_dump_state ( tcp );
  928. tcp_close ( tcp, -ECONNRESET );
  929. DBGC ( tcp, "TCP %p connection reset by peer\n", tcp );
  930. return -ECONNRESET;
  931. }
  932. /**
  933. * Enqueue received TCP packet
  934. *
  935. * @v tcp TCP connection
  936. * @v seq SEQ value (in host-endian order)
  937. * @v flags TCP flags
  938. * @v iobuf I/O buffer
  939. */
  940. static void tcp_rx_enqueue ( struct tcp_connection *tcp, uint32_t seq,
  941. uint8_t flags, struct io_buffer *iobuf ) {
  942. struct tcp_rx_queued_header *tcpqhdr;
  943. struct io_buffer *queued;
  944. size_t len;
  945. uint32_t seq_len;
  946. /* Calculate remaining flags and sequence length. Note that
  947. * SYN, if present, has already been processed by this point.
  948. */
  949. flags &= TCP_FIN;
  950. len = iob_len ( iobuf );
  951. seq_len = ( len + ( flags ? 1 : 0 ) );
  952. /* Discard immediately (to save memory) if:
  953. *
  954. * a) we have not yet received a SYN (and so have no defined
  955. * receive window), or
  956. * b) the packet lies entirely outside the receive window, or
  957. * c) there is no further content to process.
  958. */
  959. if ( ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) ||
  960. ( tcp_cmp ( seq, tcp->rcv_ack + tcp->rcv_win ) >= 0 ) ||
  961. ( tcp_cmp ( seq + seq_len, tcp->rcv_ack ) < 0 ) ||
  962. ( seq_len == 0 ) ) {
  963. free_iob ( iobuf );
  964. return;
  965. }
  966. /* Add internal header */
  967. tcpqhdr = iob_push ( iobuf, sizeof ( *tcpqhdr ) );
  968. tcpqhdr->seq = seq;
  969. tcpqhdr->flags = flags;
  970. /* Add to RX queue */
  971. list_for_each_entry ( queued, &tcp->rx_queue, list ) {
  972. tcpqhdr = queued->data;
  973. if ( tcp_cmp ( seq, tcpqhdr->seq ) < 0 )
  974. break;
  975. }
  976. list_add_tail ( &iobuf->list, &queued->list );
  977. }
  978. /**
  979. * Process receive queue
  980. *
  981. * @v tcp TCP connection
  982. */
  983. static void tcp_process_rx_queue ( struct tcp_connection *tcp ) {
  984. struct io_buffer *iobuf;
  985. struct tcp_rx_queued_header *tcpqhdr;
  986. uint32_t seq;
  987. unsigned int flags;
  988. size_t len;
  989. /* Process all applicable received buffers. Note that we
  990. * cannot use list_for_each_entry() to iterate over the RX
  991. * queue, since tcp_discard() may remove packets from the RX
  992. * queue while we are processing.
  993. */
  994. while ( ( iobuf = list_first_entry ( &tcp->rx_queue, struct io_buffer,
  995. list ) ) ) {
  996. /* Stop processing when we hit the first gap */
  997. tcpqhdr = iobuf->data;
  998. if ( tcp_cmp ( tcpqhdr->seq, tcp->rcv_ack ) > 0 )
  999. break;
  1000. /* Strip internal header and remove from RX queue */
  1001. list_del ( &iobuf->list );
  1002. seq = tcpqhdr->seq;
  1003. flags = tcpqhdr->flags;
  1004. iob_pull ( iobuf, sizeof ( *tcpqhdr ) );
  1005. len = iob_len ( iobuf );
  1006. /* Handle new data, if any */
  1007. tcp_rx_data ( tcp, seq, iob_disown ( iobuf ) );
  1008. seq += len;
  1009. /* Handle FIN, if present */
  1010. if ( flags & TCP_FIN ) {
  1011. tcp_rx_fin ( tcp, seq );
  1012. seq++;
  1013. }
  1014. }
  1015. }
  1016. /**
  1017. * Process received packet
  1018. *
  1019. * @v iobuf I/O buffer
  1020. * @v netdev Network device
  1021. * @v st_src Partially-filled source address
  1022. * @v st_dest Partially-filled destination address
  1023. * @v pshdr_csum Pseudo-header checksum
  1024. * @ret rc Return status code
  1025. */
  1026. static int tcp_rx ( struct io_buffer *iobuf,
  1027. struct net_device *netdev __unused,
  1028. struct sockaddr_tcpip *st_src,
  1029. struct sockaddr_tcpip *st_dest __unused,
  1030. uint16_t pshdr_csum ) {
  1031. struct tcp_header *tcphdr = iobuf->data;
  1032. struct tcp_connection *tcp;
  1033. struct tcp_options options;
  1034. size_t hlen;
  1035. uint16_t csum;
  1036. uint32_t seq;
  1037. uint32_t ack;
  1038. uint16_t raw_win;
  1039. uint32_t win;
  1040. unsigned int flags;
  1041. size_t len;
  1042. uint32_t seq_len;
  1043. size_t old_xfer_window;
  1044. int rc;
  1045. /* Start profiling */
  1046. profile_start ( &tcp_rx_profiler );
  1047. /* Sanity check packet */
  1048. if ( iob_len ( iobuf ) < sizeof ( *tcphdr ) ) {
  1049. DBG ( "TCP packet too short at %zd bytes (min %zd bytes)\n",
  1050. iob_len ( iobuf ), sizeof ( *tcphdr ) );
  1051. rc = -EINVAL;
  1052. goto discard;
  1053. }
  1054. hlen = ( ( tcphdr->hlen & TCP_MASK_HLEN ) / 16 ) * 4;
  1055. if ( hlen < sizeof ( *tcphdr ) ) {
  1056. DBG ( "TCP header too short at %zd bytes (min %zd bytes)\n",
  1057. hlen, sizeof ( *tcphdr ) );
  1058. rc = -EINVAL;
  1059. goto discard;
  1060. }
  1061. if ( hlen > iob_len ( iobuf ) ) {
  1062. DBG ( "TCP header too long at %zd bytes (max %zd bytes)\n",
  1063. hlen, iob_len ( iobuf ) );
  1064. rc = -EINVAL;
  1065. goto discard;
  1066. }
  1067. csum = tcpip_continue_chksum ( pshdr_csum, iobuf->data,
  1068. iob_len ( iobuf ) );
  1069. if ( csum != 0 ) {
  1070. DBG ( "TCP checksum incorrect (is %04x including checksum "
  1071. "field, should be 0000)\n", csum );
  1072. rc = -EINVAL;
  1073. goto discard;
  1074. }
  1075. /* Parse parameters from header and strip header */
  1076. tcp = tcp_demux ( ntohs ( tcphdr->dest ) );
  1077. seq = ntohl ( tcphdr->seq );
  1078. ack = ntohl ( tcphdr->ack );
  1079. raw_win = ntohs ( tcphdr->win );
  1080. flags = tcphdr->flags;
  1081. tcp_rx_opts ( tcp, ( ( ( void * ) tcphdr ) + sizeof ( *tcphdr ) ),
  1082. ( hlen - sizeof ( *tcphdr ) ), &options );
  1083. if ( tcp && options.tsopt )
  1084. tcp->ts_val = ntohl ( options.tsopt->tsval );
  1085. iob_pull ( iobuf, hlen );
  1086. len = iob_len ( iobuf );
  1087. seq_len = ( len + ( ( flags & TCP_SYN ) ? 1 : 0 ) +
  1088. ( ( flags & TCP_FIN ) ? 1 : 0 ) );
  1089. /* Dump header */
  1090. DBGC2 ( tcp, "TCP %p RX %d<-%d %08x %08x..%08x %4zd",
  1091. tcp, ntohs ( tcphdr->dest ), ntohs ( tcphdr->src ),
  1092. ntohl ( tcphdr->ack ), ntohl ( tcphdr->seq ),
  1093. ( ntohl ( tcphdr->seq ) + seq_len ), len );
  1094. tcp_dump_flags ( tcp, tcphdr->flags );
  1095. DBGC2 ( tcp, "\n" );
  1096. /* If no connection was found, silently drop packet */
  1097. if ( ! tcp ) {
  1098. rc = -ENOTCONN;
  1099. goto discard;
  1100. }
  1101. /* Record old data-transfer window */
  1102. old_xfer_window = tcp_xfer_window ( tcp );
  1103. /* Handle ACK, if present */
  1104. if ( flags & TCP_ACK ) {
  1105. win = ( raw_win << tcp->snd_win_scale );
  1106. if ( ( rc = tcp_rx_ack ( tcp, ack, win ) ) != 0 ) {
  1107. tcp_xmit_reset ( tcp, st_src, tcphdr );
  1108. goto discard;
  1109. }
  1110. }
  1111. /* Force an ACK if this packet is out of order */
  1112. if ( ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) &&
  1113. ( seq != tcp->rcv_ack ) ) {
  1114. tcp->flags |= TCP_ACK_PENDING;
  1115. }
  1116. /* Handle SYN, if present */
  1117. if ( flags & TCP_SYN ) {
  1118. tcp_rx_syn ( tcp, seq, &options );
  1119. seq++;
  1120. }
  1121. /* Handle RST, if present */
  1122. if ( flags & TCP_RST ) {
  1123. if ( ( rc = tcp_rx_rst ( tcp, seq ) ) != 0 )
  1124. goto discard;
  1125. }
  1126. /* Enqueue received data */
  1127. tcp_rx_enqueue ( tcp, seq, flags, iob_disown ( iobuf ) );
  1128. /* Process receive queue */
  1129. tcp_process_rx_queue ( tcp );
  1130. /* Dump out any state change as a result of the received packet */
  1131. tcp_dump_state ( tcp );
  1132. /* Schedule transmission of ACK (and any pending data). If we
  1133. * have received any out-of-order packets (i.e. if the receive
  1134. * queue remains non-empty after processing) then send the ACK
  1135. * immediately in order to trigger Fast Retransmission.
  1136. */
  1137. if ( list_empty ( &tcp->rx_queue ) ) {
  1138. process_add ( &tcp->process );
  1139. } else {
  1140. tcp_xmit ( tcp );
  1141. }
  1142. /* If this packet was the last we expect to receive, set up
  1143. * timer to expire and cause the connection to be freed.
  1144. */
  1145. if ( TCP_CLOSED_GRACEFULLY ( tcp->tcp_state ) ) {
  1146. stop_timer ( &tcp->wait );
  1147. start_timer_fixed ( &tcp->wait, ( 2 * TCP_MSL ) );
  1148. }
  1149. /* Notify application if window has changed */
  1150. if ( tcp_xfer_window ( tcp ) != old_xfer_window )
  1151. xfer_window_changed ( &tcp->xfer );
  1152. profile_stop ( &tcp_rx_profiler );
  1153. return 0;
  1154. discard:
  1155. /* Free received packet */
  1156. free_iob ( iobuf );
  1157. return rc;
  1158. }
  1159. /** TCP protocol */
  1160. struct tcpip_protocol tcp_protocol __tcpip_protocol = {
  1161. .name = "TCP",
  1162. .rx = tcp_rx,
  1163. .tcpip_proto = IP_TCP,
  1164. };
  1165. /**
  1166. * Discard some cached TCP data
  1167. *
  1168. * @ret discarded Number of cached items discarded
  1169. */
  1170. static unsigned int tcp_discard ( void ) {
  1171. struct tcp_connection *tcp;
  1172. struct io_buffer *iobuf;
  1173. struct tcp_rx_queued_header *tcpqhdr;
  1174. uint32_t max_win;
  1175. unsigned int discarded = 0;
  1176. /* Try to drop one queued RX packet from each connection */
  1177. list_for_each_entry ( tcp, &tcp_conns, list ) {
  1178. list_for_each_entry_reverse ( iobuf, &tcp->rx_queue, list ) {
  1179. /* Limit window to prevent future discards */
  1180. tcpqhdr = iobuf->data;
  1181. max_win = ( tcpqhdr->seq - tcp->rcv_ack );
  1182. if ( max_win < tcp->max_rcv_win ) {
  1183. DBGC ( tcp, "TCP %p reducing maximum window "
  1184. "from %d to %d\n",
  1185. tcp, tcp->max_rcv_win, max_win );
  1186. tcp->max_rcv_win = max_win;
  1187. }
  1188. /* Remove packet from queue */
  1189. list_del ( &iobuf->list );
  1190. free_iob ( iobuf );
  1191. /* Report discard */
  1192. discarded++;
  1193. break;
  1194. }
  1195. }
  1196. return discarded;
  1197. }
  1198. /** TCP cache discarder */
  1199. struct cache_discarder tcp_discarder __cache_discarder ( CACHE_NORMAL ) = {
  1200. .discard = tcp_discard,
  1201. };
  1202. /**
  1203. * Shut down all TCP connections
  1204. *
  1205. */
  1206. static void tcp_shutdown ( int booting __unused ) {
  1207. struct tcp_connection *tcp;
  1208. while ( ( tcp = list_first_entry ( &tcp_conns, struct tcp_connection,
  1209. list ) ) != NULL ) {
  1210. tcp->tcp_state = TCP_CLOSED;
  1211. tcp_dump_state ( tcp );
  1212. tcp_close ( tcp, -ECANCELED );
  1213. }
  1214. }
  1215. /** TCP shutdown function */
  1216. struct startup_fn tcp_startup_fn __startup_fn ( STARTUP_EARLY ) = {
  1217. .shutdown = tcp_shutdown,
  1218. };
  1219. /***************************************************************************
  1220. *
  1221. * Data transfer interface
  1222. *
  1223. ***************************************************************************
  1224. */
  1225. /**
  1226. * Close interface
  1227. *
  1228. * @v tcp TCP connection
  1229. * @v rc Reason for close
  1230. */
  1231. static void tcp_xfer_close ( struct tcp_connection *tcp, int rc ) {
  1232. /* Close data transfer interface */
  1233. tcp_close ( tcp, rc );
  1234. /* Transmit FIN, if possible */
  1235. tcp_xmit ( tcp );
  1236. }
  1237. /**
  1238. * Deliver datagram as I/O buffer
  1239. *
  1240. * @v tcp TCP connection
  1241. * @v iobuf Datagram I/O buffer
  1242. * @v meta Data transfer metadata
  1243. * @ret rc Return status code
  1244. */
  1245. static int tcp_xfer_deliver ( struct tcp_connection *tcp,
  1246. struct io_buffer *iobuf,
  1247. struct xfer_metadata *meta __unused ) {
  1248. /* Enqueue packet */
  1249. list_add_tail ( &iobuf->list, &tcp->tx_queue );
  1250. /* Each enqueued packet is a pending operation */
  1251. pending_get ( &tcp->pending_data );
  1252. /* Transmit data, if possible */
  1253. tcp_xmit ( tcp );
  1254. return 0;
  1255. }
  1256. /** TCP data transfer interface operations */
  1257. static struct interface_operation tcp_xfer_operations[] = {
  1258. INTF_OP ( xfer_deliver, struct tcp_connection *, tcp_xfer_deliver ),
  1259. INTF_OP ( xfer_window, struct tcp_connection *, tcp_xfer_window ),
  1260. INTF_OP ( intf_close, struct tcp_connection *, tcp_xfer_close ),
  1261. };
  1262. /** TCP data transfer interface descriptor */
  1263. static struct interface_descriptor tcp_xfer_desc =
  1264. INTF_DESC ( struct tcp_connection, xfer, tcp_xfer_operations );
  1265. /***************************************************************************
  1266. *
  1267. * Openers
  1268. *
  1269. ***************************************************************************
  1270. */
  1271. /** TCP IPv4 socket opener */
  1272. struct socket_opener tcp_ipv4_socket_opener __socket_opener = {
  1273. .semantics = TCP_SOCK_STREAM,
  1274. .family = AF_INET,
  1275. .open = tcp_open,
  1276. };
  1277. /** TCP IPv6 socket opener */
  1278. struct socket_opener tcp_ipv6_socket_opener __socket_opener = {
  1279. .semantics = TCP_SOCK_STREAM,
  1280. .family = AF_INET6,
  1281. .open = tcp_open,
  1282. };
  1283. /** Linkage hack */
  1284. int tcp_sock_stream = TCP_SOCK_STREAM;
  1285. /**
  1286. * Open TCP URI
  1287. *
  1288. * @v xfer Data transfer interface
  1289. * @v uri URI
  1290. * @ret rc Return status code
  1291. */
  1292. static int tcp_open_uri ( struct interface *xfer, struct uri *uri ) {
  1293. struct sockaddr_tcpip peer;
  1294. /* Sanity check */
  1295. if ( ! uri->host )
  1296. return -EINVAL;
  1297. memset ( &peer, 0, sizeof ( peer ) );
  1298. peer.st_port = htons ( uri_port ( uri, 0 ) );
  1299. return xfer_open_named_socket ( xfer, SOCK_STREAM,
  1300. ( struct sockaddr * ) &peer,
  1301. uri->host, NULL );
  1302. }
  1303. /** TCP URI opener */
  1304. struct uri_opener tcp_uri_opener __uri_opener = {
  1305. .scheme = "tcp",
  1306. .open = tcp_open_uri,
  1307. };