Improve TCP option handling, VPP-757
[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 #include <vnet/tcp/tcp.h>
17 #include <vnet/session/session.h>
18 #include <vnet/fib/fib.h>
19 #include <math.h>
20
21 tcp_main_t tcp_main;
22
23 static u32
24 tcp_connection_bind (u32 session_index, ip46_address_t * ip,
25                      u16 port_host_byte_order, u8 is_ip4)
26 {
27   tcp_main_t *tm = &tcp_main;
28   tcp_connection_t *listener;
29
30   pool_get (tm->listener_pool, listener);
31   memset (listener, 0, sizeof (*listener));
32
33   listener->c_c_index = listener - tm->listener_pool;
34   listener->c_lcl_port = clib_host_to_net_u16 (port_host_byte_order);
35
36   if (is_ip4)
37     {
38       listener->c_lcl_ip4.as_u32 = ip->ip4.as_u32;
39       listener->c_is_ip4 = 1;
40       listener->c_proto = SESSION_TYPE_IP4_TCP;
41     }
42   else
43     {
44       clib_memcpy (&listener->c_lcl_ip6, &ip->ip6, sizeof (ip6_address_t));
45       listener->c_proto = SESSION_TYPE_IP6_TCP;
46     }
47
48   listener->c_s_index = session_index;
49   listener->state = TCP_STATE_LISTEN;
50
51   tcp_connection_timers_init (listener);
52
53   TCP_EVT_DBG (TCP_EVT_BIND, listener);
54
55   return listener->c_c_index;
56 }
57
58 u32
59 tcp_session_bind_ip4 (u32 session_index, ip46_address_t * ip,
60                       u16 port_host_byte_order)
61 {
62   return tcp_connection_bind (session_index, ip, port_host_byte_order, 1);
63 }
64
65 u32
66 tcp_session_bind_ip6 (u32 session_index, ip46_address_t * ip,
67                       u16 port_host_byte_order)
68 {
69   return tcp_connection_bind (session_index, ip, port_host_byte_order, 0);
70 }
71
72 static void
73 tcp_connection_unbind (u32 listener_index)
74 {
75   tcp_main_t *tm = vnet_get_tcp_main ();
76   TCP_EVT_DBG (TCP_EVT_UNBIND,
77                pool_elt_at_index (tm->listener_pool, listener_index));
78   pool_put_index (tm->listener_pool, listener_index);
79 }
80
81 u32
82 tcp_session_unbind (u32 listener_index)
83 {
84   tcp_connection_unbind (listener_index);
85   return 0;
86 }
87
88 transport_connection_t *
89 tcp_session_get_listener (u32 listener_index)
90 {
91   tcp_main_t *tm = vnet_get_tcp_main ();
92   tcp_connection_t *tc;
93   tc = pool_elt_at_index (tm->listener_pool, listener_index);
94   return &tc->connection;
95 }
96
97 /**
98  * Cleans up connection state.
99  *
100  * No notifications.
101  */
102 void
103 tcp_connection_cleanup (tcp_connection_t * tc)
104 {
105   tcp_main_t *tm = &tcp_main;
106   u32 tepi;
107   transport_endpoint_t *tep;
108
109   /* Cleanup local endpoint if this was an active connect */
110   tepi = transport_endpoint_lookup (&tm->local_endpoints_table, &tc->c_lcl_ip,
111                                     tc->c_lcl_port);
112
113   /*XXX lock */
114   if (tepi != TRANSPORT_ENDPOINT_INVALID_INDEX)
115     {
116       tep = pool_elt_at_index (tm->local_endpoints, tepi);
117       transport_endpoint_table_del (&tm->local_endpoints_table, tep);
118       pool_put (tm->local_endpoints, tep);
119     }
120
121   /* Make sure all timers are cleared */
122   tcp_connection_timers_reset (tc);
123
124   /* Check if half-open */
125   if (tc->state == TCP_STATE_SYN_SENT)
126     pool_put (tm->half_open_connections, tc);
127   else
128     pool_put (tm->connections[tc->c_thread_index], tc);
129 }
130
131 /**
132  * Connection removal.
133  *
134  * This should be called only once connection enters CLOSED state. Note
135  * that it notifies the session of the removal event, so if the goal is to
136  * just remove the connection, call tcp_connection_cleanup instead.
137  */
138 void
139 tcp_connection_del (tcp_connection_t * tc)
140 {
141   TCP_EVT_DBG (TCP_EVT_DELETE, tc);
142   stream_session_delete_notify (&tc->connection);
143   tcp_connection_cleanup (tc);
144 }
145
146 /** Notify session that connection has been reset.
147  *
148  * Switch state to closed and wait for session to call cleanup.
149  */
150 void
151 tcp_connection_reset (tcp_connection_t * tc)
152 {
153   if (tc->state == TCP_STATE_CLOSED)
154     return;
155
156   tc->state = TCP_STATE_CLOSED;
157
158   /* Make sure all timers are cleared */
159   tcp_connection_timers_reset (tc);
160
161   stream_session_reset_notify (&tc->connection);
162 }
163
164 /**
165  * Begin connection closing procedure.
166  *
167  * If at the end the connection is not in CLOSED state, it is not removed.
168  * Instead, we rely on on TCP to advance through state machine to either
169  * 1) LAST_ACK (passive close) whereby when the last ACK is received
170  * tcp_connection_del is called. This notifies session of the delete and
171  * calls cleanup.
172  * 2) TIME_WAIT (active close) whereby after 2MSL the 2MSL timer triggers
173  * and cleanup is called.
174  *
175  * N.B. Half-close connections are not supported
176  */
177 void
178 tcp_connection_close (tcp_connection_t * tc)
179 {
180   TCP_EVT_DBG (TCP_EVT_CLOSE, tc);
181
182   /* Send FIN if needed */
183   if (tc->state == TCP_STATE_ESTABLISHED || tc->state == TCP_STATE_SYN_RCVD
184       || tc->state == TCP_STATE_CLOSE_WAIT)
185     tcp_send_fin (tc);
186
187   /* Switch state */
188   if (tc->state == TCP_STATE_ESTABLISHED || tc->state == TCP_STATE_SYN_RCVD)
189     tc->state = TCP_STATE_FIN_WAIT_1;
190   else if (tc->state == TCP_STATE_SYN_SENT)
191     tc->state = TCP_STATE_CLOSED;
192   else if (tc->state == TCP_STATE_CLOSE_WAIT)
193     tc->state = TCP_STATE_LAST_ACK;
194
195   /* If in CLOSED and WAITCLOSE timer is not set, delete connection now */
196   if (tc->timers[TCP_TIMER_WAITCLOSE] == TCP_TIMER_HANDLE_INVALID
197       && tc->state == TCP_STATE_CLOSED)
198     tcp_connection_del (tc);
199 }
200
201 void
202 tcp_session_close (u32 conn_index, u32 thread_index)
203 {
204   tcp_connection_t *tc;
205   tc = tcp_connection_get (conn_index, thread_index);
206   tcp_connection_close (tc);
207 }
208
209 void
210 tcp_session_cleanup (u32 conn_index, u32 thread_index)
211 {
212   tcp_connection_t *tc;
213   tc = tcp_connection_get (conn_index, thread_index);
214
215   /* Wait for the session tx events to clear */
216   tc->state = TCP_STATE_CLOSED;
217   tcp_timer_update (tc, TCP_TIMER_WAITCLOSE, TCP_CLEANUP_TIME);
218 }
219
220 void *
221 ip_interface_get_first_ip (u32 sw_if_index, u8 is_ip4)
222 {
223   ip_lookup_main_t *lm4 = &ip4_main.lookup_main;
224   ip_lookup_main_t *lm6 = &ip6_main.lookup_main;
225   ip_interface_address_t *ia = 0;
226
227   if (is_ip4)
228     {
229       /* *INDENT-OFF* */
230       foreach_ip_interface_address (lm4, ia, sw_if_index, 1 /* unnumbered */ ,
231       ({
232         return ip_interface_address_get_address (lm4, ia);
233       }));
234       /* *INDENT-ON* */
235     }
236   else
237     {
238       /* *INDENT-OFF* */
239       foreach_ip_interface_address (lm6, ia, sw_if_index, 1 /* unnumbered */ ,
240       ({
241         return ip_interface_address_get_address (lm6, ia);
242       }));
243       /* *INDENT-ON* */
244     }
245
246   return 0;
247 }
248
249 #define PORT_MASK ((1 << 16)- 1)
250 /**
251  * Allocate local port and add if successful add entry to local endpoint
252  * table to mark the pair as used.
253  */
254 u16
255 tcp_allocate_local_port (tcp_main_t * tm, ip46_address_t * ip)
256 {
257   transport_endpoint_t *tep;
258   u32 time_now, tei;
259   u16 min = 1024, max = 65535;  /* XXX configurable ? */
260   int tries;
261
262   tries = max - min;
263   time_now = tcp_time_now ();
264
265   /* Start at random point or max */
266   pool_get (tm->local_endpoints, tep);
267   clib_memcpy (&tep->ip, ip, sizeof (*ip));
268
269   /* Search for first free slot */
270   for (; tries >= 0; tries--)
271     {
272       u16 port = 0;
273
274       /* Find a port in the specified range */
275       while (1)
276         {
277           port = random_u32 (&time_now) & PORT_MASK;
278           if (PREDICT_TRUE (port >= min && port < max))
279             break;
280         }
281
282       tep->port = port;
283
284       /* Look it up */
285       tei = transport_endpoint_lookup (&tm->local_endpoints_table, &tep->ip,
286                                        tep->port);
287       /* If not found, we're done */
288       if (tei == TRANSPORT_ENDPOINT_INVALID_INDEX)
289         {
290           transport_endpoint_table_add (&tm->local_endpoints_table, tep,
291                                         tep - tm->local_endpoints);
292           return tep->port;
293         }
294     }
295   /* No free ports */
296   pool_put (tm->local_endpoints, tep);
297   return -1;
298 }
299
300 /**
301  * Initialize all connection timers as invalid
302  */
303 void
304 tcp_connection_timers_init (tcp_connection_t * tc)
305 {
306   int i;
307
308   /* Set all to invalid */
309   for (i = 0; i < TCP_N_TIMERS; i++)
310     {
311       tc->timers[i] = TCP_TIMER_HANDLE_INVALID;
312     }
313
314   tc->rto = TCP_RTO_INIT;
315 }
316
317 /**
318  * Stop all connection timers
319  */
320 void
321 tcp_connection_timers_reset (tcp_connection_t * tc)
322 {
323   int i;
324   for (i = 0; i < TCP_N_TIMERS; i++)
325     {
326       tcp_timer_reset (tc, i);
327     }
328 }
329
330 /** Initialize tcp connection variables
331  *
332  * Should be called after having received a msg from the peer, i.e., a SYN or
333  * a SYNACK, such that connection options have already been exchanged. */
334 void
335 tcp_connection_init_vars (tcp_connection_t * tc)
336 {
337   tcp_connection_timers_init (tc);
338   tcp_init_mss (tc);
339   scoreboard_init (&tc->sack_sb);
340   tcp_cc_init (tc);
341 }
342
343 int
344 tcp_connection_open (ip46_address_t * rmt_addr, u16 rmt_port, u8 is_ip4)
345 {
346   tcp_main_t *tm = vnet_get_tcp_main ();
347   tcp_connection_t *tc;
348   fib_prefix_t prefix;
349   u32 fei, sw_if_index;
350   ip46_address_t lcl_addr;
351   u16 lcl_port;
352
353   /*
354    * Find the local address and allocate port
355    */
356   memset (&lcl_addr, 0, sizeof (lcl_addr));
357
358   /* Find a FIB path to the destination */
359   clib_memcpy (&prefix.fp_addr, rmt_addr, sizeof (*rmt_addr));
360   prefix.fp_proto = is_ip4 ? FIB_PROTOCOL_IP4 : FIB_PROTOCOL_IP6;
361   prefix.fp_len = is_ip4 ? 32 : 128;
362
363   fei = fib_table_lookup (0, &prefix);
364
365   /* Couldn't find route to destination. Bail out. */
366   if (fei == FIB_NODE_INDEX_INVALID)
367     return -1;
368
369   sw_if_index = fib_entry_get_resolving_interface (fei);
370
371   if (sw_if_index == (u32) ~ 0)
372     return -1;
373
374   if (is_ip4)
375     {
376       ip4_address_t *ip4;
377       ip4 = ip_interface_get_first_ip (sw_if_index, 1);
378       lcl_addr.ip4.as_u32 = ip4->as_u32;
379     }
380   else
381     {
382       ip6_address_t *ip6;
383       ip6 = ip_interface_get_first_ip (sw_if_index, 0);
384       clib_memcpy (&lcl_addr.ip6, ip6, sizeof (*ip6));
385     }
386
387   /* Allocate source port */
388   lcl_port = tcp_allocate_local_port (tm, &lcl_addr);
389   if (lcl_port < 1)
390     {
391       clib_warning ("Failed to allocate src port");
392       return -1;
393     }
394
395   /*
396    * Create connection and send SYN
397    */
398
399   pool_get (tm->half_open_connections, tc);
400   memset (tc, 0, sizeof (*tc));
401
402   clib_memcpy (&tc->c_rmt_ip, rmt_addr, sizeof (ip46_address_t));
403   clib_memcpy (&tc->c_lcl_ip, &lcl_addr, sizeof (ip46_address_t));
404   tc->c_rmt_port = clib_host_to_net_u16 (rmt_port);
405   tc->c_lcl_port = clib_host_to_net_u16 (lcl_port);
406   tc->c_c_index = tc - tm->half_open_connections;
407   tc->c_is_ip4 = is_ip4;
408   tc->c_proto = is_ip4 ? SESSION_TYPE_IP4_TCP : SESSION_TYPE_IP6_TCP;
409
410   /* The other connection vars will be initialized after SYN ACK */
411   tcp_connection_timers_init (tc);
412
413   tcp_send_syn (tc);
414
415   tc->state = TCP_STATE_SYN_SENT;
416
417   TCP_EVT_DBG (TCP_EVT_OPEN, tc);
418
419   return tc->c_c_index;
420 }
421
422 int
423 tcp_session_open_ip4 (ip46_address_t * addr, u16 port)
424 {
425   return tcp_connection_open (addr, port, 1);
426 }
427
428 int
429 tcp_session_open_ip6 (ip46_address_t * addr, u16 port)
430 {
431   return tcp_connection_open (addr, port, 0);
432 }
433
434 const char *tcp_dbg_evt_str[] = {
435 #define _(sym, str) str,
436   foreach_tcp_dbg_evt
437 #undef _
438 };
439
440 const char *tcp_fsm_states[] = {
441 #define _(sym, str) str,
442   foreach_tcp_fsm_state
443 #undef _
444 };
445
446 u8 *
447 format_tcp_state (u8 * s, va_list * args)
448 {
449   tcp_state_t *state = va_arg (*args, tcp_state_t *);
450
451   if (*state < TCP_N_STATES)
452     s = format (s, "%s", tcp_fsm_states[*state]);
453   else
454     s = format (s, "UNKNOWN (%d (0x%x))", *state, *state);
455
456   return s;
457 }
458
459 const char *tcp_conn_timers[] = {
460 #define _(sym, str) str,
461   foreach_tcp_timer
462 #undef _
463 };
464
465 u8 *
466 format_tcp_timers (u8 * s, va_list * args)
467 {
468   tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
469   int i, last = 0;
470
471   for (i = 0; i < TCP_N_TIMERS; i++)
472     if (tc->timers[i] != TCP_TIMER_HANDLE_INVALID)
473       last = i;
474
475   s = format (s, "[");
476   for (i = 0; i < last; i++)
477     {
478       if (tc->timers[i] != TCP_TIMER_HANDLE_INVALID)
479         s = format (s, "%s,", tcp_conn_timers[i]);
480     }
481
482   if (last > 0)
483     s = format (s, "%s]", tcp_conn_timers[i]);
484   else
485     s = format (s, "]");
486
487   return s;
488 }
489
490 u8 *
491 format_tcp_connection (u8 * s, va_list * args)
492 {
493   tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
494   if (!tc)
495     return s;
496   if (tc->c_is_ip4)
497     {
498       s = format (s, "[#%d][%s] %U:%d->%U:%d", tc->c_thread_index, "T",
499                   format_ip4_address, &tc->c_lcl_ip4,
500                   clib_net_to_host_u16 (tc->c_lcl_port), format_ip4_address,
501                   &tc->c_rmt_ip4, clib_net_to_host_u16 (tc->c_rmt_port));
502     }
503   else
504     {
505       s = format (s, "[#%d][%s] %U:%d->%U:%d", tc->c_thread_index, "T",
506                   format_ip6_address, &tc->c_lcl_ip6,
507                   clib_net_to_host_u16 (tc->c_lcl_port), format_ip6_address,
508                   &tc->c_rmt_ip6, clib_net_to_host_u16 (tc->c_rmt_port));
509     }
510
511   return s;
512 }
513
514 u8 *
515 format_tcp_connection_verbose (u8 * s, va_list * args)
516 {
517   tcp_connection_t *tc = va_arg (*args, tcp_connection_t *);
518   s = format (s, "%U %U %U", format_tcp_connection, tc, format_tcp_state,
519               &tc->state, format_tcp_timers, tc);
520   return s;
521 }
522
523 u8 *
524 format_tcp_session (u8 * s, va_list * args)
525 {
526   u32 tci = va_arg (*args, u32);
527   u32 thread_index = va_arg (*args, u32);
528   tcp_connection_t *tc;
529
530   tc = tcp_connection_get (tci, thread_index);
531   if (tc)
532     return format (s, "%U", format_tcp_connection, tc);
533   else
534     return format (s, "empty");
535 }
536
537 u8 *
538 format_tcp_listener_session (u8 * s, va_list * args)
539 {
540   u32 tci = va_arg (*args, u32);
541   tcp_connection_t *tc = tcp_listener_get (tci);
542   return format (s, "%U", format_tcp_connection, tc);
543 }
544
545 u8 *
546 format_tcp_half_open_session (u8 * s, va_list * args)
547 {
548   u32 tci = va_arg (*args, u32);
549   tcp_connection_t *tc = tcp_half_open_connection_get (tci);
550   return format (s, "%U", format_tcp_connection, tc);
551 }
552
553 transport_connection_t *
554 tcp_session_get_transport (u32 conn_index, u32 thread_index)
555 {
556   tcp_connection_t *tc = tcp_connection_get (conn_index, thread_index);
557   return &tc->connection;
558 }
559
560 transport_connection_t *
561 tcp_half_open_session_get_transport (u32 conn_index)
562 {
563   tcp_connection_t *tc = tcp_half_open_connection_get (conn_index);
564   return &tc->connection;
565 }
566
567 /**
568  * Compute maximum segment size for session layer.
569  *
570  * Since the result needs to be the actual data length, it first computes
571  * the tcp options to be used in the next burst and subtracts their
572  * length from the connection's snd_mss.
573  */
574 u16
575 tcp_session_send_mss (transport_connection_t * trans_conn)
576 {
577   tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
578
579   /* Ensure snd_mss does accurately reflect the amount of data we can push
580    * in a segment. This also makes sure that options are updated according to
581    * the current state of the connection. */
582   tcp_update_snd_mss (tc);
583
584   return tc->snd_mss;
585 }
586
587 always_inline u32
588 tcp_round_snd_space (tcp_connection_t * tc, u32 snd_space)
589 {
590   if (tc->snd_wnd < tc->snd_mss)
591     {
592       return tc->snd_wnd <= snd_space ? tc->snd_wnd : 0;
593     }
594
595   /* If we can't write at least a segment, don't try at all */
596   if (snd_space < tc->snd_mss)
597     return 0;
598
599   /* round down to mss multiple */
600   return snd_space - (snd_space % tc->snd_mss);
601 }
602
603 /**
604  * Compute tx window session is allowed to fill.
605  */
606 u32
607 tcp_session_send_space (transport_connection_t * trans_conn)
608 {
609   int snd_space;
610   tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
611
612   /* If we haven't gotten dupacks or if we did and have gotten sacked bytes
613    * then we can still send */
614   if (PREDICT_TRUE (tcp_in_cong_recovery (tc) == 0
615                     && (tc->rcv_dupacks == 0
616                         || tc->sack_sb.last_sacked_bytes)))
617     {
618       snd_space = tcp_available_snd_space (tc);
619       return tcp_round_snd_space (tc, snd_space);
620     }
621
622   if (tcp_in_recovery (tc))
623     {
624       tc->snd_nxt = tc->snd_una_max;
625       snd_space = tcp_available_wnd (tc) - tc->rtx_bytes
626         - (tc->snd_una_max - tc->snd_congestion);
627       if (snd_space <= 0 || (tc->snd_una_max - tc->snd_una) >= tc->snd_wnd)
628         return 0;
629       return tcp_round_snd_space (tc, snd_space);
630     }
631
632   /* If in fast recovery, send 1 SMSS if wnd allows */
633   if (tcp_in_fastrecovery (tc) && tcp_available_snd_space (tc)
634       && tcp_fastrecovery_sent_1_smss (tc))
635     {
636       tcp_fastrecovery_1_smss_on (tc);
637       return tc->snd_mss;
638     }
639
640   return 0;
641 }
642
643 u32
644 tcp_session_tx_fifo_offset (transport_connection_t * trans_conn)
645 {
646   tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
647
648   ASSERT (seq_geq (tc->snd_nxt, tc->snd_una));
649
650   /* This still works if fast retransmit is on */
651   return (tc->snd_nxt - tc->snd_una);
652 }
653
654 /* *INDENT-OFF* */
655 const static transport_proto_vft_t tcp4_proto = {
656   .bind = tcp_session_bind_ip4,
657   .unbind = tcp_session_unbind,
658   .push_header = tcp_push_header,
659   .get_connection = tcp_session_get_transport,
660   .get_listener = tcp_session_get_listener,
661   .get_half_open = tcp_half_open_session_get_transport,
662   .open = tcp_session_open_ip4,
663   .close = tcp_session_close,
664   .cleanup = tcp_session_cleanup,
665   .send_mss = tcp_session_send_mss,
666   .send_space = tcp_session_send_space,
667   .tx_fifo_offset = tcp_session_tx_fifo_offset,
668   .format_connection = format_tcp_session,
669   .format_listener = format_tcp_listener_session,
670   .format_half_open = format_tcp_half_open_session,
671 };
672
673 const static transport_proto_vft_t tcp6_proto = {
674   .bind = tcp_session_bind_ip6,
675   .unbind = tcp_session_unbind,
676   .push_header = tcp_push_header,
677   .get_connection = tcp_session_get_transport,
678   .get_listener = tcp_session_get_listener,
679   .get_half_open = tcp_half_open_session_get_transport,
680   .open = tcp_session_open_ip6,
681   .close = tcp_session_close,
682   .cleanup = tcp_session_cleanup,
683   .send_mss = tcp_session_send_mss,
684   .send_space = tcp_session_send_space,
685   .tx_fifo_offset = tcp_session_tx_fifo_offset,
686   .format_connection = format_tcp_session,
687   .format_listener = format_tcp_listener_session,
688   .format_half_open = format_tcp_half_open_session,
689 };
690 /* *INDENT-ON* */
691
692 void
693 tcp_timer_keep_handler (u32 conn_index)
694 {
695   u32 thread_index = vlib_get_thread_index ();
696   tcp_connection_t *tc;
697
698   tc = tcp_connection_get (conn_index, thread_index);
699   tc->timers[TCP_TIMER_KEEP] = TCP_TIMER_HANDLE_INVALID;
700
701   tcp_connection_close (tc);
702 }
703
704 void
705 tcp_timer_establish_handler (u32 conn_index)
706 {
707   tcp_connection_t *tc;
708   u8 sst;
709
710   tc = tcp_half_open_connection_get (conn_index);
711   tc->timers[TCP_TIMER_ESTABLISH] = TCP_TIMER_HANDLE_INVALID;
712
713   ASSERT (tc->state == TCP_STATE_SYN_SENT);
714
715   sst = tc->c_is_ip4 ? SESSION_TYPE_IP4_TCP : SESSION_TYPE_IP6_TCP;
716   stream_session_connect_notify (&tc->connection, sst, 1 /* fail */ );
717
718   tcp_connection_cleanup (tc);
719 }
720
721 void
722 tcp_timer_waitclose_handler (u32 conn_index)
723 {
724   u32 thread_index = vlib_get_thread_index ();
725   tcp_connection_t *tc;
726
727   tc = tcp_connection_get (conn_index, thread_index);
728   tc->timers[TCP_TIMER_WAITCLOSE] = TCP_TIMER_HANDLE_INVALID;
729
730   /* Session didn't come back with a close(). Send FIN either way
731    * and switch to LAST_ACK. */
732   if (tc->state == TCP_STATE_CLOSE_WAIT)
733     {
734       if (tc->flags & TCP_CONN_FINSNT)
735         {
736           clib_warning ("FIN was sent and still in CLOSE WAIT. Weird!");
737         }
738
739       tcp_send_fin (tc);
740       tc->state = TCP_STATE_LAST_ACK;
741
742       /* Make sure we don't wait in LAST ACK forever */
743       tcp_timer_set (tc, TCP_TIMER_WAITCLOSE, TCP_2MSL_TIME);
744
745       /* Don't delete the connection yet */
746       return;
747     }
748
749   tcp_connection_del (tc);
750 }
751
752 /* *INDENT-OFF* */
753 static timer_expiration_handler *timer_expiration_handlers[TCP_N_TIMERS] =
754 {
755     tcp_timer_retransmit_handler,
756     tcp_timer_delack_handler,
757     tcp_timer_persist_handler,
758     tcp_timer_keep_handler,
759     tcp_timer_waitclose_handler,
760     tcp_timer_retransmit_syn_handler,
761     tcp_timer_establish_handler
762 };
763 /* *INDENT-ON* */
764
765 static void
766 tcp_expired_timers_dispatch (u32 * expired_timers)
767 {
768   int i;
769   u32 connection_index, timer_id;
770
771   for (i = 0; i < vec_len (expired_timers); i++)
772     {
773       /* Get session index and timer id */
774       connection_index = expired_timers[i] & 0x0FFFFFFF;
775       timer_id = expired_timers[i] >> 28;
776
777       TCP_EVT_DBG (TCP_EVT_TIMER_POP, connection_index, timer_id);
778
779       /* Handle expiration */
780       (*timer_expiration_handlers[timer_id]) (connection_index);
781     }
782 }
783
784 void
785 tcp_initialize_timer_wheels (tcp_main_t * tm)
786 {
787   tw_timer_wheel_16t_2w_512sl_t *tw;
788   /* *INDENT-OFF* */
789   foreach_vlib_main (({
790     tw = &tm->timer_wheels[ii];
791     tw_timer_wheel_init_16t_2w_512sl (tw, tcp_expired_timers_dispatch,
792                                       100e-3 /* timer period 100ms */ , ~0);
793     tw->last_run_time = vlib_time_now (this_vlib_main);
794   }));
795   /* *INDENT-ON* */
796 }
797
798 clib_error_t *
799 tcp_main_enable (vlib_main_t * vm)
800 {
801   tcp_main_t *tm = vnet_get_tcp_main ();
802   ip_protocol_info_t *pi;
803   ip_main_t *im = &ip_main;
804   vlib_thread_main_t *vtm = vlib_get_thread_main ();
805   clib_error_t *error = 0;
806   u32 num_threads;
807
808   if ((error = vlib_call_init_function (vm, ip_main_init)))
809     return error;
810   if ((error = vlib_call_init_function (vm, ip4_lookup_init)))
811     return error;
812   if ((error = vlib_call_init_function (vm, ip6_lookup_init)))
813     return error;
814
815   /*
816    * Registrations
817    */
818
819   /* Register with IP */
820   pi = ip_get_protocol_info (im, IP_PROTOCOL_TCP);
821   if (pi == 0)
822     return clib_error_return (0, "TCP protocol info AWOL");
823   pi->format_header = format_tcp_header;
824   pi->unformat_pg_edit = unformat_pg_tcp_header;
825
826   ip4_register_protocol (IP_PROTOCOL_TCP, tcp4_input_node.index);
827
828   /* Register as transport with URI */
829   session_register_transport (SESSION_TYPE_IP4_TCP, &tcp4_proto);
830   session_register_transport (SESSION_TYPE_IP6_TCP, &tcp6_proto);
831
832   /*
833    * Initialize data structures
834    */
835
836   num_threads = 1 /* main thread */  + vtm->n_threads;
837   vec_validate (tm->connections, num_threads - 1);
838
839   /* Initialize per worker thread tx buffers (used for control messages) */
840   vec_validate (tm->tx_buffers, num_threads - 1);
841
842   /* Initialize timer wheels */
843   vec_validate (tm->timer_wheels, num_threads - 1);
844   tcp_initialize_timer_wheels (tm);
845
846 //  vec_validate (tm->delack_connections, num_threads - 1);
847
848   /* Initialize clocks per tick for TCP timestamp. Used to compute
849    * monotonically increasing timestamps. */
850   tm->tstamp_ticks_per_clock = vm->clib_time.seconds_per_clock
851     / TCP_TSTAMP_RESOLUTION;
852
853   clib_bihash_init_24_8 (&tm->local_endpoints_table, "local endpoint table",
854                          200000 /* $$$$ config parameter nbuckets */ ,
855                          (64 << 20) /*$$$ config parameter table size */ );
856
857   return error;
858 }
859
860 clib_error_t *
861 vnet_tcp_enable_disable (vlib_main_t * vm, u8 is_en)
862 {
863   if (is_en)
864     {
865       if (tcp_main.is_enabled)
866         return 0;
867
868       return tcp_main_enable (vm);
869     }
870   else
871     {
872       tcp_main.is_enabled = 0;
873     }
874
875   return 0;
876 }
877
878 clib_error_t *
879 tcp_init (vlib_main_t * vm)
880 {
881   tcp_main_t *tm = vnet_get_tcp_main ();
882
883   tm->vlib_main = vm;
884   tm->vnet_main = vnet_get_main ();
885   tm->is_enabled = 0;
886
887   return 0;
888 }
889
890 VLIB_INIT_FUNCTION (tcp_init);
891
892 /*
893  * fd.io coding-style-patch-verification: ON
894  *
895  * Local Variables:
896  * eval: (c-set-style "gnu")
897  * End:
898  */