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