[tcp] Treat ACKs as sent only when successfully transmitted
[gpxe.git] / src / net / tcp.c
blob8df80a8de3c5f27acd5293fa111f263c8f98b675
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 <gpxe/timer.h>
8 #include <gpxe/iobuf.h>
9 #include <gpxe/malloc.h>
10 #include <gpxe/retry.h>
11 #include <gpxe/refcnt.h>
12 #include <gpxe/xfer.h>
13 #include <gpxe/open.h>
14 #include <gpxe/uri.h>
15 #include <gpxe/tcpip.h>
16 #include <gpxe/tcp.h>
18 /** @file
20 * TCP protocol
24 FILE_LICENCE ( GPL2_OR_LATER );
26 /** A TCP connection */
27 struct tcp_connection {
28 /** Reference counter */
29 struct refcnt refcnt;
30 /** List of TCP connections */
31 struct list_head list;
33 /** Flags */
34 unsigned int flags;
36 /** Data transfer interface */
37 struct xfer_interface xfer;
39 /** Remote socket address */
40 struct sockaddr_tcpip peer;
41 /** Local port */
42 unsigned int local_port;
44 /** Current TCP state */
45 unsigned int tcp_state;
46 /** Previous TCP state
48 * Maintained only for debug messages
50 unsigned int prev_tcp_state;
51 /** Current sequence number
53 * Equivalent to SND.UNA in RFC 793 terminology.
55 uint32_t snd_seq;
56 /** Unacknowledged sequence count
58 * Equivalent to (SND.NXT-SND.UNA) in RFC 793 terminology.
60 uint32_t snd_sent;
61 /** Send window
63 * Equivalent to SND.WND in RFC 793 terminology
65 uint32_t snd_win;
66 /** Current acknowledgement number
68 * Equivalent to RCV.NXT in RFC 793 terminology.
70 uint32_t rcv_ack;
71 /** Receive window
73 * Equivalent to RCV.WND in RFC 793 terminology.
75 uint32_t rcv_win;
76 /** Most recent received timestamp
78 * Equivalent to TS.Recent in RFC 1323 terminology.
80 uint32_t ts_recent;
82 /** Transmit queue */
83 struct list_head queue;
84 /** Retransmission timer */
85 struct retry_timer timer;
86 /** Shutdown (TIME_WAIT) timer */
87 struct retry_timer wait;
90 /** TCP flags */
91 enum tcp_flags {
92 /** TCP data transfer interface has been closed */
93 TCP_XFER_CLOSED = 0x0001,
94 /** TCP timestamps are enabled */
95 TCP_TS_ENABLED = 0x0002,
96 /** TCP acknowledgement is pending */
97 TCP_ACK_PENDING = 0x0004,
101 * List of registered TCP connections
103 static LIST_HEAD ( tcp_conns );
105 /* Forward declarations */
106 static struct xfer_interface_operations tcp_xfer_operations;
107 static void tcp_expired ( struct retry_timer *timer, int over );
108 static void tcp_wait_expired ( struct retry_timer *timer, int over );
109 static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
110 uint32_t win );
113 * Name TCP state
115 * @v state TCP state
116 * @ret name Name of TCP state
118 static inline __attribute__ (( always_inline )) const char *
119 tcp_state ( int state ) {
120 switch ( state ) {
121 case TCP_CLOSED: return "CLOSED";
122 case TCP_LISTEN: return "LISTEN";
123 case TCP_SYN_SENT: return "SYN_SENT";
124 case TCP_SYN_RCVD: return "SYN_RCVD";
125 case TCP_ESTABLISHED: return "ESTABLISHED";
126 case TCP_FIN_WAIT_1: return "FIN_WAIT_1";
127 case TCP_FIN_WAIT_2: return "FIN_WAIT_2";
128 case TCP_CLOSING_OR_LAST_ACK: return "CLOSING/LAST_ACK";
129 case TCP_TIME_WAIT: return "TIME_WAIT";
130 case TCP_CLOSE_WAIT: return "CLOSE_WAIT";
131 default: return "INVALID";
136 * Dump TCP state transition
138 * @v tcp TCP connection
140 static inline __attribute__ (( always_inline )) void
141 tcp_dump_state ( struct tcp_connection *tcp ) {
143 if ( tcp->tcp_state != tcp->prev_tcp_state ) {
144 DBGC ( tcp, "TCP %p transitioned from %s to %s\n", tcp,
145 tcp_state ( tcp->prev_tcp_state ),
146 tcp_state ( tcp->tcp_state ) );
148 tcp->prev_tcp_state = tcp->tcp_state;
152 * Dump TCP flags
154 * @v flags TCP flags
156 static inline __attribute__ (( always_inline )) void
157 tcp_dump_flags ( struct tcp_connection *tcp, unsigned int flags ) {
158 if ( flags & TCP_RST )
159 DBGC2 ( tcp, " RST" );
160 if ( flags & TCP_SYN )
161 DBGC2 ( tcp, " SYN" );
162 if ( flags & TCP_PSH )
163 DBGC2 ( tcp, " PSH" );
164 if ( flags & TCP_FIN )
165 DBGC2 ( tcp, " FIN" );
166 if ( flags & TCP_ACK )
167 DBGC2 ( tcp, " ACK" );
170 /***************************************************************************
172 * Open and close
174 ***************************************************************************
178 * Bind TCP connection to local port
180 * @v tcp TCP connection
181 * @v port Local port number
182 * @ret rc Return status code
184 * If the port is 0, the connection is assigned an available port
185 * between 1024 and 65535.
187 static int tcp_bind ( struct tcp_connection *tcp, unsigned int port ) {
188 struct tcp_connection *existing;
189 uint16_t try_port;
190 int i;
192 /* If no port specified, find an available port */
193 if ( ! port ) {
194 try_port = ( random() % 64512 ) + 1023;
195 for ( i = 0 ; i < 65536 ; ++i ) {
196 if ( ++try_port < 1024 )
197 continue;
198 if ( tcp_bind ( tcp, try_port ) == 0 )
199 return 0;
201 DBGC ( tcp, "TCP %p could not bind: no free ports\n", tcp );
202 return -EADDRINUSE;
205 /* Attempt bind to local port */
206 list_for_each_entry ( existing, &tcp_conns, list ) {
207 if ( existing->local_port == port ) {
208 DBGC ( tcp, "TCP %p could not bind: port %d in use\n",
209 tcp, port );
210 return -EADDRINUSE;
213 tcp->local_port = port;
215 DBGC ( tcp, "TCP %p bound to port %d\n", tcp, port );
216 return 0;
220 * Open a TCP connection
222 * @v xfer Data transfer interface
223 * @v peer Peer socket address
224 * @v local Local socket address, or NULL
225 * @ret rc Return status code
227 static int tcp_open ( struct xfer_interface *xfer, struct sockaddr *peer,
228 struct sockaddr *local ) {
229 struct sockaddr_tcpip *st_peer = ( struct sockaddr_tcpip * ) peer;
230 struct sockaddr_tcpip *st_local = ( struct sockaddr_tcpip * ) local;
231 struct tcp_connection *tcp;
232 unsigned int bind_port;
233 int rc;
235 /* Allocate and initialise structure */
236 tcp = zalloc ( sizeof ( *tcp ) );
237 if ( ! tcp )
238 return -ENOMEM;
239 DBGC ( tcp, "TCP %p allocated\n", tcp );
240 ref_init ( &tcp->refcnt, NULL );
241 xfer_init ( &tcp->xfer, &tcp_xfer_operations, &tcp->refcnt );
242 timer_init ( &tcp->timer, tcp_expired );
243 timer_init ( &tcp->wait, tcp_wait_expired );
244 tcp->prev_tcp_state = TCP_CLOSED;
245 tcp->tcp_state = TCP_STATE_SENT ( TCP_SYN );
246 tcp_dump_state ( tcp );
247 tcp->snd_seq = random();
248 INIT_LIST_HEAD ( &tcp->queue );
249 memcpy ( &tcp->peer, st_peer, sizeof ( tcp->peer ) );
251 /* Bind to local port */
252 bind_port = ( st_local ? ntohs ( st_local->st_port ) : 0 );
253 if ( ( rc = tcp_bind ( tcp, bind_port ) ) != 0 )
254 goto err;
256 /* Start timer to initiate SYN */
257 start_timer_nodelay ( &tcp->timer );
259 /* Attach parent interface, transfer reference to connection
260 * list and return
262 xfer_plug_plug ( &tcp->xfer, xfer );
263 list_add ( &tcp->list, &tcp_conns );
264 return 0;
266 err:
267 ref_put ( &tcp->refcnt );
268 return rc;
272 * Close TCP connection
274 * @v tcp TCP connection
275 * @v rc Reason for close
277 * Closes the data transfer interface. If the TCP state machine is in
278 * a suitable state, the connection will be deleted.
280 static void tcp_close ( struct tcp_connection *tcp, int rc ) {
281 struct io_buffer *iobuf;
282 struct io_buffer *tmp;
284 /* Close data transfer interface */
285 xfer_nullify ( &tcp->xfer );
286 xfer_close ( &tcp->xfer, rc );
287 tcp->flags |= TCP_XFER_CLOSED;
289 /* If we are in CLOSED, or have otherwise not yet received a
290 * SYN (i.e. we are in LISTEN or SYN_SENT), just delete the
291 * connection.
293 if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
295 /* Transition to CLOSED for the sake of debugging messages */
296 tcp->tcp_state = TCP_CLOSED;
297 tcp_dump_state ( tcp );
299 /* Free any unsent I/O buffers */
300 list_for_each_entry_safe ( iobuf, tmp, &tcp->queue, list ) {
301 list_del ( &iobuf->list );
302 free_iob ( iobuf );
305 /* Remove from list and drop reference */
306 stop_timer ( &tcp->timer );
307 list_del ( &tcp->list );
308 ref_put ( &tcp->refcnt );
309 DBGC ( tcp, "TCP %p connection deleted\n", tcp );
310 return;
313 /* If we have not had our SYN acknowledged (i.e. we are in
314 * SYN_RCVD), pretend that it has been acknowledged so that we
315 * can send a FIN without breaking things.
317 if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
318 tcp_rx_ack ( tcp, ( tcp->snd_seq + 1 ), 0 );
320 /* If we have no data remaining to send, start sending FIN */
321 if ( list_empty ( &tcp->queue ) ) {
322 tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
323 tcp_dump_state ( tcp );
327 /***************************************************************************
329 * Transmit data path
331 ***************************************************************************
335 * Calculate transmission window
337 * @v tcp TCP connection
338 * @ret len Maximum length that can be sent in a single packet
340 static size_t tcp_xmit_win ( struct tcp_connection *tcp ) {
341 size_t len;
343 /* Not ready if we're not in a suitable connection state */
344 if ( ! TCP_CAN_SEND_DATA ( tcp->tcp_state ) )
345 return 0;
347 /* Length is the minimum of the receiver's window and the path MTU */
348 len = tcp->snd_win;
349 if ( len > TCP_PATH_MTU )
350 len = TCP_PATH_MTU;
352 return len;
356 * Process TCP transmit queue
358 * @v tcp TCP connection
359 * @v max_len Maximum length to process
360 * @v dest I/O buffer to fill with data, or NULL
361 * @v remove Remove data from queue
362 * @ret len Length of data processed
364 * This processes at most @c max_len bytes from the TCP connection's
365 * transmit queue. Data will be copied into the @c dest I/O buffer
366 * (if provided) and, if @c remove is true, removed from the transmit
367 * queue.
369 static size_t tcp_process_queue ( struct tcp_connection *tcp, size_t max_len,
370 struct io_buffer *dest, int remove ) {
371 struct io_buffer *iobuf;
372 struct io_buffer *tmp;
373 size_t frag_len;
374 size_t len = 0;
376 list_for_each_entry_safe ( iobuf, tmp, &tcp->queue, list ) {
377 frag_len = iob_len ( iobuf );
378 if ( frag_len > max_len )
379 frag_len = max_len;
380 if ( dest ) {
381 memcpy ( iob_put ( dest, frag_len ), iobuf->data,
382 frag_len );
384 if ( remove ) {
385 iob_pull ( iobuf, frag_len );
386 if ( ! iob_len ( iobuf ) ) {
387 list_del ( &iobuf->list );
388 free_iob ( iobuf );
391 len += frag_len;
392 max_len -= frag_len;
394 return len;
398 * Transmit any outstanding data
400 * @v tcp TCP connection
402 * Transmits any outstanding data on the connection.
404 * Note that even if an error is returned, the retransmission timer
405 * will have been started if necessary, and so the stack will
406 * eventually attempt to retransmit the failed packet.
408 static int tcp_xmit ( struct tcp_connection *tcp ) {
409 struct io_buffer *iobuf;
410 struct tcp_header *tcphdr;
411 struct tcp_mss_option *mssopt;
412 struct tcp_timestamp_padded_option *tsopt;
413 void *payload;
414 unsigned int flags;
415 size_t len = 0;
416 uint32_t seq_len;
417 uint32_t app_win;
418 uint32_t max_rcv_win;
419 int rc;
421 /* If retransmission timer is already running, do nothing */
422 if ( timer_running ( &tcp->timer ) )
423 return 0;
425 /* Calculate both the actual (payload) and sequence space
426 * lengths that we wish to transmit.
428 if ( TCP_CAN_SEND_DATA ( tcp->tcp_state ) ) {
429 len = tcp_process_queue ( tcp, tcp_xmit_win ( tcp ),
430 NULL, 0 );
432 seq_len = len;
433 flags = TCP_FLAGS_SENDING ( tcp->tcp_state );
434 if ( flags & ( TCP_SYN | TCP_FIN ) ) {
435 /* SYN or FIN consume one byte, and we can never send both */
436 assert ( ! ( ( flags & TCP_SYN ) && ( flags & TCP_FIN ) ) );
437 seq_len++;
439 tcp->snd_sent = seq_len;
441 /* If we have nothing to transmit, stop now */
442 if ( ( seq_len == 0 ) && ! ( tcp->flags & TCP_ACK_PENDING ) )
443 return 0;
445 /* If we are transmitting anything that requires
446 * acknowledgement (i.e. consumes sequence space), start the
447 * retransmission timer. Do this before attempting to
448 * allocate the I/O buffer, in case allocation itself fails.
450 if ( seq_len )
451 start_timer ( &tcp->timer );
453 /* Allocate I/O buffer */
454 iobuf = alloc_iob ( len + MAX_HDR_LEN );
455 if ( ! iobuf ) {
456 DBGC ( tcp, "TCP %p could not allocate iobuf for %08x..%08x "
457 "%08x\n", tcp, tcp->snd_seq, ( tcp->snd_seq + seq_len ),
458 tcp->rcv_ack );
459 return -ENOMEM;
461 iob_reserve ( iobuf, MAX_HDR_LEN );
463 /* Fill data payload from transmit queue */
464 tcp_process_queue ( tcp, len, iobuf, 0 );
466 /* Expand receive window if possible */
467 max_rcv_win = ( ( freemem * 3 ) / 4 );
468 if ( max_rcv_win > TCP_MAX_WINDOW_SIZE )
469 max_rcv_win = TCP_MAX_WINDOW_SIZE;
470 app_win = xfer_window ( &tcp->xfer );
471 if ( max_rcv_win > app_win )
472 max_rcv_win = app_win;
473 max_rcv_win &= ~0x03; /* Keep everything dword-aligned */
474 if ( tcp->rcv_win < max_rcv_win )
475 tcp->rcv_win = max_rcv_win;
477 /* Fill up the TCP header */
478 payload = iobuf->data;
479 if ( flags & TCP_SYN ) {
480 mssopt = iob_push ( iobuf, sizeof ( *mssopt ) );
481 mssopt->kind = TCP_OPTION_MSS;
482 mssopt->length = sizeof ( *mssopt );
483 mssopt->mss = htons ( TCP_MSS );
485 if ( ( flags & TCP_SYN ) || ( tcp->flags & TCP_TS_ENABLED ) ) {
486 tsopt = iob_push ( iobuf, sizeof ( *tsopt ) );
487 memset ( tsopt->nop, TCP_OPTION_NOP, sizeof ( tsopt->nop ) );
488 tsopt->tsopt.kind = TCP_OPTION_TS;
489 tsopt->tsopt.length = sizeof ( tsopt->tsopt );
490 tsopt->tsopt.tsval = htonl ( currticks() );
491 tsopt->tsopt.tsecr = htonl ( tcp->ts_recent );
493 if ( ! ( flags & TCP_SYN ) )
494 flags |= TCP_PSH;
495 tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
496 memset ( tcphdr, 0, sizeof ( *tcphdr ) );
497 tcphdr->src = htons ( tcp->local_port );
498 tcphdr->dest = tcp->peer.st_port;
499 tcphdr->seq = htonl ( tcp->snd_seq );
500 tcphdr->ack = htonl ( tcp->rcv_ack );
501 tcphdr->hlen = ( ( payload - iobuf->data ) << 2 );
502 tcphdr->flags = flags;
503 tcphdr->win = htons ( tcp->rcv_win );
504 tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
506 /* Dump header */
507 DBGC2 ( tcp, "TCP %p TX %d->%d %08x..%08x %08x %4zd",
508 tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
509 ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) + seq_len ),
510 ntohl ( tcphdr->ack ), len );
511 tcp_dump_flags ( tcp, tcphdr->flags );
512 DBGC2 ( tcp, "\n" );
514 /* Transmit packet */
515 if ( ( rc = tcpip_tx ( iobuf, &tcp_protocol, NULL, &tcp->peer, NULL,
516 &tcphdr->csum ) ) != 0 ) {
517 DBGC ( tcp, "TCP %p could not transmit %08x..%08x %08x: %s\n",
518 tcp, tcp->snd_seq, ( tcp->snd_seq + tcp->snd_sent ),
519 tcp->rcv_ack, strerror ( rc ) );
520 return rc;
523 /* Clear ACK-pending flag */
524 tcp->flags &= ~TCP_ACK_PENDING;
526 return 0;
530 * Retransmission timer expired
532 * @v timer Retransmission timer
533 * @v over Failure indicator
535 static void tcp_expired ( struct retry_timer *timer, int over ) {
536 struct tcp_connection *tcp =
537 container_of ( timer, struct tcp_connection, timer );
539 DBGC ( tcp, "TCP %p timer %s in %s for %08x..%08x %08x\n", tcp,
540 ( over ? "expired" : "fired" ), tcp_state ( tcp->tcp_state ),
541 tcp->snd_seq, ( tcp->snd_seq + tcp->snd_sent ), tcp->rcv_ack );
543 assert ( ( tcp->tcp_state == TCP_SYN_SENT ) ||
544 ( tcp->tcp_state == TCP_SYN_RCVD ) ||
545 ( tcp->tcp_state == TCP_ESTABLISHED ) ||
546 ( tcp->tcp_state == TCP_FIN_WAIT_1 ) ||
547 ( tcp->tcp_state == TCP_CLOSE_WAIT ) ||
548 ( tcp->tcp_state == TCP_CLOSING_OR_LAST_ACK ) );
550 if ( over ) {
551 /* If we have finally timed out and given up,
552 * terminate the connection
554 tcp->tcp_state = TCP_CLOSED;
555 tcp_dump_state ( tcp );
556 tcp_close ( tcp, -ETIMEDOUT );
557 } else {
558 /* Otherwise, retransmit the packet */
559 tcp_xmit ( tcp );
564 * Shutdown timer expired
566 * @v timer Shutdown timer
567 * @v over Failure indicator
569 static void tcp_wait_expired ( struct retry_timer *timer, int over __unused ) {
570 struct tcp_connection *tcp =
571 container_of ( timer, struct tcp_connection, wait );
573 assert ( tcp->tcp_state == TCP_TIME_WAIT );
575 DBGC ( tcp, "TCP %p wait complete in %s for %08x..%08x %08x\n", tcp,
576 tcp_state ( tcp->tcp_state ), tcp->snd_seq,
577 ( tcp->snd_seq + tcp->snd_sent ), tcp->rcv_ack );
579 tcp->tcp_state = TCP_CLOSED;
580 tcp_dump_state ( tcp );
581 tcp_close ( tcp, 0 );
585 * Send RST response to incoming packet
587 * @v in_tcphdr TCP header of incoming packet
588 * @ret rc Return status code
590 static int tcp_xmit_reset ( struct tcp_connection *tcp,
591 struct sockaddr_tcpip *st_dest,
592 struct tcp_header *in_tcphdr ) {
593 struct io_buffer *iobuf;
594 struct tcp_header *tcphdr;
595 int rc;
597 /* Allocate space for dataless TX buffer */
598 iobuf = alloc_iob ( MAX_HDR_LEN );
599 if ( ! iobuf ) {
600 DBGC ( tcp, "TCP %p could not allocate iobuf for RST "
601 "%08x..%08x %08x\n", tcp, ntohl ( in_tcphdr->ack ),
602 ntohl ( in_tcphdr->ack ), ntohl ( in_tcphdr->seq ) );
603 return -ENOMEM;
605 iob_reserve ( iobuf, MAX_HDR_LEN );
607 /* Construct RST response */
608 tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
609 memset ( tcphdr, 0, sizeof ( *tcphdr ) );
610 tcphdr->src = in_tcphdr->dest;
611 tcphdr->dest = in_tcphdr->src;
612 tcphdr->seq = in_tcphdr->ack;
613 tcphdr->ack = in_tcphdr->seq;
614 tcphdr->hlen = ( ( sizeof ( *tcphdr ) / 4 ) << 4 );
615 tcphdr->flags = ( TCP_RST | TCP_ACK );
616 tcphdr->win = htons ( TCP_MAX_WINDOW_SIZE );
617 tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
619 /* Dump header */
620 DBGC2 ( tcp, "TCP %p TX %d->%d %08x..%08x %08x %4d",
621 tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
622 ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) ),
623 ntohl ( tcphdr->ack ), 0 );
624 tcp_dump_flags ( tcp, tcphdr->flags );
625 DBGC2 ( tcp, "\n" );
627 /* Transmit packet */
628 if ( ( rc = tcpip_tx ( iobuf, &tcp_protocol, NULL, st_dest,
629 NULL, &tcphdr->csum ) ) != 0 ) {
630 DBGC ( tcp, "TCP %p could not transmit RST %08x..%08x %08x: "
631 "%s\n", tcp, ntohl ( in_tcphdr->ack ),
632 ntohl ( in_tcphdr->ack ), ntohl ( in_tcphdr->seq ),
633 strerror ( rc ) );
634 return rc;
637 return 0;
640 /***************************************************************************
642 * Receive data path
644 ***************************************************************************
648 * Identify TCP connection by local port number
650 * @v local_port Local port
651 * @ret tcp TCP connection, or NULL
653 static struct tcp_connection * tcp_demux ( unsigned int local_port ) {
654 struct tcp_connection *tcp;
656 list_for_each_entry ( tcp, &tcp_conns, list ) {
657 if ( tcp->local_port == local_port )
658 return tcp;
660 return NULL;
664 * Parse TCP received options
666 * @v tcp TCP connection
667 * @v data Raw options data
668 * @v len Raw options length
669 * @v options Options structure to fill in
671 static void tcp_rx_opts ( struct tcp_connection *tcp, const void *data,
672 size_t len, struct tcp_options *options ) {
673 const void *end = ( data + len );
674 const struct tcp_option *option;
675 unsigned int kind;
677 memset ( options, 0, sizeof ( *options ) );
678 while ( data < end ) {
679 option = data;
680 kind = option->kind;
681 if ( kind == TCP_OPTION_END )
682 return;
683 if ( kind == TCP_OPTION_NOP ) {
684 data++;
685 continue;
687 switch ( kind ) {
688 case TCP_OPTION_MSS:
689 options->mssopt = data;
690 break;
691 case TCP_OPTION_TS:
692 options->tsopt = data;
693 break;
694 default:
695 DBGC ( tcp, "TCP %p received unknown option %d\n",
696 tcp, kind );
697 break;
699 data += option->length;
704 * Consume received sequence space
706 * @v tcp TCP connection
707 * @v seq_len Sequence space length to consume
709 static void tcp_rx_seq ( struct tcp_connection *tcp, uint32_t seq_len ) {
710 tcp->rcv_ack += seq_len;
711 if ( tcp->rcv_win > seq_len ) {
712 tcp->rcv_win -= seq_len;
713 } else {
714 tcp->rcv_win = 0;
716 tcp->flags |= TCP_ACK_PENDING;
720 * Handle TCP received SYN
722 * @v tcp TCP connection
723 * @v seq SEQ value (in host-endian order)
724 * @v options TCP options
725 * @ret rc Return status code
727 static int tcp_rx_syn ( struct tcp_connection *tcp, uint32_t seq,
728 struct tcp_options *options ) {
730 /* Synchronise sequence numbers on first SYN */
731 if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
732 tcp->rcv_ack = seq;
733 if ( options->tsopt )
734 tcp->flags |= TCP_TS_ENABLED;
737 /* Ignore duplicate SYN */
738 if ( ( tcp->rcv_ack - seq ) > 0 )
739 return 0;
741 /* Acknowledge SYN */
742 tcp_rx_seq ( tcp, 1 );
744 /* Mark SYN as received and start sending ACKs with each packet */
745 tcp->tcp_state |= ( TCP_STATE_SENT ( TCP_ACK ) |
746 TCP_STATE_RCVD ( TCP_SYN ) );
748 return 0;
752 * Handle TCP received ACK
754 * @v tcp TCP connection
755 * @v ack ACK value (in host-endian order)
756 * @v win WIN value (in host-endian order)
757 * @ret rc Return status code
759 static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
760 uint32_t win ) {
761 uint32_t ack_len = ( ack - tcp->snd_seq );
762 size_t len;
763 unsigned int acked_flags;
765 /* Check for out-of-range or old duplicate ACKs */
766 if ( ack_len > tcp->snd_sent ) {
767 DBGC ( tcp, "TCP %p received ACK for %08x..%08x, "
768 "sent only %08x..%08x\n", tcp, tcp->snd_seq,
769 ( tcp->snd_seq + ack_len ), tcp->snd_seq,
770 ( tcp->snd_seq + tcp->snd_sent ) );
772 if ( TCP_HAS_BEEN_ESTABLISHED ( tcp->tcp_state ) ) {
773 /* Just ignore what might be old duplicate ACKs */
774 return 0;
775 } else {
776 /* Send RST if an out-of-range ACK is received
777 * on a not-yet-established connection, as per
778 * RFC 793.
780 return -EINVAL;
784 /* Ignore ACKs that don't actually acknowledge any new data.
785 * (In particular, do not stop the retransmission timer; this
786 * avoids creating a sorceror's apprentice syndrome when a
787 * duplicate ACK is received and we still have data in our
788 * transmit queue.)
790 if ( ack_len == 0 )
791 return 0;
793 /* Stop the retransmission timer */
794 stop_timer ( &tcp->timer );
796 /* Determine acknowledged flags and data length */
797 len = ack_len;
798 acked_flags = ( TCP_FLAGS_SENDING ( tcp->tcp_state ) &
799 ( TCP_SYN | TCP_FIN ) );
800 if ( acked_flags )
801 len--;
803 /* Update SEQ and sent counters, and window size */
804 tcp->snd_seq = ack;
805 tcp->snd_sent = 0;
806 tcp->snd_win = win;
808 /* Remove any acknowledged data from transmit queue */
809 tcp_process_queue ( tcp, len, NULL, 1 );
811 /* Mark SYN/FIN as acknowledged if applicable. */
812 if ( acked_flags )
813 tcp->tcp_state |= TCP_STATE_ACKED ( acked_flags );
815 /* Start sending FIN if we've had all possible data ACKed */
816 if ( list_empty ( &tcp->queue ) && ( tcp->flags & TCP_XFER_CLOSED ) )
817 tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
819 return 0;
823 * Handle TCP received data
825 * @v tcp TCP connection
826 * @v seq SEQ value (in host-endian order)
827 * @v iobuf I/O buffer
828 * @ret rc Return status code
830 * This function takes ownership of the I/O buffer.
832 static int tcp_rx_data ( struct tcp_connection *tcp, uint32_t seq,
833 struct io_buffer *iobuf ) {
834 uint32_t already_rcvd;
835 uint32_t len;
836 int rc;
838 /* Ignore duplicate or out-of-order data */
839 already_rcvd = ( tcp->rcv_ack - seq );
840 len = iob_len ( iobuf );
841 if ( already_rcvd >= len ) {
842 free_iob ( iobuf );
843 return 0;
845 iob_pull ( iobuf, already_rcvd );
846 len -= already_rcvd;
848 /* Acknowledge new data */
849 tcp_rx_seq ( tcp, len );
851 /* Deliver data to application */
852 if ( ( rc = xfer_deliver_iob ( &tcp->xfer, iobuf ) ) != 0 ) {
853 DBGC ( tcp, "TCP %p could not deliver %08x..%08x: %s\n",
854 tcp, seq, ( seq + len ), strerror ( rc ) );
855 return rc;
858 return 0;
862 * Handle TCP received FIN
864 * @v tcp TCP connection
865 * @v seq SEQ value (in host-endian order)
866 * @ret rc Return status code
868 static int tcp_rx_fin ( struct tcp_connection *tcp, uint32_t seq ) {
870 /* Ignore duplicate or out-of-order FIN */
871 if ( ( tcp->rcv_ack - seq ) > 0 )
872 return 0;
874 /* Acknowledge FIN */
875 tcp_rx_seq ( tcp, 1 );
877 /* Mark FIN as received */
878 tcp->tcp_state |= TCP_STATE_RCVD ( TCP_FIN );
880 /* Close connection */
881 tcp_close ( tcp, 0 );
883 return 0;
887 * Handle TCP received RST
889 * @v tcp TCP connection
890 * @v seq SEQ value (in host-endian order)
891 * @ret rc Return status code
893 static int tcp_rx_rst ( struct tcp_connection *tcp, uint32_t seq ) {
895 /* Accept RST only if it falls within the window. If we have
896 * not yet received a SYN, then we have no window to test
897 * against, so fall back to checking that our SYN has been
898 * ACKed.
900 if ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) {
901 if ( ( seq - tcp->rcv_ack ) >= tcp->rcv_win )
902 return 0;
903 } else {
904 if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
905 return 0;
908 /* Abort connection */
909 tcp->tcp_state = TCP_CLOSED;
910 tcp_dump_state ( tcp );
911 tcp_close ( tcp, -ECONNRESET );
913 DBGC ( tcp, "TCP %p connection reset by peer\n", tcp );
914 return -ECONNRESET;
918 * Process received packet
920 * @v iobuf I/O buffer
921 * @v st_src Partially-filled source address
922 * @v st_dest Partially-filled destination address
923 * @v pshdr_csum Pseudo-header checksum
924 * @ret rc Return status code
926 static int tcp_rx ( struct io_buffer *iobuf,
927 struct sockaddr_tcpip *st_src,
928 struct sockaddr_tcpip *st_dest __unused,
929 uint16_t pshdr_csum ) {
930 struct tcp_header *tcphdr = iobuf->data;
931 struct tcp_connection *tcp;
932 struct tcp_options options;
933 size_t hlen;
934 uint16_t csum;
935 uint32_t seq;
936 uint32_t ack;
937 uint32_t win;
938 uint32_t ts_recent;
939 unsigned int flags;
940 size_t len;
941 int rc;
943 /* Sanity check packet */
944 if ( iob_len ( iobuf ) < sizeof ( *tcphdr ) ) {
945 DBG ( "TCP packet too short at %zd bytes (min %zd bytes)\n",
946 iob_len ( iobuf ), sizeof ( *tcphdr ) );
947 rc = -EINVAL;
948 goto discard;
950 hlen = ( ( tcphdr->hlen & TCP_MASK_HLEN ) / 16 ) * 4;
951 if ( hlen < sizeof ( *tcphdr ) ) {
952 DBG ( "TCP header too short at %zd bytes (min %zd bytes)\n",
953 hlen, sizeof ( *tcphdr ) );
954 rc = -EINVAL;
955 goto discard;
957 if ( hlen > iob_len ( iobuf ) ) {
958 DBG ( "TCP header too long at %zd bytes (max %zd bytes)\n",
959 hlen, iob_len ( iobuf ) );
960 rc = -EINVAL;
961 goto discard;
963 csum = tcpip_continue_chksum ( pshdr_csum, iobuf->data,
964 iob_len ( iobuf ) );
965 if ( csum != 0 ) {
966 DBG ( "TCP checksum incorrect (is %04x including checksum "
967 "field, should be 0000)\n", csum );
968 rc = -EINVAL;
969 goto discard;
972 /* Parse parameters from header and strip header */
973 tcp = tcp_demux ( ntohs ( tcphdr->dest ) );
974 seq = ntohl ( tcphdr->seq );
975 ack = ntohl ( tcphdr->ack );
976 win = ntohs ( tcphdr->win );
977 flags = tcphdr->flags;
978 tcp_rx_opts ( tcp, ( ( ( void * ) tcphdr ) + sizeof ( *tcphdr ) ),
979 ( hlen - sizeof ( *tcphdr ) ), &options );
980 ts_recent = ( options.tsopt ?
981 ntohl ( options.tsopt->tsval ) : tcp->ts_recent );
982 iob_pull ( iobuf, hlen );
983 len = iob_len ( iobuf );
985 /* Dump header */
986 DBGC2 ( tcp, "TCP %p RX %d<-%d %08x %08x..%08zx %4zd",
987 tcp, ntohs ( tcphdr->dest ), ntohs ( tcphdr->src ),
988 ntohl ( tcphdr->ack ), ntohl ( tcphdr->seq ),
989 ( ntohl ( tcphdr->seq ) + len +
990 ( ( tcphdr->flags & ( TCP_SYN | TCP_FIN ) ) ? 1 : 0 )), len);
991 tcp_dump_flags ( tcp, tcphdr->flags );
992 DBGC2 ( tcp, "\n" );
994 /* If no connection was found, send RST */
995 if ( ! tcp ) {
996 tcp_xmit_reset ( tcp, st_src, tcphdr );
997 rc = -ENOTCONN;
998 goto discard;
1001 /* Handle ACK, if present */
1002 if ( flags & TCP_ACK ) {
1003 if ( ( rc = tcp_rx_ack ( tcp, ack, win ) ) != 0 ) {
1004 tcp_xmit_reset ( tcp, st_src, tcphdr );
1005 goto discard;
1009 /* Force an ACK if this packet is out of order */
1010 if ( ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) &&
1011 ( seq != tcp->rcv_ack ) ) {
1012 tcp->flags |= TCP_ACK_PENDING;
1015 /* Handle SYN, if present */
1016 if ( flags & TCP_SYN ) {
1017 tcp_rx_syn ( tcp, seq, &options );
1018 seq++;
1021 /* Handle RST, if present */
1022 if ( flags & TCP_RST ) {
1023 if ( ( rc = tcp_rx_rst ( tcp, seq ) ) != 0 )
1024 goto discard;
1027 /* Handle new data, if any */
1028 tcp_rx_data ( tcp, seq, iob_disown ( iobuf ) );
1029 seq += len;
1031 /* Handle FIN, if present */
1032 if ( flags & TCP_FIN ) {
1033 tcp_rx_fin ( tcp, seq );
1034 seq++;
1037 /* Update timestamp, if applicable */
1038 if ( seq == tcp->rcv_ack )
1039 tcp->ts_recent = ts_recent;
1041 /* Dump out any state change as a result of the received packet */
1042 tcp_dump_state ( tcp );
1044 /* Send out any pending data */
1045 tcp_xmit ( tcp );
1047 /* If this packet was the last we expect to receive, set up
1048 * timer to expire and cause the connection to be freed.
1050 if ( TCP_CLOSED_GRACEFULLY ( tcp->tcp_state ) ) {
1051 stop_timer ( &tcp->wait );
1052 start_timer_fixed ( &tcp->wait, ( 2 * TCP_MSL ) );
1055 return 0;
1057 discard:
1058 /* Free received packet */
1059 free_iob ( iobuf );
1060 return rc;
1063 /** TCP protocol */
1064 struct tcpip_protocol tcp_protocol __tcpip_protocol = {
1065 .name = "TCP",
1066 .rx = tcp_rx,
1067 .tcpip_proto = IP_TCP,
1070 /***************************************************************************
1072 * Data transfer interface
1074 ***************************************************************************
1078 * Close interface
1080 * @v xfer Data transfer interface
1081 * @v rc Reason for close
1083 static void tcp_xfer_close ( struct xfer_interface *xfer, int rc ) {
1084 struct tcp_connection *tcp =
1085 container_of ( xfer, struct tcp_connection, xfer );
1087 /* Close data transfer interface */
1088 tcp_close ( tcp, rc );
1090 /* Transmit FIN, if possible */
1091 tcp_xmit ( tcp );
1095 * Check flow control window
1097 * @v xfer Data transfer interface
1098 * @ret len Length of window
1100 static size_t tcp_xfer_window ( struct xfer_interface *xfer ) {
1101 struct tcp_connection *tcp =
1102 container_of ( xfer, struct tcp_connection, xfer );
1104 /* Not ready if data queue is non-empty. This imposes a limit
1105 * of only one unACKed packet in the TX queue at any time; we
1106 * do this to conserve memory usage.
1108 if ( ! list_empty ( &tcp->queue ) )
1109 return 0;
1111 /* Return TCP window length */
1112 return tcp_xmit_win ( tcp );
1116 * Deliver datagram as I/O buffer
1118 * @v xfer Data transfer interface
1119 * @v iobuf Datagram I/O buffer
1120 * @v meta Data transfer metadata
1121 * @ret rc Return status code
1123 static int tcp_xfer_deliver_iob ( struct xfer_interface *xfer,
1124 struct io_buffer *iobuf,
1125 struct xfer_metadata *meta __unused ) {
1126 struct tcp_connection *tcp =
1127 container_of ( xfer, struct tcp_connection, xfer );
1129 /* Enqueue packet */
1130 list_add_tail ( &iobuf->list, &tcp->queue );
1132 /* Transmit data, if possible */
1133 tcp_xmit ( tcp );
1135 return 0;
1138 /** TCP data transfer interface operations */
1139 static struct xfer_interface_operations tcp_xfer_operations = {
1140 .close = tcp_xfer_close,
1141 .vredirect = ignore_xfer_vredirect,
1142 .window = tcp_xfer_window,
1143 .alloc_iob = default_xfer_alloc_iob,
1144 .deliver_iob = tcp_xfer_deliver_iob,
1145 .deliver_raw = xfer_deliver_as_iob,
1148 /***************************************************************************
1150 * Openers
1152 ***************************************************************************
1155 /** TCP socket opener */
1156 struct socket_opener tcp_socket_opener __socket_opener = {
1157 .semantics = TCP_SOCK_STREAM,
1158 .family = AF_INET,
1159 .open = tcp_open,
1162 /** Linkage hack */
1163 int tcp_sock_stream = TCP_SOCK_STREAM;
1166 * Open TCP URI
1168 * @v xfer Data transfer interface
1169 * @v uri URI
1170 * @ret rc Return status code
1172 static int tcp_open_uri ( struct xfer_interface *xfer, struct uri *uri ) {
1173 struct sockaddr_tcpip peer;
1175 /* Sanity check */
1176 if ( ! uri->host )
1177 return -EINVAL;
1179 memset ( &peer, 0, sizeof ( peer ) );
1180 peer.st_port = htons ( uri_port ( uri, 0 ) );
1181 return xfer_open_named_socket ( xfer, SOCK_STREAM,
1182 ( struct sockaddr * ) &peer,
1183 uri->host, NULL );
1186 /** TCP URI opener */
1187 struct uri_opener tcp_uri_opener __uri_opener = {
1188 .scheme = "tcp",
1189 .open = tcp_open_uri,