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