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