tcp: fix close wait timeout with no fin
[vpp.git] / src / vnet / tcp / tcp.c
1 /*
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:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
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.
14  */
15
16 /**
17  * @file
18  * @brief TCP host stack utilities
19  */
20
21 #include <vnet/tcp/tcp.h>
22 #include <vnet/session/session.h>
23 #include <vnet/fib/fib.h>
24 #include <vnet/dpo/load_balance.h>
25 #include <vnet/dpo/receive_dpo.h>
26 #include <vnet/ip/ip6_neighbor.h>
27 #include <math.h>
28
29 tcp_main_t tcp_main;
30
31 typedef struct
32 {
33   fib_protocol_t nh_proto;
34   vnet_link_t link_type;
35   ip46_address_t ip;
36   u32 sw_if_index;
37   u8 is_add;
38 } tcp_add_del_adj_args_t;
39
40 static void
41 tcp_add_del_adj_cb (tcp_add_del_adj_args_t * args)
42 {
43   u32 ai;
44   if (args->is_add)
45     {
46       adj_nbr_add_or_lock (args->nh_proto, args->link_type, &args->ip,
47                            args->sw_if_index);
48     }
49   else
50     {
51       ai = adj_nbr_find (FIB_PROTOCOL_IP6, VNET_LINK_IP6, &args->ip,
52                          args->sw_if_index);
53       if (ai != ADJ_INDEX_INVALID)
54         adj_unlock (ai);
55     }
56 }
57
58 static void
59 tcp_add_del_adjacency (tcp_connection_t * tc, u8 is_add)
60 {
61   tcp_add_del_adj_args_t args = {
62     .nh_proto = FIB_PROTOCOL_IP6,
63     .link_type = VNET_LINK_IP6,
64     .ip = tc->c_rmt_ip,
65     .sw_if_index = tc->sw_if_index,
66     .is_add = is_add
67   };
68   vlib_rpc_call_main_thread (tcp_add_del_adj_cb, (u8 *) & args,
69                              sizeof (args));
70 }
71
72 static u32
73 tcp_connection_bind (u32 session_index, transport_endpoint_t * lcl)
74 {
75   tcp_main_t *tm = &tcp_main;
76   tcp_connection_t *listener;
77   void *iface_ip;
78
79   pool_get (tm->listener_pool, listener);
80   memset (listener, 0, sizeof (*listener));
81
82   listener->c_c_index = listener - tm->listener_pool;
83   listener->c_lcl_port = lcl->port;
84
85   /* If we are provided a sw_if_index, bind using one of its ips */
86   if (ip_is_zero (&lcl->ip, 1) && lcl->sw_if_index != ENDPOINT_INVALID_INDEX)
87     {
88       if ((iface_ip = ip_interface_get_first_ip (lcl->sw_if_index,
89                                                  lcl->is_ip4)))
90         ip_set (&lcl->ip, iface_ip, lcl->is_ip4);
91     }
92   ip_copy (&listener->c_lcl_ip, &lcl->ip, lcl->is_ip4);
93   listener->c_is_ip4 = lcl->is_ip4;
94   listener->c_proto = TRANSPORT_PROTO_TCP;
95   listener->c_s_index = session_index;
96   listener->c_fib_index = lcl->fib_index;
97   listener->state = TCP_STATE_LISTEN;
98
99   tcp_connection_timers_init (listener);
100
101   TCP_EVT_DBG (TCP_EVT_BIND, listener);
102
103   return listener->c_c_index;
104 }
105
106 static u32
107 tcp_session_bind (u32 session_index, transport_endpoint_t * tep)
108 {
109   return tcp_connection_bind (session_index, tep);
110 }
111
112 static void
113 tcp_connection_unbind (u32 listener_index)
114 {
115   tcp_main_t *tm = vnet_get_tcp_main ();
116   tcp_connection_t *tc;
117
118   tc = pool_elt_at_index (tm->listener_pool, listener_index);
119
120   TCP_EVT_DBG (TCP_EVT_UNBIND, tc);
121
122   /* Poison the entry */
123   if (CLIB_DEBUG > 0)
124     memset (tc, 0xFA, sizeof (*tc));
125
126   pool_put_index (tm->listener_pool, listener_index);
127 }
128
129 static u32
130 tcp_session_unbind (u32 listener_index)
131 {
132   tcp_connection_unbind (listener_index);
133   return 0;
134 }
135
136 static transport_connection_t *
137 tcp_session_get_listener (u32 listener_index)
138 {
139   tcp_main_t *tm = vnet_get_tcp_main ();
140   tcp_connection_t *tc;
141   tc = pool_elt_at_index (tm->listener_pool, listener_index);
142   return &tc->connection;
143 }
144
145 /**
146  * Cleanup half-open connection
147  *
148  */
149 static void
150 tcp_half_open_connection_del (tcp_connection_t * tc)
151 {
152   tcp_main_t *tm = vnet_get_tcp_main ();
153   clib_spinlock_lock_if_init (&tm->half_open_lock);
154   pool_put_index (tm->half_open_connections, tc->c_c_index);
155   if (CLIB_DEBUG)
156     memset (tc, 0xFA, sizeof (*tc));
157   clib_spinlock_unlock_if_init (&tm->half_open_lock);
158 }
159
160 /**
161  * Try to cleanup half-open connection
162  *
163  * If called from a thread that doesn't own tc, the call won't have any
164  * effect.
165  *
166  * @param tc - connection to be cleaned up
167  * @return non-zero if cleanup failed.
168  */
169 int
170 tcp_half_open_connection_cleanup (tcp_connection_t * tc)
171 {
172   /* Make sure this is the owning thread */
173   if (tc->c_thread_index != vlib_get_thread_index ())
174     return 1;
175   tcp_timer_reset (tc, TCP_TIMER_ESTABLISH);
176   tcp_timer_reset (tc, TCP_TIMER_RETRANSMIT_SYN);
177   tcp_half_open_connection_del (tc);
178   return 0;
179 }
180
181 static tcp_connection_t *
182 tcp_half_open_connection_new (void)
183 {
184   tcp_main_t *tm = vnet_get_tcp_main ();
185   tcp_connection_t *tc = 0;
186   ASSERT (vlib_get_thread_index () == 0);
187   pool_get (tm->half_open_connections, tc);
188   memset (tc, 0, sizeof (*tc));
189   tc->c_c_index = tc - tm->half_open_connections;
190   return tc;
191 }
192
193 /**
194  * Cleans up connection state.
195  *
196  * No notifications.
197  */
198 void
199 tcp_connection_cleanup (tcp_connection_t * tc)
200 {
201   tcp_main_t *tm = &tcp_main;
202
203   /* Cleanup local endpoint if this was an active connect */
204   transport_endpoint_cleanup (TRANSPORT_PROTO_TCP, &tc->c_lcl_ip,
205                               tc->c_lcl_port);
206
207   /* Check if connection is not yet fully established */
208   if (tc->state == TCP_STATE_SYN_SENT)
209     {
210       /* Try to remove the half-open connection. If this is not the owning
211        * thread, tc won't be removed. Retransmit or establish timers will
212        * eventually expire and call again cleanup on the right thread. */
213       tcp_half_open_connection_cleanup (tc);
214     }
215   else
216     {
217       int thread_index = tc->c_thread_index;
218
219       /* Make sure all timers are cleared */
220       tcp_connection_timers_reset (tc);
221
222       if (!tc->c_is_ip4 && ip6_address_is_link_local_unicast (&tc->c_rmt_ip6))
223         tcp_add_del_adjacency (tc, 0);
224
225       /* Poison the entry */
226       if (CLIB_DEBUG > 0)
227         memset (tc, 0xFA, sizeof (*tc));
228       pool_put (tm->connections[thread_index], tc);
229     }
230 }
231
232 /**
233  * Connection removal.
234  *
235  * This should be called only once connection enters CLOSED state. Note
236  * that it notifies the session of the removal event, so if the goal is to
237  * just remove the connection, call tcp_connection_cleanup instead.
238  */
239 void
240 tcp_connection_del (tcp_connection_t * tc)
241 {
242   TCP_EVT_DBG (TCP_EVT_DELETE, tc);
243   stream_session_delete_notify (&tc->connection);
244   tcp_connection_cleanup (tc);
245 }
246
247 tcp_connection_t *
248 tcp_connection_new (u8 thread_index)
249 {
250   tcp_main_t *tm = vnet_get_tcp_main ();
251   tcp_connection_t *tc;
252
253   pool_get (tm->connections[thread_index], tc);
254   memset (tc, 0, sizeof (*tc));
255   tc->c_c_index = tc - tm->connections[thread_index];
256   tc->c_thread_index = thread_index;
257   return tc;
258 }
259
260 /** Notify session that connection has been reset.
261  *
262  * Switch state to closed and wait for session to call cleanup.
263  */
264 void
265 tcp_connection_reset (tcp_connection_t * tc)
266 {
267   TCP_EVT_DBG (TCP_EVT_RST_RCVD, tc);
268   switch (tc->state)
269     {
270     case TCP_STATE_SYN_RCVD:
271       /* Cleanup everything. App wasn't notified yet */
272       stream_session_delete_notify (&tc->connection);
273       tcp_connection_cleanup (tc);
274       break;
275     case TCP_STATE_SYN_SENT:
276       session_stream_connect_notify (&tc->connection, 1 /* fail */ );
277       tcp_connection_cleanup (tc);
278       break;
279     case TCP_STATE_ESTABLISHED:
280       tcp_connection_timers_reset (tc);
281       /* Set the cleanup timer, in case the session layer/app don't
282        * cleanly close the connection */
283       tcp_timer_update (tc, TCP_TIMER_WAITCLOSE, TCP_CLEANUP_TIME);
284       stream_session_reset_notify (&tc->connection);
285       break;
286     case TCP_STATE_CLOSE_WAIT:
287     case TCP_STATE_FIN_WAIT_1:
288     case TCP_STATE_FIN_WAIT_2:
289     case TCP_STATE_CLOSING:
290       tc->state = TCP_STATE_CLOSED;
291       TCP_EVT_DBG (TCP_EVT_STATE_CHANGE, tc);
292       tcp_connection_timers_reset (tc);
293       tcp_timer_update (tc, TCP_TIMER_WAITCLOSE, TCP_CLEANUP_TIME);
294       break;
295     case TCP_STATE_CLOSED:
296       return;
297     }
298 }
299
300 /**
301  * Begin connection closing procedure.
302  *
303  * If at the end the connection is not in CLOSED state, it is not removed.
304  * Instead, we rely on on TCP to advance through state machine to either
305  * 1) LAST_ACK (passive close) whereby when the last ACK is received
306  * tcp_connection_del is called. This notifies session of the delete and
307  * calls cleanup.
308  * 2) TIME_WAIT (active close) whereby after 2MSL the 2MSL timer triggers
309  * and cleanup is called.
310  *
311  * N.B. Half-close connections are not supported
312  */
313 void
314 tcp_connection_close (tcp_connection_t * tc)
315 {
316   TCP_EVT_DBG (TCP_EVT_CLOSE, tc);
317
318   /* Send/Program FIN if needed and switch state */
319   switch (tc->state)
320     {
321     case TCP_STATE_SYN_SENT:
322       tc->state = TCP_STATE_CLOSED;
323       break;
324     case TCP_STATE_SYN_RCVD:
325       tcp_send_fin (tc);
326       tc->state = TCP_STATE_FIN_WAIT_1;
327       break;
328     case TCP_STATE_ESTABLISHED:
329       if (!session_tx_fifo_max_dequeue (&tc->connection))
330         tcp_send_fin (tc);
331       else
332         tc->flags |= TCP_CONN_FINPNDG;
333       tc->state = TCP_STATE_FIN_WAIT_1;
334       break;
335     case TCP_STATE_CLOSE_WAIT:
336       if (!session_tx_fifo_max_dequeue (&tc->connection))
337         {
338           tcp_send_fin (tc);
339           tcp_connection_timers_reset (tc);
340           tc->state = TCP_STATE_LAST_ACK;
341           tcp_timer_update (tc, TCP_TIMER_WAITCLOSE, TCP_2MSL_TIME);
342         }
343       else
344         tc->flags |= TCP_CONN_FINPNDG;
345       break;
346     case TCP_STATE_FIN_WAIT_1:
347       tcp_timer_update (tc, TCP_TIMER_WAITCLOSE, TCP_2MSL_TIME);
348       break;
349     default:
350       TCP_DBG ("state: %u", tc->state);
351     }
352
353   TCP_EVT_DBG (TCP_EVT_STATE_CHANGE, tc);
354
355   /* If in CLOSED and WAITCLOSE timer is not set, delete connection now */
356   if (!tcp_timer_is_active (tc, TCP_TIMER_WAITCLOSE)
357       && tc->state == TCP_STATE_CLOSED)
358     tcp_connection_del (tc);
359 }
360
361 static void
362 tcp_session_close (u32 conn_index, u32 thread_index)
363 {
364   tcp_connection_t *tc;
365   tc = tcp_connection_get (conn_index, thread_index);
366   tcp_connection_close (tc);
367 }
368
369 static void
370 tcp_session_cleanup (u32 conn_index, u32 thread_index)
371 {
372   tcp_connection_t *tc;
373   tc = tcp_connection_get (conn_index, thread_index);
374   tcp_connection_timers_reset (tc);
375   tc->state = TCP_STATE_CLOSED;
376   TCP_EVT_DBG (TCP_EVT_STATE_CHANGE, tc);
377   tcp_connection_cleanup (tc);
378 }
379
380 /**
381  * Initialize all connection timers as invalid
382  */
383 void
384 tcp_connection_timers_init (tcp_connection_t * tc)
385 {
386   int i;
387
388   /* Set all to invalid */
389   for (i = 0; i < TCP_N_TIMERS; i++)
390     {
391       tc->timers[i] = TCP_TIMER_HANDLE_INVALID;
392     }
393
394   tc->rto = TCP_RTO_INIT;
395 }
396
397 /**
398  * Stop all connection timers
399  */
400 void
401 tcp_connection_timers_reset (tcp_connection_t * tc)
402 {
403   int i;
404   for (i = 0; i < TCP_N_TIMERS; i++)
405     {
406       tcp_timer_reset (tc, i);
407     }
408 }
409
410 #if 0
411 typedef struct ip4_tcp_hdr
412 {
413   ip4_header_t ip;
414   tcp_header_t tcp;
415 } ip4_tcp_hdr_t;
416
417 typedef struct ip6_tcp_hdr
418 {
419   ip6_header_t ip;
420   tcp_header_t tcp;
421 } ip6_tcp_hdr_t;
422
423 static void
424 tcp_connection_select_lb_bucket (tcp_connection_t * tc, const dpo_id_t * dpo,
425                                  dpo_id_t * result)
426 {
427   const dpo_id_t *choice;
428   load_balance_t *lb;
429   int hash;
430
431   lb = load_balance_get (dpo->dpoi_index);
432   if (tc->c_is_ip4)
433     {
434       ip4_tcp_hdr_t hdr;
435       memset (&hdr, 0, sizeof (hdr));
436       hdr.ip.protocol = IP_PROTOCOL_TCP;
437       hdr.ip.address_pair.src.as_u32 = tc->c_lcl_ip.ip4.as_u32;
438       hdr.ip.address_pair.dst.as_u32 = tc->c_rmt_ip.ip4.as_u32;
439       hdr.tcp.src_port = tc->c_lcl_port;
440       hdr.tcp.dst_port = tc->c_rmt_port;
441       hash = ip4_compute_flow_hash (&hdr.ip, lb->lb_hash_config);
442     }
443   else
444     {
445       ip6_tcp_hdr_t hdr;
446       memset (&hdr, 0, sizeof (hdr));
447       hdr.ip.protocol = IP_PROTOCOL_TCP;
448       clib_memcpy (&hdr.ip.src_address, &tc->c_lcl_ip.ip6,
449                    sizeof (ip6_address_t));
450       clib_memcpy (&hdr.ip.dst_address, &tc->c_rmt_ip.ip6,
451                    sizeof (ip6_address_t));
452       hdr.tcp.src_port = tc->c_lcl_port;
453       hdr.tcp.dst_port = tc->c_rmt_port;
454       hash = ip6_compute_flow_hash (&hdr.ip, lb->lb_hash_config);
455     }
456   choice = load_balance_get_bucket_i (lb, hash & lb->lb_n_buckets_minus_1);
457   dpo_copy (result, choice);
458 }
459
460 fib_node_index_t
461 tcp_lookup_rmt_in_fib (tcp_connection_t * tc)
462 {
463   fib_prefix_t prefix;
464   u32 fib_index;
465
466   clib_memcpy (&prefix.fp_addr, &tc->c_rmt_ip, sizeof (prefix.fp_addr));
467   prefix.fp_proto = tc->c_is_ip4 ? FIB_PROTOCOL_IP4 : FIB_PROTOCOL_IP6;
468   prefix.fp_len = tc->c_is_ip4 ? 32 : 128;
469   fib_index = fib_table_find (prefix.fp_proto, tc->c_fib_index);
470   return fib_table_lookup (fib_index, &prefix);
471 }
472
473 static int
474 tcp_connection_stack_on_fib_entry (tcp_connection_t * tc)
475 {
476   dpo_id_t choice = DPO_INVALID;
477   u32 output_node_index;
478   fib_entry_t *fe;
479
480   fe = fib_entry_get (tc->c_rmt_fei);
481   if (fe->fe_lb.dpoi_type != DPO_LOAD_BALANCE)
482     return -1;
483
484   tcp_connection_select_lb_bucket (tc, &fe->fe_lb, &choice);
485
486   output_node_index =
487     tc->c_is_ip4 ? tcp4_output_node.index : tcp6_output_node.index;
488   dpo_stack_from_node (output_node_index, &tc->c_rmt_dpo, &choice);
489   return 0;
490 }
491
492 /** Stack tcp connection on peer's fib entry.
493  *
494  * This ultimately populates the dpo the connection will use to send packets.
495  */
496 static void
497 tcp_connection_fib_attach (tcp_connection_t * tc)
498 {
499   tc->c_rmt_fei = tcp_lookup_rmt_in_fib (tc);
500
501   ASSERT (tc->c_rmt_fei != FIB_NODE_INDEX_INVALID);
502
503   tcp_connection_stack_on_fib_entry (tc);
504 }
505 #endif /* 0 */
506
507 static void
508 tcp_cc_init (tcp_connection_t * tc)
509 {
510   tc->cc_algo = tcp_cc_algo_get (TCP_CC_NEWRENO);
511   tc->cc_algo->init (tc);
512 }
513
514 void
515 tcp_cc_algo_register (tcp_cc_algorithm_type_e type,
516                       const tcp_cc_algorithm_t * vft)
517 {
518   tcp_main_t *tm = vnet_get_tcp_main ();
519   vec_validate (tm->cc_algos, type);
520
521   tm->cc_algos[type] = *vft;
522 }
523
524 tcp_cc_algorithm_t *
525 tcp_cc_algo_get (tcp_cc_algorithm_type_e type)
526 {
527   tcp_main_t *tm = vnet_get_tcp_main ();
528   return &tm->cc_algos[type];
529 }
530
531
532 /**
533  * Initialize connection send variables.
534  */
535 void
536 tcp_init_snd_vars (tcp_connection_t * tc)
537 {
538   u32 time_now;
539
540   /*
541    * We use the time to randomize iss and for setting up the initial
542    * timestamp. Make sure it's updated otherwise syn and ack in the
543    * handshake may make it look as if time has flown in the opposite
544    * direction for us.
545    */
546   tcp_set_time_now (vlib_get_thread_index ());
547   time_now = tcp_time_now ();
548
549   tc->iss = random_u32 (&time_now);
550   tc->snd_una = tc->iss;
551   tc->snd_nxt = tc->iss + 1;
552   tc->snd_una_max = tc->snd_nxt;
553 }
554
555 /** Initialize tcp connection variables
556  *
557  * Should be called after having received a msg from the peer, i.e., a SYN or
558  * a SYNACK, such that connection options have already been exchanged. */
559 void
560 tcp_connection_init_vars (tcp_connection_t * tc)
561 {
562   tcp_connection_timers_init (tc);
563   tcp_init_mss (tc);
564   scoreboard_init (&tc->sack_sb);
565   tcp_cc_init (tc);
566   if (tc->state == TCP_STATE_SYN_RCVD)
567     tcp_init_snd_vars (tc);
568
569   if (!tc->c_is_ip4 && ip6_address_is_link_local_unicast (&tc->c_rmt_ip6))
570     tcp_add_del_adjacency (tc, 1);
571
572   //  tcp_connection_fib_attach (tc);
573 }
574
575 static int
576 tcp_alloc_custom_local_endpoint (tcp_main_t * tm, ip46_address_t * lcl_addr,
577                                  u16 * lcl_port, u8 is_ip4)
578 {
579   int index, port;
580   if (is_ip4)
581     {
582       index = tm->last_v4_address_rotor++;
583       if (tm->last_v4_address_rotor >= vec_len (tm->ip4_src_addresses))
584         tm->last_v4_address_rotor = 0;
585       lcl_addr->ip4.as_u32 = tm->ip4_src_addresses[index].as_u32;
586     }
587   else
588     {
589       index = tm->last_v6_address_rotor++;
590       if (tm->last_v6_address_rotor >= vec_len (tm->ip6_src_addresses))
591         tm->last_v6_address_rotor = 0;
592       clib_memcpy (&lcl_addr->ip6, &tm->ip6_src_addresses[index],
593                    sizeof (ip6_address_t));
594     }
595   port = transport_alloc_local_port (TRANSPORT_PROTO_TCP, lcl_addr);
596   if (port < 1)
597     {
598       clib_warning ("Failed to allocate src port");
599       return -1;
600     }
601   *lcl_port = port;
602   return 0;
603 }
604
605 static int
606 tcp_connection_open (transport_endpoint_t * rmt)
607 {
608   tcp_main_t *tm = vnet_get_tcp_main ();
609   tcp_connection_t *tc;
610   ip46_address_t lcl_addr;
611   u16 lcl_port;
612   int rv;
613
614   /*
615    * Allocate local endpoint
616    */
617   if ((rmt->is_ip4 && vec_len (tm->ip4_src_addresses))
618       || (!rmt->is_ip4 && vec_len (tm->ip6_src_addresses)))
619     rv = tcp_alloc_custom_local_endpoint (tm, &lcl_addr, &lcl_port,
620                                           rmt->is_ip4);
621   else
622     rv = transport_alloc_local_endpoint (TRANSPORT_PROTO_TCP,
623                                          rmt, &lcl_addr, &lcl_port);
624
625   if (rv)
626     return -1;
627
628   /*
629    * Create connection and send SYN
630    */
631   clib_spinlock_lock_if_init (&tm->half_open_lock);
632   tc = tcp_half_open_connection_new ();
633   ip_copy (&tc->c_rmt_ip, &rmt->ip, rmt->is_ip4);
634   ip_copy (&tc->c_lcl_ip, &lcl_addr, rmt->is_ip4);
635   tc->c_rmt_port = rmt->port;
636   tc->c_lcl_port = clib_host_to_net_u16 (lcl_port);
637   tc->c_is_ip4 = rmt->is_ip4;
638   tc->c_proto = TRANSPORT_PROTO_TCP;
639   tc->c_fib_index = rmt->fib_index;
640   /* The other connection vars will be initialized after SYN ACK */
641   tcp_connection_timers_init (tc);
642
643   TCP_EVT_DBG (TCP_EVT_OPEN, tc);
644   tc->state = TCP_STATE_SYN_SENT;
645   tcp_init_snd_vars (tc);
646   tcp_send_syn (tc);
647   clib_spinlock_unlock_if_init (&tm->half_open_lock);
648
649   return tc->c_c_index;
650 }
651
652 static int
653 tcp_session_open (transport_endpoint_t * tep)
654 {
655   return tcp_connection_open (tep);
656 }
657
658 const char *tcp_dbg_evt_str[] = {
659 #define _(sym, str) str,
660   foreach_tcp_dbg_evt
661 #undef _
662 };
663
664 const char *tcp_fsm_states[] = {
665 #define _(sym, str) str,
666   foreach_tcp_fsm_state
667 #undef _
668 };
669
670 u8 *
671 format_tcp_state (u8 * s, va_list * args)
672 {
673   u32 state = va_arg (*args, u32);
674
675   if (state < TCP_N_STATES)
676     s = format (s, "%s", tcp_fsm_states[state]);
677   else
678     s = format (s, "UNKNOWN (%d (0x%x))", state, state);
679   return s;
680 }
681
682 const char *tcp_connection_flags_str[] = {
683 #define _(sym, str) str,
684   foreach_tcp_connection_flag
685 #undef _
686 };
687
688 static u8 *
689 format_tcp_connection_flags (u8 * s, va_list * args)
690 {
691   tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
692   int i, last = -1;
693
694   for (i = 0; i < TCP_CONN_N_FLAG_BITS; i++)
695     if (tc->flags & (1 << i))
696       last = i;
697   for (i = 0; i < last; i++)
698     {
699       if (tc->flags & (1 << i))
700         s = format (s, "%s, ", tcp_connection_flags_str[i]);
701     }
702   if (last >= 0)
703     s = format (s, "%s", tcp_connection_flags_str[last]);
704   return s;
705 }
706
707 const char *tcp_conn_timers[] = {
708 #define _(sym, str) str,
709   foreach_tcp_timer
710 #undef _
711 };
712
713 static u8 *
714 format_tcp_timers (u8 * s, va_list * args)
715 {
716   tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
717   int i, last = -1;
718
719   for (i = 0; i < TCP_N_TIMERS; i++)
720     if (tc->timers[i] != TCP_TIMER_HANDLE_INVALID)
721       last = i;
722
723   s = format (s, "[");
724   for (i = 0; i < last; i++)
725     {
726       if (tc->timers[i] != TCP_TIMER_HANDLE_INVALID)
727         s = format (s, "%s,", tcp_conn_timers[i]);
728     }
729
730   if (last >= 0)
731     s = format (s, "%s]", tcp_conn_timers[i]);
732   else
733     s = format (s, "]");
734
735   return s;
736 }
737
738 static u8 *
739 format_tcp_congestion_status (u8 * s, va_list * args)
740 {
741   tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
742   if (tcp_in_recovery (tc))
743     s = format (s, "recovery");
744   else if (tcp_in_fastrecovery (tc))
745     s = format (s, "fastrecovery");
746   else
747     s = format (s, "none");
748   return s;
749 }
750
751 static i32
752 tcp_rcv_wnd_available (tcp_connection_t * tc)
753 {
754   return (i32) tc->rcv_wnd - (tc->rcv_nxt - tc->rcv_las);
755 }
756
757 static u8 *
758 format_tcp_vars (u8 * s, va_list * args)
759 {
760   tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
761   s = format (s, " flags: %U timers: %U\n", format_tcp_connection_flags, tc,
762               format_tcp_timers, tc);
763   s = format (s, " snd_una %u snd_nxt %u snd_una_max %u",
764               tc->snd_una - tc->iss, tc->snd_nxt - tc->iss,
765               tc->snd_una_max - tc->iss);
766   s = format (s, " rcv_nxt %u rcv_las %u\n",
767               tc->rcv_nxt - tc->irs, tc->rcv_las - tc->irs);
768   s = format (s, " snd_wnd %u rcv_wnd %u rcv_wscale %u ",
769               tc->snd_wnd, tc->rcv_wnd, tc->rcv_wscale);
770   s = format (s, "snd_wl1 %u snd_wl2 %u\n", tc->snd_wl1 - tc->irs,
771               tc->snd_wl2 - tc->iss);
772   s = format (s, " flight size %u out space %u cc space %u rcv_wnd_av %u\n",
773               tcp_flight_size (tc), tcp_available_output_snd_space (tc),
774               tcp_available_cc_snd_space (tc), tcp_rcv_wnd_available (tc));
775   s = format (s, " cong %U ", format_tcp_congestion_status, tc);
776   s = format (s, "cwnd %u ssthresh %u rtx_bytes %u bytes_acked %u\n",
777               tc->cwnd, tc->ssthresh, tc->snd_rxt_bytes, tc->bytes_acked);
778   s = format (s, " prev_ssthresh %u snd_congestion %u dupack %u",
779               tc->prev_ssthresh, tc->snd_congestion - tc->iss,
780               tc->rcv_dupacks);
781   s = format (s, " limited_transmit %u\n", tc->limited_transmit - tc->iss);
782   s = format (s, " tsecr %u tsecr_last_ack %u\n", tc->rcv_opts.tsecr,
783               tc->tsecr_last_ack);
784   s = format (s, " rto %u rto_boff %u srtt %u rttvar %u rtt_ts %u ", tc->rto,
785               tc->rto_boff, tc->srtt, tc->rttvar, tc->rtt_ts);
786   s = format (s, "rtt_seq %u\n", tc->rtt_seq);
787   s = format (s, " tsval_recent %u tsval_recent_age %u\n", tc->tsval_recent,
788               tcp_time_now () - tc->tsval_recent_age);
789   if (tc->state >= TCP_STATE_ESTABLISHED)
790     s = format (s, " scoreboard: %U\n", format_tcp_scoreboard, &tc->sack_sb,
791                 tc);
792   if (vec_len (tc->snd_sacks))
793     s = format (s, " sacks tx: %U\n", format_tcp_sacks, tc);
794
795   return s;
796 }
797
798 static u8 *
799 format_tcp_connection_id (u8 * s, va_list * args)
800 {
801   tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
802   if (!tc)
803     return s;
804   if (tc->c_is_ip4)
805     {
806       s = format (s, "[#%d][%s] %U:%d->%U:%d", tc->c_thread_index, "T",
807                   format_ip4_address, &tc->c_lcl_ip4,
808                   clib_net_to_host_u16 (tc->c_lcl_port), format_ip4_address,
809                   &tc->c_rmt_ip4, clib_net_to_host_u16 (tc->c_rmt_port));
810     }
811   else
812     {
813       s = format (s, "[#%d][%s] %U:%d->%U:%d", tc->c_thread_index, "T",
814                   format_ip6_address, &tc->c_lcl_ip6,
815                   clib_net_to_host_u16 (tc->c_lcl_port), format_ip6_address,
816                   &tc->c_rmt_ip6, clib_net_to_host_u16 (tc->c_rmt_port));
817     }
818
819   return s;
820 }
821
822 u8 *
823 format_tcp_connection (u8 * s, va_list * args)
824 {
825   tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
826   u32 verbose = va_arg (*args, u32);
827
828   if (!tc)
829     return s;
830   s = format (s, "%-50U", format_tcp_connection_id, tc);
831   if (verbose)
832     {
833       s = format (s, "%-15U", format_tcp_state, tc->state);
834       if (verbose > 1)
835         s = format (s, "\n%U", format_tcp_vars, tc);
836     }
837
838   return s;
839 }
840
841 static u8 *
842 format_tcp_session (u8 * s, va_list * args)
843 {
844   u32 tci = va_arg (*args, u32);
845   u32 thread_index = va_arg (*args, u32);
846   u32 verbose = va_arg (*args, u32);
847   tcp_connection_t *tc;
848
849   tc = tcp_connection_get (tci, thread_index);
850   if (tc)
851     s = format (s, "%U", format_tcp_connection, tc, verbose);
852   else
853     s = format (s, "empty\n");
854   return s;
855 }
856
857 static u8 *
858 format_tcp_listener_session (u8 * s, va_list * args)
859 {
860   u32 tci = va_arg (*args, u32);
861   tcp_connection_t *tc = tcp_listener_get (tci);
862   return format (s, "%U", format_tcp_connection_id, tc);
863 }
864
865 static u8 *
866 format_tcp_half_open_session (u8 * s, va_list * args)
867 {
868   u32 tci = va_arg (*args, u32);
869   tcp_connection_t *tc = tcp_half_open_connection_get (tci);
870   return format (s, "%U", format_tcp_connection_id, tc);
871 }
872
873 u8 *
874 format_tcp_sacks (u8 * s, va_list * args)
875 {
876   tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
877   sack_block_t *sacks = tc->snd_sacks;
878   sack_block_t *block;
879   int i, len = 0;
880
881   len = vec_len (sacks);
882   for (i = 0; i < len - 1; i++)
883     {
884       block = &sacks[i];
885       s = format (s, " start %u end %u\n", block->start - tc->irs,
886                   block->end - tc->irs);
887     }
888   if (len)
889     {
890       block = &sacks[len - 1];
891       s = format (s, " start %u end %u", block->start - tc->irs,
892                   block->end - tc->irs);
893     }
894   return s;
895 }
896
897 u8 *
898 format_tcp_rcv_sacks (u8 * s, va_list * args)
899 {
900   tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
901   sack_block_t *sacks = tc->rcv_opts.sacks;
902   sack_block_t *block;
903   int i, len = 0;
904
905   len = vec_len (sacks);
906   for (i = 0; i < len - 1; i++)
907     {
908       block = &sacks[i];
909       s = format (s, " start %u end %u\n", block->start - tc->iss,
910                   block->end - tc->iss);
911     }
912   if (len)
913     {
914       block = &sacks[len - 1];
915       s = format (s, " start %u end %u", block->start - tc->iss,
916                   block->end - tc->iss);
917     }
918   return s;
919 }
920
921 static u8 *
922 format_tcp_sack_hole (u8 * s, va_list * args)
923 {
924   sack_scoreboard_hole_t *hole = va_arg (*args, sack_scoreboard_hole_t *);
925   tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
926   if (tc)
927     s = format (s, "  [%u, %u]", hole->start - tc->iss, hole->end - tc->iss);
928   else
929     s = format (s, "  [%u, %u]", hole->start, hole->end);
930   return s;
931 }
932
933 u8 *
934 format_tcp_scoreboard (u8 * s, va_list * args)
935 {
936   sack_scoreboard_t *sb = va_arg (*args, sack_scoreboard_t *);
937   tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
938   sack_scoreboard_hole_t *hole;
939   s = format (s, "sacked_bytes %u last_sacked_bytes %u lost_bytes %u\n",
940               sb->sacked_bytes, sb->last_sacked_bytes, sb->lost_bytes);
941   s = format (s, " last_bytes_delivered %u high_sacked %u snd_una_adv %u\n",
942               sb->last_bytes_delivered, sb->high_sacked, sb->snd_una_adv);
943   s = format (s, " cur_rxt_hole %u high_rxt %u rescue_rxt %u",
944               sb->cur_rxt_hole, sb->high_rxt, sb->rescue_rxt);
945
946   hole = scoreboard_first_hole (sb);
947   if (hole)
948     s = format (s, "\n head %u tail %u holes:\n", sb->head, sb->tail);
949
950   while (hole)
951     {
952       s = format (s, "%U", format_tcp_sack_hole, hole, tc);
953       hole = scoreboard_next_hole (sb, hole);
954     }
955
956   return s;
957 }
958
959 static transport_connection_t *
960 tcp_session_get_transport (u32 conn_index, u32 thread_index)
961 {
962   tcp_connection_t *tc = tcp_connection_get (conn_index, thread_index);
963   return &tc->connection;
964 }
965
966 static transport_connection_t *
967 tcp_half_open_session_get_transport (u32 conn_index)
968 {
969   tcp_connection_t *tc = tcp_half_open_connection_get (conn_index);
970   return &tc->connection;
971 }
972
973 /**
974  * Compute maximum segment size for session layer.
975  *
976  * Since the result needs to be the actual data length, it first computes
977  * the tcp options to be used in the next burst and subtracts their
978  * length from the connection's snd_mss.
979  */
980 static u16
981 tcp_session_send_mss (transport_connection_t * trans_conn)
982 {
983   tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
984
985   /* Ensure snd_mss does accurately reflect the amount of data we can push
986    * in a segment. This also makes sure that options are updated according to
987    * the current state of the connection. */
988   tcp_update_burst_snd_vars (tc);
989
990   return tc->snd_mss;
991 }
992
993 always_inline u32
994 tcp_round_snd_space (tcp_connection_t * tc, u32 snd_space)
995 {
996   if (PREDICT_FALSE (tc->snd_wnd < tc->snd_mss))
997     {
998       return tc->snd_wnd <= snd_space ? tc->snd_wnd : 0;
999     }
1000
1001   /* If not snd_wnd constrained and we can't write at least a segment,
1002    * don't try at all */
1003   if (PREDICT_FALSE (snd_space < tc->snd_mss))
1004     return snd_space < tc->cwnd ? 0 : snd_space;
1005
1006   /* round down to mss multiple */
1007   return snd_space - (snd_space % tc->snd_mss);
1008 }
1009
1010 /**
1011  * Compute tx window session is allowed to fill.
1012  *
1013  * Takes into account available send space, snd_mss and the congestion
1014  * state of the connection. If possible, the value returned is a multiple
1015  * of snd_mss.
1016  *
1017  * @param tc tcp connection
1018  * @return number of bytes session is allowed to write
1019  */
1020 static inline u32
1021 tcp_snd_space_inline (tcp_connection_t * tc)
1022 {
1023   int snd_space, snt_limited;
1024
1025   if (PREDICT_TRUE (tcp_in_cong_recovery (tc) == 0))
1026     {
1027       snd_space = tcp_available_output_snd_space (tc);
1028
1029       /* If we haven't gotten dupacks or if we did and have gotten sacked
1030        * bytes then we can still send as per Limited Transmit (RFC3042) */
1031       if (PREDICT_FALSE (tc->rcv_dupacks != 0
1032                          && (tcp_opts_sack_permitted (tc)
1033                              && tc->sack_sb.last_sacked_bytes == 0)))
1034         {
1035           if (tc->rcv_dupacks == 1 && tc->limited_transmit != tc->snd_nxt)
1036             tc->limited_transmit = tc->snd_nxt;
1037           ASSERT (seq_leq (tc->limited_transmit, tc->snd_nxt));
1038
1039           snt_limited = tc->snd_nxt - tc->limited_transmit;
1040           snd_space = clib_max (2 * tc->snd_mss - snt_limited, 0);
1041         }
1042       return tcp_round_snd_space (tc, snd_space);
1043     }
1044
1045   if (tcp_in_recovery (tc))
1046     {
1047       tc->snd_nxt = tc->snd_una_max;
1048       snd_space = tcp_available_snd_wnd (tc) - tc->snd_rxt_bytes
1049         - (tc->snd_una_max - tc->snd_congestion);
1050       if (snd_space <= 0 || (tc->snd_una_max - tc->snd_una) >= tc->snd_wnd)
1051         return 0;
1052       return tcp_round_snd_space (tc, snd_space);
1053     }
1054
1055   /* RFC 5681: When previously unsent data is available and the new value of
1056    * cwnd and the receiver's advertised window allow, a TCP SHOULD send 1*SMSS
1057    * bytes of previously unsent data. */
1058   if (tcp_in_fastrecovery (tc) && !tcp_fastrecovery_sent_1_smss (tc))
1059     {
1060       if (tcp_available_cc_snd_space (tc) < tc->snd_mss)
1061         return 0;
1062       tcp_fastrecovery_1_smss_on (tc);
1063       return tc->snd_mss;
1064     }
1065
1066   return 0;
1067 }
1068
1069 u32
1070 tcp_snd_space (tcp_connection_t * tc)
1071 {
1072   return tcp_snd_space_inline (tc);
1073 }
1074
1075 static u32
1076 tcp_session_send_space (transport_connection_t * trans_conn)
1077 {
1078   tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
1079   return clib_min (tcp_snd_space_inline (tc),
1080                    tc->snd_wnd - (tc->snd_nxt - tc->snd_una));
1081 }
1082
1083 static u32
1084 tcp_session_tx_fifo_offset (transport_connection_t * trans_conn)
1085 {
1086   tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
1087
1088   ASSERT (seq_geq (tc->snd_nxt, tc->snd_una));
1089
1090   /* This still works if fast retransmit is on */
1091   return (tc->snd_nxt - tc->snd_una);
1092 }
1093
1094 static void
1095 tcp_update_time (f64 now, u8 thread_index)
1096 {
1097   tcp_set_time_now (thread_index);
1098   tw_timer_expire_timers_16t_2w_512sl (&tcp_main.
1099                                        wrk_ctx[thread_index].timer_wheel,
1100                                        now);
1101   tcp_flush_frames_to_output (thread_index);
1102 }
1103
1104 static u32
1105 tcp_session_push_header (transport_connection_t * tconn, vlib_buffer_t * b)
1106 {
1107   tcp_connection_t *tc = (tcp_connection_t *) tconn;
1108   return tcp_push_header (tc, b);
1109 }
1110
1111 /* *INDENT-OFF* */
1112 const static transport_proto_vft_t tcp_proto = {
1113   .enable = vnet_tcp_enable_disable,
1114   .bind = tcp_session_bind,
1115   .unbind = tcp_session_unbind,
1116   .push_header = tcp_session_push_header,
1117   .get_connection = tcp_session_get_transport,
1118   .get_listener = tcp_session_get_listener,
1119   .get_half_open = tcp_half_open_session_get_transport,
1120   .open = tcp_session_open,
1121   .close = tcp_session_close,
1122   .cleanup = tcp_session_cleanup,
1123   .send_mss = tcp_session_send_mss,
1124   .send_space = tcp_session_send_space,
1125   .update_time = tcp_update_time,
1126   .tx_fifo_offset = tcp_session_tx_fifo_offset,
1127   .format_connection = format_tcp_session,
1128   .format_listener = format_tcp_listener_session,
1129   .format_half_open = format_tcp_half_open_session,
1130   .tx_type = TRANSPORT_TX_PEEK,
1131   .service_type = TRANSPORT_SERVICE_VC,
1132 };
1133 /* *INDENT-ON* */
1134
1135 static void
1136 tcp_timer_keep_handler (u32 conn_index)
1137 {
1138   u32 thread_index = vlib_get_thread_index ();
1139   tcp_connection_t *tc;
1140
1141   tc = tcp_connection_get (conn_index, thread_index);
1142   tc->timers[TCP_TIMER_KEEP] = TCP_TIMER_HANDLE_INVALID;
1143
1144   tcp_connection_close (tc);
1145 }
1146
1147 static void
1148 tcp_timer_establish_handler (u32 conn_index)
1149 {
1150   tcp_connection_t *tc;
1151
1152   tc = tcp_half_open_connection_get (conn_index);
1153   if (tc)
1154     {
1155       ASSERT (tc->state == TCP_STATE_SYN_SENT);
1156       session_stream_connect_notify (&tc->connection, 1 /* fail */ );
1157       TCP_DBG ("establish pop: %U", format_tcp_connection, tc, 2);
1158     }
1159   else
1160     {
1161       tc = tcp_connection_get (conn_index, vlib_get_thread_index ());
1162       /* note: the connection may have already disappeared */
1163       if (PREDICT_FALSE (tc == 0))
1164         return;
1165       TCP_DBG ("establish pop: %U", format_tcp_connection, tc, 2);
1166       ASSERT (tc->state == TCP_STATE_SYN_RCVD);
1167       /* Start cleanup. App wasn't notified yet so use delete notify as
1168        * opposed to delete to cleanup session layer state. */
1169       stream_session_delete_notify (&tc->connection);
1170     }
1171   tc->timers[TCP_TIMER_ESTABLISH] = TCP_TIMER_HANDLE_INVALID;
1172   tcp_connection_cleanup (tc);
1173 }
1174
1175 static void
1176 tcp_timer_waitclose_handler (u32 conn_index)
1177 {
1178   u32 thread_index = vlib_get_thread_index ();
1179   tcp_connection_t *tc;
1180
1181   tc = tcp_connection_get (conn_index, thread_index);
1182   if (!tc)
1183     return;
1184   tc->timers[TCP_TIMER_WAITCLOSE] = TCP_TIMER_HANDLE_INVALID;
1185
1186   /* Session didn't come back with a close(). Send FIN either way
1187    * and switch to LAST_ACK. */
1188   if (tc->state == TCP_STATE_CLOSE_WAIT)
1189     {
1190       if (tc->flags & TCP_CONN_FINSNT)
1191         {
1192           clib_warning ("FIN was sent and still in CLOSE WAIT. Weird!");
1193         }
1194
1195       /* Make sure we don't try to send unsent data */
1196       tcp_connection_timers_reset (tc);
1197       tcp_cong_recovery_off (tc);
1198       tc->snd_una_max = tc->snd_nxt = tc->snd_una;
1199       tcp_send_fin (tc);
1200       tc->state = TCP_STATE_LAST_ACK;
1201
1202       /* Make sure we don't wait in LAST ACK forever */
1203       tcp_timer_set (tc, TCP_TIMER_WAITCLOSE, TCP_2MSL_TIME);
1204
1205       /* Don't delete the connection yet */
1206       return;
1207     }
1208
1209   tcp_connection_del (tc);
1210 }
1211
1212 /* *INDENT-OFF* */
1213 static timer_expiration_handler *timer_expiration_handlers[TCP_N_TIMERS] =
1214 {
1215     tcp_timer_retransmit_handler,
1216     tcp_timer_delack_handler,
1217     tcp_timer_persist_handler,
1218     tcp_timer_keep_handler,
1219     tcp_timer_waitclose_handler,
1220     tcp_timer_retransmit_syn_handler,
1221     tcp_timer_establish_handler
1222 };
1223 /* *INDENT-ON* */
1224
1225 static void
1226 tcp_expired_timers_dispatch (u32 * expired_timers)
1227 {
1228   int i;
1229   u32 connection_index, timer_id;
1230
1231   for (i = 0; i < vec_len (expired_timers); i++)
1232     {
1233       /* Get session index and timer id */
1234       connection_index = expired_timers[i] & 0x0FFFFFFF;
1235       timer_id = expired_timers[i] >> 28;
1236
1237       TCP_EVT_DBG (TCP_EVT_TIMER_POP, connection_index, timer_id);
1238
1239       /* Handle expiration */
1240       (*timer_expiration_handlers[timer_id]) (connection_index);
1241     }
1242 }
1243
1244 static void
1245 tcp_initialize_timer_wheels (tcp_main_t * tm)
1246 {
1247   tw_timer_wheel_16t_2w_512sl_t *tw;
1248   /* *INDENT-OFF* */
1249   foreach_vlib_main (({
1250     tw = &tm->wrk_ctx[ii].timer_wheel;
1251     tw_timer_wheel_init_16t_2w_512sl (tw, tcp_expired_timers_dispatch,
1252                                       100e-3 /* timer period 100ms */ , ~0);
1253     tw->last_run_time = vlib_time_now (this_vlib_main);
1254   }));
1255   /* *INDENT-ON* */
1256 }
1257
1258 static clib_error_t *
1259 tcp_main_enable (vlib_main_t * vm)
1260 {
1261   tcp_main_t *tm = vnet_get_tcp_main ();
1262   vlib_thread_main_t *vtm = vlib_get_thread_main ();
1263   clib_error_t *error = 0;
1264   u32 num_threads;
1265   int thread;
1266   tcp_connection_t *tc __attribute__ ((unused));
1267   u32 preallocated_connections_per_thread;
1268
1269   if ((error = vlib_call_init_function (vm, ip_main_init)))
1270     return error;
1271   if ((error = vlib_call_init_function (vm, ip4_lookup_init)))
1272     return error;
1273   if ((error = vlib_call_init_function (vm, ip6_lookup_init)))
1274     return error;
1275
1276   /*
1277    * Registrations
1278    */
1279
1280   ip4_register_protocol (IP_PROTOCOL_TCP, tcp4_input_node.index);
1281   ip6_register_protocol (IP_PROTOCOL_TCP, tcp6_input_node.index);
1282
1283   /*
1284    * Initialize data structures
1285    */
1286
1287   num_threads = 1 /* main thread */  + vtm->n_threads;
1288   vec_validate (tm->connections, num_threads - 1);
1289
1290   /*
1291    * Preallocate connections. Assume that thread 0 won't
1292    * use preallocated threads when running multi-core
1293    */
1294   if (num_threads == 1)
1295     {
1296       thread = 0;
1297       preallocated_connections_per_thread = tm->preallocated_connections;
1298     }
1299   else
1300     {
1301       thread = 1;
1302       preallocated_connections_per_thread =
1303         tm->preallocated_connections / (num_threads - 1);
1304     }
1305   for (; thread < num_threads; thread++)
1306     {
1307       if (preallocated_connections_per_thread)
1308         pool_init_fixed (tm->connections[thread],
1309                          preallocated_connections_per_thread);
1310     }
1311
1312   /*
1313    * Use a preallocated half-open connection pool?
1314    */
1315   if (tm->preallocated_half_open_connections)
1316     pool_init_fixed (tm->half_open_connections,
1317                      tm->preallocated_half_open_connections);
1318
1319   /* Initialize clocks per tick for TCP timestamp. Used to compute
1320    * monotonically increasing timestamps. */
1321   tm->tstamp_ticks_per_clock = vm->clib_time.seconds_per_clock
1322     / TCP_TSTAMP_RESOLUTION;
1323
1324   if (num_threads > 1)
1325     {
1326       clib_spinlock_init (&tm->half_open_lock);
1327     }
1328
1329   vec_validate (tm->wrk_ctx, num_threads - 1);
1330   tcp_initialize_timer_wheels (tm);
1331
1332   tm->bytes_per_buffer = vlib_buffer_free_list_buffer_size
1333     (vm, VLIB_BUFFER_DEFAULT_FREE_LIST_INDEX);
1334
1335   return error;
1336 }
1337
1338 clib_error_t *
1339 vnet_tcp_enable_disable (vlib_main_t * vm, u8 is_en)
1340 {
1341   if (is_en)
1342     {
1343       if (tcp_main.is_enabled)
1344         return 0;
1345
1346       return tcp_main_enable (vm);
1347     }
1348   else
1349     {
1350       tcp_main.is_enabled = 0;
1351     }
1352
1353   return 0;
1354 }
1355
1356 void
1357 tcp_punt_unknown (vlib_main_t * vm, u8 is_ip4, u8 is_add)
1358 {
1359   tcp_main_t *tm = &tcp_main;
1360   if (is_ip4)
1361     tm->punt_unknown4 = is_add;
1362   else
1363     tm->punt_unknown6 = is_add;
1364 }
1365
1366 static clib_error_t *
1367 tcp_init (vlib_main_t * vm)
1368 {
1369   tcp_main_t *tm = vnet_get_tcp_main ();
1370   ip_main_t *im = &ip_main;
1371   ip_protocol_info_t *pi;
1372
1373   /* Session layer, and by implication tcp, are disabled by default */
1374   tm->is_enabled = 0;
1375
1376   /* Register with IP for header parsing */
1377   pi = ip_get_protocol_info (im, IP_PROTOCOL_TCP);
1378   if (pi == 0)
1379     return clib_error_return (0, "TCP protocol info AWOL");
1380   pi->format_header = format_tcp_header;
1381   pi->unformat_pg_edit = unformat_pg_tcp_header;
1382
1383   /* Register as transport with session layer */
1384   transport_register_protocol (TRANSPORT_PROTO_TCP, &tcp_proto,
1385                                FIB_PROTOCOL_IP4, tcp4_output_node.index);
1386   transport_register_protocol (TRANSPORT_PROTO_TCP, &tcp_proto,
1387                                FIB_PROTOCOL_IP6, tcp6_output_node.index);
1388
1389   tcp_api_reference ();
1390   return 0;
1391 }
1392
1393 VLIB_INIT_FUNCTION (tcp_init);
1394
1395 static clib_error_t *
1396 tcp_config_fn (vlib_main_t * vm, unformat_input_t * input)
1397 {
1398   tcp_main_t *tm = vnet_get_tcp_main ();
1399
1400   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1401     {
1402       if (unformat (input, "preallocated-connections %d",
1403                     &tm->preallocated_connections))
1404         ;
1405       else if (unformat (input, "preallocated-half-open-connections %d",
1406                          &tm->preallocated_half_open_connections))
1407         ;
1408       else if (unformat (input, "buffer-fail-fraction %f",
1409                          &tm->buffer_fail_fraction))
1410         ;
1411       else if (unformat (input, "max-rx-fifo %U", unformat_memory_size,
1412                          &tm->max_rx_fifo))
1413         ;
1414       else
1415         return clib_error_return (0, "unknown input `%U'",
1416                                   format_unformat_error, input);
1417     }
1418   return 0;
1419 }
1420
1421 VLIB_CONFIG_FUNCTION (tcp_config_fn, "tcp");
1422
1423
1424 /**
1425  * \brief Configure an ipv4 source address range
1426  * @param vm vlib_main_t pointer
1427  * @param start first ipv4 address in the source address range
1428  * @param end last ipv4 address in the source address range
1429  * @param table_id VRF / table ID, 0 for the default FIB
1430  * @return 0 if all OK, else an error indication from api_errno.h
1431  */
1432
1433 int
1434 tcp_configure_v4_source_address_range (vlib_main_t * vm,
1435                                        ip4_address_t * start,
1436                                        ip4_address_t * end, u32 table_id)
1437 {
1438   tcp_main_t *tm = vnet_get_tcp_main ();
1439   vnet_main_t *vnm = vnet_get_main ();
1440   u32 start_host_byte_order, end_host_byte_order;
1441   fib_prefix_t prefix;
1442   vnet_sw_interface_t *si;
1443   fib_node_index_t fei;
1444   u32 fib_index = 0;
1445   u32 sw_if_index;
1446   int rv;
1447   int vnet_proxy_arp_add_del (ip4_address_t * lo_addr,
1448                               ip4_address_t * hi_addr, u32 fib_index,
1449                               int is_del);
1450
1451   memset (&prefix, 0, sizeof (prefix));
1452
1453   fib_index = fib_table_find (FIB_PROTOCOL_IP4, table_id);
1454
1455   if (fib_index == ~0)
1456     return VNET_API_ERROR_NO_SUCH_FIB;
1457
1458   start_host_byte_order = clib_net_to_host_u32 (start->as_u32);
1459   end_host_byte_order = clib_net_to_host_u32 (end->as_u32);
1460
1461   /* sanity check for reversed args or some such */
1462   if ((end_host_byte_order - start_host_byte_order) > (10 << 10))
1463     return VNET_API_ERROR_INVALID_ARGUMENT;
1464
1465   /* Lookup the last address, to identify the interface involved */
1466   prefix.fp_len = 32;
1467   prefix.fp_proto = FIB_PROTOCOL_IP4;
1468   memcpy (&prefix.fp_addr.ip4, end, sizeof (ip4_address_t));
1469
1470   fei = fib_table_lookup (fib_index, &prefix);
1471
1472   /* Couldn't find route to destination. Bail out. */
1473   if (fei == FIB_NODE_INDEX_INVALID)
1474     return VNET_API_ERROR_NEXT_HOP_NOT_IN_FIB;
1475
1476   sw_if_index = fib_entry_get_resolving_interface (fei);
1477
1478   /* Enable proxy arp on the interface */
1479   si = vnet_get_sw_interface (vnm, sw_if_index);
1480   si->flags |= VNET_SW_INTERFACE_FLAG_PROXY_ARP;
1481
1482   /* Configure proxy arp across the range */
1483   rv = vnet_proxy_arp_add_del (start, end, fib_index, 0 /* is_del */ );
1484
1485   if (rv)
1486     return rv;
1487
1488   do
1489     {
1490       dpo_id_t dpo = DPO_INVALID;
1491
1492       vec_add1 (tm->ip4_src_addresses, start[0]);
1493
1494       /* Add local adjacencies for the range */
1495
1496       receive_dpo_add_or_lock (DPO_PROTO_IP4, ~0 /* sw_if_index */ ,
1497                                NULL, &dpo);
1498       prefix.fp_len = 32;
1499       prefix.fp_proto = FIB_PROTOCOL_IP4;
1500       prefix.fp_addr.ip4.as_u32 = start->as_u32;
1501
1502       fib_table_entry_special_dpo_update (fib_index,
1503                                           &prefix,
1504                                           FIB_SOURCE_API,
1505                                           FIB_ENTRY_FLAG_EXCLUSIVE, &dpo);
1506       dpo_reset (&dpo);
1507
1508       start_host_byte_order++;
1509       start->as_u32 = clib_host_to_net_u32 (start_host_byte_order);
1510     }
1511   while (start_host_byte_order <= end_host_byte_order);
1512
1513   return 0;
1514 }
1515
1516 /**
1517  * \brief Configure an ipv6 source address range
1518  * @param vm vlib_main_t pointer
1519  * @param start first ipv6 address in the source address range
1520  * @param end last ipv6 address in the source address range
1521  * @param table_id VRF / table ID, 0 for the default FIB
1522  * @return 0 if all OK, else an error indication from api_errno.h
1523  */
1524
1525 int
1526 tcp_configure_v6_source_address_range (vlib_main_t * vm,
1527                                        ip6_address_t * start,
1528                                        ip6_address_t * end, u32 table_id)
1529 {
1530   tcp_main_t *tm = vnet_get_tcp_main ();
1531   fib_prefix_t prefix;
1532   u32 fib_index = 0;
1533   fib_node_index_t fei;
1534   u32 sw_if_index;
1535
1536   memset (&prefix, 0, sizeof (prefix));
1537
1538   fib_index = fib_table_find (FIB_PROTOCOL_IP6, table_id);
1539
1540   if (fib_index == ~0)
1541     return VNET_API_ERROR_NO_SUCH_FIB;
1542
1543   while (1)
1544     {
1545       int i;
1546       ip6_address_t tmp;
1547       dpo_id_t dpo = DPO_INVALID;
1548
1549       /* Remember this address */
1550       vec_add1 (tm->ip6_src_addresses, start[0]);
1551
1552       /* Lookup the prefix, to identify the interface involved */
1553       prefix.fp_len = 128;
1554       prefix.fp_proto = FIB_PROTOCOL_IP6;
1555       memcpy (&prefix.fp_addr.ip6, start, sizeof (ip6_address_t));
1556
1557       fei = fib_table_lookup (fib_index, &prefix);
1558
1559       /* Couldn't find route to destination. Bail out. */
1560       if (fei == FIB_NODE_INDEX_INVALID)
1561         return VNET_API_ERROR_NEXT_HOP_NOT_IN_FIB;
1562
1563       sw_if_index = fib_entry_get_resolving_interface (fei);
1564
1565       if (sw_if_index == (u32) ~ 0)
1566         return VNET_API_ERROR_NO_MATCHING_INTERFACE;
1567
1568       /* Add a proxy neighbor discovery entry for this address */
1569       ip6_neighbor_proxy_add_del (sw_if_index, start, 0 /* is_del */ );
1570
1571       /* Add a receive adjacency for this address */
1572       receive_dpo_add_or_lock (DPO_PROTO_IP6, ~0 /* sw_if_index */ ,
1573                                NULL, &dpo);
1574
1575       fib_table_entry_special_dpo_update (fib_index,
1576                                           &prefix,
1577                                           FIB_SOURCE_API,
1578                                           FIB_ENTRY_FLAG_EXCLUSIVE, &dpo);
1579       dpo_reset (&dpo);
1580
1581       /* Done with the entire range? */
1582       if (!memcmp (start, end, sizeof (start[0])))
1583         break;
1584
1585       /* Increment the address. DGMS. */
1586       tmp = start[0];
1587       for (i = 15; i >= 0; i--)
1588         {
1589           tmp.as_u8[i] += 1;
1590           if (tmp.as_u8[i] != 0)
1591             break;
1592         }
1593       start[0] = tmp;
1594     }
1595   return 0;
1596 }
1597
1598 static clib_error_t *
1599 tcp_src_address (vlib_main_t * vm,
1600                  unformat_input_t * input, vlib_cli_command_t * cmd_arg)
1601 {
1602   ip4_address_t v4start, v4end;
1603   ip6_address_t v6start, v6end;
1604   u32 table_id = 0;
1605   int v4set = 0;
1606   int v6set = 0;
1607   int rv;
1608
1609   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1610     {
1611       if (unformat (input, "%U - %U", unformat_ip4_address, &v4start,
1612                     unformat_ip4_address, &v4end))
1613         v4set = 1;
1614       else if (unformat (input, "%U", unformat_ip4_address, &v4start))
1615         {
1616           memcpy (&v4end, &v4start, sizeof (v4start));
1617           v4set = 1;
1618         }
1619       else if (unformat (input, "%U - %U", unformat_ip6_address, &v6start,
1620                          unformat_ip6_address, &v6end))
1621         v6set = 1;
1622       else if (unformat (input, "%U", unformat_ip6_address, &v6start))
1623         {
1624           memcpy (&v6end, &v6start, sizeof (v6start));
1625           v6set = 1;
1626         }
1627       else if (unformat (input, "fib-table %d", &table_id))
1628         ;
1629       else
1630         break;
1631     }
1632
1633   if (!v4set && !v6set)
1634     return clib_error_return (0, "at least one v4 or v6 address required");
1635
1636   if (v4set)
1637     {
1638       rv = tcp_configure_v4_source_address_range (vm, &v4start, &v4end,
1639                                                   table_id);
1640       switch (rv)
1641         {
1642         case 0:
1643           break;
1644
1645         case VNET_API_ERROR_NO_SUCH_FIB:
1646           return clib_error_return (0, "Invalid table-id %d", table_id);
1647
1648         case VNET_API_ERROR_INVALID_ARGUMENT:
1649           return clib_error_return (0, "Invalid address range %U - %U",
1650                                     format_ip4_address, &v4start,
1651                                     format_ip4_address, &v4end);
1652         default:
1653           return clib_error_return (0, "error %d", rv);
1654           break;
1655         }
1656     }
1657   if (v6set)
1658     {
1659       rv = tcp_configure_v6_source_address_range (vm, &v6start, &v6end,
1660                                                   table_id);
1661       switch (rv)
1662         {
1663         case 0:
1664           break;
1665
1666         case VNET_API_ERROR_NO_SUCH_FIB:
1667           return clib_error_return (0, "Invalid table-id %d", table_id);
1668
1669         default:
1670           return clib_error_return (0, "error %d", rv);
1671           break;
1672         }
1673     }
1674   return 0;
1675 }
1676
1677 /* *INDENT-OFF* */
1678 VLIB_CLI_COMMAND (tcp_src_address_command, static) =
1679 {
1680   .path = "tcp src-address",
1681   .short_help = "tcp src-address <ip-addr> [- <ip-addr>] add src address range",
1682   .function = tcp_src_address,
1683 };
1684 /* *INDENT-ON* */
1685
1686 static u8 *
1687 tcp_scoreboard_dump_trace (u8 * s, sack_scoreboard_t * sb)
1688 {
1689 #if TCP_SCOREBOARD_TRACE
1690
1691   scoreboard_trace_elt_t *block;
1692   int i = 0;
1693
1694   if (!sb->trace)
1695     return s;
1696
1697   s = format (s, "scoreboard trace:");
1698   vec_foreach (block, sb->trace)
1699   {
1700     s = format (s, "{%u, %u, %u, %u, %u}, ", block->start, block->end,
1701                 block->ack, block->snd_una_max, block->group);
1702     if ((++i % 3) == 0)
1703       s = format (s, "\n");
1704   }
1705   return s;
1706 #else
1707   return 0;
1708 #endif
1709 }
1710
1711 static clib_error_t *
1712 tcp_show_scoreboard_trace_fn (vlib_main_t * vm, unformat_input_t * input,
1713                               vlib_cli_command_t * cmd_arg)
1714 {
1715   transport_connection_t *tconn = 0;
1716   tcp_connection_t *tc;
1717   u8 *s = 0;
1718   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1719     {
1720       if (unformat (input, "%U", unformat_transport_connection, &tconn,
1721                     TRANSPORT_PROTO_TCP))
1722         ;
1723       else
1724         return clib_error_return (0, "unknown input `%U'",
1725                                   format_unformat_error, input);
1726     }
1727
1728   if (!TCP_SCOREBOARD_TRACE)
1729     {
1730       vlib_cli_output (vm, "scoreboard tracing not enabled");
1731       return 0;
1732     }
1733
1734   tc = tcp_get_connection_from_transport (tconn);
1735   s = tcp_scoreboard_dump_trace (s, &tc->sack_sb);
1736   vlib_cli_output (vm, "%v", s);
1737   return 0;
1738 }
1739
1740 /* *INDENT-OFF* */
1741 VLIB_CLI_COMMAND (tcp_show_scoreboard_trace_command, static) =
1742 {
1743   .path = "show tcp scoreboard trace",
1744   .short_help = "show tcp scoreboard trace <connection>",
1745   .function = tcp_show_scoreboard_trace_fn,
1746 };
1747 /* *INDENT-ON* */
1748
1749 u8 *
1750 tcp_scoreboard_replay (u8 * s, tcp_connection_t * tc, u8 verbose)
1751 {
1752   int i, trace_len;
1753   scoreboard_trace_elt_t *trace;
1754   u32 next_ack, left, group, has_new_ack = 0;
1755   tcp_connection_t _dummy_tc, *dummy_tc = &_dummy_tc;
1756   sack_block_t *block;
1757
1758   if (!tc)
1759     return s;
1760
1761   memset (dummy_tc, 0, sizeof (*dummy_tc));
1762   tcp_connection_timers_init (dummy_tc);
1763   scoreboard_init (&dummy_tc->sack_sb);
1764   dummy_tc->rcv_opts.flags |= TCP_OPTS_FLAG_SACK;
1765
1766 #if TCP_SCOREBOARD_TRACE
1767   trace = tc->sack_sb.trace;
1768   trace_len = vec_len (tc->sack_sb.trace);
1769 #else
1770   trace = 0;
1771   trace_len = 0;
1772 #endif
1773
1774   for (i = 0; i < trace_len; i++)
1775     {
1776       if (trace[i].ack != 0)
1777         {
1778           dummy_tc->snd_una = trace[i].ack - 1448;
1779           dummy_tc->snd_una_max = trace[i].ack;
1780         }
1781     }
1782
1783   left = 0;
1784   while (left < trace_len)
1785     {
1786       group = trace[left].group;
1787       vec_reset_length (dummy_tc->rcv_opts.sacks);
1788       has_new_ack = 0;
1789       while (trace[left].group == group)
1790         {
1791           if (trace[left].ack != 0)
1792             {
1793               if (verbose)
1794                 s = format (s, "Adding ack %u, snd_una_max %u, segs: ",
1795                             trace[left].ack, trace[left].snd_una_max);
1796               dummy_tc->snd_una_max = trace[left].snd_una_max;
1797               next_ack = trace[left].ack;
1798               has_new_ack = 1;
1799             }
1800           else
1801             {
1802               if (verbose)
1803                 s = format (s, "[%u, %u], ", trace[left].start,
1804                             trace[left].end);
1805               vec_add2 (dummy_tc->rcv_opts.sacks, block, 1);
1806               block->start = trace[left].start;
1807               block->end = trace[left].end;
1808             }
1809           left++;
1810         }
1811
1812       /* Push segments */
1813       tcp_rcv_sacks (dummy_tc, next_ack);
1814       if (has_new_ack)
1815         dummy_tc->snd_una = next_ack + dummy_tc->sack_sb.snd_una_adv;
1816
1817       if (verbose)
1818         s = format (s, "result: %U", format_tcp_scoreboard,
1819                     &dummy_tc->sack_sb);
1820
1821     }
1822   s = format (s, "result: %U", format_tcp_scoreboard, &dummy_tc->sack_sb);
1823
1824   return s;
1825 }
1826
1827 static clib_error_t *
1828 tcp_scoreboard_trace_fn (vlib_main_t * vm, unformat_input_t * input,
1829                          vlib_cli_command_t * cmd_arg)
1830 {
1831   transport_connection_t *tconn = 0;
1832   tcp_connection_t *tc = 0;
1833   u8 *str = 0;
1834   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1835     {
1836       if (unformat (input, "%U", unformat_transport_connection, &tconn,
1837                     TRANSPORT_PROTO_TCP))
1838         ;
1839       else
1840         return clib_error_return (0, "unknown input `%U'",
1841                                   format_unformat_error, input);
1842     }
1843
1844   if (!TCP_SCOREBOARD_TRACE)
1845     {
1846       vlib_cli_output (vm, "scoreboard tracing not enabled");
1847       return 0;
1848     }
1849
1850   tc = tcp_get_connection_from_transport (tconn);
1851   if (!tc)
1852     {
1853       vlib_cli_output (vm, "connection not found");
1854       return 0;
1855     }
1856   str = tcp_scoreboard_replay (str, tc, 1);
1857   vlib_cli_output (vm, "%v", str);
1858   return 0;
1859 }
1860
1861 /* *INDENT-OFF* */
1862 VLIB_CLI_COMMAND (tcp_replay_scoreboard_command, static) =
1863 {
1864   .path = "tcp replay scoreboard",
1865   .short_help = "tcp replay scoreboard <connection>",
1866   .function = tcp_scoreboard_trace_fn,
1867 };
1868 /* *INDENT-ON* */
1869
1870 static clib_error_t *
1871 show_tcp_punt_fn (vlib_main_t * vm, unformat_input_t * input,
1872                   vlib_cli_command_t * cmd_arg)
1873 {
1874   tcp_main_t *tm = vnet_get_tcp_main ();
1875   if (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1876     return clib_error_return (0, "unknown input `%U'", format_unformat_error,
1877                               input);
1878   vlib_cli_output (vm, "IPv4 TCP punt: %s",
1879                    tm->punt_unknown4 ? "enabled" : "disabled");
1880   vlib_cli_output (vm, "IPv6 TCP punt: %s",
1881                    tm->punt_unknown6 ? "enabled" : "disabled");
1882   return 0;
1883 }
1884 /* *INDENT-OFF* */
1885 VLIB_CLI_COMMAND (show_tcp_punt_command, static) =
1886 {
1887   .path = "show tcp punt",
1888   .short_help = "show tcp punt",
1889   .function = show_tcp_punt_fn,
1890 };
1891 /* *INDENT-ON* */
1892
1893 /*
1894  * fd.io coding-style-patch-verification: ON
1895  *
1896  * Local Variables:
1897  * eval: (c-set-style "gnu")
1898  * End:
1899  */