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