8cbad0d397fa4cf03e0561a1a6aa5205fecf2b40
[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 (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 /**
316  * Allocate local port and add if successful add entry to local endpoint
317  * table to mark the pair as used.
318  */
319 int
320 transport_alloc_local_port (u8 proto, ip46_address_t * ip)
321 {
322   transport_endpoint_t *tep;
323   u32 tei;
324   u16 min = 1024, max = 65535;  /* XXX configurable ? */
325   int tries, limit;
326
327   limit = max - min;
328
329   /* Only support active opens from thread 0 */
330   ASSERT (vlib_get_thread_index () == 0);
331
332   /* Search for first free slot */
333   for (tries = 0; tries < limit; tries++)
334     {
335       u16 port = 0;
336
337       /* Find a port in the specified range */
338       while (1)
339         {
340           port = random_u32 (&port_allocator_seed) & PORT_MASK;
341           if (PREDICT_TRUE (port >= min && port < max))
342             break;
343         }
344
345       /* Look it up. If not found, we're done */
346       tei = transport_endpoint_lookup (&local_endpoints_table, proto, ip,
347                                        port);
348       if (tei == ENDPOINT_INVALID_INDEX)
349         {
350           clib_spinlock_lock_if_init (&local_endpoints_lock);
351           tep = transport_endpoint_new ();
352           clib_memcpy (&tep->ip, ip, sizeof (*ip));
353           tep->port = port;
354           transport_endpoint_table_add (&local_endpoints_table, proto, tep,
355                                         tep - local_endpoints);
356           clib_spinlock_unlock_if_init (&local_endpoints_lock);
357
358           return tep->port;
359         }
360     }
361   return -1;
362 }
363
364 int
365 transport_alloc_local_endpoint (u8 proto, transport_endpoint_t * rmt,
366                                 ip46_address_t * lcl_addr, u16 * lcl_port)
367 {
368   fib_prefix_t prefix;
369   fib_node_index_t fei;
370   u32 sw_if_index;
371   int port;
372
373   /*
374    * Find the local address and allocate port
375    */
376
377   /* Find a FIB path to the destination */
378   clib_memcpy (&prefix.fp_addr, &rmt->ip, sizeof (rmt->ip));
379   prefix.fp_proto = rmt->is_ip4 ? FIB_PROTOCOL_IP4 : FIB_PROTOCOL_IP6;
380   prefix.fp_len = rmt->is_ip4 ? 32 : 128;
381
382   ASSERT (rmt->fib_index != ENDPOINT_INVALID_INDEX);
383   fei = fib_table_lookup (rmt->fib_index, &prefix);
384
385   /* Couldn't find route to destination. Bail out. */
386   if (fei == FIB_NODE_INDEX_INVALID)
387     {
388       clib_warning ("no route to destination");
389       return -1;
390     }
391
392   sw_if_index = rmt->sw_if_index;
393   if (sw_if_index == ENDPOINT_INVALID_INDEX)
394     sw_if_index = fib_entry_get_resolving_interface (fei);
395
396   if (sw_if_index == ENDPOINT_INVALID_INDEX)
397     {
398       clib_warning ("no resolving interface for %U", format_ip46_address,
399                     &rmt->ip, (rmt->is_ip4 == 0) + 1);
400       return -1;
401     }
402
403   clib_memset (lcl_addr, 0, sizeof (*lcl_addr));
404
405   if (rmt->is_ip4)
406     {
407       ip4_address_t *ip4;
408       ip4 = ip_interface_get_first_ip (sw_if_index, 1);
409       if (!ip4)
410         {
411           clib_warning ("no routable ip4 address on %U",
412                         format_vnet_sw_if_index_name, vnet_get_main (),
413                         sw_if_index);
414           return -1;
415         }
416       lcl_addr->ip4.as_u32 = ip4->as_u32;
417     }
418   else
419     {
420       ip6_address_t *ip6;
421       ip6 = ip_interface_get_first_ip (sw_if_index, 0);
422       if (ip6 == 0)
423         {
424           clib_warning ("no routable ip6 addresses on %U",
425                         format_vnet_sw_if_index_name, vnet_get_main (),
426                         sw_if_index);
427           return -1;
428         }
429       clib_memcpy (&lcl_addr->ip6, ip6, sizeof (*ip6));
430     }
431
432   /* Allocate source port */
433   port = transport_alloc_local_port (proto, lcl_addr);
434   if (port < 1)
435     {
436       clib_warning ("Failed to allocate src port");
437       return -1;
438     }
439   *lcl_port = port;
440   return 0;
441 }
442
443 #define SPACER_CPU_TICKS_PER_PERIOD_SHIFT 10
444 #define SPACER_CPU_TICKS_PER_PERIOD (1 << SPACER_CPU_TICKS_PER_PERIOD_SHIFT)
445
446 u8 *
447 format_transport_pacer (u8 * s, va_list * args)
448 {
449   spacer_t *pacer = va_arg (*args, spacer_t *);
450
451   s = format (s, "bucket %u max_burst %u tokens/period %.3f last_update %x",
452               pacer->bucket, pacer->max_burst_size, pacer->tokens_per_period,
453               pacer->last_update);
454   return s;
455 }
456
457 static inline u32
458 spacer_max_burst (spacer_t * pacer, u64 norm_time_now)
459 {
460   u64 n_periods = norm_time_now - pacer->last_update;
461
462   pacer->last_update = norm_time_now;
463   pacer->bucket += n_periods * pacer->tokens_per_period;
464   return clib_min (pacer->bucket, pacer->max_burst_size);
465 }
466
467 static inline void
468 spacer_update_bucket (spacer_t * pacer, u32 bytes)
469 {
470   ASSERT (pacer->bucket >= bytes);
471   pacer->bucket -= bytes;
472 }
473
474 static inline void
475 spacer_update_max_burst_size (spacer_t * pacer, u32 max_burst_bytes)
476 {
477   pacer->max_burst_size = clib_max (max_burst_bytes, TRANSPORT_PACER_MIN_MSS);
478 }
479
480 static inline void
481 spacer_set_pace_rate (spacer_t * pacer, u64 rate_bytes_per_sec)
482 {
483   ASSERT (rate_bytes_per_sec != 0);
484   pacer->tokens_per_period = rate_bytes_per_sec / transport_pacer_period;
485 }
486
487 void
488 transport_connection_tx_pacer_init (transport_connection_t * tc,
489                                     u32 rate_bytes_per_sec, u32 burst_bytes)
490 {
491   vlib_main_t *vm = vlib_get_main ();
492   u64 time_now = vm->clib_time.last_cpu_time;
493   spacer_t *pacer = &tc->pacer;
494
495   tc->flags |= TRANSPORT_CONNECTION_F_IS_TX_PACED;
496   spacer_update_max_burst_size (&tc->pacer, burst_bytes);
497   spacer_set_pace_rate (&tc->pacer, rate_bytes_per_sec);
498   pacer->last_update = time_now >> SPACER_CPU_TICKS_PER_PERIOD_SHIFT;
499   pacer->bucket = burst_bytes;
500 }
501
502 void
503 transport_connection_tx_pacer_update (transport_connection_t * tc,
504                                       u64 bytes_per_sec)
505 {
506   u32 burst_size;
507
508   burst_size = bytes_per_sec * transport_dispatch_period (tc->thread_index);
509   spacer_set_pace_rate (&tc->pacer, bytes_per_sec);
510   spacer_update_max_burst_size (&tc->pacer, burst_size);
511 }
512
513 u32
514 transport_connection_max_tx_burst (transport_connection_t * tc, u64 time_now)
515 {
516   u32 snd_space, max_paced_burst;
517   u32 mss;
518
519   snd_space = tp_vfts[tc->proto].send_space (tc);
520   if (transport_connection_is_tx_paced (tc))
521     {
522       time_now >>= SPACER_CPU_TICKS_PER_PERIOD_SHIFT;
523       max_paced_burst = spacer_max_burst (&tc->pacer, time_now);
524       mss = tp_vfts[tc->proto].send_mss (tc);
525       max_paced_burst = (max_paced_burst < mss) ? 0 : max_paced_burst;
526       snd_space = clib_min (snd_space, max_paced_burst);
527       snd_space = snd_space - snd_space % mss;
528     }
529   return snd_space;
530 }
531
532 void
533 transport_connection_update_tx_stats (transport_connection_t * tc, u32 bytes)
534 {
535   tc->stats.tx_bytes += bytes;
536   if (transport_connection_is_tx_paced (tc))
537     spacer_update_bucket (&tc->pacer, bytes);
538 }
539
540 void
541 transport_init_tx_pacers_period (void)
542 {
543   f64 cpu_freq = os_cpu_clock_frequency ();
544   transport_pacer_period = cpu_freq / SPACER_CPU_TICKS_PER_PERIOD;
545 }
546
547 void
548 transport_update_time (f64 time_now, u8 thread_index)
549 {
550   transport_proto_vft_t *vft;
551   vec_foreach (vft, tp_vfts)
552   {
553     if (vft->update_time)
554       (vft->update_time) (time_now, thread_index);
555   }
556 }
557
558 void
559 transport_enable_disable (vlib_main_t * vm, u8 is_en)
560 {
561   transport_proto_vft_t *vft;
562   vec_foreach (vft, tp_vfts)
563   {
564     if (vft->enable)
565       (vft->enable) (vm, is_en);
566   }
567 }
568
569 void
570 transport_init (void)
571 {
572   vlib_thread_main_t *vtm = vlib_get_thread_main ();
573   session_manager_main_t *smm = vnet_get_session_manager_main ();
574   u32 num_threads;
575
576   if (smm->local_endpoints_table_buckets == 0)
577     smm->local_endpoints_table_buckets = 250000;
578   if (smm->local_endpoints_table_memory == 0)
579     smm->local_endpoints_table_memory = 512 << 20;
580
581   /* Initialize [port-allocator] random number seed */
582   port_allocator_seed = (u32) clib_cpu_time_now ();
583
584   clib_bihash_init_24_8 (&local_endpoints_table, "local endpoints table",
585                          smm->local_endpoints_table_buckets,
586                          smm->local_endpoints_table_memory);
587   num_threads = 1 /* main thread */  + vtm->n_threads;
588   if (num_threads > 1)
589     clib_spinlock_init (&local_endpoints_lock);
590 }
591
592 /*
593  * fd.io coding-style-patch-verification: ON
594  *
595  * Local Variables:
596  * eval: (c-set-style "gnu")
597  * End:
598  */