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