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