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.

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