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>
19 #include <vnet/dpo/load_balance.h>
25 tcp_connection_bind (u32 session_index, transport_endpoint_t * lcl)
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 (lcl->port);
38 listener->c_lcl_ip4.as_u32 = lcl->ip.ip4.as_u32;
39 listener->c_is_ip4 = 1;
43 clib_memcpy (&listener->c_lcl_ip6, &lcl->ip.ip6,
44 sizeof (ip6_address_t));
47 listener->c_transport_proto = TRANSPORT_PROTO_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 (u32 session_index, transport_endpoint_t * tep)
61 return tcp_connection_bind (session_index, tep);
65 tcp_connection_unbind (u32 listener_index)
67 tcp_main_t *tm = vnet_get_tcp_main ();
70 tc = pool_elt_at_index (tm->listener_pool, listener_index);
72 TCP_EVT_DBG (TCP_EVT_UNBIND, tc);
74 /* Poison the entry */
76 memset (tc, 0xFA, sizeof (*tc));
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 transport_endpoint_del (u32 tepi)
100 tcp_main_t *tm = vnet_get_tcp_main ();
101 clib_spinlock_lock_if_init (&tm->local_endpoints_lock);
102 pool_put_index (tm->local_endpoints, tepi);
103 clib_spinlock_unlock_if_init (&tm->local_endpoints_lock);
106 always_inline transport_endpoint_t *
107 transport_endpoint_new (void)
109 tcp_main_t *tm = vnet_get_tcp_main ();
110 transport_endpoint_t *tep;
111 pool_get (tm->local_endpoints, tep);
116 * Cleanup half-open connection
120 tcp_half_open_connection_del (tcp_connection_t * tc)
122 tcp_main_t *tm = vnet_get_tcp_main ();
123 clib_spinlock_lock_if_init (&tm->half_open_lock);
124 pool_put_index (tm->half_open_connections, tc->c_c_index);
126 memset (tc, 0xFA, sizeof (*tc));
127 clib_spinlock_unlock_if_init (&tm->half_open_lock);
131 * Try to cleanup half-open connection
133 * If called from a thread that doesn't own tc, the call won't have any
136 * @param tc - connection to be cleaned up
137 * @return non-zero if cleanup failed.
140 tcp_half_open_connection_cleanup (tcp_connection_t * tc)
142 /* Make sure this is the owning thread */
143 if (tc->c_thread_index != vlib_get_thread_index ())
145 tcp_timer_reset (tc, TCP_TIMER_ESTABLISH);
146 tcp_timer_reset (tc, TCP_TIMER_RETRANSMIT_SYN);
147 tcp_half_open_connection_del (tc);
152 tcp_half_open_connection_new (void)
154 tcp_main_t *tm = vnet_get_tcp_main ();
155 tcp_connection_t *tc = 0;
156 pool_get (tm->half_open_connections, tc);
157 memset (tc, 0, sizeof (*tc));
158 tc->c_c_index = tc - tm->half_open_connections;
163 * Cleans up connection state.
168 tcp_connection_cleanup (tcp_connection_t * tc)
170 tcp_main_t *tm = &tcp_main;
172 transport_endpoint_t *tep;
174 /* Cleanup local endpoint if this was an active connect */
175 tepi = transport_endpoint_lookup (&tm->local_endpoints_table, &tc->c_lcl_ip,
176 clib_net_to_host_u16 (tc->c_lcl_port));
177 if (tepi != TRANSPORT_ENDPOINT_INVALID_INDEX)
179 tep = pool_elt_at_index (tm->local_endpoints, tepi);
180 transport_endpoint_table_del (&tm->local_endpoints_table, tep);
181 transport_endpoint_del (tepi);
184 /* Check if connection is not yet fully established */
185 if (tc->state == TCP_STATE_SYN_SENT)
187 /* Try to remove the half-open connection. If this is not the owning
188 * thread, tc won't be removed. Retransmit or establish timers will
189 * eventually expire and call again cleanup on the right thread. */
190 tcp_half_open_connection_cleanup (tc);
194 int thread_index = tc->c_thread_index;
196 /* Make sure all timers are cleared */
197 tcp_connection_timers_reset (tc);
199 /* Poison the entry */
201 memset (tc, 0xFA, sizeof (*tc));
202 pool_put (tm->connections[thread_index], tc);
207 * Connection removal.
209 * This should be called only once connection enters CLOSED state. Note
210 * that it notifies the session of the removal event, so if the goal is to
211 * just remove the connection, call tcp_connection_cleanup instead.
214 tcp_connection_del (tcp_connection_t * tc)
216 TCP_EVT_DBG (TCP_EVT_DELETE, tc);
217 stream_session_delete_notify (&tc->connection);
218 tcp_connection_cleanup (tc);
222 tcp_connection_new (u8 thread_index)
224 tcp_main_t *tm = vnet_get_tcp_main ();
225 tcp_connection_t *tc;
227 pool_get (tm->connections[thread_index], tc);
228 memset (tc, 0, sizeof (*tc));
229 tc->c_c_index = tc - tm->connections[thread_index];
230 tc->c_thread_index = thread_index;
234 /** Notify session that connection has been reset.
236 * Switch state to closed and wait for session to call cleanup.
239 tcp_connection_reset (tcp_connection_t * tc)
241 TCP_EVT_DBG (TCP_EVT_RST_RCVD, tc);
244 case TCP_STATE_SYN_RCVD:
245 /* Cleanup everything. App wasn't notified yet */
246 stream_session_delete_notify (&tc->connection);
247 tcp_connection_cleanup (tc);
249 case TCP_STATE_SYN_SENT:
250 stream_session_connect_notify (&tc->connection, 1 /* fail */ );
251 tcp_connection_cleanup (tc);
253 case TCP_STATE_ESTABLISHED:
254 case TCP_STATE_CLOSE_WAIT:
255 case TCP_STATE_FIN_WAIT_1:
256 case TCP_STATE_FIN_WAIT_2:
257 case TCP_STATE_CLOSING:
258 tc->state = TCP_STATE_CLOSED;
259 TCP_EVT_DBG (TCP_EVT_STATE_CHANGE, tc);
261 /* Make sure all timers are cleared */
262 tcp_connection_timers_reset (tc);
263 stream_session_reset_notify (&tc->connection);
265 /* Wait for cleanup from session layer but not forever */
266 tcp_timer_update (tc, TCP_TIMER_WAITCLOSE, TCP_CLEANUP_TIME);
268 case TCP_STATE_CLOSED:
274 * Begin connection closing procedure.
276 * If at the end the connection is not in CLOSED state, it is not removed.
277 * Instead, we rely on on TCP to advance through state machine to either
278 * 1) LAST_ACK (passive close) whereby when the last ACK is received
279 * tcp_connection_del is called. This notifies session of the delete and
281 * 2) TIME_WAIT (active close) whereby after 2MSL the 2MSL timer triggers
282 * and cleanup is called.
284 * N.B. Half-close connections are not supported
287 tcp_connection_close (tcp_connection_t * tc)
289 TCP_EVT_DBG (TCP_EVT_CLOSE, tc);
291 /* Send/Program FIN if needed and switch state */
294 case TCP_STATE_SYN_SENT:
295 tc->state = TCP_STATE_CLOSED;
297 case TCP_STATE_SYN_RCVD:
299 tc->state = TCP_STATE_FIN_WAIT_1;
301 case TCP_STATE_ESTABLISHED:
302 if (!stream_session_tx_fifo_max_dequeue (&tc->connection))
305 tc->flags |= TCP_CONN_FINPNDG;
306 tc->state = TCP_STATE_FIN_WAIT_1;
308 case TCP_STATE_CLOSE_WAIT:
310 tc->state = TCP_STATE_LAST_ACK;
313 clib_warning ("shouldn't be here");
316 TCP_EVT_DBG (TCP_EVT_STATE_CHANGE, tc);
318 /* If in CLOSED and WAITCLOSE timer is not set, delete connection now */
319 if (tc->timers[TCP_TIMER_WAITCLOSE] == TCP_TIMER_HANDLE_INVALID
320 && tc->state == TCP_STATE_CLOSED)
321 tcp_connection_del (tc);
325 tcp_session_close (u32 conn_index, u32 thread_index)
327 tcp_connection_t *tc;
328 tc = tcp_connection_get (conn_index, thread_index);
329 tcp_connection_close (tc);
333 tcp_session_cleanup (u32 conn_index, u32 thread_index)
335 tcp_connection_t *tc;
336 tc = tcp_connection_get (conn_index, thread_index);
338 /* Wait for the session tx events to clear */
339 tc->state = TCP_STATE_CLOSED;
340 TCP_EVT_DBG (TCP_EVT_STATE_CHANGE, tc);
341 tcp_timer_update (tc, TCP_TIMER_WAITCLOSE, TCP_CLEANUP_TIME);
345 ip_interface_get_first_ip (u32 sw_if_index, u8 is_ip4)
347 ip_lookup_main_t *lm4 = &ip4_main.lookup_main;
348 ip_lookup_main_t *lm6 = &ip6_main.lookup_main;
349 ip_interface_address_t *ia = 0;
354 foreach_ip_interface_address (lm4, ia, sw_if_index, 1 /* unnumbered */ ,
356 return ip_interface_address_get_address (lm4, ia);
363 foreach_ip_interface_address (lm6, ia, sw_if_index, 1 /* unnumbered */ ,
365 return ip_interface_address_get_address (lm6, ia);
373 #define PORT_MASK ((1 << 16)- 1)
375 * Allocate local port and add if successful add entry to local endpoint
376 * table to mark the pair as used.
379 tcp_allocate_local_port (ip46_address_t * ip)
381 tcp_main_t *tm = vnet_get_tcp_main ();
382 transport_endpoint_t *tep;
384 u16 min = 1024, max = 65535; /* XXX configurable ? */
389 /* Only support active opens from thread 0 */
390 ASSERT (vlib_get_thread_index () == 0);
392 /* Search for first free slot */
393 for (tries = 0; tries < limit; tries++)
397 /* Find a port in the specified range */
400 port = random_u32 (&tm->port_allocator_seed) & PORT_MASK;
401 if (PREDICT_TRUE (port >= min && port < max))
406 tei = transport_endpoint_lookup (&tm->local_endpoints_table, ip, port);
407 /* If not found, we're done */
408 if (tei == TRANSPORT_ENDPOINT_INVALID_INDEX)
410 clib_spinlock_lock_if_init (&tm->local_endpoints_lock);
411 tep = transport_endpoint_new ();
412 clib_memcpy (&tep->ip, ip, sizeof (*ip));
414 transport_endpoint_table_add (&tm->local_endpoints_table, tep,
415 tep - tm->local_endpoints);
416 clib_spinlock_unlock_if_init (&tm->local_endpoints_lock);
425 * Initialize all connection timers as invalid
428 tcp_connection_timers_init (tcp_connection_t * tc)
432 /* Set all to invalid */
433 for (i = 0; i < TCP_N_TIMERS; i++)
435 tc->timers[i] = TCP_TIMER_HANDLE_INVALID;
438 tc->rto = TCP_RTO_INIT;
442 * Stop all connection timers
445 tcp_connection_timers_reset (tcp_connection_t * tc)
448 for (i = 0; i < TCP_N_TIMERS; i++)
450 tcp_timer_reset (tc, i);
455 typedef struct ip4_tcp_hdr
461 typedef struct ip6_tcp_hdr
468 tcp_connection_select_lb_bucket (tcp_connection_t * tc, const dpo_id_t * dpo,
471 const dpo_id_t *choice;
475 lb = load_balance_get (dpo->dpoi_index);
479 memset (&hdr, 0, sizeof (hdr));
480 hdr.ip.protocol = IP_PROTOCOL_TCP;
481 hdr.ip.address_pair.src.as_u32 = tc->c_lcl_ip.ip4.as_u32;
482 hdr.ip.address_pair.dst.as_u32 = tc->c_rmt_ip.ip4.as_u32;
483 hdr.tcp.src_port = tc->c_lcl_port;
484 hdr.tcp.dst_port = tc->c_rmt_port;
485 hash = ip4_compute_flow_hash (&hdr.ip, lb->lb_hash_config);
490 memset (&hdr, 0, sizeof (hdr));
491 hdr.ip.protocol = IP_PROTOCOL_TCP;
492 clib_memcpy (&hdr.ip.src_address, &tc->c_lcl_ip.ip6,
493 sizeof (ip6_address_t));
494 clib_memcpy (&hdr.ip.dst_address, &tc->c_rmt_ip.ip6,
495 sizeof (ip6_address_t));
496 hdr.tcp.src_port = tc->c_lcl_port;
497 hdr.tcp.dst_port = tc->c_rmt_port;
498 hash = ip6_compute_flow_hash (&hdr.ip, lb->lb_hash_config);
500 choice = load_balance_get_bucket_i (lb, hash & lb->lb_n_buckets_minus_1);
501 dpo_copy (result, choice);
505 tcp_lookup_rmt_in_fib (tcp_connection_t * tc)
510 clib_memcpy (&prefix.fp_addr, &tc->c_rmt_ip, sizeof (prefix.fp_addr));
511 prefix.fp_proto = tc->c_is_ip4 ? FIB_PROTOCOL_IP4 : FIB_PROTOCOL_IP6;
512 prefix.fp_len = tc->c_is_ip4 ? 32 : 128;
513 fib_index = fib_table_find (prefix.fp_proto, tc->c_vrf);
514 return fib_table_lookup (fib_index, &prefix);
518 tcp_connection_stack_on_fib_entry (tcp_connection_t * tc)
520 dpo_id_t choice = DPO_INVALID;
521 u32 output_node_index;
524 fe = fib_entry_get (tc->c_rmt_fei);
525 if (fe->fe_lb.dpoi_type != DPO_LOAD_BALANCE)
528 tcp_connection_select_lb_bucket (tc, &fe->fe_lb, &choice);
531 tc->c_is_ip4 ? tcp4_output_node.index : tcp6_output_node.index;
532 dpo_stack_from_node (output_node_index, &tc->c_rmt_dpo, &choice);
536 /** Stack tcp connection on peer's fib entry.
538 * This ultimately populates the dpo the connection will use to send packets.
541 tcp_connection_fib_attach (tcp_connection_t * tc)
543 tc->c_rmt_fei = tcp_lookup_rmt_in_fib (tc);
545 ASSERT (tc->c_rmt_fei != FIB_NODE_INDEX_INVALID);
547 tcp_connection_stack_on_fib_entry (tc);
551 /** Initialize tcp connection variables
553 * Should be called after having received a msg from the peer, i.e., a SYN or
554 * a SYNACK, such that connection options have already been exchanged. */
556 tcp_connection_init_vars (tcp_connection_t * tc)
558 tcp_connection_timers_init (tc);
560 scoreboard_init (&tc->sack_sb);
562 // tcp_connection_fib_attach (tc);
566 tcp_connection_open (transport_endpoint_t * rmt)
568 tcp_main_t *tm = vnet_get_tcp_main ();
569 tcp_connection_t *tc;
571 fib_node_index_t fei;
572 u32 sw_if_index, fib_index;
573 ip46_address_t lcl_addr;
577 * Find the local address and allocate port
579 memset (&lcl_addr, 0, sizeof (lcl_addr));
581 /* Find a FIB path to the destination */
582 clib_memcpy (&prefix.fp_addr, &rmt->ip, sizeof (rmt->ip));
583 prefix.fp_proto = rmt->is_ip4 ? FIB_PROTOCOL_IP4 : FIB_PROTOCOL_IP6;
584 prefix.fp_len = rmt->is_ip4 ? 32 : 128;
586 fib_index = fib_table_find (prefix.fp_proto, rmt->vrf);
587 fei = fib_table_lookup (fib_index, &prefix);
589 /* Couldn't find route to destination. Bail out. */
590 if (fei == FIB_NODE_INDEX_INVALID)
592 clib_warning ("no route to destination");
596 sw_if_index = fib_entry_get_resolving_interface (fei);
598 if (sw_if_index == (u32) ~ 0)
600 clib_warning ("no resolving interface for %U", format_ip46_address,
601 &rmt->ip, IP46_TYPE_IP4);
609 if (vec_len (tm->ip4_src_addresses))
611 index = tm->last_v4_address_rotor++;
612 if (tm->last_v4_address_rotor >= vec_len (tm->ip4_src_addresses))
613 tm->last_v4_address_rotor = 0;
614 lcl_addr.ip4.as_u32 = tm->ip4_src_addresses[index].as_u32;
618 ip4 = ip_interface_get_first_ip (sw_if_index, 1);
619 lcl_addr.ip4.as_u32 = ip4->as_u32;
627 if (vec_len (tm->ip6_src_addresses))
629 index = tm->last_v6_address_rotor++;
630 if (tm->last_v6_address_rotor >= vec_len (tm->ip6_src_addresses))
631 tm->last_v6_address_rotor = 0;
632 clib_memcpy (&lcl_addr.ip6, &tm->ip6_src_addresses[index],
637 ip6 = ip_interface_get_first_ip (sw_if_index, 0);
638 clib_memcpy (&lcl_addr.ip6, ip6, sizeof (*ip6));
642 /* Allocate source port */
643 lcl_port = tcp_allocate_local_port (&lcl_addr);
646 clib_warning ("Failed to allocate src port");
651 * Create connection and send SYN
653 clib_spinlock_lock_if_init (&tm->half_open_lock);
654 tc = tcp_half_open_connection_new ();
655 clib_memcpy (&tc->c_rmt_ip, &rmt->ip, sizeof (ip46_address_t));
656 clib_memcpy (&tc->c_lcl_ip, &lcl_addr, sizeof (ip46_address_t));
657 tc->c_rmt_port = clib_host_to_net_u16 (rmt->port);
658 tc->c_lcl_port = clib_host_to_net_u16 (lcl_port);
659 tc->c_is_ip4 = rmt->is_ip4;
660 tc->c_transport_proto = TRANSPORT_PROTO_TCP;
661 tc->c_vrf = rmt->vrf;
662 /* The other connection vars will be initialized after SYN ACK */
663 tcp_connection_timers_init (tc);
665 TCP_EVT_DBG (TCP_EVT_OPEN, tc);
666 tc->state = TCP_STATE_SYN_SENT;
668 clib_spinlock_unlock_if_init (&tm->half_open_lock);
670 return tc->c_c_index;
674 tcp_session_open (transport_endpoint_t * tep)
676 return tcp_connection_open (tep);
679 const char *tcp_dbg_evt_str[] = {
680 #define _(sym, str) str,
685 const char *tcp_fsm_states[] = {
686 #define _(sym, str) str,
687 foreach_tcp_fsm_state
692 format_tcp_state (u8 * s, va_list * args)
694 u32 state = va_arg (*args, u32);
696 if (state < TCP_N_STATES)
697 s = format (s, "%s", tcp_fsm_states[state]);
699 s = format (s, "UNKNOWN (%d (0x%x))", state, state);
703 const char *tcp_conn_timers[] = {
704 #define _(sym, str) str,
710 format_tcp_timers (u8 * s, va_list * args)
712 tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
715 for (i = 0; i < TCP_N_TIMERS; i++)
716 if (tc->timers[i] != TCP_TIMER_HANDLE_INVALID)
720 for (i = 0; i < last; i++)
722 if (tc->timers[i] != TCP_TIMER_HANDLE_INVALID)
723 s = format (s, "%s,", tcp_conn_timers[i]);
727 s = format (s, "%s]", tcp_conn_timers[i]);
735 format_tcp_congestion_status (u8 * s, va_list * args)
737 tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
738 if (tcp_in_recovery (tc))
739 s = format (s, "recovery");
740 else if (tcp_in_fastrecovery (tc))
741 s = format (s, "fastrecovery");
743 s = format (s, "none");
748 format_tcp_vars (u8 * s, va_list * args)
750 tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
751 s = format (s, " snd_una %u snd_nxt %u snd_una_max %u",
752 tc->snd_una - tc->iss, tc->snd_nxt - tc->iss,
753 tc->snd_una_max - tc->iss);
754 s = format (s, " rcv_nxt %u rcv_las %u\n",
755 tc->rcv_nxt - tc->irs, tc->rcv_las - tc->irs);
756 s = format (s, " snd_wnd %u rcv_wnd %u snd_wl1 %u snd_wl2 %u\n",
757 tc->snd_wnd, tc->rcv_wnd, tc->snd_wl1 - tc->irs,
758 tc->snd_wl2 - tc->iss);
759 s = format (s, " flight size %u send space %u rcv_wnd_av %d\n",
760 tcp_flight_size (tc), tcp_available_snd_space (tc),
761 tcp_rcv_wnd_available (tc));
762 s = format (s, " cong %U ", format_tcp_congestion_status, tc);
763 s = format (s, "cwnd %u ssthresh %u rtx_bytes %u bytes_acked %u\n",
764 tc->cwnd, tc->ssthresh, tc->snd_rxt_bytes, tc->bytes_acked);
765 s = format (s, " prev_ssthresh %u snd_congestion %u dupack %u",
766 tc->prev_ssthresh, tc->snd_congestion - tc->iss,
768 s = format (s, " limited_transmit %u\n", tc->limited_transmit - tc->iss);
769 s = format (s, " tsecr %u tsecr_last_ack %u\n", tc->rcv_opts.tsecr,
771 s = format (s, " rto %u rto_boff %u srtt %u rttvar %u rtt_ts %u ", tc->rto,
772 tc->rto_boff, tc->srtt, tc->rttvar, tc->rtt_ts);
773 s = format (s, "rtt_seq %u\n", tc->rtt_seq);
774 s = format (s, " tsval_recent %u tsval_recent_age %u\n", tc->tsval_recent,
775 tcp_time_now () - tc->tsval_recent_age);
776 s = format (s, " scoreboard: %U\n", format_tcp_scoreboard, &tc->sack_sb);
777 if (vec_len (tc->snd_sacks))
778 s = format (s, " sacks tx: %U\n", format_tcp_sacks, tc);
784 format_tcp_connection_id (u8 * s, va_list * args)
786 tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
791 s = format (s, "[#%d][%s] %U:%d->%U:%d", tc->c_thread_index, "T",
792 format_ip4_address, &tc->c_lcl_ip4,
793 clib_net_to_host_u16 (tc->c_lcl_port), format_ip4_address,
794 &tc->c_rmt_ip4, clib_net_to_host_u16 (tc->c_rmt_port));
798 s = format (s, "[#%d][%s] %U:%d->%U:%d", tc->c_thread_index, "T",
799 format_ip6_address, &tc->c_lcl_ip6,
800 clib_net_to_host_u16 (tc->c_lcl_port), format_ip6_address,
801 &tc->c_rmt_ip6, clib_net_to_host_u16 (tc->c_rmt_port));
808 format_tcp_connection (u8 * s, va_list * args)
810 tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
811 u32 verbose = va_arg (*args, u32);
813 s = format (s, "%-50U", format_tcp_connection_id, tc);
816 s = format (s, "%-15U", format_tcp_state, tc->state);
818 s = format (s, " %U\n%U", format_tcp_timers, tc, format_tcp_vars, tc);
825 format_tcp_session (u8 * s, va_list * args)
827 u32 tci = va_arg (*args, u32);
828 u32 thread_index = va_arg (*args, u32);
829 u32 verbose = va_arg (*args, u32);
830 tcp_connection_t *tc;
832 tc = tcp_connection_get (tci, thread_index);
834 s = format (s, "%U", format_tcp_connection, tc, verbose);
836 s = format (s, "empty");
841 format_tcp_listener_session (u8 * s, va_list * args)
843 u32 tci = va_arg (*args, u32);
844 tcp_connection_t *tc = tcp_listener_get (tci);
845 return format (s, "%U", format_tcp_connection_id, tc);
849 format_tcp_half_open_session (u8 * s, va_list * args)
851 u32 tci = va_arg (*args, u32);
852 tcp_connection_t *tc = tcp_half_open_connection_get (tci);
853 return format (s, "%U", format_tcp_connection_id, tc);
857 format_tcp_sacks (u8 * s, va_list * args)
859 tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
860 sack_block_t *sacks = tc->snd_sacks;
864 len = vec_len (sacks);
865 for (i = 0; i < len - 1; i++)
868 s = format (s, " start %u end %u\n", block->start - tc->irs,
869 block->end - tc->irs);
873 block = &sacks[len - 1];
874 s = format (s, " start %u end %u", block->start - tc->irs,
875 block->end - tc->irs);
881 format_tcp_rcv_sacks (u8 * s, va_list * args)
883 tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
884 sack_block_t *sacks = tc->rcv_opts.sacks;
888 len = vec_len (sacks);
889 for (i = 0; i < len - 1; i++)
892 s = format (s, " start %u end %u\n", block->start - tc->iss,
893 block->end - tc->iss);
897 block = &sacks[len - 1];
898 s = format (s, " start %u end %u", block->start - tc->iss,
899 block->end - tc->iss);
905 format_tcp_sack_hole (u8 * s, va_list * args)
907 sack_scoreboard_hole_t *hole = va_arg (*args, sack_scoreboard_hole_t *);
908 s = format (s, "[%u, %u]", hole->start, hole->end);
913 format_tcp_scoreboard (u8 * s, va_list * args)
915 sack_scoreboard_t *sb = va_arg (*args, sack_scoreboard_t *);
916 sack_scoreboard_hole_t *hole;
917 s = format (s, "sacked_bytes %u last_sacked_bytes %u lost_bytes %u\n",
918 sb->sacked_bytes, sb->last_sacked_bytes, sb->lost_bytes);
919 s = format (s, " last_bytes_delivered %u high_sacked %u snd_una_adv %u\n",
920 sb->last_bytes_delivered, sb->high_sacked, sb->snd_una_adv);
921 s = format (s, " cur_rxt_hole %u high_rxt %u rescue_rxt %u",
922 sb->cur_rxt_hole, sb->high_rxt, sb->rescue_rxt);
924 hole = scoreboard_first_hole (sb);
926 s = format (s, "\n head %u tail %u holes:\n", sb->head, sb->tail);
930 s = format (s, "%U", format_tcp_sack_hole, hole);
931 hole = scoreboard_next_hole (sb, hole);
937 transport_connection_t *
938 tcp_session_get_transport (u32 conn_index, u32 thread_index)
940 tcp_connection_t *tc = tcp_connection_get (conn_index, thread_index);
941 return &tc->connection;
944 transport_connection_t *
945 tcp_half_open_session_get_transport (u32 conn_index)
947 tcp_connection_t *tc = tcp_half_open_connection_get (conn_index);
948 return &tc->connection;
952 * Compute maximum segment size for session layer.
954 * Since the result needs to be the actual data length, it first computes
955 * the tcp options to be used in the next burst and subtracts their
956 * length from the connection's snd_mss.
959 tcp_session_send_mss (transport_connection_t * trans_conn)
961 tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
963 /* Ensure snd_mss does accurately reflect the amount of data we can push
964 * in a segment. This also makes sure that options are updated according to
965 * the current state of the connection. */
966 tcp_update_snd_mss (tc);
972 tcp_round_snd_space (tcp_connection_t * tc, u32 snd_space)
974 if (PREDICT_FALSE (tc->snd_wnd < tc->snd_mss))
976 return tc->snd_wnd <= snd_space ? tc->snd_wnd : 0;
979 /* If we can't write at least a segment, don't try at all */
980 if (PREDICT_FALSE (snd_space < tc->snd_mss))
982 if (snd_space > clib_min (tc->mss, tc->rcv_opts.mss) - TCP_HDR_LEN_MAX)
987 /* round down to mss multiple */
988 return snd_space - (snd_space % tc->snd_mss);
992 * Compute tx window session is allowed to fill.
994 * Takes into account available send space, snd_mss and the congestion
995 * state of the connection. If possible, the value returned is a multiple
998 * @param tc tcp connection
999 * @return number of bytes session is allowed to write
1002 tcp_snd_space (tcp_connection_t * tc)
1004 int snd_space, snt_limited;
1006 if (PREDICT_TRUE (tcp_in_cong_recovery (tc) == 0))
1008 snd_space = tcp_available_snd_space (tc);
1010 /* If we haven't gotten dupacks or if we did and have gotten sacked
1011 * bytes then we can still send as per Limited Transmit (RFC3042) */
1012 if (PREDICT_FALSE (tc->rcv_dupacks != 0
1013 && (tcp_opts_sack_permitted (tc)
1014 && tc->sack_sb.last_sacked_bytes == 0)))
1016 if (tc->rcv_dupacks == 1 && tc->limited_transmit != tc->snd_nxt)
1017 tc->limited_transmit = tc->snd_nxt;
1018 ASSERT (seq_leq (tc->limited_transmit, tc->snd_nxt));
1020 snt_limited = tc->snd_nxt - tc->limited_transmit;
1021 snd_space = clib_max (2 * tc->snd_mss - snt_limited, 0);
1023 return tcp_round_snd_space (tc, snd_space);
1026 if (tcp_in_recovery (tc))
1028 tc->snd_nxt = tc->snd_una_max;
1029 snd_space = tcp_available_wnd (tc) - tc->snd_rxt_bytes
1030 - (tc->snd_una_max - tc->snd_congestion);
1031 if (snd_space <= 0 || (tc->snd_una_max - tc->snd_una) >= tc->snd_wnd)
1033 return tcp_round_snd_space (tc, snd_space);
1036 /* If in fast recovery, send 1 SMSS if wnd allows */
1037 if (tcp_in_fastrecovery (tc)
1038 && tcp_available_snd_space (tc) && !tcp_fastrecovery_sent_1_smss (tc))
1040 tcp_fastrecovery_1_smss_on (tc);
1048 tcp_session_send_space (transport_connection_t * trans_conn)
1050 tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
1051 return tcp_snd_space (tc);
1055 tcp_rcv_wnd_available (tcp_connection_t * tc)
1057 return (i32) tc->rcv_wnd - (tc->rcv_nxt - tc->rcv_las);
1061 tcp_session_tx_fifo_offset (transport_connection_t * trans_conn)
1063 tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
1065 ASSERT (seq_geq (tc->snd_nxt, tc->snd_una));
1067 /* This still works if fast retransmit is on */
1068 return (tc->snd_nxt - tc->snd_una);
1072 const static transport_proto_vft_t tcp_proto = {
1073 .bind = tcp_session_bind,
1074 .unbind = tcp_session_unbind,
1075 .push_header = tcp_push_header,
1076 .get_connection = tcp_session_get_transport,
1077 .get_listener = tcp_session_get_listener,
1078 .get_half_open = tcp_half_open_session_get_transport,
1079 .open = tcp_session_open,
1080 .close = tcp_session_close,
1081 .cleanup = tcp_session_cleanup,
1082 .send_mss = tcp_session_send_mss,
1083 .send_space = tcp_session_send_space,
1084 .tx_fifo_offset = tcp_session_tx_fifo_offset,
1085 .format_connection = format_tcp_session,
1086 .format_listener = format_tcp_listener_session,
1087 .format_half_open = format_tcp_half_open_session,
1092 tcp_timer_keep_handler (u32 conn_index)
1094 u32 thread_index = vlib_get_thread_index ();
1095 tcp_connection_t *tc;
1097 tc = tcp_connection_get (conn_index, thread_index);
1098 tc->timers[TCP_TIMER_KEEP] = TCP_TIMER_HANDLE_INVALID;
1100 tcp_connection_close (tc);
1104 tcp_timer_establish_handler (u32 conn_index)
1106 tcp_connection_t *tc;
1108 tc = tcp_half_open_connection_get (conn_index);
1111 ASSERT (tc->state == TCP_STATE_SYN_SENT);
1112 tc->timers[TCP_TIMER_ESTABLISH] = TCP_TIMER_HANDLE_INVALID;
1113 stream_session_connect_notify (&tc->connection, 1 /* fail */ );
1117 tc = tcp_connection_get (conn_index, vlib_get_thread_index ());
1118 ASSERT (tc->state == TCP_STATE_SYN_RCVD);
1120 tcp_connection_cleanup (tc);
1124 tcp_timer_waitclose_handler (u32 conn_index)
1126 u32 thread_index = vlib_get_thread_index ();
1127 tcp_connection_t *tc;
1129 tc = tcp_connection_get (conn_index, thread_index);
1132 tc->timers[TCP_TIMER_WAITCLOSE] = TCP_TIMER_HANDLE_INVALID;
1134 /* Session didn't come back with a close(). Send FIN either way
1135 * and switch to LAST_ACK. */
1136 if (tc->state == TCP_STATE_CLOSE_WAIT)
1138 if (tc->flags & TCP_CONN_FINSNT)
1140 clib_warning ("FIN was sent and still in CLOSE WAIT. Weird!");
1144 tc->state = TCP_STATE_LAST_ACK;
1146 /* Make sure we don't wait in LAST ACK forever */
1147 tcp_timer_set (tc, TCP_TIMER_WAITCLOSE, TCP_2MSL_TIME);
1149 /* Don't delete the connection yet */
1153 tcp_connection_del (tc);
1157 static timer_expiration_handler *timer_expiration_handlers[TCP_N_TIMERS] =
1159 tcp_timer_retransmit_handler,
1160 tcp_timer_delack_handler,
1161 tcp_timer_persist_handler,
1162 tcp_timer_keep_handler,
1163 tcp_timer_waitclose_handler,
1164 tcp_timer_retransmit_syn_handler,
1165 tcp_timer_establish_handler
1170 tcp_expired_timers_dispatch (u32 * expired_timers)
1173 u32 connection_index, timer_id;
1175 for (i = 0; i < vec_len (expired_timers); i++)
1177 /* Get session index and timer id */
1178 connection_index = expired_timers[i] & 0x0FFFFFFF;
1179 timer_id = expired_timers[i] >> 28;
1181 TCP_EVT_DBG (TCP_EVT_TIMER_POP, connection_index, timer_id);
1183 /* Handle expiration */
1184 (*timer_expiration_handlers[timer_id]) (connection_index);
1189 tcp_initialize_timer_wheels (tcp_main_t * tm)
1191 tw_timer_wheel_16t_2w_512sl_t *tw;
1193 foreach_vlib_main (({
1194 tw = &tm->timer_wheels[ii];
1195 tw_timer_wheel_init_16t_2w_512sl (tw, tcp_expired_timers_dispatch,
1196 100e-3 /* timer period 100ms */ , ~0);
1197 tw->last_run_time = vlib_time_now (this_vlib_main);
1203 tcp_main_enable (vlib_main_t * vm)
1205 tcp_main_t *tm = vnet_get_tcp_main ();
1206 ip_protocol_info_t *pi;
1207 ip_main_t *im = &ip_main;
1208 vlib_thread_main_t *vtm = vlib_get_thread_main ();
1209 clib_error_t *error = 0;
1212 tcp_connection_t *tc __attribute__ ((unused));
1213 u32 preallocated_connections_per_thread;
1215 if ((error = vlib_call_init_function (vm, ip_main_init)))
1217 if ((error = vlib_call_init_function (vm, ip4_lookup_init)))
1219 if ((error = vlib_call_init_function (vm, ip6_lookup_init)))
1226 /* Register with IP */
1227 pi = ip_get_protocol_info (im, IP_PROTOCOL_TCP);
1229 return clib_error_return (0, "TCP protocol info AWOL");
1230 pi->format_header = format_tcp_header;
1231 pi->unformat_pg_edit = unformat_pg_tcp_header;
1233 ip4_register_protocol (IP_PROTOCOL_TCP, tcp4_input_node.index);
1235 /* Register as transport with session layer */
1236 session_register_transport (TRANSPORT_PROTO_TCP, 1, &tcp_proto);
1237 session_register_transport (TRANSPORT_PROTO_TCP, 0, &tcp_proto);
1240 * Initialize data structures
1243 num_threads = 1 /* main thread */ + vtm->n_threads;
1244 vec_validate (tm->connections, num_threads - 1);
1247 * Preallocate connections. Assume that thread 0 won't
1248 * use preallocated threads when running multi-core
1250 if (num_threads == 1)
1253 preallocated_connections_per_thread = tm->preallocated_connections;
1258 preallocated_connections_per_thread =
1259 tm->preallocated_connections / (num_threads - 1);
1261 for (; thread < num_threads; thread++)
1263 for (i = 0; i < preallocated_connections_per_thread; i++)
1264 pool_get (tm->connections[thread], tc);
1266 for (i = 0; i < preallocated_connections_per_thread; i++)
1267 pool_put_index (tm->connections[thread], i);
1271 * Preallocate half-open connections
1273 for (i = 0; i < tm->preallocated_half_open_connections; i++)
1274 pool_get (tm->half_open_connections, tc);
1276 for (i = 0; i < tm->preallocated_half_open_connections; i++)
1277 pool_put_index (tm->half_open_connections, i);
1279 /* Initialize per worker thread tx buffers (used for control messages) */
1280 vec_validate (tm->tx_buffers, num_threads - 1);
1282 /* Initialize timer wheels */
1283 vec_validate (tm->timer_wheels, num_threads - 1);
1284 tcp_initialize_timer_wheels (tm);
1286 /* Initialize clocks per tick for TCP timestamp. Used to compute
1287 * monotonically increasing timestamps. */
1288 tm->tstamp_ticks_per_clock = vm->clib_time.seconds_per_clock
1289 / TCP_TSTAMP_RESOLUTION;
1291 clib_bihash_init_24_8 (&tm->local_endpoints_table, "local endpoint table",
1292 1000000 /* $$$$ config parameter nbuckets */ ,
1293 (512 << 20) /*$$$ config parameter table size */ );
1295 /* Initialize [port-allocator] random number seed */
1296 tm->port_allocator_seed = (u32) clib_cpu_time_now ();
1298 if (num_threads > 1)
1300 clib_spinlock_init (&tm->half_open_lock);
1301 clib_spinlock_init (&tm->local_endpoints_lock);
1304 vec_validate (tm->tx_frames[0], num_threads - 1);
1305 vec_validate (tm->tx_frames[1], num_threads - 1);
1307 tm->bytes_per_buffer = vlib_buffer_free_list_buffer_size
1308 (vm, VLIB_BUFFER_DEFAULT_FREE_LIST_INDEX);
1310 vec_validate (tm->time_now, num_threads - 1);
1315 vnet_tcp_enable_disable (vlib_main_t * vm, u8 is_en)
1319 if (tcp_main.is_enabled)
1322 return tcp_main_enable (vm);
1326 tcp_main.is_enabled = 0;
1333 tcp_init (vlib_main_t * vm)
1335 tcp_main_t *tm = vnet_get_tcp_main ();
1340 VLIB_INIT_FUNCTION (tcp_init);
1342 static clib_error_t *
1343 tcp_config_fn (vlib_main_t * vm, unformat_input_t * input)
1345 tcp_main_t *tm = vnet_get_tcp_main ();
1347 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1350 (input, "preallocated-connections %d",
1351 &tm->preallocated_connections))
1353 else if (unformat (input, "preallocated-half-open-connections %d",
1354 &tm->preallocated_half_open_connections))
1357 return clib_error_return (0, "unknown input `%U'",
1358 format_unformat_error, input);
1363 VLIB_CONFIG_FUNCTION (tcp_config_fn, "tcp");
1365 static clib_error_t *
1366 tcp_src_address (vlib_main_t * vm,
1367 unformat_input_t * input, vlib_cli_command_t * cmd_arg)
1369 tcp_main_t *tm = vnet_get_tcp_main ();
1370 ip4_address_t v4start, v4end;
1371 ip6_address_t v6start, v6end;
1375 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1377 if (unformat (input, "%U - %U", unformat_ip4_address, &v4start,
1378 unformat_ip4_address, &v4end))
1380 else if (unformat (input, "%U", unformat_ip4_address, &v4start))
1382 memcpy (&v4end, &v4start, sizeof (v4start));
1385 else if (unformat (input, "%U - %U", unformat_ip6_address, &v6start,
1386 unformat_ip4_address, &v6end))
1388 else if (unformat (input, "%U", unformat_ip6_address, &v6start))
1390 memcpy (&v6end, &v6start, sizeof (v4start));
1397 if (!v4set && !v6set)
1398 return clib_error_return (0, "at least one v4 or v6 address required");
1406 vec_add1 (tm->ip4_src_addresses, v4start);
1407 tmp = clib_net_to_host_u32 (v4start.as_u32);
1409 v4start.as_u32 = clib_host_to_net_u32 (tmp);
1411 while (clib_host_to_net_u32 (v4start.as_u32) <=
1412 clib_host_to_net_u32 (v4end.as_u32));
1416 clib_warning ("v6 src address list unimplemented...");
1422 VLIB_CLI_COMMAND (tcp_src_address_command, static) =
1424 .path = "tcp src-address",
1425 .short_help = "tcp src-address <ip-addr> [- <ip-addr>] add src address range",
1426 .function = tcp_src_address,
1431 tcp_scoreboard_dump_trace (u8 * s, sack_scoreboard_t * sb)
1433 #if TCP_SCOREBOARD_TRACE
1435 scoreboard_trace_elt_t *block;
1441 s = format (s, "scoreboard trace:");
1442 vec_foreach (block, sb->trace)
1444 s = format (s, "{%u, %u, %u, %u, %u}, ", block->start, block->end,
1445 block->ack, block->snd_una_max, block->group);
1447 s = format (s, "\n");
1455 static clib_error_t *
1456 tcp_show_scoreboard_trace_fn (vlib_main_t * vm, unformat_input_t * input,
1457 vlib_cli_command_t * cmd_arg)
1459 transport_connection_t *tconn = 0;
1460 tcp_connection_t *tc;
1462 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1464 if (unformat (input, "%U", unformat_transport_connection, &tconn,
1465 TRANSPORT_PROTO_TCP))
1468 return clib_error_return (0, "unknown input `%U'",
1469 format_unformat_error, input);
1472 if (!TCP_SCOREBOARD_TRACE)
1474 vlib_cli_output (vm, "scoreboard tracing not enabled");
1478 tc = tcp_get_connection_from_transport (tconn);
1479 s = tcp_scoreboard_dump_trace (s, &tc->sack_sb);
1480 vlib_cli_output (vm, "%v", s);
1485 VLIB_CLI_COMMAND (tcp_show_scoreboard_trace_command, static) =
1487 .path = "show tcp scoreboard trace",
1488 .short_help = "show tcp scoreboard trace <connection>",
1489 .function = tcp_show_scoreboard_trace_fn,
1494 tcp_scoreboard_replay (u8 * s, tcp_connection_t * tc, u8 verbose)
1497 scoreboard_trace_elt_t *trace;
1498 u32 next_ack, left, group, has_new_ack = 0;
1499 tcp_connection_t _dummy_tc, *dummy_tc = &_dummy_tc;
1500 sack_block_t *block;
1505 memset (dummy_tc, 0, sizeof (*dummy_tc));
1506 tcp_connection_timers_init (dummy_tc);
1507 scoreboard_init (&dummy_tc->sack_sb);
1508 dummy_tc->rcv_opts.flags |= TCP_OPTS_FLAG_SACK;
1510 #if TCP_SCOREBOARD_TRACE
1511 trace = tc->sack_sb.trace;
1512 trace_len = vec_len (tc->sack_sb.trace);
1518 for (i = 0; i < trace_len; i++)
1520 if (trace[i].ack != 0)
1522 dummy_tc->snd_una = trace[i].ack - 1448;
1523 dummy_tc->snd_una_max = trace[i].ack;
1528 while (left < trace_len)
1530 group = trace[left].group;
1531 vec_reset_length (dummy_tc->rcv_opts.sacks);
1533 while (trace[left].group == group)
1535 if (trace[left].ack != 0)
1538 s = format (s, "Adding ack %u, snd_una_max %u, segs: ",
1539 trace[left].ack, trace[left].snd_una_max);
1540 dummy_tc->snd_una_max = trace[left].snd_una_max;
1541 next_ack = trace[left].ack;
1547 s = format (s, "[%u, %u], ", trace[left].start,
1549 vec_add2 (dummy_tc->rcv_opts.sacks, block, 1);
1550 block->start = trace[left].start;
1551 block->end = trace[left].end;
1557 tcp_rcv_sacks (dummy_tc, next_ack);
1559 dummy_tc->snd_una = next_ack + dummy_tc->sack_sb.snd_una_adv;
1562 s = format (s, "result: %U", format_tcp_scoreboard,
1563 &dummy_tc->sack_sb);
1566 s = format (s, "result: %U", format_tcp_scoreboard, &dummy_tc->sack_sb);
1571 static clib_error_t *
1572 tcp_scoreboard_trace_fn (vlib_main_t * vm, unformat_input_t * input,
1573 vlib_cli_command_t * cmd_arg)
1575 transport_connection_t *tconn = 0;
1576 tcp_connection_t *tc = 0;
1578 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1580 if (unformat (input, "%U", unformat_transport_connection, &tconn,
1581 TRANSPORT_PROTO_TCP))
1584 return clib_error_return (0, "unknown input `%U'",
1585 format_unformat_error, input);
1588 if (!TCP_SCOREBOARD_TRACE)
1590 vlib_cli_output (vm, "scoreboard tracing not enabled");
1594 tc = tcp_get_connection_from_transport (tconn);
1597 vlib_cli_output (vm, "connection not found");
1600 str = tcp_scoreboard_replay (str, tc, 1);
1601 vlib_cli_output (vm, "%v", str);
1606 VLIB_CLI_COMMAND (tcp_replay_scoreboard_command, static) =
1608 .path = "tcp replay scoreboard",
1609 .short_help = "tcp replay scoreboard <connection>",
1610 .function = tcp_scoreboard_trace_fn,
1615 * fd.io coding-style-patch-verification: ON
1618 * eval: (c-set-style "gnu")