tcp: use main thread pool for half-opens
[vpp.git] / src / vnet / tcp / tcp.c
1 /*
2  * Copyright (c) 2016-2019 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/tcp/tcp_inlines.h>
23 #include <vnet/session/session.h>
24 #include <vnet/fib/fib.h>
25 #include <vnet/dpo/load_balance.h>
26 #include <math.h>
27
28 tcp_main_t tcp_main;
29
30 typedef struct
31 {
32   fib_protocol_t nh_proto;
33   vnet_link_t link_type;
34   ip46_address_t ip;
35   u32 sw_if_index;
36   u8 is_add;
37 } tcp_add_del_adj_args_t;
38
39 static void
40 tcp_add_del_adj_cb (tcp_add_del_adj_args_t * args)
41 {
42   u32 ai;
43   if (args->is_add)
44     {
45       adj_nbr_add_or_lock (args->nh_proto, args->link_type, &args->ip,
46                            args->sw_if_index);
47     }
48   else
49     {
50       ai = adj_nbr_find (FIB_PROTOCOL_IP6, VNET_LINK_IP6, &args->ip,
51                          args->sw_if_index);
52       if (ai != ADJ_INDEX_INVALID)
53         adj_unlock (ai);
54     }
55 }
56
57 static void
58 tcp_add_del_adjacency (tcp_connection_t * tc, u8 is_add)
59 {
60   tcp_add_del_adj_args_t args = {
61     .nh_proto = FIB_PROTOCOL_IP6,
62     .link_type = VNET_LINK_IP6,
63     .ip = tc->c_rmt_ip,
64     .sw_if_index = tc->sw_if_index,
65     .is_add = is_add
66   };
67   vlib_rpc_call_main_thread (tcp_add_del_adj_cb, (u8 *) & args,
68                              sizeof (args));
69 }
70
71 static void
72 tcp_cc_init (tcp_connection_t * tc)
73 {
74   tc->cc_algo->init (tc);
75 }
76
77 static void
78 tcp_cc_cleanup (tcp_connection_t * tc)
79 {
80   if (tc->cc_algo->cleanup)
81     tc->cc_algo->cleanup (tc);
82 }
83
84 void
85 tcp_cc_algo_register (tcp_cc_algorithm_type_e type,
86                       const tcp_cc_algorithm_t * vft)
87 {
88   tcp_main_t *tm = vnet_get_tcp_main ();
89   vec_validate (tm->cc_algos, type);
90
91   tm->cc_algos[type] = *vft;
92   hash_set_mem (tm->cc_algo_by_name, vft->name, type);
93 }
94
95 tcp_cc_algorithm_t *
96 tcp_cc_algo_get (tcp_cc_algorithm_type_e type)
97 {
98   tcp_main_t *tm = vnet_get_tcp_main ();
99   return &tm->cc_algos[type];
100 }
101
102 tcp_cc_algorithm_type_e
103 tcp_cc_algo_new_type (const tcp_cc_algorithm_t * vft)
104 {
105   tcp_main_t *tm = vnet_get_tcp_main ();
106   tcp_cc_algo_register (++tm->cc_last_type, vft);
107   return tm->cc_last_type;
108 }
109
110 static u32
111 tcp_connection_bind (u32 session_index, transport_endpoint_t * lcl)
112 {
113   tcp_main_t *tm = &tcp_main;
114   tcp_connection_t *listener;
115   void *iface_ip;
116
117   pool_get (tm->listener_pool, listener);
118   clib_memset (listener, 0, sizeof (*listener));
119
120   listener->c_c_index = listener - tm->listener_pool;
121   listener->c_lcl_port = lcl->port;
122
123   /* If we are provided a sw_if_index, bind using one of its ips */
124   if (ip_is_zero (&lcl->ip, 1) && lcl->sw_if_index != ENDPOINT_INVALID_INDEX)
125     {
126       if ((iface_ip = ip_interface_get_first_ip (lcl->sw_if_index,
127                                                  lcl->is_ip4)))
128         ip_set (&lcl->ip, iface_ip, lcl->is_ip4);
129     }
130   ip_copy (&listener->c_lcl_ip, &lcl->ip, lcl->is_ip4);
131   listener->c_is_ip4 = lcl->is_ip4;
132   listener->c_proto = TRANSPORT_PROTO_TCP;
133   listener->c_s_index = session_index;
134   listener->c_fib_index = lcl->fib_index;
135   listener->state = TCP_STATE_LISTEN;
136   listener->cc_algo = tcp_cc_algo_get (tcp_cfg.cc_algo);
137
138   tcp_connection_timers_init (listener);
139
140   TCP_EVT (TCP_EVT_BIND, listener);
141
142   return listener->c_c_index;
143 }
144
145 static u32
146 tcp_session_bind (u32 session_index, transport_endpoint_t * tep)
147 {
148   return tcp_connection_bind (session_index, tep);
149 }
150
151 static void
152 tcp_connection_unbind (u32 listener_index)
153 {
154   tcp_main_t *tm = vnet_get_tcp_main ();
155   tcp_connection_t *tc;
156
157   tc = pool_elt_at_index (tm->listener_pool, listener_index);
158
159   TCP_EVT (TCP_EVT_UNBIND, tc);
160
161   /* Poison the entry */
162   if (CLIB_DEBUG > 0)
163     clib_memset (tc, 0xFA, sizeof (*tc));
164
165   pool_put_index (tm->listener_pool, listener_index);
166 }
167
168 static u32
169 tcp_session_unbind (u32 listener_index)
170 {
171   tcp_connection_unbind (listener_index);
172   return 0;
173 }
174
175 static transport_connection_t *
176 tcp_session_get_listener (u32 listener_index)
177 {
178   tcp_main_t *tm = vnet_get_tcp_main ();
179   tcp_connection_t *tc;
180   tc = pool_elt_at_index (tm->listener_pool, listener_index);
181   return &tc->connection;
182 }
183
184 static tcp_connection_t *
185 tcp_half_open_connection_alloc (void)
186 {
187   ASSERT (vlib_get_thread_index () == 0);
188   return tcp_connection_alloc (0);
189 }
190
191 /**
192  * Cleanup half-open connection
193  *
194  */
195 static void
196 tcp_half_open_connection_free (tcp_connection_t * tc)
197 {
198   ASSERT (vlib_get_thread_index () == 0);
199   return tcp_connection_free (tc);
200 }
201
202 /**
203  * Try to cleanup half-open connection
204  *
205  * If called from a thread that doesn't own tc, the call won't have any
206  * effect.
207  *
208  * @param tc - connection to be cleaned up
209  * @return non-zero if cleanup failed.
210  */
211 int
212 tcp_half_open_connection_cleanup (tcp_connection_t * tc)
213 {
214   tcp_worker_ctx_t *wrk;
215
216   /* Make sure this is the owning thread */
217   if (tc->c_thread_index != vlib_get_thread_index ())
218     return 1;
219
220   session_half_open_delete_notify (&tc->connection);
221   wrk = tcp_get_worker (tc->c_thread_index);
222   tcp_timer_reset (&wrk->timer_wheel, tc, TCP_TIMER_RETRANSMIT_SYN);
223   tcp_half_open_connection_free (tc);
224   return 0;
225 }
226
227 /**
228  * Cleans up connection state.
229  *
230  * No notifications.
231  */
232 void
233 tcp_connection_cleanup (tcp_connection_t * tc)
234 {
235   TCP_EVT (TCP_EVT_DELETE, tc);
236
237   /* Cleanup local endpoint if this was an active connect */
238   if (!(tc->cfg_flags & TCP_CFG_F_NO_ENDPOINT))
239     transport_endpoint_cleanup (TRANSPORT_PROTO_TCP, &tc->c_lcl_ip,
240                                 tc->c_lcl_port);
241
242   /* Check if connection is not yet fully established */
243   if (tc->state == TCP_STATE_SYN_SENT)
244     {
245       /* Try to remove the half-open connection. If this is not the owning
246        * thread, tc won't be removed. Retransmit or establish timers will
247        * eventually expire and call again cleanup on the right thread. */
248       if (tcp_half_open_connection_cleanup (tc))
249         tc->flags |= TCP_CONN_HALF_OPEN_DONE;
250     }
251   else
252     {
253       /* Make sure all timers are cleared */
254       tcp_connection_timers_reset (tc);
255
256       if (!tc->c_is_ip4 && ip6_address_is_link_local_unicast (&tc->c_rmt_ip6))
257         tcp_add_del_adjacency (tc, 0);
258
259       tcp_cc_cleanup (tc);
260       vec_free (tc->snd_sacks);
261       vec_free (tc->snd_sacks_fl);
262       vec_free (tc->rcv_opts.sacks);
263       pool_free (tc->sack_sb.holes);
264
265       if (tc->cfg_flags & TCP_CFG_F_RATE_SAMPLE)
266         tcp_bt_cleanup (tc);
267
268       tcp_connection_free (tc);
269     }
270 }
271
272 /**
273  * Connection removal.
274  *
275  * This should be called only once connection enters CLOSED state. Note
276  * that it notifies the session of the removal event, so if the goal is to
277  * just remove the connection, call tcp_connection_cleanup instead.
278  */
279 void
280 tcp_connection_del (tcp_connection_t * tc)
281 {
282   session_transport_delete_notify (&tc->connection);
283   tcp_connection_cleanup (tc);
284 }
285
286 tcp_connection_t *
287 tcp_connection_alloc (u8 thread_index)
288 {
289   tcp_worker_ctx_t *wrk = tcp_get_worker (thread_index);
290   tcp_connection_t *tc;
291
292   pool_get (wrk->connections, tc);
293   clib_memset (tc, 0, sizeof (*tc));
294   tc->c_c_index = tc - wrk->connections;
295   tc->c_thread_index = thread_index;
296   return tc;
297 }
298
299 tcp_connection_t *
300 tcp_connection_alloc_w_base (u8 thread_index, tcp_connection_t **base)
301 {
302   tcp_worker_ctx_t *wrk = tcp_get_worker (thread_index);
303   tcp_connection_t *tc;
304
305   /* Make sure connection is still valid if pool moves */
306   if ((*base)->c_thread_index == thread_index)
307     {
308       u32 base_index = (*base)->c_c_index;
309       pool_get (wrk->connections, tc);
310       *base = tcp_connection_get (base_index, thread_index);
311     }
312   else
313     {
314       pool_get (wrk->connections, tc);
315     }
316   clib_memcpy_fast (tc, *base, sizeof (*tc));
317   tc->c_c_index = tc - wrk->connections;
318   tc->c_thread_index = thread_index;
319   return tc;
320 }
321
322 void
323 tcp_connection_free (tcp_connection_t * tc)
324 {
325   tcp_worker_ctx_t *wrk = tcp_get_worker (tc->c_thread_index);
326   if (CLIB_DEBUG)
327     {
328       clib_memset (tc, 0xFA, sizeof (*tc));
329       pool_put (wrk->connections, tc);
330       return;
331     }
332   pool_put (wrk->connections, tc);
333 }
334
335 void
336 tcp_program_cleanup (tcp_worker_ctx_t * wrk, tcp_connection_t * tc)
337 {
338   tcp_cleanup_req_t *req;
339   clib_time_type_t now;
340
341   now = tcp_time_now_us (tc->c_thread_index);
342   clib_fifo_add2 (wrk->pending_cleanups, req);
343   req->connection_index = tc->c_c_index;
344   req->free_time = now + tcp_cfg.cleanup_time;
345 }
346
347 /**
348  * Begin connection closing procedure.
349  *
350  * If at the end the connection is not in CLOSED state, it is not removed.
351  * Instead, we rely on on TCP to advance through state machine to either
352  * 1) LAST_ACK (passive close) whereby when the last ACK is received
353  * tcp_connection_del is called. This notifies session of the delete and
354  * calls cleanup.
355  * 2) TIME_WAIT (active close) whereby after 2MSL the 2MSL timer triggers
356  * and cleanup is called.
357  *
358  */
359 void
360 tcp_connection_close (tcp_connection_t * tc)
361 {
362   tcp_worker_ctx_t *wrk = tcp_get_worker (tc->c_thread_index);
363
364   TCP_EVT (TCP_EVT_CLOSE, tc);
365
366   /* Send/Program FIN if needed and switch state */
367   switch (tc->state)
368     {
369     case TCP_STATE_SYN_SENT:
370       /* Try to cleanup. If not on the right thread, mark as half-open done.
371        * Connection will be cleaned up when establish timer pops */
372       tcp_connection_cleanup (tc);
373       break;
374     case TCP_STATE_SYN_RCVD:
375       tcp_connection_timers_reset (tc);
376       tcp_send_fin (tc);
377       tcp_connection_set_state (tc, TCP_STATE_FIN_WAIT_1);
378       tcp_timer_update (&wrk->timer_wheel, tc, TCP_TIMER_WAITCLOSE,
379                         tcp_cfg.finwait1_time);
380       break;
381     case TCP_STATE_ESTABLISHED:
382       /* If closing with unread data, reset the connection */
383       if (transport_max_rx_dequeue (&tc->connection))
384         {
385           tcp_send_reset (tc);
386           tcp_connection_timers_reset (tc);
387           tcp_connection_set_state (tc, TCP_STATE_CLOSED);
388           session_transport_closed_notify (&tc->connection);
389           tcp_program_cleanup (tcp_get_worker (tc->c_thread_index), tc);
390           tcp_worker_stats_inc (wrk, rst_unread, 1);
391           break;
392         }
393       if (!transport_max_tx_dequeue (&tc->connection))
394         tcp_send_fin (tc);
395       else
396         tc->flags |= TCP_CONN_FINPNDG;
397       tcp_connection_set_state (tc, TCP_STATE_FIN_WAIT_1);
398       /* Set a timer in case the peer stops responding. Otherwise the
399        * connection will be stuck here forever. */
400       ASSERT (tc->timers[TCP_TIMER_WAITCLOSE] == TCP_TIMER_HANDLE_INVALID);
401       tcp_timer_set (&wrk->timer_wheel, tc, TCP_TIMER_WAITCLOSE,
402                      tcp_cfg.finwait1_time);
403       break;
404     case TCP_STATE_CLOSE_WAIT:
405       if (!transport_max_tx_dequeue (&tc->connection))
406         {
407           tcp_send_fin (tc);
408           tcp_connection_timers_reset (tc);
409           tcp_connection_set_state (tc, TCP_STATE_LAST_ACK);
410           tcp_timer_update (&wrk->timer_wheel, tc, TCP_TIMER_WAITCLOSE,
411                             tcp_cfg.lastack_time);
412         }
413       else
414         tc->flags |= TCP_CONN_FINPNDG;
415       break;
416     case TCP_STATE_FIN_WAIT_1:
417       tcp_timer_update (&wrk->timer_wheel, tc, TCP_TIMER_WAITCLOSE,
418                         tcp_cfg.finwait1_time);
419       break;
420     case TCP_STATE_CLOSED:
421       /* Cleanup should've been programmed already */
422       break;
423     default:
424       TCP_DBG ("state: %u", tc->state);
425     }
426 }
427
428 static void
429 tcp_session_half_close (u32 conn_index, u32 thread_index)
430 {
431   tcp_worker_ctx_t *wrk;
432   tcp_connection_t *tc;
433
434   tc = tcp_connection_get (conn_index, thread_index);
435   wrk = tcp_get_worker (tc->c_thread_index);
436
437   /* If the connection is not in ESTABLISHED state, ignore it */
438   if (tc->state != TCP_STATE_ESTABLISHED)
439     return;
440   if (!transport_max_tx_dequeue (&tc->connection))
441     tcp_send_fin (tc);
442   else
443     tc->flags |= TCP_CONN_FINPNDG;
444   tcp_connection_set_state (tc, TCP_STATE_FIN_WAIT_1);
445   /* Set a timer in case the peer stops responding. Otherwise the
446    * connection will be stuck here forever. */
447   ASSERT (tc->timers[TCP_TIMER_WAITCLOSE] == TCP_TIMER_HANDLE_INVALID);
448   tcp_timer_set (&wrk->timer_wheel, tc, TCP_TIMER_WAITCLOSE,
449                  tcp_cfg.finwait1_time);
450 }
451
452 static void
453 tcp_session_close (u32 conn_index, u32 thread_index)
454 {
455   tcp_connection_t *tc;
456   tc = tcp_connection_get (conn_index, thread_index);
457   tcp_connection_close (tc);
458 }
459
460 static void
461 tcp_session_cleanup (u32 conn_index, u32 thread_index)
462 {
463   tcp_connection_t *tc;
464   tc = tcp_connection_get (conn_index, thread_index);
465   if (!tc)
466     return;
467   tcp_connection_set_state (tc, TCP_STATE_CLOSED);
468   tcp_connection_cleanup (tc);
469 }
470
471 static void
472 tcp_session_cleanup_ho (u32 conn_index)
473 {
474   tcp_worker_ctx_t *wrk;
475   tcp_connection_t *tc;
476
477   tc = tcp_half_open_connection_get (conn_index);
478   wrk = tcp_get_worker (tc->c_thread_index);
479   tcp_timer_reset (&wrk->timer_wheel, tc, TCP_TIMER_RETRANSMIT_SYN);
480   tcp_half_open_connection_free (tc);
481 }
482
483 static void
484 tcp_session_reset (u32 conn_index, u32 thread_index)
485 {
486   tcp_connection_t *tc;
487   tc = tcp_connection_get (conn_index, thread_index);
488   tcp_send_reset (tc);
489   tcp_connection_timers_reset (tc);
490   tcp_cong_recovery_off (tc);
491   tcp_connection_set_state (tc, TCP_STATE_CLOSED);
492   session_transport_closed_notify (&tc->connection);
493   tcp_program_cleanup (tcp_get_worker (thread_index), tc);
494 }
495
496 /**
497  * Initialize all connection timers as invalid
498  */
499 void
500 tcp_connection_timers_init (tcp_connection_t * tc)
501 {
502   int i;
503
504   /* Set all to invalid */
505   for (i = 0; i < TCP_N_TIMERS; i++)
506     {
507       tc->timers[i] = TCP_TIMER_HANDLE_INVALID;
508     }
509
510   tc->rto = TCP_RTO_INIT;
511 }
512
513 /**
514  * Stop all connection timers
515  */
516 void
517 tcp_connection_timers_reset (tcp_connection_t * tc)
518 {
519   tcp_worker_ctx_t *wrk = tcp_get_worker (tc->c_thread_index);
520   int i;
521
522   for (i = 0; i < TCP_N_TIMERS; i++)
523     tcp_timer_reset (&wrk->timer_wheel, tc, i);
524 }
525
526 #if 0
527 typedef struct ip4_tcp_hdr
528 {
529   ip4_header_t ip;
530   tcp_header_t tcp;
531 } ip4_tcp_hdr_t;
532
533 typedef struct ip6_tcp_hdr
534 {
535   ip6_header_t ip;
536   tcp_header_t tcp;
537 } ip6_tcp_hdr_t;
538
539 static void
540 tcp_connection_select_lb_bucket (tcp_connection_t * tc, const dpo_id_t * dpo,
541                                  dpo_id_t * result)
542 {
543   const dpo_id_t *choice;
544   load_balance_t *lb;
545   int hash;
546
547   lb = load_balance_get (dpo->dpoi_index);
548   if (tc->c_is_ip4)
549     {
550       ip4_tcp_hdr_t hdr;
551       clib_memset (&hdr, 0, sizeof (hdr));
552       hdr.ip.protocol = IP_PROTOCOL_TCP;
553       hdr.ip.address_pair.src.as_u32 = tc->c_lcl_ip.ip4.as_u32;
554       hdr.ip.address_pair.dst.as_u32 = tc->c_rmt_ip.ip4.as_u32;
555       hdr.tcp.src_port = tc->c_lcl_port;
556       hdr.tcp.dst_port = tc->c_rmt_port;
557       hash = ip4_compute_flow_hash (&hdr.ip, lb->lb_hash_config);
558     }
559   else
560     {
561       ip6_tcp_hdr_t hdr;
562       clib_memset (&hdr, 0, sizeof (hdr));
563       hdr.ip.protocol = IP_PROTOCOL_TCP;
564       clib_memcpy_fast (&hdr.ip.src_address, &tc->c_lcl_ip.ip6,
565                         sizeof (ip6_address_t));
566       clib_memcpy_fast (&hdr.ip.dst_address, &tc->c_rmt_ip.ip6,
567                         sizeof (ip6_address_t));
568       hdr.tcp.src_port = tc->c_lcl_port;
569       hdr.tcp.dst_port = tc->c_rmt_port;
570       hash = ip6_compute_flow_hash (&hdr.ip, lb->lb_hash_config);
571     }
572   choice = load_balance_get_bucket_i (lb, hash & lb->lb_n_buckets_minus_1);
573   dpo_copy (result, choice);
574 }
575
576 fib_node_index_t
577 tcp_lookup_rmt_in_fib (tcp_connection_t * tc)
578 {
579   fib_prefix_t prefix;
580   u32 fib_index;
581
582   clib_memcpy_fast (&prefix.fp_addr, &tc->c_rmt_ip, sizeof (prefix.fp_addr));
583   prefix.fp_proto = tc->c_is_ip4 ? FIB_PROTOCOL_IP4 : FIB_PROTOCOL_IP6;
584   prefix.fp_len = tc->c_is_ip4 ? 32 : 128;
585   fib_index = fib_table_find (prefix.fp_proto, tc->c_fib_index);
586   return fib_table_lookup (fib_index, &prefix);
587 }
588
589 static int
590 tcp_connection_stack_on_fib_entry (tcp_connection_t * tc)
591 {
592   dpo_id_t choice = DPO_INVALID;
593   u32 output_node_index;
594   fib_entry_t *fe;
595
596   fe = fib_entry_get (tc->c_rmt_fei);
597   if (fe->fe_lb.dpoi_type != DPO_LOAD_BALANCE)
598     return -1;
599
600   tcp_connection_select_lb_bucket (tc, &fe->fe_lb, &choice);
601
602   output_node_index =
603     tc->c_is_ip4 ? tcp4_output_node.index : tcp6_output_node.index;
604   dpo_stack_from_node (output_node_index, &tc->c_rmt_dpo, &choice);
605   return 0;
606 }
607
608 /** Stack tcp connection on peer's fib entry.
609  *
610  * This ultimately populates the dpo the connection will use to send packets.
611  */
612 static void
613 tcp_connection_fib_attach (tcp_connection_t * tc)
614 {
615   tc->c_rmt_fei = tcp_lookup_rmt_in_fib (tc);
616
617   ASSERT (tc->c_rmt_fei != FIB_NODE_INDEX_INVALID);
618
619   tcp_connection_stack_on_fib_entry (tc);
620 }
621 #endif /* 0 */
622
623 /**
624  * Generate random iss as per rfc6528
625  */
626 static u32
627 tcp_generate_random_iss (tcp_connection_t * tc)
628 {
629   tcp_main_t *tm = &tcp_main;
630   u64 tmp;
631
632   if (tc->c_is_ip4)
633     tmp = (u64) tc->c_lcl_ip.ip4.as_u32 << 32 | (u64) tc->c_rmt_ip.ip4.as_u32;
634   else
635     tmp = tc->c_lcl_ip.ip6.as_u64[0] ^ tc->c_lcl_ip.ip6.as_u64[1]
636       ^ tc->c_rmt_ip.ip6.as_u64[0] ^ tc->c_rmt_ip.ip6.as_u64[1];
637
638   tmp ^= tm->iss_seed.first | ((u64) tc->c_lcl_port << 16 | tc->c_rmt_port);
639   tmp ^= tm->iss_seed.second;
640   tmp = clib_xxhash (tmp) + clib_cpu_time_now ();
641   return ((tmp >> 32) ^ (tmp & 0xffffffff));
642 }
643
644 /**
645  * Initialize max segment size we're able to process.
646  *
647  * The value is constrained by the output interface's MTU and by the size
648  * of the IP and TCP headers (see RFC6691). It is also what we advertise
649  * to our peer.
650  */
651 static void
652 tcp_init_rcv_mss (tcp_connection_t * tc)
653 {
654   u8 ip_hdr_len;
655
656   /* Already provided at connection init time */
657   if (tc->mss)
658     return;
659
660   ip_hdr_len = tc->c_is_ip4 ? sizeof (ip4_header_t) : sizeof (ip6_header_t);
661   tc->mss = tcp_cfg.default_mtu - sizeof (tcp_header_t) - ip_hdr_len;
662 }
663
664 static void
665 tcp_init_mss (tcp_connection_t * tc)
666 {
667   u16 default_min_mss = 536;
668
669   tcp_init_rcv_mss (tc);
670
671   /* TODO consider PMTU discovery */
672   tc->snd_mss = clib_min (tc->rcv_opts.mss, tc->mss);
673
674   if (tc->snd_mss < 45)
675     {
676       /* Assume that at least the min default mss works */
677       tc->snd_mss = default_min_mss;
678       tc->rcv_opts.mss = default_min_mss;
679     }
680
681   /* We should have enough space for 40 bytes of options */
682   ASSERT (tc->snd_mss > 45);
683
684   /* If we use timestamp option, account for it and make sure
685    * the options are 4-byte aligned */
686   if (tcp_opts_tstamp (&tc->rcv_opts))
687     tc->snd_mss -= TCP_OPTION_LEN_TIMESTAMP + 2 /* alignment */;
688 }
689
690 /**
691  * Initialize connection send variables.
692  */
693 void
694 tcp_init_snd_vars (tcp_connection_t * tc)
695 {
696   /*
697    * We use the time to randomize iss and for setting up the initial
698    * timestamp. Make sure it's updated otherwise syn and ack in the
699    * handshake may make it look as if time has flown in the opposite
700    * direction for us.
701    */
702   tcp_update_time_now (tcp_get_worker (vlib_get_thread_index ()));
703
704   tcp_init_rcv_mss (tc);
705   tc->iss = tcp_generate_random_iss (tc);
706   tc->snd_una = tc->iss;
707   tc->snd_nxt = tc->iss + 1;
708   tc->srtt = 0.1 * THZ;         /* 100 ms */
709
710   if (!tcp_cfg.csum_offload)
711     tc->cfg_flags |= TCP_CFG_F_NO_CSUM_OFFLOAD;
712 }
713
714 void
715 tcp_enable_pacing (tcp_connection_t * tc)
716 {
717   u32 byte_rate;
718   byte_rate = tc->cwnd / (tc->srtt * TCP_TICK);
719   transport_connection_tx_pacer_init (&tc->connection, byte_rate, tc->cwnd);
720   tc->mrtt_us = (u32) ~ 0;
721 }
722
723 /** Initialize tcp connection variables
724  *
725  * Should be called after having received a msg from the peer, i.e., a SYN or
726  * a SYNACK, such that connection options have already been exchanged. */
727 void
728 tcp_connection_init_vars (tcp_connection_t * tc)
729 {
730   tcp_connection_timers_init (tc);
731   tcp_init_mss (tc);
732   scoreboard_init (&tc->sack_sb);
733   if (tc->state == TCP_STATE_SYN_RCVD)
734     tcp_init_snd_vars (tc);
735
736   tcp_cc_init (tc);
737
738   if (!tc->c_is_ip4 && ip6_address_is_link_local_unicast (&tc->c_rmt_ip6))
739     tcp_add_del_adjacency (tc, 1);
740
741   /*  tcp_connection_fib_attach (tc); */
742
743   if (transport_connection_is_tx_paced (&tc->connection)
744       || tcp_cfg.enable_tx_pacing)
745     tcp_enable_pacing (tc);
746
747   if (tc->cfg_flags & TCP_CFG_F_RATE_SAMPLE)
748     tcp_bt_init (tc);
749
750   if (!tcp_cfg.allow_tso)
751     tc->cfg_flags |= TCP_CFG_F_NO_TSO;
752
753   tc->start_ts = tcp_time_now_us (tc->c_thread_index);
754 }
755
756 static int
757 tcp_alloc_custom_local_endpoint (tcp_main_t * tm, ip46_address_t * lcl_addr,
758                                  u16 * lcl_port, u8 is_ip4)
759 {
760   int index, port;
761   if (is_ip4)
762     {
763       index = tm->last_v4_addr_rotor++;
764       if (tm->last_v4_addr_rotor >= vec_len (tcp_cfg.ip4_src_addrs))
765         tm->last_v4_addr_rotor = 0;
766       lcl_addr->ip4.as_u32 = tcp_cfg.ip4_src_addrs[index].as_u32;
767     }
768   else
769     {
770       index = tm->last_v6_addr_rotor++;
771       if (tm->last_v6_addr_rotor >= vec_len (tcp_cfg.ip6_src_addrs))
772         tm->last_v6_addr_rotor = 0;
773       clib_memcpy_fast (&lcl_addr->ip6, &tcp_cfg.ip6_src_addrs[index],
774                         sizeof (ip6_address_t));
775     }
776   port = transport_alloc_local_port (TRANSPORT_PROTO_TCP, lcl_addr);
777   if (port < 1)
778     return SESSION_E_NOPORT;
779   *lcl_port = port;
780   return 0;
781 }
782
783 static int
784 tcp_session_open (transport_endpoint_cfg_t * rmt)
785 {
786   tcp_main_t *tm = vnet_get_tcp_main ();
787   tcp_connection_t *tc;
788   ip46_address_t lcl_addr;
789   u16 lcl_port;
790   int rv;
791
792   /*
793    * Allocate local endpoint
794    */
795   if ((rmt->is_ip4 && vec_len (tcp_cfg.ip4_src_addrs))
796       || (!rmt->is_ip4 && vec_len (tcp_cfg.ip6_src_addrs)))
797     rv = tcp_alloc_custom_local_endpoint (tm, &lcl_addr, &lcl_port,
798                                           rmt->is_ip4);
799   else
800     rv = transport_alloc_local_endpoint (TRANSPORT_PROTO_TCP,
801                                          rmt, &lcl_addr, &lcl_port);
802
803   if (rv)
804     {
805       if (rv != SESSION_E_PORTINUSE)
806         return rv;
807
808       if (session_lookup_connection (rmt->fib_index, &lcl_addr, &rmt->ip,
809                                      lcl_port, rmt->port, TRANSPORT_PROTO_TCP,
810                                      rmt->is_ip4))
811         return SESSION_E_PORTINUSE;
812
813       /* 5-tuple is available so increase lcl endpoint refcount and proceed
814        * with connection allocation */
815       transport_share_local_endpoint (TRANSPORT_PROTO_TCP, &lcl_addr,
816                                       lcl_port);
817     }
818
819   /*
820    * Create connection and send SYN
821    */
822   tc = tcp_half_open_connection_alloc ();
823   ip_copy (&tc->c_rmt_ip, &rmt->ip, rmt->is_ip4);
824   ip_copy (&tc->c_lcl_ip, &lcl_addr, rmt->is_ip4);
825   tc->c_rmt_port = rmt->port;
826   tc->c_lcl_port = clib_host_to_net_u16 (lcl_port);
827   tc->c_is_ip4 = rmt->is_ip4;
828   tc->c_proto = TRANSPORT_PROTO_TCP;
829   tc->c_fib_index = rmt->fib_index;
830   tc->cc_algo = tcp_cc_algo_get (tcp_cfg.cc_algo);
831   /* The other connection vars will be initialized after SYN ACK */
832   tcp_connection_timers_init (tc);
833   tc->mss = rmt->mss;
834
835   TCP_EVT (TCP_EVT_OPEN, tc);
836   tc->state = TCP_STATE_SYN_SENT;
837   tcp_init_snd_vars (tc);
838   tcp_send_syn (tc);
839
840   return tc->c_c_index;
841 }
842
843 static u8 *
844 format_tcp_session (u8 * s, va_list * args)
845 {
846   u32 tci = va_arg (*args, u32);
847   u32 thread_index = va_arg (*args, u32);
848   u32 verbose = va_arg (*args, u32);
849   tcp_connection_t *tc;
850
851   tc = tcp_connection_get (tci, thread_index);
852   if (tc)
853     s = format (s, "%U", format_tcp_connection, tc, verbose);
854   else
855     s = format (s, "empty\n");
856   return s;
857 }
858
859 static u8 *
860 format_tcp_listener_session (u8 * s, va_list * args)
861 {
862   u32 tci = va_arg (*args, u32);
863   u32 __clib_unused thread_index = va_arg (*args, u32);
864   u32 verbose = va_arg (*args, u32);
865   tcp_connection_t *tc = tcp_listener_get (tci);
866   s = format (s, "%-" SESSION_CLI_ID_LEN "U", format_tcp_connection_id, tc);
867   if (verbose)
868     s = format (s, "%-" SESSION_CLI_STATE_LEN "U", format_tcp_state,
869                 tc->state);
870   return s;
871 }
872
873 static u8 *
874 format_tcp_half_open_session (u8 * s, va_list * args)
875 {
876   u32 tci = va_arg (*args, u32);
877   u32 __clib_unused thread_index = va_arg (*args, u32);
878   u32 verbose = va_arg (*args, u32);
879   tcp_connection_t *tc;
880   u8 *state = 0;
881
882   tc = tcp_half_open_connection_get (tci);
883   if (tc->flags & TCP_CONN_HALF_OPEN_DONE)
884     state = format (state, "%s", "CLOSED");
885   else
886     state = format (state, "%U", format_tcp_state, tc->state);
887   s = format (s, "%-" SESSION_CLI_ID_LEN "U", format_tcp_connection_id, tc);
888   if (verbose)
889     s = format (s, "%-" SESSION_CLI_STATE_LEN "v", state);
890   vec_free (state);
891   return s;
892 }
893
894 static transport_connection_t *
895 tcp_session_get_transport (u32 conn_index, u32 thread_index)
896 {
897   tcp_connection_t *tc = tcp_connection_get (conn_index, thread_index);
898   if (PREDICT_FALSE (!tc))
899     return 0;
900   return &tc->connection;
901 }
902
903 static transport_connection_t *
904 tcp_half_open_session_get_transport (u32 conn_index)
905 {
906   tcp_connection_t *tc = tcp_half_open_connection_get (conn_index);
907   return &tc->connection;
908 }
909
910 static int
911 tcp_set_attribute (tcp_connection_t *tc, transport_endpt_attr_t *attr)
912 {
913   int rv = 0;
914
915   switch (attr->type)
916     {
917     case TRANSPORT_ENDPT_ATTR_NEXT_OUTPUT_NODE:
918       tc->next_node_index = attr->next_output_node & 0xffffffff;
919       tc->next_node_opaque = attr->next_output_node >> 32;
920       break;
921     case TRANSPORT_ENDPT_ATTR_MSS:
922       tc->mss = attr->mss;
923       tc->snd_mss = clib_min (tc->snd_mss, tc->mss);
924       break;
925     case TRANSPORT_ENDPT_ATTR_FLAGS:
926       if (attr->flags & TRANSPORT_ENDPT_ATTR_F_CSUM_OFFLOAD)
927         tc->cfg_flags |= TCP_CFG_F_NO_CSUM_OFFLOAD;
928       else
929         tc->cfg_flags &= ~TCP_CFG_F_NO_CSUM_OFFLOAD;
930       if (attr->flags & TRANSPORT_ENDPT_ATTR_F_GSO)
931         {
932           if (!(tc->cfg_flags & TCP_CFG_F_TSO))
933             tcp_check_gso (tc);
934           tc->cfg_flags &= ~TCP_CFG_F_NO_TSO;
935         }
936       else
937         {
938           tc->cfg_flags |= TCP_CFG_F_NO_TSO;
939           tc->cfg_flags &= ~TCP_CFG_F_TSO;
940         }
941       if (attr->flags & TRANSPORT_ENDPT_ATTR_F_RATE_SAMPLING)
942         {
943           if (!(tc->cfg_flags & TCP_CFG_F_RATE_SAMPLE))
944             tcp_bt_init (tc);
945           tc->cfg_flags |= TCP_CFG_F_RATE_SAMPLE;
946         }
947       else
948         {
949           if (tc->cfg_flags & TCP_CFG_F_RATE_SAMPLE)
950             tcp_bt_cleanup (tc);
951           tc->cfg_flags &= ~TCP_CFG_F_RATE_SAMPLE;
952         }
953       break;
954     case TRANSPORT_ENDPT_ATTR_CC_ALGO:
955       if (tc->cc_algo == tcp_cc_algo_get (attr->cc_algo))
956         break;
957       tcp_cc_cleanup (tc);
958       tc->cc_algo = tcp_cc_algo_get (attr->cc_algo);
959       tcp_cc_init (tc);
960       break;
961     default:
962       rv = -1;
963       break;
964     }
965
966   return rv;
967 }
968
969 static int
970 tcp_get_attribute (tcp_connection_t *tc, transport_endpt_attr_t *attr)
971 {
972   int rv = 0;
973   u64 non;
974
975   switch (attr->type)
976     {
977     case TRANSPORT_ENDPT_ATTR_NEXT_OUTPUT_NODE:
978       non = (u64) tc->next_node_opaque << 32 | tc->next_node_index;
979       attr->next_output_node = non;
980       break;
981     case TRANSPORT_ENDPT_ATTR_MSS:
982       attr->mss = tc->snd_mss;
983       break;
984     case TRANSPORT_ENDPT_ATTR_FLAGS:
985       attr->flags = 0;
986       if (!(tc->cfg_flags & TCP_CFG_F_NO_CSUM_OFFLOAD))
987         attr->flags |= TRANSPORT_ENDPT_ATTR_F_CSUM_OFFLOAD;
988       if (tc->cfg_flags & TCP_CFG_F_TSO)
989         attr->flags |= TRANSPORT_ENDPT_ATTR_F_GSO;
990       if (tc->cfg_flags & TCP_CFG_F_RATE_SAMPLE)
991         attr->flags |= TRANSPORT_ENDPT_ATTR_F_RATE_SAMPLING;
992       break;
993     case TRANSPORT_ENDPT_ATTR_CC_ALGO:
994       attr->cc_algo = tc->cc_algo - tcp_main.cc_algos;
995       break;
996     default:
997       rv = -1;
998       break;
999     }
1000
1001   return rv;
1002 }
1003
1004 static int
1005 tcp_session_attribute (u32 conn_index, u32 thread_index, u8 is_get,
1006                        transport_endpt_attr_t *attr)
1007 {
1008   tcp_connection_t *tc = tcp_connection_get (conn_index, thread_index);
1009
1010   if (PREDICT_FALSE (!tc))
1011     return -1;
1012
1013   if (is_get)
1014     return tcp_get_attribute (tc, attr);
1015   else
1016     return tcp_set_attribute (tc, attr);
1017 }
1018
1019 static u16
1020 tcp_session_cal_goal_size (tcp_connection_t * tc)
1021 {
1022   u16 goal_size = tc->snd_mss;
1023
1024   goal_size = tcp_cfg.max_gso_size - tc->snd_mss % tcp_cfg.max_gso_size;
1025   goal_size = clib_min (goal_size, tc->snd_wnd / 2);
1026
1027   return goal_size > tc->snd_mss ? goal_size : tc->snd_mss;
1028 }
1029
1030 always_inline u32
1031 tcp_round_snd_space (tcp_connection_t * tc, u32 snd_space)
1032 {
1033   if (PREDICT_FALSE (tc->snd_wnd < tc->snd_mss))
1034     {
1035       return tc->snd_wnd <= snd_space ? tc->snd_wnd : 0;
1036     }
1037
1038   /* If not snd_wnd constrained and we can't write at least a segment,
1039    * don't try at all */
1040   if (PREDICT_FALSE (snd_space < tc->snd_mss))
1041     return snd_space < tc->cwnd ? 0 : snd_space;
1042
1043   /* round down to mss multiple */
1044   return snd_space - (snd_space % tc->snd_mss);
1045 }
1046
1047 /**
1048  * Compute tx window session is allowed to fill.
1049  *
1050  * Takes into account available send space, snd_mss and the congestion
1051  * state of the connection. If possible, the value returned is a multiple
1052  * of snd_mss.
1053  *
1054  * @param tc tcp connection
1055  * @return number of bytes session is allowed to write
1056  */
1057 static inline u32
1058 tcp_snd_space_inline (tcp_connection_t * tc)
1059 {
1060   int snd_space;
1061
1062   /* Fast path is disabled when recovery is on. @ref tcp_session_custom_tx
1063    * controls both retransmits and the sending of new data while congested
1064    */
1065   if (PREDICT_FALSE (tcp_in_cong_recovery (tc)
1066                      || tc->state == TCP_STATE_CLOSED))
1067     return 0;
1068
1069   snd_space = tcp_available_output_snd_space (tc);
1070
1071   /* If we got dupacks or sacked bytes but we're not yet in recovery, try
1072    * to force the peer to send enough dupacks to start retransmitting as
1073    * per Limited Transmit (RFC3042)
1074    */
1075   if (PREDICT_FALSE (tc->rcv_dupacks || tc->sack_sb.sacked_bytes))
1076     {
1077       int snt_limited, n_pkts;
1078
1079       n_pkts = tcp_opts_sack_permitted (&tc->rcv_opts)
1080         ? tc->sack_sb.reorder - 1 : 2;
1081
1082       if ((seq_lt (tc->limited_transmit, tc->snd_nxt - n_pkts * tc->snd_mss)
1083            || seq_gt (tc->limited_transmit, tc->snd_nxt)))
1084         tc->limited_transmit = tc->snd_nxt;
1085
1086       ASSERT (seq_leq (tc->limited_transmit, tc->snd_nxt));
1087
1088       snt_limited = tc->snd_nxt - tc->limited_transmit;
1089       snd_space = clib_max (n_pkts * tc->snd_mss - snt_limited, 0);
1090     }
1091   return tcp_round_snd_space (tc, snd_space);
1092 }
1093
1094 u32
1095 tcp_snd_space (tcp_connection_t * tc)
1096 {
1097   return tcp_snd_space_inline (tc);
1098 }
1099
1100 static int
1101 tcp_session_send_params (transport_connection_t * trans_conn,
1102                          transport_send_params_t * sp)
1103 {
1104   tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
1105
1106   /* Ensure snd_mss does accurately reflect the amount of data we can push
1107    * in a segment. This also makes sure that options are updated according to
1108    * the current state of the connection. */
1109   tcp_update_burst_snd_vars (tc);
1110
1111   if (PREDICT_FALSE (tc->cfg_flags & TCP_CFG_F_TSO))
1112     sp->snd_mss = tcp_session_cal_goal_size (tc);
1113   else
1114     sp->snd_mss = tc->snd_mss;
1115
1116   sp->snd_space = clib_min (tcp_snd_space_inline (tc),
1117                             tc->snd_wnd - (tc->snd_nxt - tc->snd_una));
1118
1119   ASSERT (seq_geq (tc->snd_nxt, tc->snd_una));
1120   /* This still works if fast retransmit is on */
1121   sp->tx_offset = tc->snd_nxt - tc->snd_una;
1122
1123   sp->flags = sp->snd_space ? 0 : TRANSPORT_SND_F_DESCHED;
1124
1125   return 0;
1126 }
1127
1128 static void
1129 tcp_timer_waitclose_handler (tcp_connection_t * tc)
1130 {
1131   tcp_worker_ctx_t *wrk = tcp_get_worker (tc->c_thread_index);
1132
1133   switch (tc->state)
1134     {
1135     case TCP_STATE_CLOSE_WAIT:
1136       tcp_connection_timers_reset (tc);
1137       /* App never returned with a close */
1138       if (!(tc->flags & TCP_CONN_FINPNDG))
1139         {
1140           tcp_connection_set_state (tc, TCP_STATE_CLOSED);
1141           session_transport_closed_notify (&tc->connection);
1142           tcp_program_cleanup (wrk, tc);
1143           tcp_worker_stats_inc (wrk, to_closewait, 1);
1144           break;
1145         }
1146
1147       /* Send FIN either way and switch to LAST_ACK. */
1148       tcp_cong_recovery_off (tc);
1149       /* Make sure we don't try to send unsent data */
1150       tc->snd_nxt = tc->snd_una;
1151       tcp_send_fin (tc);
1152       tcp_connection_set_state (tc, TCP_STATE_LAST_ACK);
1153       session_transport_closed_notify (&tc->connection);
1154
1155       /* Make sure we don't wait in LAST ACK forever */
1156       tcp_timer_set (&wrk->timer_wheel, tc, TCP_TIMER_WAITCLOSE,
1157                      tcp_cfg.lastack_time);
1158       tcp_worker_stats_inc (wrk, to_closewait2, 1);
1159
1160       /* Don't delete the connection yet */
1161       break;
1162     case TCP_STATE_FIN_WAIT_1:
1163       tcp_connection_timers_reset (tc);
1164       if (tc->flags & TCP_CONN_FINPNDG)
1165         {
1166           /* If FIN pending, we haven't sent everything, but we did try.
1167            * Notify session layer that transport is closed. */
1168           tcp_connection_set_state (tc, TCP_STATE_CLOSED);
1169           tcp_send_reset (tc);
1170           tcp_program_cleanup (wrk, tc);
1171         }
1172       else
1173         {
1174           /* We've sent the fin but no progress. Close the connection and
1175            * to make sure everything is flushed, setup a cleanup timer */
1176           tcp_connection_set_state (tc, TCP_STATE_CLOSED);
1177           tcp_program_cleanup (wrk, tc);
1178         }
1179       session_transport_closed_notify (&tc->connection);
1180       tcp_worker_stats_inc (wrk, to_finwait1, 1);
1181       break;
1182     case TCP_STATE_LAST_ACK:
1183       tcp_connection_timers_reset (tc);
1184       tcp_connection_set_state (tc, TCP_STATE_CLOSED);
1185       session_transport_closed_notify (&tc->connection);
1186       tcp_program_cleanup (wrk, tc);
1187       tcp_worker_stats_inc (wrk, to_lastack, 1);
1188       break;
1189     case TCP_STATE_CLOSING:
1190       tcp_connection_timers_reset (tc);
1191       tcp_connection_set_state (tc, TCP_STATE_CLOSED);
1192       session_transport_closed_notify (&tc->connection);
1193       tcp_program_cleanup (wrk, tc);
1194       tcp_worker_stats_inc (wrk, to_closing, 1);
1195       break;
1196     case TCP_STATE_FIN_WAIT_2:
1197       tcp_send_reset (tc);
1198       tcp_connection_timers_reset (tc);
1199       tcp_connection_set_state (tc, TCP_STATE_CLOSED);
1200       session_transport_closed_notify (&tc->connection);
1201       tcp_program_cleanup (wrk, tc);
1202       tcp_worker_stats_inc (wrk, to_finwait2, 1);
1203       break;
1204     case TCP_STATE_TIME_WAIT:
1205       tcp_connection_set_state (tc, TCP_STATE_CLOSED);
1206       tcp_program_cleanup (wrk, tc);
1207       break;
1208     default:
1209       clib_warning ("waitclose in state: %U", format_tcp_state, tc->state);
1210       break;
1211     }
1212 }
1213
1214 /* *INDENT-OFF* */
1215 static timer_expiration_handler *timer_expiration_handlers[TCP_N_TIMERS] =
1216 {
1217     tcp_timer_retransmit_handler,
1218     tcp_timer_persist_handler,
1219     tcp_timer_waitclose_handler,
1220     tcp_timer_retransmit_syn_handler,
1221 };
1222 /* *INDENT-ON* */
1223
1224 static void
1225 tcp_dispatch_pending_timers (tcp_worker_ctx_t * wrk)
1226 {
1227   u32 n_timers, connection_index, timer_id, thread_index, timer_handle;
1228   tcp_connection_t *tc;
1229   int i;
1230
1231   if (!(n_timers = clib_fifo_elts (wrk->pending_timers)))
1232     return;
1233
1234   thread_index = wrk->vm->thread_index;
1235   for (i = 0; i < clib_min (n_timers, wrk->max_timers_per_loop); i++)
1236     {
1237       clib_fifo_sub1 (wrk->pending_timers, timer_handle);
1238       connection_index = timer_handle & 0x0FFFFFFF;
1239       timer_id = timer_handle >> 28;
1240
1241       if (PREDICT_TRUE (timer_id != TCP_TIMER_RETRANSMIT_SYN))
1242         tc = tcp_connection_get (connection_index, thread_index);
1243       else
1244         tc = tcp_half_open_connection_get (connection_index);
1245
1246       if (PREDICT_FALSE (!tc))
1247         continue;
1248
1249       /* Skip if the timer is not pending. Probably it was reset while
1250        * waiting for dispatch */
1251       if (PREDICT_FALSE (!(tc->pending_timers & (1 << timer_id))))
1252         continue;
1253
1254       tc->pending_timers &= ~(1 << timer_id);
1255
1256       /* Skip timer if it was rearmed while pending dispatch */
1257       if (PREDICT_FALSE (tc->timers[timer_id] != TCP_TIMER_HANDLE_INVALID))
1258         continue;
1259
1260       (*timer_expiration_handlers[timer_id]) (tc);
1261     }
1262
1263   if (thread_index == 0 && clib_fifo_elts (wrk->pending_timers))
1264     session_queue_run_on_main_thread (wrk->vm);
1265 }
1266
1267 static void
1268 tcp_handle_cleanups (tcp_worker_ctx_t * wrk, clib_time_type_t now)
1269 {
1270   u32 thread_index = wrk->vm->thread_index;
1271   tcp_cleanup_req_t *req;
1272   tcp_connection_t *tc;
1273
1274   while (clib_fifo_elts (wrk->pending_cleanups))
1275     {
1276       req = clib_fifo_head (wrk->pending_cleanups);
1277       if (req->free_time > now)
1278         break;
1279       clib_fifo_sub2 (wrk->pending_cleanups, req);
1280       tc = tcp_connection_get (req->connection_index, thread_index);
1281       if (PREDICT_FALSE (!tc))
1282         continue;
1283       session_transport_delete_notify (&tc->connection);
1284       tcp_connection_cleanup (tc);
1285     }
1286 }
1287
1288 static void
1289 tcp_update_time (f64 now, u8 thread_index)
1290 {
1291   tcp_worker_ctx_t *wrk = tcp_get_worker (thread_index);
1292
1293   tcp_set_time_now (wrk, now);
1294   tcp_handle_cleanups (wrk, now);
1295   tcp_timer_expire_timers (&wrk->timer_wheel, now);
1296   tcp_dispatch_pending_timers (wrk);
1297 }
1298
1299 static void
1300 tcp_session_flush_data (transport_connection_t * tconn)
1301 {
1302   tcp_connection_t *tc = (tcp_connection_t *) tconn;
1303   if (tc->flags & TCP_CONN_PSH_PENDING)
1304     return;
1305   tc->flags |= TCP_CONN_PSH_PENDING;
1306   tc->psh_seq = tc->snd_una + transport_max_tx_dequeue (tconn) - 1;
1307 }
1308
1309 static int
1310 tcp_session_app_rx_evt (transport_connection_t *conn)
1311 {
1312   tcp_connection_t *tc = (tcp_connection_t *) conn;
1313   u32 min_free, lo = 4 << 10, hi = 128 << 10;
1314
1315   if (!(tc->flags & TCP_CONN_ZERO_RWND_SENT))
1316     return 0;
1317
1318   min_free = clib_clamp (transport_rx_fifo_size (conn) >> 3, lo, hi);
1319   if (transport_max_rx_enqueue (conn) < min_free)
1320     {
1321       transport_rx_fifo_req_deq_ntf (conn);
1322       return 0;
1323     }
1324
1325   tcp_send_ack (tc);
1326
1327   return 0;
1328 }
1329
1330 /* *INDENT-OFF* */
1331 const static transport_proto_vft_t tcp_proto = {
1332   .enable = vnet_tcp_enable_disable,
1333   .start_listen = tcp_session_bind,
1334   .stop_listen = tcp_session_unbind,
1335   .push_header = tcp_session_push_header,
1336   .get_connection = tcp_session_get_transport,
1337   .get_listener = tcp_session_get_listener,
1338   .get_half_open = tcp_half_open_session_get_transport,
1339   .attribute = tcp_session_attribute,
1340   .connect = tcp_session_open,
1341   .half_close = tcp_session_half_close,
1342   .close = tcp_session_close,
1343   .cleanup = tcp_session_cleanup,
1344   .cleanup_ho = tcp_session_cleanup_ho,
1345   .reset = tcp_session_reset,
1346   .send_params = tcp_session_send_params,
1347   .update_time = tcp_update_time,
1348   .flush_data = tcp_session_flush_data,
1349   .custom_tx = tcp_session_custom_tx,
1350   .app_rx_evt = tcp_session_app_rx_evt,
1351   .format_connection = format_tcp_session,
1352   .format_listener = format_tcp_listener_session,
1353   .format_half_open = format_tcp_half_open_session,
1354   .transport_options = {
1355     .name = "tcp",
1356     .short_name = "T",
1357     .tx_type = TRANSPORT_TX_PEEK,
1358     .service_type = TRANSPORT_SERVICE_VC,
1359   },
1360 };
1361 /* *INDENT-ON* */
1362
1363 void
1364 tcp_connection_tx_pacer_update (tcp_connection_t * tc)
1365 {
1366   if (!transport_connection_is_tx_paced (&tc->connection))
1367     return;
1368
1369   f64 srtt = clib_min ((f64) tc->srtt * TCP_TICK, tc->mrtt_us);
1370
1371   transport_connection_tx_pacer_update (&tc->connection,
1372                                         tcp_cc_get_pacing_rate (tc),
1373                                         srtt * CLIB_US_TIME_FREQ);
1374 }
1375
1376 void
1377 tcp_connection_tx_pacer_reset (tcp_connection_t * tc, u32 window,
1378                                u32 start_bucket)
1379 {
1380   f64 srtt = clib_min ((f64) tc->srtt * TCP_TICK, tc->mrtt_us);
1381   transport_connection_tx_pacer_reset (&tc->connection,
1382                                        tcp_cc_get_pacing_rate (tc),
1383                                        start_bucket,
1384                                        srtt * CLIB_US_TIME_FREQ);
1385 }
1386
1387 void
1388 tcp_reschedule (tcp_connection_t * tc)
1389 {
1390   if (tcp_in_cong_recovery (tc) || tcp_snd_space_inline (tc))
1391     transport_connection_reschedule (&tc->connection);
1392 }
1393
1394 static void
1395 tcp_expired_timers_dispatch (u32 * expired_timers)
1396 {
1397   u32 thread_index = vlib_get_thread_index (), n_left, max_per_loop;
1398   u32 connection_index, timer_id, n_expired, max_loops;
1399   tcp_worker_ctx_t *wrk;
1400   tcp_connection_t *tc;
1401   int i;
1402
1403   wrk = tcp_get_worker (thread_index);
1404   n_expired = vec_len (expired_timers);
1405   tcp_worker_stats_inc (wrk, timer_expirations, n_expired);
1406   n_left = clib_fifo_elts (wrk->pending_timers);
1407
1408   /*
1409    * Invalidate all timer handles before dispatching. This avoids dangling
1410    * index references to timer wheel pool entries that have been freed.
1411    */
1412   for (i = 0; i < n_expired; i++)
1413     {
1414       connection_index = expired_timers[i] & 0x0FFFFFFF;
1415       timer_id = expired_timers[i] >> 28;
1416
1417       if (timer_id != TCP_TIMER_RETRANSMIT_SYN)
1418         tc = tcp_connection_get (connection_index, thread_index);
1419       else
1420         tc = tcp_half_open_connection_get (connection_index);
1421
1422       TCP_EVT (TCP_EVT_TIMER_POP, connection_index, timer_id);
1423
1424       tc->timers[timer_id] = TCP_TIMER_HANDLE_INVALID;
1425       tc->pending_timers |= (1 << timer_id);
1426     }
1427
1428   clib_fifo_add (wrk->pending_timers, expired_timers, n_expired);
1429
1430   max_loops = clib_max (1, 0.5 * TCP_TIMER_TICK * wrk->vm->loops_per_second);
1431   max_per_loop = clib_max ((n_left + n_expired) / max_loops, 10);
1432   max_per_loop = clib_min (max_per_loop, VLIB_FRAME_SIZE);
1433   wrk->max_timers_per_loop = clib_max (n_left ? wrk->max_timers_per_loop : 0,
1434                                        max_per_loop);
1435
1436   if (thread_index == 0)
1437     session_queue_run_on_main_thread (wrk->vm);
1438 }
1439
1440 static void
1441 tcp_initialize_iss_seed (tcp_main_t * tm)
1442 {
1443   u32 default_seed = random_default_seed ();
1444   u64 time_now = clib_cpu_time_now ();
1445
1446   tm->iss_seed.first = (u64) random_u32 (&default_seed) << 32;
1447   tm->iss_seed.second = random_u64 (&time_now);
1448 }
1449
1450 static clib_error_t *
1451 tcp_main_enable (vlib_main_t * vm)
1452 {
1453   vlib_thread_main_t *vtm = vlib_get_thread_main ();
1454   u32 num_threads, n_workers, prealloc_conn_per_wrk;
1455   tcp_connection_t *tc __attribute__ ((unused));
1456   tcp_main_t *tm = vnet_get_tcp_main ();
1457   tcp_worker_ctx_t *wrk;
1458   clib_error_t *error = 0;
1459   int thread;
1460
1461   if ((error = vlib_call_init_function (vm, ip_main_init)))
1462     return error;
1463   if ((error = vlib_call_init_function (vm, ip4_lookup_init)))
1464     return error;
1465   if ((error = vlib_call_init_function (vm, ip6_lookup_init)))
1466     return error;
1467
1468   /*
1469    * Registrations
1470    */
1471
1472   ip4_register_protocol (IP_PROTOCOL_TCP, tcp4_input_node.index);
1473   ip6_register_protocol (IP_PROTOCOL_TCP, tcp6_input_node.index);
1474
1475   /*
1476    * Initialize data structures
1477    */
1478
1479   num_threads = 1 /* main thread */  + vtm->n_threads;
1480   vec_validate (tm->wrk_ctx, num_threads - 1);
1481   n_workers = num_threads == 1 ? 1 : vtm->n_threads;
1482   prealloc_conn_per_wrk = tcp_cfg.preallocated_connections / n_workers;
1483
1484   wrk = &tm->wrk_ctx[0];
1485   wrk->tco_next_node[0] = vlib_node_get_next (vm, session_queue_node.index,
1486                                               tcp4_output_node.index);
1487   wrk->tco_next_node[1] = vlib_node_get_next (vm, session_queue_node.index,
1488                                               tcp6_output_node.index);
1489
1490   for (thread = 0; thread < num_threads; thread++)
1491     {
1492       wrk = &tm->wrk_ctx[thread];
1493
1494       vec_validate (wrk->pending_deq_acked, 255);
1495       vec_validate (wrk->pending_disconnects, 255);
1496       vec_validate (wrk->pending_resets, 255);
1497       vec_reset_length (wrk->pending_deq_acked);
1498       vec_reset_length (wrk->pending_disconnects);
1499       vec_reset_length (wrk->pending_resets);
1500       wrk->vm = vlib_get_main_by_index (thread);
1501       wrk->max_timers_per_loop = 10;
1502
1503       if (thread > 0)
1504         {
1505           wrk->tco_next_node[0] = tm->wrk_ctx[0].tco_next_node[0];
1506           wrk->tco_next_node[1] = tm->wrk_ctx[0].tco_next_node[1];
1507         }
1508
1509       /*
1510        * Preallocate connections. Assume that thread 0 won't
1511        * use preallocated threads when running multi-core
1512        */
1513       if ((thread > 0 || num_threads == 1) && prealloc_conn_per_wrk)
1514         pool_init_fixed (wrk->connections, prealloc_conn_per_wrk);
1515
1516       tcp_timer_initialize_wheel (&wrk->timer_wheel,
1517                                   tcp_expired_timers_dispatch,
1518                                   vlib_time_now (vm));
1519     }
1520
1521   tcp_initialize_iss_seed (tm);
1522
1523   tm->bytes_per_buffer = vlib_buffer_get_default_data_size (vm);
1524   tm->cc_last_type = TCP_CC_LAST;
1525
1526   tm->ipl_next_node[0] = vlib_node_get_next (vm, session_queue_node.index,
1527                                              ip4_lookup_node.index);
1528   tm->ipl_next_node[1] = vlib_node_get_next (vm, session_queue_node.index,
1529                                              ip6_lookup_node.index);
1530   return error;
1531 }
1532
1533 clib_error_t *
1534 vnet_tcp_enable_disable (vlib_main_t * vm, u8 is_en)
1535 {
1536   if (is_en)
1537     {
1538       if (tcp_main.is_enabled)
1539         return 0;
1540
1541       return tcp_main_enable (vm);
1542     }
1543   else
1544     {
1545       tcp_main.is_enabled = 0;
1546     }
1547
1548   return 0;
1549 }
1550
1551 void
1552 tcp_punt_unknown (vlib_main_t * vm, u8 is_ip4, u8 is_add)
1553 {
1554   tcp_main_t *tm = &tcp_main;
1555   if (is_ip4)
1556     tm->punt_unknown4 = is_add;
1557   else
1558     tm->punt_unknown6 = is_add;
1559 }
1560
1561 /**
1562  * Initialize default values for tcp parameters
1563  */
1564 static void
1565 tcp_configuration_init (void)
1566 {
1567   /* Initial wnd for SYN. Fifos are not allocated at that point so use some
1568    * predefined value. For SYN-ACK we still want the scale to be computed in
1569    * the same way */
1570   tcp_cfg.max_rx_fifo = 32 << 20;
1571   tcp_cfg.min_rx_fifo = 4 << 10;
1572
1573   tcp_cfg.default_mtu = 1500;
1574   tcp_cfg.initial_cwnd_multiplier = 0;
1575   tcp_cfg.enable_tx_pacing = 1;
1576   tcp_cfg.allow_tso = 0;
1577   tcp_cfg.csum_offload = 1;
1578   tcp_cfg.cc_algo = TCP_CC_CUBIC;
1579   tcp_cfg.rwnd_min_update_ack = 1;
1580   tcp_cfg.max_gso_size = TCP_MAX_GSO_SZ;
1581
1582   /* Time constants defined as timer tick (100us) multiples */
1583   tcp_cfg.closewait_time = 20000;       /* 2s */
1584   tcp_cfg.timewait_time = 100000;       /* 10s */
1585   tcp_cfg.finwait1_time = 600000;       /* 60s */
1586   tcp_cfg.lastack_time = 300000;        /* 30s */
1587   tcp_cfg.finwait2_time = 300000;       /* 30s */
1588   tcp_cfg.closing_time = 300000;        /* 30s */
1589   tcp_cfg.alloc_err_timeout = 1000;     /* 100ms */
1590
1591   /* This value is seconds */
1592   tcp_cfg.cleanup_time = 0.1;   /* 100ms */
1593 }
1594
1595 static clib_error_t *
1596 tcp_init (vlib_main_t * vm)
1597 {
1598   tcp_main_t *tm = vnet_get_tcp_main ();
1599   ip_main_t *im = &ip_main;
1600   ip_protocol_info_t *pi;
1601
1602   /* Session layer, and by implication tcp, are disabled by default */
1603   tm->is_enabled = 0;
1604
1605   /* Register with IP for header parsing */
1606   pi = ip_get_protocol_info (im, IP_PROTOCOL_TCP);
1607   if (pi == 0)
1608     return clib_error_return (0, "TCP protocol info AWOL");
1609   pi->format_header = format_tcp_header;
1610   pi->unformat_pg_edit = unformat_pg_tcp_header;
1611
1612   /* Register as transport with session layer */
1613   transport_register_protocol (TRANSPORT_PROTO_TCP, &tcp_proto,
1614                                FIB_PROTOCOL_IP4, tcp4_output_node.index);
1615   transport_register_protocol (TRANSPORT_PROTO_TCP, &tcp_proto,
1616                                FIB_PROTOCOL_IP6, tcp6_output_node.index);
1617
1618   tcp_configuration_init ();
1619
1620   tm->cc_algo_by_name = hash_create_string (0, sizeof (uword));
1621
1622   return 0;
1623 }
1624
1625 VLIB_INIT_FUNCTION (tcp_init);
1626
1627 /*
1628  * fd.io coding-style-patch-verification: ON
1629  *
1630  * Local Variables:
1631  * eval: (c-set-style "gnu")
1632  * End:
1633  */