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