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