session: extend connect api for internal apps
[vpp.git] / src / vnet / session / transport.c
1 /*
2  * Copyright (c) 2017 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <vnet/session/transport_interface.h>
17 #include <vnet/session/session.h>
18 #include <vnet/fib/fib.h>
19
20 /**
21  * Per-type vector of transport protocol virtual function tables
22  */
23 transport_proto_vft_t *tp_vfts;
24
25 /*
26  * Port allocator seed
27  */
28 static u32 port_allocator_seed;
29
30 /*
31  * Local endpoints table
32  */
33 static transport_endpoint_table_t local_endpoints_table;
34
35 /*
36  * Pool of local endpoints
37  */
38 static transport_endpoint_t *local_endpoints;
39
40 /*
41  * Local endpoints pool lock
42  */
43 static clib_spinlock_t local_endpoints_lock;
44
45 /*
46  * Period used by transport pacers. Initialized by session layer
47  */
48 static double transport_pacer_period;
49
50 #define TRANSPORT_PACER_MIN_MSS 1460
51
52 u8 *
53 format_transport_proto (u8 * s, va_list * args)
54 {
55   u32 transport_proto = va_arg (*args, u32);
56   switch (transport_proto)
57     {
58     case TRANSPORT_PROTO_TCP:
59       s = format (s, "TCP");
60       break;
61     case TRANSPORT_PROTO_UDP:
62       s = format (s, "UDP");
63       break;
64     case TRANSPORT_PROTO_SCTP:
65       s = format (s, "SCTP");
66       break;
67     case TRANSPORT_PROTO_UDPC:
68       s = format (s, "UDPC");
69       break;
70     }
71   return s;
72 }
73
74 u8 *
75 format_transport_proto_short (u8 * s, va_list * args)
76 {
77   u32 transport_proto = va_arg (*args, u32);
78   switch (transport_proto)
79     {
80     case TRANSPORT_PROTO_TCP:
81       s = format (s, "T");
82       break;
83     case TRANSPORT_PROTO_UDP:
84       s = format (s, "U");
85       break;
86     case TRANSPORT_PROTO_SCTP:
87       s = format (s, "S");
88       break;
89     case TRANSPORT_PROTO_UDPC:
90       s = format (s, "U");
91       break;
92     }
93   return s;
94 }
95
96 u8 *
97 format_transport_connection (u8 * s, va_list * args)
98 {
99   u32 transport_proto = va_arg (*args, u32);
100   u32 conn_index = va_arg (*args, u32);
101   u32 thread_index = va_arg (*args, u32);
102   u32 verbose = va_arg (*args, u32);
103   transport_proto_vft_t *tp_vft;
104   transport_connection_t *tc;
105   u32 indent;
106
107   tp_vft = transport_protocol_get_vft (transport_proto);
108   if (!tp_vft)
109     return s;
110
111   s = format (s, "%U", tp_vft->format_connection, conn_index, thread_index,
112               verbose);
113   tc = tp_vft->get_connection (conn_index, thread_index);
114   if (tc && transport_connection_is_tx_paced (tc) && verbose > 1)
115     {
116       indent = format_get_indent (s) + 1;
117       s = format (s, "%Upacer: %U\n", format_white_space, indent,
118                   format_transport_pacer, &tc->pacer);
119     }
120   return s;
121 }
122
123 u8 *
124 format_transport_listen_connection (u8 * s, va_list * args)
125 {
126   u32 transport_proto = va_arg (*args, u32);
127   u32 listen_index = va_arg (*args, u32);
128   transport_proto_vft_t *tp_vft;
129
130   tp_vft = transport_protocol_get_vft (transport_proto);
131   if (!tp_vft)
132     return s;
133
134   s = format (s, "%U", tp_vft->format_listener, listen_index);
135   return s;
136 }
137
138 u8 *
139 format_transport_half_open_connection (u8 * s, va_list * args)
140 {
141   u32 transport_proto = va_arg (*args, u32);
142   u32 listen_index = va_arg (*args, u32);
143   transport_proto_vft_t *tp_vft;
144
145   tp_vft = transport_protocol_get_vft (transport_proto);
146   if (!tp_vft)
147     return s;
148
149   s = format (s, "%U", tp_vft->format_half_open, listen_index);
150   return s;
151 }
152
153 uword
154 unformat_transport_proto (unformat_input_t * input, va_list * args)
155 {
156   u32 *proto = va_arg (*args, u32 *);
157   if (unformat (input, "tcp"))
158     *proto = TRANSPORT_PROTO_TCP;
159   else if (unformat (input, "TCP"))
160     *proto = TRANSPORT_PROTO_TCP;
161   else if (unformat (input, "udp"))
162     *proto = TRANSPORT_PROTO_UDP;
163   else if (unformat (input, "UDP"))
164     *proto = TRANSPORT_PROTO_UDP;
165   else if (unformat (input, "sctp"))
166     *proto = TRANSPORT_PROTO_SCTP;
167   else if (unformat (input, "SCTP"))
168     *proto = TRANSPORT_PROTO_SCTP;
169   else if (unformat (input, "tls"))
170     *proto = TRANSPORT_PROTO_TLS;
171   else if (unformat (input, "TLS"))
172     *proto = TRANSPORT_PROTO_TLS;
173   else if (unformat (input, "udpc"))
174     *proto = TRANSPORT_PROTO_UDPC;
175   else if (unformat (input, "UDPC"))
176     *proto = TRANSPORT_PROTO_UDPC;
177   else
178     return 0;
179   return 1;
180 }
181
182 u32
183 transport_endpoint_lookup (transport_endpoint_table_t * ht, u8 proto,
184                            ip46_address_t * ip, u16 port)
185 {
186   clib_bihash_kv_24_8_t kv;
187   int rv;
188
189   kv.key[0] = ip->as_u64[0];
190   kv.key[1] = ip->as_u64[1];
191   kv.key[2] = (u64) port << 8 | (u64) proto;
192
193   rv = clib_bihash_search_inline_24_8 (ht, &kv);
194   if (rv == 0)
195     return kv.value;
196
197   return ENDPOINT_INVALID_INDEX;
198 }
199
200 void
201 transport_endpoint_table_add (transport_endpoint_table_t * ht, u8 proto,
202                               transport_endpoint_t * te, u32 value)
203 {
204   clib_bihash_kv_24_8_t kv;
205
206   kv.key[0] = te->ip.as_u64[0];
207   kv.key[1] = te->ip.as_u64[1];
208   kv.key[2] = (u64) te->port << 8 | (u64) proto;
209   kv.value = value;
210
211   clib_bihash_add_del_24_8 (ht, &kv, 1);
212 }
213
214 void
215 transport_endpoint_table_del (transport_endpoint_table_t * ht, u8 proto,
216                               transport_endpoint_t * te)
217 {
218   clib_bihash_kv_24_8_t kv;
219
220   kv.key[0] = te->ip.as_u64[0];
221   kv.key[1] = te->ip.as_u64[1];
222   kv.key[2] = (u64) te->port << 8 | (u64) proto;
223
224   clib_bihash_add_del_24_8 (ht, &kv, 0);
225 }
226
227 /**
228  * Register transport virtual function table.
229  *
230  * @param transport_proto - transport protocol type (i.e., TCP, UDP ..)
231  * @param vft - virtual function table for transport proto
232  * @param fib_proto - network layer protocol
233  * @param output_node - output node index that session layer will hand off
234  *                      buffers to, for requested fib proto
235  */
236 void
237 transport_register_protocol (transport_proto_t transport_proto,
238                              const transport_proto_vft_t * vft,
239                              fib_protocol_t fib_proto, u32 output_node)
240 {
241   u8 is_ip4 = fib_proto == FIB_PROTOCOL_IP4;
242
243   vec_validate (tp_vfts, transport_proto);
244   tp_vfts[transport_proto] = *vft;
245
246   session_register_transport (transport_proto, vft, is_ip4, output_node);
247 }
248
249 /**
250  * Get transport virtual function table
251  *
252  * @param type - session type (not protocol type)
253  */
254 transport_proto_vft_t *
255 transport_protocol_get_vft (transport_proto_t transport_proto)
256 {
257   if (transport_proto >= vec_len (tp_vfts))
258     return 0;
259   return &tp_vfts[transport_proto];
260 }
261
262 transport_service_type_t
263 transport_protocol_service_type (transport_proto_t tp)
264 {
265   return tp_vfts[tp].service_type;
266 }
267
268 transport_tx_fn_type_t
269 transport_protocol_tx_fn_type (transport_proto_t tp)
270 {
271   return tp_vfts[tp].tx_type;
272 }
273
274 u8
275 transport_protocol_is_cl (transport_proto_t tp)
276 {
277   return (tp_vfts[tp].service_type == TRANSPORT_SERVICE_CL);
278 }
279
280 #define PORT_MASK ((1 << 16)- 1)
281
282 void
283 transport_endpoint_del (u32 tepi)
284 {
285   clib_spinlock_lock_if_init (&local_endpoints_lock);
286   pool_put_index (local_endpoints, tepi);
287   clib_spinlock_unlock_if_init (&local_endpoints_lock);
288 }
289
290 always_inline transport_endpoint_t *
291 transport_endpoint_new (void)
292 {
293   transport_endpoint_t *tep;
294   pool_get_zero (local_endpoints, tep);
295   return tep;
296 }
297
298 void
299 transport_endpoint_cleanup (u8 proto, ip46_address_t * lcl_ip, u16 port)
300 {
301   u32 tepi;
302   transport_endpoint_t *tep;
303
304   /* Cleanup local endpoint if this was an active connect */
305   tepi = transport_endpoint_lookup (&local_endpoints_table, proto, lcl_ip,
306                                     clib_net_to_host_u16 (port));
307   if (tepi != ENDPOINT_INVALID_INDEX)
308     {
309       tep = pool_elt_at_index (local_endpoints, tepi);
310       transport_endpoint_table_del (&local_endpoints_table, proto, tep);
311       transport_endpoint_del (tepi);
312     }
313 }
314
315 static void
316 transport_endpoint_mark_used (u8 proto, ip46_address_t * ip, u16 port)
317 {
318   transport_endpoint_t *tep;
319   clib_spinlock_lock_if_init (&local_endpoints_lock);
320   tep = transport_endpoint_new ();
321   clib_memcpy (&tep->ip, ip, sizeof (*ip));
322   tep->port = port;
323   transport_endpoint_table_add (&local_endpoints_table, proto, tep,
324                                 tep - local_endpoints);
325   clib_spinlock_unlock_if_init (&local_endpoints_lock);
326 }
327
328 /**
329  * Allocate local port and add if successful add entry to local endpoint
330  * table to mark the pair as used.
331  */
332 int
333 transport_alloc_local_port (u8 proto, ip46_address_t * ip)
334 {
335   u16 min = 1024, max = 65535;  /* XXX configurable ? */
336   int tries, limit;
337   u32 tei;
338
339   limit = max - min;
340
341   /* Only support active opens from thread 0 */
342   ASSERT (vlib_get_thread_index () == 0);
343
344   /* Search for first free slot */
345   for (tries = 0; tries < limit; tries++)
346     {
347       u16 port = 0;
348
349       /* Find a port in the specified range */
350       while (1)
351         {
352           port = random_u32 (&port_allocator_seed) & PORT_MASK;
353           if (PREDICT_TRUE (port >= min && port < max))
354             break;
355         }
356
357       /* Look it up. If not found, we're done */
358       tei = transport_endpoint_lookup (&local_endpoints_table, proto, ip,
359                                        port);
360       if (tei == ENDPOINT_INVALID_INDEX)
361         {
362           transport_endpoint_mark_used (proto, ip, port);
363           return port;
364         }
365     }
366   return -1;
367 }
368
369 static clib_error_t *
370 transport_get_interface_ip (u32 sw_if_index, u8 is_ip4, ip46_address_t * addr)
371 {
372   if (is_ip4)
373     {
374       ip4_address_t *ip4;
375       ip4 = ip_interface_get_first_ip (sw_if_index, 1);
376       if (!ip4)
377         return clib_error_return (0, "no routable ip4 address on %U",
378                                   format_vnet_sw_if_index_name,
379                                   vnet_get_main (), sw_if_index);
380       addr->ip4.as_u32 = ip4->as_u32;
381     }
382   else
383     {
384       ip6_address_t *ip6;
385       ip6 = ip_interface_get_first_ip (sw_if_index, 0);
386       if (ip6 == 0)
387         return clib_error_return (0, "no routable ip6 addresses on %U",
388                                   format_vnet_sw_if_index_name,
389                                   vnet_get_main (), sw_if_index);
390       clib_memcpy (&addr->ip6, ip6, sizeof (*ip6));
391     }
392   return 0;
393 }
394
395 static clib_error_t *
396 transport_find_local_ip_for_remote (u32 sw_if_index,
397                                     transport_endpoint_t * rmt,
398                                     ip46_address_t * lcl_addr)
399 {
400   fib_node_index_t fei;
401   fib_prefix_t prefix;
402
403   if (sw_if_index == ENDPOINT_INVALID_INDEX)
404     {
405       /* Find a FIB path to the destination */
406       clib_memcpy (&prefix.fp_addr, &rmt->ip, sizeof (rmt->ip));
407       prefix.fp_proto = rmt->is_ip4 ? FIB_PROTOCOL_IP4 : FIB_PROTOCOL_IP6;
408       prefix.fp_len = rmt->is_ip4 ? 32 : 128;
409
410       ASSERT (rmt->fib_index != ENDPOINT_INVALID_INDEX);
411       fei = fib_table_lookup (rmt->fib_index, &prefix);
412
413       /* Couldn't find route to destination. Bail out. */
414       if (fei == FIB_NODE_INDEX_INVALID)
415         return clib_error_return (0, "no route to %U", format_ip46_address,
416                                   &rmt->ip, (rmt->is_ip4 == 0) + 1);
417
418       sw_if_index = fib_entry_get_resolving_interface (fei);
419       if (sw_if_index == ENDPOINT_INVALID_INDEX)
420         return clib_error_return (0, "no resolving interface for %U",
421                                   format_ip46_address, &rmt->ip,
422                                   (rmt->is_ip4 == 0) + 1);
423     }
424
425   clib_memset (lcl_addr, 0, sizeof (*lcl_addr));
426   return transport_get_interface_ip (sw_if_index, rmt->is_ip4, lcl_addr);
427 }
428
429 int
430 transport_alloc_local_endpoint (u8 proto, transport_endpoint_cfg_t * rmt_cfg,
431                                 ip46_address_t * lcl_addr, u16 * lcl_port)
432 {
433   transport_endpoint_t *rmt = (transport_endpoint_t *) rmt_cfg;
434   clib_error_t *error;
435   int port;
436   u32 tei;
437
438   /*
439    * Find the local address
440    */
441   if (ip_is_zero (&rmt_cfg->peer.ip, rmt_cfg->peer.is_ip4))
442     {
443       error = transport_find_local_ip_for_remote (rmt_cfg->peer.sw_if_index,
444                                                   rmt, lcl_addr);
445       if (error)
446         return -1;
447     }
448   else
449     {
450       /* Assume session layer vetted this address */
451       clib_memcpy (lcl_addr, &rmt_cfg->peer.ip, sizeof (rmt_cfg->peer.ip));
452     }
453
454   /*
455    * Allocate source port
456    */
457   if (rmt_cfg->peer.port == 0)
458     {
459       port = transport_alloc_local_port (proto, lcl_addr);
460       if (port < 1)
461         {
462           clib_warning ("Failed to allocate src port");
463           return -1;
464         }
465       *lcl_port = port;
466     }
467   else
468     {
469       port = clib_net_to_host_u16 (rmt_cfg->peer.port);
470       tei = transport_endpoint_lookup (&local_endpoints_table, proto,
471                                        lcl_addr, port);
472       if (tei != ENDPOINT_INVALID_INDEX)
473         return -1;
474
475       transport_endpoint_mark_used (proto, lcl_addr, port);
476       *lcl_port = port;
477     }
478
479   return 0;
480 }
481
482 #define SPACER_CPU_TICKS_PER_PERIOD_SHIFT 10
483 #define SPACER_CPU_TICKS_PER_PERIOD (1 << SPACER_CPU_TICKS_PER_PERIOD_SHIFT)
484
485 u8 *
486 format_transport_pacer (u8 * s, va_list * args)
487 {
488   spacer_t *pacer = va_arg (*args, spacer_t *);
489
490   s = format (s, "bucket %u max_burst %u tokens/period %.3f last_update %x",
491               pacer->bucket, pacer->max_burst_size, pacer->tokens_per_period,
492               pacer->last_update);
493   return s;
494 }
495
496 static inline u32
497 spacer_max_burst (spacer_t * pacer, u64 norm_time_now)
498 {
499   u64 n_periods = norm_time_now - pacer->last_update;
500
501   pacer->last_update = norm_time_now;
502   pacer->bucket += n_periods * pacer->tokens_per_period;
503   return clib_min (pacer->bucket, pacer->max_burst_size);
504 }
505
506 static inline void
507 spacer_update_bucket (spacer_t * pacer, u32 bytes)
508 {
509   ASSERT (pacer->bucket >= bytes);
510   pacer->bucket -= bytes;
511 }
512
513 static inline void
514 spacer_update_max_burst_size (spacer_t * pacer, u32 max_burst_bytes)
515 {
516   pacer->max_burst_size = clib_max (max_burst_bytes, TRANSPORT_PACER_MIN_MSS);
517 }
518
519 static inline void
520 spacer_set_pace_rate (spacer_t * pacer, u64 rate_bytes_per_sec)
521 {
522   ASSERT (rate_bytes_per_sec != 0);
523   pacer->tokens_per_period = rate_bytes_per_sec / transport_pacer_period;
524 }
525
526 void
527 transport_connection_tx_pacer_init (transport_connection_t * tc,
528                                     u32 rate_bytes_per_sec, u32 burst_bytes)
529 {
530   vlib_main_t *vm = vlib_get_main ();
531   u64 time_now = vm->clib_time.last_cpu_time;
532   spacer_t *pacer = &tc->pacer;
533
534   tc->flags |= TRANSPORT_CONNECTION_F_IS_TX_PACED;
535   spacer_update_max_burst_size (&tc->pacer, burst_bytes);
536   spacer_set_pace_rate (&tc->pacer, rate_bytes_per_sec);
537   pacer->last_update = time_now >> SPACER_CPU_TICKS_PER_PERIOD_SHIFT;
538   pacer->bucket = burst_bytes;
539 }
540
541 void
542 transport_connection_tx_pacer_update (transport_connection_t * tc,
543                                       u64 bytes_per_sec)
544 {
545   u32 burst_size;
546
547   burst_size = bytes_per_sec * transport_dispatch_period (tc->thread_index);
548   spacer_set_pace_rate (&tc->pacer, bytes_per_sec);
549   spacer_update_max_burst_size (&tc->pacer, burst_size);
550 }
551
552 u32
553 transport_connection_max_tx_burst (transport_connection_t * tc, u64 time_now)
554 {
555   u32 snd_space, max_paced_burst;
556   u32 mss;
557
558   snd_space = tp_vfts[tc->proto].send_space (tc);
559   if (transport_connection_is_tx_paced (tc))
560     {
561       time_now >>= SPACER_CPU_TICKS_PER_PERIOD_SHIFT;
562       max_paced_burst = spacer_max_burst (&tc->pacer, time_now);
563       mss = tp_vfts[tc->proto].send_mss (tc);
564       max_paced_burst = (max_paced_burst < mss) ? 0 : max_paced_burst;
565       snd_space = clib_min (snd_space, max_paced_burst);
566       snd_space = snd_space - snd_space % mss;
567     }
568   return snd_space;
569 }
570
571 void
572 transport_connection_update_tx_stats (transport_connection_t * tc, u32 bytes)
573 {
574   tc->stats.tx_bytes += bytes;
575   if (transport_connection_is_tx_paced (tc))
576     spacer_update_bucket (&tc->pacer, bytes);
577 }
578
579 void
580 transport_init_tx_pacers_period (void)
581 {
582   f64 cpu_freq = os_cpu_clock_frequency ();
583   transport_pacer_period = cpu_freq / SPACER_CPU_TICKS_PER_PERIOD;
584 }
585
586 void
587 transport_update_time (f64 time_now, u8 thread_index)
588 {
589   transport_proto_vft_t *vft;
590   vec_foreach (vft, tp_vfts)
591   {
592     if (vft->update_time)
593       (vft->update_time) (time_now, thread_index);
594   }
595 }
596
597 void
598 transport_enable_disable (vlib_main_t * vm, u8 is_en)
599 {
600   transport_proto_vft_t *vft;
601   vec_foreach (vft, tp_vfts)
602   {
603     if (vft->enable)
604       (vft->enable) (vm, is_en);
605   }
606 }
607
608 void
609 transport_init (void)
610 {
611   vlib_thread_main_t *vtm = vlib_get_thread_main ();
612   session_manager_main_t *smm = vnet_get_session_manager_main ();
613   u32 num_threads;
614
615   if (smm->local_endpoints_table_buckets == 0)
616     smm->local_endpoints_table_buckets = 250000;
617   if (smm->local_endpoints_table_memory == 0)
618     smm->local_endpoints_table_memory = 512 << 20;
619
620   /* Initialize [port-allocator] random number seed */
621   port_allocator_seed = (u32) clib_cpu_time_now ();
622
623   clib_bihash_init_24_8 (&local_endpoints_table, "local endpoints table",
624                          smm->local_endpoints_table_buckets,
625                          smm->local_endpoints_table_memory);
626   num_threads = 1 /* main thread */  + vtm->n_threads;
627   if (num_threads > 1)
628     clib_spinlock_init (&local_endpoints_lock);
629 }
630
631 /*
632  * fd.io coding-style-patch-verification: ON
633  *
634  * Local Variables:
635  * eval: (c-set-style "gnu")
636  * End:
637  */