2 * Copyright (c) 2016 Cisco and/or its affiliates.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at:
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
16 #include <vnet/tcp/tcp.h>
17 #include <vnet/session/session.h>
18 #include <vnet/fib/fib.h>
24 tcp_connection_bind (u32 session_index, ip46_address_t * ip,
25 u16 port_host_byte_order, u8 is_ip4)
27 tcp_main_t *tm = &tcp_main;
28 tcp_connection_t *listener;
30 pool_get (tm->listener_pool, listener);
31 memset (listener, 0, sizeof (*listener));
33 listener->c_c_index = listener - tm->listener_pool;
34 listener->c_lcl_port = clib_host_to_net_u16 (port_host_byte_order);
38 listener->c_lcl_ip4.as_u32 = ip->ip4.as_u32;
39 listener->c_is_ip4 = 1;
40 listener->c_proto = SESSION_TYPE_IP4_TCP;
44 clib_memcpy (&listener->c_lcl_ip6, &ip->ip6, sizeof (ip6_address_t));
45 listener->c_proto = SESSION_TYPE_IP6_TCP;
48 listener->c_s_index = session_index;
49 listener->state = TCP_STATE_LISTEN;
51 tcp_connection_timers_init (listener);
53 TCP_EVT_DBG (TCP_EVT_BIND, listener);
55 return listener->c_c_index;
59 tcp_session_bind_ip4 (u32 session_index, ip46_address_t * ip,
60 u16 port_host_byte_order)
62 return tcp_connection_bind (session_index, ip, port_host_byte_order, 1);
66 tcp_session_bind_ip6 (u32 session_index, ip46_address_t * ip,
67 u16 port_host_byte_order)
69 return tcp_connection_bind (session_index, ip, port_host_byte_order, 0);
73 tcp_connection_unbind (u32 listener_index)
75 tcp_main_t *tm = vnet_get_tcp_main ();
76 TCP_EVT_DBG (TCP_EVT_UNBIND,
77 pool_elt_at_index (tm->listener_pool, listener_index));
78 pool_put_index (tm->listener_pool, listener_index);
82 tcp_session_unbind (u32 listener_index)
84 tcp_connection_unbind (listener_index);
88 transport_connection_t *
89 tcp_session_get_listener (u32 listener_index)
91 tcp_main_t *tm = vnet_get_tcp_main ();
93 tc = pool_elt_at_index (tm->listener_pool, listener_index);
94 return &tc->connection;
98 * Cleans up connection state.
103 tcp_connection_cleanup (tcp_connection_t * tc)
105 tcp_main_t *tm = &tcp_main;
107 transport_endpoint_t *tep;
109 /* Cleanup local endpoint if this was an active connect */
110 tepi = transport_endpoint_lookup (&tm->local_endpoints_table, &tc->c_lcl_ip,
114 if (tepi != TRANSPORT_ENDPOINT_INVALID_INDEX)
116 tep = pool_elt_at_index (tm->local_endpoints, tepi);
117 transport_endpoint_table_del (&tm->local_endpoints_table, tep);
118 pool_put (tm->local_endpoints, tep);
121 /* Make sure all timers are cleared */
122 tcp_connection_timers_reset (tc);
124 /* Check if half-open */
125 if (tc->state == TCP_STATE_SYN_SENT)
126 pool_put (tm->half_open_connections, tc);
128 pool_put (tm->connections[tc->c_thread_index], tc);
132 * Connection removal.
134 * This should be called only once connection enters CLOSED state. Note
135 * that it notifies the session of the removal event, so if the goal is to
136 * just remove the connection, call tcp_connection_cleanup instead.
139 tcp_connection_del (tcp_connection_t * tc)
141 TCP_EVT_DBG (TCP_EVT_DELETE, tc);
142 stream_session_delete_notify (&tc->connection);
143 tcp_connection_cleanup (tc);
146 /** Notify session that connection has been reset.
148 * Switch state to closed and wait for session to call cleanup.
151 tcp_connection_reset (tcp_connection_t * tc)
153 if (tc->state == TCP_STATE_CLOSED)
156 tc->state = TCP_STATE_CLOSED;
157 stream_session_reset_notify (&tc->connection);
161 * Begin connection closing procedure.
163 * If at the end the connection is not in CLOSED state, it is not removed.
164 * Instead, we rely on on TCP to advance through state machine to either
165 * 1) LAST_ACK (passive close) whereby when the last ACK is received
166 * tcp_connection_del is called. This notifies session of the delete and
168 * 2) TIME_WAIT (active close) whereby after 2MSL the 2MSL timer triggers
169 * and cleanup is called.
171 * N.B. Half-close connections are not supported
174 tcp_connection_close (tcp_connection_t * tc)
176 TCP_EVT_DBG (TCP_EVT_CLOSE, tc);
178 /* Send FIN if needed */
179 if (tc->state == TCP_STATE_ESTABLISHED || tc->state == TCP_STATE_SYN_RCVD
180 || tc->state == TCP_STATE_CLOSE_WAIT)
184 if (tc->state == TCP_STATE_ESTABLISHED || tc->state == TCP_STATE_SYN_RCVD)
185 tc->state = TCP_STATE_FIN_WAIT_1;
186 else if (tc->state == TCP_STATE_SYN_SENT)
187 tc->state = TCP_STATE_CLOSED;
188 else if (tc->state == TCP_STATE_CLOSE_WAIT)
189 tc->state = TCP_STATE_LAST_ACK;
191 /* If in CLOSED and WAITCLOSE timer is not set, delete connection now */
192 if (tc->timers[TCP_TIMER_WAITCLOSE] == TCP_TIMER_HANDLE_INVALID
193 && tc->state == TCP_STATE_CLOSED)
194 tcp_connection_del (tc);
198 tcp_session_close (u32 conn_index, u32 thread_index)
200 tcp_connection_t *tc;
201 tc = tcp_connection_get (conn_index, thread_index);
202 tcp_connection_close (tc);
206 tcp_session_cleanup (u32 conn_index, u32 thread_index)
208 tcp_connection_t *tc;
209 tc = tcp_connection_get (conn_index, thread_index);
211 /* Wait for the session tx events to clear */
212 tc->state = TCP_STATE_CLOSED;
213 tcp_timer_update (tc, TCP_TIMER_WAITCLOSE, TCP_CLEANUP_TIME);
217 ip_interface_get_first_ip (u32 sw_if_index, u8 is_ip4)
219 ip_lookup_main_t *lm4 = &ip4_main.lookup_main;
220 ip_lookup_main_t *lm6 = &ip6_main.lookup_main;
221 ip_interface_address_t *ia = 0;
226 foreach_ip_interface_address (lm4, ia, sw_if_index, 1 /* unnumbered */ ,
228 return ip_interface_address_get_address (lm4, ia);
235 foreach_ip_interface_address (lm6, ia, sw_if_index, 1 /* unnumbered */ ,
237 return ip_interface_address_get_address (lm6, ia);
245 #define PORT_MASK ((1 << 16)- 1)
247 * Allocate local port and add if successful add entry to local endpoint
248 * table to mark the pair as used.
251 tcp_allocate_local_port (tcp_main_t * tm, ip46_address_t * ip)
253 transport_endpoint_t *tep;
255 u16 min = 1024, max = 65535; /* XXX configurable ? */
259 time_now = tcp_time_now ();
261 /* Start at random point or max */
262 pool_get (tm->local_endpoints, tep);
263 clib_memcpy (&tep->ip, ip, sizeof (*ip));
265 /* Search for first free slot */
266 for (; tries >= 0; tries--)
270 /* Find a port in the specified range */
273 port = random_u32 (&time_now) & PORT_MASK;
274 if (PREDICT_TRUE (port >= min && port < max))
281 tei = transport_endpoint_lookup (&tm->local_endpoints_table, &tep->ip,
283 /* If not found, we're done */
284 if (tei == TRANSPORT_ENDPOINT_INVALID_INDEX)
286 transport_endpoint_table_add (&tm->local_endpoints_table, tep,
287 tep - tm->local_endpoints);
292 pool_put (tm->local_endpoints, tep);
297 * Initialize all connection timers as invalid
300 tcp_connection_timers_init (tcp_connection_t * tc)
304 /* Set all to invalid */
305 for (i = 0; i < TCP_N_TIMERS; i++)
307 tc->timers[i] = TCP_TIMER_HANDLE_INVALID;
310 tc->rto = TCP_RTO_INIT;
314 * Stop all connection timers
317 tcp_connection_timers_reset (tcp_connection_t * tc)
320 for (i = 0; i < TCP_N_TIMERS; i++)
322 tcp_timer_reset (tc, i);
326 /** Initialize tcp connection variables
328 * Should be called after having received a msg from the peer, i.e., a SYN or
329 * a SYNACK, such that connection options have already been exchanged. */
331 tcp_connection_init_vars (tcp_connection_t * tc)
333 tcp_connection_timers_init (tc);
334 tcp_set_snd_mss (tc);
335 scoreboard_init (&tc->sack_sb);
340 tcp_connection_open (ip46_address_t * rmt_addr, u16 rmt_port, u8 is_ip4)
342 tcp_main_t *tm = vnet_get_tcp_main ();
343 tcp_connection_t *tc;
345 u32 fei, sw_if_index;
346 ip46_address_t lcl_addr;
350 * Find the local address and allocate port
352 memset (&lcl_addr, 0, sizeof (lcl_addr));
354 /* Find a FIB path to the destination */
355 clib_memcpy (&prefix.fp_addr, rmt_addr, sizeof (*rmt_addr));
356 prefix.fp_proto = is_ip4 ? FIB_PROTOCOL_IP4 : FIB_PROTOCOL_IP6;
357 prefix.fp_len = is_ip4 ? 32 : 128;
359 fei = fib_table_lookup (0, &prefix);
361 /* Couldn't find route to destination. Bail out. */
362 if (fei == FIB_NODE_INDEX_INVALID)
365 sw_if_index = fib_entry_get_resolving_interface (fei);
367 if (sw_if_index == (u32) ~ 0)
373 ip4 = ip_interface_get_first_ip (sw_if_index, 1);
374 lcl_addr.ip4.as_u32 = ip4->as_u32;
379 ip6 = ip_interface_get_first_ip (sw_if_index, 0);
380 clib_memcpy (&lcl_addr.ip6, ip6, sizeof (*ip6));
383 /* Allocate source port */
384 lcl_port = tcp_allocate_local_port (tm, &lcl_addr);
387 clib_warning ("Failed to allocate src port");
392 * Create connection and send SYN
395 pool_get (tm->half_open_connections, tc);
396 memset (tc, 0, sizeof (*tc));
398 clib_memcpy (&tc->c_rmt_ip, rmt_addr, sizeof (ip46_address_t));
399 clib_memcpy (&tc->c_lcl_ip, &lcl_addr, sizeof (ip46_address_t));
400 tc->c_rmt_port = clib_host_to_net_u16 (rmt_port);
401 tc->c_lcl_port = clib_host_to_net_u16 (lcl_port);
402 tc->c_c_index = tc - tm->half_open_connections;
403 tc->c_is_ip4 = is_ip4;
404 tc->c_proto = is_ip4 ? SESSION_TYPE_IP4_TCP : SESSION_TYPE_IP6_TCP;
406 /* The other connection vars will be initialized after SYN ACK */
407 tcp_connection_timers_init (tc);
411 tc->state = TCP_STATE_SYN_SENT;
413 TCP_EVT_DBG (TCP_EVT_OPEN, tc);
415 return tc->c_c_index;
419 tcp_session_open_ip4 (ip46_address_t * addr, u16 port)
421 return tcp_connection_open (addr, port, 1);
425 tcp_session_open_ip6 (ip46_address_t * addr, u16 port)
427 return tcp_connection_open (addr, port, 0);
430 const char *tcp_dbg_evt_str[] = {
431 #define _(sym, str) str,
436 const char *tcp_fsm_states[] = {
437 #define _(sym, str) str,
438 foreach_tcp_fsm_state
443 format_tcp_state (u8 * s, va_list * args)
445 tcp_state_t *state = va_arg (*args, tcp_state_t *);
447 if (*state < TCP_N_STATES)
448 s = format (s, "%s", tcp_fsm_states[*state]);
450 s = format (s, "UNKNOWN");
455 const char *tcp_conn_timers[] = {
456 #define _(sym, str) str,
462 format_tcp_timers (u8 * s, va_list * args)
464 tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
467 for (i = 0; i < TCP_N_TIMERS; i++)
468 if (tc->timers[i] != TCP_TIMER_HANDLE_INVALID)
472 for (i = 0; i < last; i++)
474 if (tc->timers[i] != TCP_TIMER_HANDLE_INVALID)
475 s = format (s, "%s,", tcp_conn_timers[i]);
479 s = format (s, "%s]", tcp_conn_timers[i]);
487 format_tcp_connection (u8 * s, va_list * args)
489 tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
493 s = format (s, "[#%d][%s] %U:%d->%U:%d", tc->c_thread_index, "T",
494 format_ip4_address, &tc->c_lcl_ip4,
495 clib_net_to_host_u16 (tc->c_lcl_port), format_ip4_address,
496 &tc->c_rmt_ip4, clib_net_to_host_u16 (tc->c_rmt_port));
500 s = format (s, "[#%d][%s] %U:%d->%U:%d", tc->c_thread_index, "T",
501 format_ip6_address, &tc->c_lcl_ip6,
502 clib_net_to_host_u16 (tc->c_lcl_port), format_ip6_address,
503 &tc->c_rmt_ip6, clib_net_to_host_u16 (tc->c_rmt_port));
510 format_tcp_connection_verbose (u8 * s, va_list * args)
512 tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
513 s = format (s, "%U %U %U", format_tcp_connection, tc, format_tcp_state,
514 &tc->state, format_tcp_timers, tc);
519 format_tcp_session (u8 * s, va_list * args)
521 u32 tci = va_arg (*args, u32);
522 u32 thread_index = va_arg (*args, u32);
523 tcp_connection_t *tc;
525 tc = tcp_connection_get (tci, thread_index);
527 return format (s, "%U", format_tcp_connection, tc);
529 return format (s, "empty");
533 format_tcp_listener_session (u8 * s, va_list * args)
535 u32 tci = va_arg (*args, u32);
536 tcp_connection_t *tc = tcp_listener_get (tci);
537 return format (s, "%U", format_tcp_connection, tc);
541 format_tcp_half_open_session (u8 * s, va_list * args)
543 u32 tci = va_arg (*args, u32);
544 tcp_connection_t *tc = tcp_half_open_connection_get (tci);
545 return format (s, "%U", format_tcp_connection, tc);
548 transport_connection_t *
549 tcp_session_get_transport (u32 conn_index, u32 thread_index)
551 tcp_connection_t *tc = tcp_connection_get (conn_index, thread_index);
552 return &tc->connection;
555 transport_connection_t *
556 tcp_half_open_session_get_transport (u32 conn_index)
558 tcp_connection_t *tc = tcp_half_open_connection_get (conn_index);
559 return &tc->connection;
563 tcp_session_send_mss (transport_connection_t * trans_conn)
565 tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
570 * Compute tx window session is allowed to fill.
573 tcp_session_send_space (transport_connection_t * trans_conn)
576 tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
578 /* If we haven't gotten dupacks or if we did and have gotten sacked bytes
579 * then we can still send */
580 if (PREDICT_TRUE (tcp_in_fastrecovery (tc) == 0
581 && (tc->rcv_dupacks == 0
582 || tc->sack_sb.last_sacked_bytes)))
584 snd_space = tcp_available_snd_space (tc);
586 /* If we can't write at least a segment, don't try at all */
587 if (snd_space < tc->snd_mss)
590 /* round down to mss multiple */
591 return snd_space - (snd_space % tc->snd_mss);
594 /* If in fast recovery, send 1 SMSS if wnd allows */
595 if (tcp_in_fastrecovery (tc) && tcp_available_snd_space (tc)
596 && tcp_fastrecovery_sent_1_smss (tc))
598 tcp_fastrecovery_1_smss_on (tc);
606 tcp_session_tx_fifo_offset (transport_connection_t * trans_conn)
608 tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
610 ASSERT (seq_geq (tc->snd_nxt, tc->snd_una));
612 /* This still works if fast retransmit is on */
613 return (tc->snd_nxt - tc->snd_una);
617 const static transport_proto_vft_t tcp4_proto = {
618 .bind = tcp_session_bind_ip4,
619 .unbind = tcp_session_unbind,
620 .push_header = tcp_push_header,
621 .get_connection = tcp_session_get_transport,
622 .get_listener = tcp_session_get_listener,
623 .get_half_open = tcp_half_open_session_get_transport,
624 .open = tcp_session_open_ip4,
625 .close = tcp_session_close,
626 .cleanup = tcp_session_cleanup,
627 .send_mss = tcp_session_send_mss,
628 .send_space = tcp_session_send_space,
629 .tx_fifo_offset = tcp_session_tx_fifo_offset,
630 .format_connection = format_tcp_session,
631 .format_listener = format_tcp_listener_session,
632 .format_half_open = format_tcp_half_open_session,
635 const static transport_proto_vft_t tcp6_proto = {
636 .bind = tcp_session_bind_ip6,
637 .unbind = tcp_session_unbind,
638 .push_header = tcp_push_header,
639 .get_connection = tcp_session_get_transport,
640 .get_listener = tcp_session_get_listener,
641 .get_half_open = tcp_half_open_session_get_transport,
642 .open = tcp_session_open_ip6,
643 .close = tcp_session_close,
644 .cleanup = tcp_session_cleanup,
645 .send_mss = tcp_session_send_mss,
646 .send_space = tcp_session_send_space,
647 .tx_fifo_offset = tcp_session_tx_fifo_offset,
648 .format_connection = format_tcp_session,
649 .format_listener = format_tcp_listener_session,
650 .format_half_open = format_tcp_half_open_session,
655 tcp_timer_keep_handler (u32 conn_index)
657 u32 thread_index = vlib_get_thread_index ();
658 tcp_connection_t *tc;
660 tc = tcp_connection_get (conn_index, thread_index);
661 tc->timers[TCP_TIMER_KEEP] = TCP_TIMER_HANDLE_INVALID;
663 tcp_connection_close (tc);
667 tcp_timer_establish_handler (u32 conn_index)
669 tcp_connection_t *tc;
672 tc = tcp_half_open_connection_get (conn_index);
673 tc->timers[TCP_TIMER_ESTABLISH] = TCP_TIMER_HANDLE_INVALID;
675 ASSERT (tc->state == TCP_STATE_SYN_SENT);
677 sst = tc->c_is_ip4 ? SESSION_TYPE_IP4_TCP : SESSION_TYPE_IP6_TCP;
678 stream_session_connect_notify (&tc->connection, sst, 1 /* fail */ );
680 tcp_connection_cleanup (tc);
684 tcp_timer_waitclose_handler (u32 conn_index)
686 u32 thread_index = vlib_get_thread_index ();
687 tcp_connection_t *tc;
689 tc = tcp_connection_get (conn_index, thread_index);
690 tc->timers[TCP_TIMER_WAITCLOSE] = TCP_TIMER_HANDLE_INVALID;
692 /* Session didn't come back with a close(). Send FIN either way
693 * and switch to LAST_ACK. */
694 if (tc->state == TCP_STATE_CLOSE_WAIT)
696 if (tc->flags & TCP_CONN_FINSNT)
698 clib_warning ("FIN was sent and still in CLOSE WAIT. Weird!");
702 tc->state = TCP_STATE_LAST_ACK;
704 /* Make sure we don't wait in LAST ACK forever */
705 tcp_timer_set (tc, TCP_TIMER_WAITCLOSE, TCP_2MSL_TIME);
707 /* Don't delete the connection yet */
711 tcp_connection_del (tc);
715 static timer_expiration_handler *timer_expiration_handlers[TCP_N_TIMERS] =
717 tcp_timer_retransmit_handler,
718 tcp_timer_delack_handler,
719 tcp_timer_persist_handler,
720 tcp_timer_keep_handler,
721 tcp_timer_waitclose_handler,
722 tcp_timer_retransmit_syn_handler,
723 tcp_timer_establish_handler
728 tcp_expired_timers_dispatch (u32 * expired_timers)
731 u32 connection_index, timer_id;
733 for (i = 0; i < vec_len (expired_timers); i++)
735 /* Get session index and timer id */
736 connection_index = expired_timers[i] & 0x0FFFFFFF;
737 timer_id = expired_timers[i] >> 28;
739 TCP_EVT_DBG (TCP_EVT_TIMER_POP, connection_index, timer_id);
741 /* Handle expiration */
742 (*timer_expiration_handlers[timer_id]) (connection_index);
747 tcp_initialize_timer_wheels (tcp_main_t * tm)
749 tw_timer_wheel_16t_2w_512sl_t *tw;
750 vec_foreach (tw, tm->timer_wheels)
752 tw_timer_wheel_init_16t_2w_512sl (tw, tcp_expired_timers_dispatch,
753 100e-3 /* timer period 100ms */ , ~0);
754 tw->last_run_time = vlib_time_now (tm->vlib_main);
759 tcp_main_enable (vlib_main_t * vm)
761 tcp_main_t *tm = vnet_get_tcp_main ();
762 ip_protocol_info_t *pi;
763 ip_main_t *im = &ip_main;
764 vlib_thread_main_t *vtm = vlib_get_thread_main ();
765 clib_error_t *error = 0;
768 if ((error = vlib_call_init_function (vm, ip_main_init)))
770 if ((error = vlib_call_init_function (vm, ip4_lookup_init)))
772 if ((error = vlib_call_init_function (vm, ip6_lookup_init)))
779 /* Register with IP */
780 pi = ip_get_protocol_info (im, IP_PROTOCOL_TCP);
782 return clib_error_return (0, "TCP protocol info AWOL");
783 pi->format_header = format_tcp_header;
784 pi->unformat_pg_edit = unformat_pg_tcp_header;
786 ip4_register_protocol (IP_PROTOCOL_TCP, tcp4_input_node.index);
788 /* Register as transport with URI */
789 session_register_transport (SESSION_TYPE_IP4_TCP, &tcp4_proto);
790 session_register_transport (SESSION_TYPE_IP6_TCP, &tcp6_proto);
793 * Initialize data structures
796 num_threads = 1 /* main thread */ + vtm->n_threads;
797 vec_validate (tm->connections, num_threads - 1);
799 /* Initialize per worker thread tx buffers (used for control messages) */
800 vec_validate (tm->tx_buffers, num_threads - 1);
802 /* Initialize timer wheels */
803 vec_validate (tm->timer_wheels, num_threads - 1);
804 tcp_initialize_timer_wheels (tm);
806 // vec_validate (tm->delack_connections, num_threads - 1);
808 /* Initialize clocks per tick for TCP timestamp. Used to compute
809 * monotonically increasing timestamps. */
810 tm->tstamp_ticks_per_clock = vm->clib_time.seconds_per_clock
811 / TCP_TSTAMP_RESOLUTION;
813 clib_bihash_init_24_8 (&tm->local_endpoints_table, "local endpoint table",
814 200000 /* $$$$ config parameter nbuckets */ ,
815 (64 << 20) /*$$$ config parameter table size */ );
821 vnet_tcp_enable_disable (vlib_main_t * vm, u8 is_en)
825 if (tcp_main.is_enabled)
828 return tcp_main_enable (vm);
832 tcp_main.is_enabled = 0;
839 tcp_init (vlib_main_t * vm)
841 tcp_main_t *tm = vnet_get_tcp_main ();
844 tm->vnet_main = vnet_get_main ();
850 VLIB_INIT_FUNCTION (tcp_init);
853 * fd.io coding-style-patch-verification: ON
856 * eval: (c-set-style "gnu")