4553701dced185a21f7364339c57e8b75c4d56bb
[vpp.git] / src / vnet / udp / udp.c
1 /*
2  * Copyright (c) 2016-2020 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/udp/udp.h>
17 #include <vnet/session/session.h>
18 #include <vnet/dpo/load_balance.h>
19 #include <vnet/ip/ip4_inlines.h>
20 #include <vnet/ip/ip6_inlines.h>
21 #include <vppinfra/sparse_vec.h>
22
23 udp_main_t udp_main;
24
25 static void
26 udp_connection_register_port (u16 lcl_port, u8 is_ip4)
27 {
28   udp_main_t *um = &udp_main;
29   u16 *n;
30
31   /* Setup udp protocol -> next index sparse vector mapping. Do not setup
32    * udp_dst_port_info_t as that is used to distinguish between external
33    * and transport consumed ports */
34
35   if (is_ip4)
36     n = sparse_vec_validate (um->next_by_dst_port4, lcl_port);
37   else
38     n = sparse_vec_validate (um->next_by_dst_port6, lcl_port);
39
40   n[0] = um->local_to_input_edge[is_ip4];
41
42   __atomic_add_fetch (&um->transport_ports_refcnt[is_ip4][lcl_port], 1,
43                       __ATOMIC_RELAXED);
44 }
45
46 static void
47 udp_connection_unregister_port (u16 lcl_port, u8 is_ip4)
48 {
49   udp_main_t *um = &udp_main;
50   u16 *n;
51
52   /* Needed because listeners are not tracked as local endpoints */
53   if (__atomic_sub_fetch (&um->transport_ports_refcnt[is_ip4][lcl_port], 1,
54                           __ATOMIC_RELAXED))
55     return;
56
57   if (is_ip4)
58     n = sparse_vec_validate (um->next_by_dst_port4, lcl_port);
59   else
60     n = sparse_vec_validate (um->next_by_dst_port6, lcl_port);
61
62   n[0] = UDP_NO_NODE_SET;
63 }
64
65 udp_connection_t *
66 udp_connection_alloc (u32 thread_index)
67 {
68   udp_worker_t *wrk = udp_worker_get (thread_index);
69   udp_connection_t *uc;
70
71   pool_get_aligned_safe (wrk->connections, uc, CLIB_CACHE_LINE_BYTES);
72
73   clib_memset (uc, 0, sizeof (*uc));
74   uc->c_c_index = uc - wrk->connections;
75   uc->c_thread_index = thread_index;
76   uc->c_proto = TRANSPORT_PROTO_UDP;
77   return uc;
78 }
79
80 void
81 udp_connection_free (udp_connection_t * uc)
82 {
83   udp_worker_t *wrk = udp_worker_get (uc->c_thread_index);
84
85   clib_spinlock_free (&uc->rx_lock);
86   if (CLIB_DEBUG)
87     clib_memset (uc, 0xFA, sizeof (*uc));
88   pool_put (wrk->connections, uc);
89 }
90
91 static void
92 udp_connection_cleanup (udp_connection_t * uc)
93 {
94   /* Unregister port from udp_local only if refcount went to zero */
95   if (!transport_release_local_endpoint (TRANSPORT_PROTO_UDP, &uc->c_lcl_ip,
96                                          uc->c_lcl_port))
97     udp_connection_unregister_port (uc->c_lcl_port, uc->c_is_ip4);
98   udp_connection_free (uc);
99 }
100
101 void
102 udp_connection_delete (udp_connection_t * uc)
103 {
104   session_transport_delete_notify (&uc->connection);
105   udp_connection_cleanup (uc);
106 }
107
108 static void
109 udp_handle_cleanups (void *args)
110 {
111   u32 thread_index = (u32) pointer_to_uword (args);
112   udp_connection_t *uc;
113   udp_worker_t *wrk;
114   u32 *uc_index;
115
116   wrk = udp_worker_get (thread_index);
117   vec_foreach (uc_index, wrk->pending_cleanups)
118     {
119       uc = udp_connection_get (*uc_index, thread_index);
120       udp_connection_delete (uc);
121     }
122   vec_reset_length (wrk->pending_cleanups);
123 }
124
125 static void
126 udp_connection_program_cleanup (udp_connection_t *uc)
127 {
128   uword thread_index = uc->c_thread_index;
129   udp_worker_t *wrk;
130
131   wrk = udp_worker_get (uc->c_thread_index);
132   vec_add1 (wrk->pending_cleanups, uc->c_c_index);
133
134   if (vec_len (wrk->pending_cleanups) == 1)
135     session_send_rpc_evt_to_thread_force (
136       thread_index, udp_handle_cleanups,
137       uword_to_pointer (thread_index, void *));
138 }
139
140 static u8
141 udp_connection_port_used_extern (u16 lcl_port, u8 is_ip4)
142 {
143   udp_main_t *um = vnet_get_udp_main ();
144   udp_dst_port_info_t *pi;
145
146   pi = udp_get_dst_port_info (um, lcl_port, is_ip4);
147   return (pi && udp_is_valid_dst_port (lcl_port, is_ip4));
148 }
149
150 static u16
151 udp_default_mtu (udp_main_t * um, u8 is_ip4)
152 {
153   u16 ip_hlen = is_ip4 ? sizeof (ip4_header_t) : sizeof (ip6_header_t);
154   return (um->default_mtu - sizeof (udp_header_t) - ip_hlen);
155 }
156
157 static u32
158 udp_session_bind (u32 session_index, transport_endpoint_cfg_t *lcl)
159 {
160   udp_main_t *um = vnet_get_udp_main ();
161   transport_endpoint_cfg_t *lcl_ext;
162   udp_connection_t *listener;
163   void *iface_ip;
164
165   if (udp_connection_port_used_extern (clib_net_to_host_u16 (lcl->port),
166                                        lcl->is_ip4))
167     {
168       clib_warning ("port already used");
169       return SESSION_E_PORTINUSE;
170     }
171
172   pool_get (um->listener_pool, listener);
173   clib_memset (listener, 0, sizeof (udp_connection_t));
174
175   listener->c_lcl_port = lcl->port;
176   listener->c_c_index = listener - um->listener_pool;
177
178   /* If we are provided a sw_if_index, bind using one of its ips */
179   if (ip_is_zero (&lcl->ip, 1) && lcl->sw_if_index != ENDPOINT_INVALID_INDEX)
180     {
181       if ((iface_ip = ip_interface_get_first_ip (lcl->sw_if_index,
182                                                  lcl->is_ip4)))
183         ip_set (&lcl->ip, iface_ip, lcl->is_ip4);
184     }
185   ip_copy (&listener->c_lcl_ip, &lcl->ip, lcl->is_ip4);
186   listener->c_is_ip4 = lcl->is_ip4;
187   listener->c_proto = TRANSPORT_PROTO_UDP;
188   listener->c_s_index = session_index;
189   listener->c_fib_index = lcl->fib_index;
190   listener->mss =
191     lcl->mss ? lcl->mss : udp_default_mtu (um, listener->c_is_ip4);
192   listener->flags |= UDP_CONN_F_OWNS_PORT | UDP_CONN_F_LISTEN;
193   lcl_ext = (transport_endpoint_cfg_t *) lcl;
194   if (lcl_ext->transport_flags & TRANSPORT_CFG_F_CONNECTED)
195     listener->flags |= UDP_CONN_F_CONNECTED;
196   else
197     listener->c_flags |= TRANSPORT_CONNECTION_F_CLESS;
198   clib_spinlock_init (&listener->rx_lock);
199   if (!um->csum_offload)
200     listener->cfg_flags |= UDP_CFG_F_NO_CSUM_OFFLOAD;
201
202   udp_connection_register_port (listener->c_lcl_port, lcl->is_ip4);
203   return listener->c_c_index;
204 }
205
206 static u32
207 udp_session_unbind (u32 listener_index)
208 {
209   udp_main_t *um = &udp_main;
210   udp_connection_t *listener;
211
212   listener = udp_listener_get (listener_index);
213   udp_connection_unregister_port (listener->c_lcl_port, listener->c_is_ip4);
214   clib_spinlock_free (&listener->rx_lock);
215   pool_put (um->listener_pool, listener);
216   return 0;
217 }
218
219 static transport_connection_t *
220 udp_session_get_listener (u32 listener_index)
221 {
222   udp_connection_t *us;
223
224   us = udp_listener_get (listener_index);
225   return &us->connection;
226 }
227
228 always_inline u32
229 udp_push_one_header (vlib_main_t *vm, udp_connection_t *uc, vlib_buffer_t *b)
230 {
231   vlib_buffer_push_udp (b, uc->c_lcl_port, uc->c_rmt_port,
232                         udp_csum_offload (uc));
233   b->flags |= VNET_BUFFER_F_LOCALLY_ORIGINATED;
234
235   /* Handle ip header now as session layer overwrite connection details for
236    * non-connected udp. */
237   if (uc->c_is_ip4)
238     vlib_buffer_push_ip4_custom (vm, b, &uc->c_lcl_ip4, &uc->c_rmt_ip4,
239                                  IP_PROTOCOL_UDP, udp_csum_offload (uc),
240                                  0 /* is_df */, uc->c_dscp);
241   else
242     vlib_buffer_push_ip6 (vm, b, &uc->c_lcl_ip6, &uc->c_rmt_ip6,
243                           IP_PROTOCOL_UDP);
244
245   /* reuse tcp medatada for now */
246   vnet_buffer (b)->tcp.connection_index = uc->c_c_index;
247
248   /* Not connected udp session. Mark buffer for custom handling in
249    * udp_output */
250   if (PREDICT_FALSE (!(uc->flags & UDP_CONN_F_CONNECTED)))
251     vnet_buffer (b)->tcp.flags |= UDP_CONN_F_LISTEN;
252   else
253     vnet_buffer (b)->tcp.flags = 0;
254
255   return 0;
256 }
257
258 static u32
259 udp_push_header (transport_connection_t *tc, vlib_buffer_t **bs, u32 n_bufs)
260 {
261   vlib_main_t *vm = vlib_get_main ();
262   udp_connection_t *uc;
263
264   uc = udp_connection_from_transport (tc);
265
266   while (n_bufs >= 4)
267     {
268       vlib_prefetch_buffer_header (bs[2], STORE);
269       vlib_prefetch_buffer_header (bs[3], STORE);
270
271       udp_push_one_header (vm, uc, bs[0]);
272       udp_push_one_header (vm, uc, bs[1]);
273
274       n_bufs -= 2;
275       bs += 2;
276     }
277   while (n_bufs)
278     {
279       if (n_bufs > 1)
280         vlib_prefetch_buffer_header (bs[1], STORE);
281
282       udp_push_one_header (vm, uc, bs[0]);
283
284       n_bufs -= 1;
285       bs += 1;
286     }
287
288   if (PREDICT_FALSE (uc->flags & UDP_CONN_F_CLOSING))
289     {
290       if (!transport_max_tx_dequeue (&uc->connection))
291         udp_connection_program_cleanup (uc);
292     }
293
294   return 0;
295 }
296
297 static transport_connection_t *
298 udp_session_get (u32 connection_index, u32 thread_index)
299 {
300   udp_connection_t *uc;
301   uc = udp_connection_get (connection_index, thread_index);
302   if (uc)
303     return &uc->connection;
304   return 0;
305 }
306
307 static void
308 udp_session_close (u32 connection_index, u32 thread_index)
309 {
310   udp_connection_t *uc;
311
312   uc = udp_connection_get (connection_index, thread_index);
313   if (!uc || (uc->flags & UDP_CONN_F_MIGRATED))
314     return;
315
316   if (!transport_max_tx_dequeue (&uc->connection))
317     udp_connection_program_cleanup (uc);
318   else
319     uc->flags |= UDP_CONN_F_CLOSING;
320 }
321
322 static void
323 udp_session_cleanup (u32 connection_index, u32 thread_index)
324 {
325   udp_connection_t *uc;
326   uc = udp_connection_get (connection_index, thread_index);
327   if (!uc)
328     return;
329   if (uc->flags & UDP_CONN_F_MIGRATED)
330     udp_connection_free (uc);
331   else
332     udp_connection_cleanup (uc);
333 }
334
335 static int
336 udp_session_send_params (transport_connection_t * tconn,
337                          transport_send_params_t * sp)
338 {
339   udp_connection_t *uc;
340
341   uc = udp_connection_from_transport (tconn);
342
343   /* No constraint on TX window */
344   sp->snd_space = ~0;
345   /* TODO figure out MTU of output interface */
346   sp->snd_mss = uc->mss;
347   sp->tx_offset = 0;
348   sp->flags = 0;
349   return 0;
350 }
351
352 static int
353 udp_open_connection (transport_endpoint_cfg_t * rmt)
354 {
355   udp_main_t *um = &udp_main;
356   ip46_address_t lcl_addr;
357   udp_connection_t *uc;
358   u32 thread_index;
359   u16 lcl_port;
360   int rv;
361
362   rv = transport_alloc_local_endpoint (TRANSPORT_PROTO_UDP, rmt, &lcl_addr,
363                                        &lcl_port);
364   if (rv)
365     {
366       if (rv != SESSION_E_PORTINUSE)
367         return rv;
368
369       if (udp_connection_port_used_extern (lcl_port, rmt->is_ip4))
370         return SESSION_E_PORTINUSE;
371
372       /* If port in use, check if 5-tuple is also in use */
373       if (session_lookup_connection (rmt->fib_index, &lcl_addr, &rmt->ip,
374                                      lcl_port, rmt->port, TRANSPORT_PROTO_UDP,
375                                      rmt->is_ip4))
376         return SESSION_E_PORTINUSE;
377
378       /* 5-tuple is available so increase lcl endpoint refcount and proceed
379        * with connection allocation */
380       transport_share_local_endpoint (TRANSPORT_PROTO_UDP, &lcl_addr,
381                                       lcl_port);
382       goto conn_alloc;
383     }
384
385   if (udp_is_valid_dst_port (lcl_port, rmt->is_ip4))
386     {
387       /* If specific source port was requested abort */
388       if (rmt->peer.port)
389         return SESSION_E_PORTINUSE;
390
391       /* Try to find a port that's not used */
392       while (udp_is_valid_dst_port (lcl_port, rmt->is_ip4))
393         {
394           lcl_port = transport_alloc_local_port (TRANSPORT_PROTO_UDP,
395                                                  &lcl_addr);
396           if (lcl_port < 1)
397             return SESSION_E_PORTINUSE;
398         }
399     }
400
401 conn_alloc:
402
403   /* We don't poll main thread if we have workers */
404   thread_index = transport_cl_thread ();
405
406   uc = udp_connection_alloc (thread_index);
407   ip_copy (&uc->c_rmt_ip, &rmt->ip, rmt->is_ip4);
408   ip_copy (&uc->c_lcl_ip, &lcl_addr, rmt->is_ip4);
409   uc->c_rmt_port = rmt->port;
410   uc->c_lcl_port = clib_host_to_net_u16 (lcl_port);
411   uc->c_is_ip4 = rmt->is_ip4;
412   uc->c_proto = TRANSPORT_PROTO_UDP;
413   uc->c_fib_index = rmt->fib_index;
414   uc->c_dscp = rmt->dscp;
415   uc->mss = rmt->mss ? rmt->mss : udp_default_mtu (um, uc->c_is_ip4);
416   if (rmt->peer.sw_if_index != ENDPOINT_INVALID_INDEX)
417     uc->sw_if_index = rmt->peer.sw_if_index;
418   uc->flags |= UDP_CONN_F_OWNS_PORT;
419   if (rmt->transport_flags & TRANSPORT_CFG_F_CONNECTED)
420     {
421       uc->flags |= UDP_CONN_F_CONNECTED;
422     }
423   else
424     {
425       clib_spinlock_init (&uc->rx_lock);
426       uc->c_flags |= TRANSPORT_CONNECTION_F_CLESS;
427     }
428   if (!um->csum_offload)
429     uc->cfg_flags |= UDP_CFG_F_NO_CSUM_OFFLOAD;
430   uc->next_node_index = rmt->next_node_index;
431   uc->next_node_opaque = rmt->next_node_opaque;
432
433   udp_connection_register_port (uc->c_lcl_port, rmt->is_ip4);
434
435   return uc->c_c_index;
436 }
437
438 static transport_connection_t *
439 udp_session_get_half_open (u32 conn_index)
440 {
441   udp_connection_t *uc;
442   u32 thread_index;
443
444   /* We don't poll main thread if we have workers */
445   thread_index = transport_cl_thread ();
446   uc = udp_connection_get (conn_index, thread_index);
447   if (!uc)
448     return 0;
449   return &uc->connection;
450 }
451
452 static u8 *
453 format_udp_session (u8 * s, va_list * args)
454 {
455   u32 uci = va_arg (*args, u32);
456   u32 thread_index = va_arg (*args, u32);
457   u32 verbose = va_arg (*args, u32);
458   udp_connection_t *uc;
459
460   uc = udp_connection_get (uci, thread_index);
461   return format (s, "%U", format_udp_connection, uc, verbose);
462 }
463
464 static u8 *
465 format_udp_half_open_session (u8 * s, va_list * args)
466 {
467   u32 __clib_unused tci = va_arg (*args, u32);
468   u32 __clib_unused thread_index = va_arg (*args, u32);
469   clib_warning ("BUG");
470   return 0;
471 }
472
473 static u8 *
474 format_udp_listener_session (u8 * s, va_list * args)
475 {
476   u32 tci = va_arg (*args, u32);
477   u32 __clib_unused thread_index = va_arg (*args, u32);
478   u32 verbose = va_arg (*args, u32);
479   udp_connection_t *uc = udp_listener_get (tci);
480   return format (s, "%U", format_udp_connection, uc, verbose);
481 }
482
483 static void
484 udp_realloc_ports_sv (u16 **ports_nh_svp)
485 {
486   u16 port, port_no, *ports_nh_sv, *mc;
487   u32 *ports = 0, *nh = 0, msum, i;
488   sparse_vec_header_t *h;
489   uword sv_index, *mb;
490
491   ports_nh_sv = *ports_nh_svp;
492
493   for (port = 1; port < 65535; port++)
494     {
495       port_no = clib_host_to_net_u16 (port);
496
497       sv_index = sparse_vec_index (ports_nh_sv, port_no);
498       if (sv_index != SPARSE_VEC_INVALID_INDEX)
499         {
500           vec_add1 (ports, port_no);
501           vec_add1 (nh, ports_nh_sv[sv_index]);
502         }
503     }
504
505   sparse_vec_free (ports_nh_sv);
506
507   ports_nh_sv =
508     sparse_vec_new (/* elt bytes */ sizeof (ports_nh_sv[0]),
509                     /* bits in index */ BITS (((udp_header_t *) 0)->dst_port));
510
511   vec_resize (ports_nh_sv, 65535);
512
513   for (port = 1; port < 65535; port++)
514     ports_nh_sv[port] = UDP_NO_NODE_SET;
515
516   for (i = 0; i < vec_len (ports); i++)
517     ports_nh_sv[ports[i]] = nh[i];
518
519   h = sparse_vec_header (ports_nh_sv);
520   vec_foreach (mb, h->is_member_bitmap)
521     *mb = (uword) ~0;
522
523   msum = 0;
524   vec_foreach (mc, h->member_counts)
525     {
526       *mc = msum;
527       msum += msum == 0 ? 63 : 64;
528     }
529
530   vec_free (ports);
531   vec_free (nh);
532
533   *ports_nh_svp = ports_nh_sv;
534 }
535
536 static clib_error_t *
537 udp_enable_disable (vlib_main_t *vm, u8 is_en)
538 {
539   udp_main_t *um = &udp_main;
540
541   /* Not ideal. The sparse vector used to map ports to next nodes assumes
542    * only a few ports are ever used. When udp transport is enabled this does
543    * not hold and, to make matters worse, ports are consumed in a random
544    * order.
545    *
546    * This can lead to a lot of slow updates to internal data structures
547    * which in turn can slow udp connection allocations until all ports are
548    * eventually consumed.
549    *
550    * Consequently, reallocate sparse vector, preallocate all ports and have
551    * them point to UDP_NO_NODE_SET. We could consider switching the sparse
552    * vector to a preallocated vector but that would increase memory
553    * consumption for vpp deployments that do not rely on host stack.
554    */
555
556   udp_realloc_ports_sv (&um->next_by_dst_port4);
557   udp_realloc_ports_sv (&um->next_by_dst_port6);
558
559   vec_validate (um->transport_ports_refcnt[0], 65535);
560   vec_validate (um->transport_ports_refcnt[1], 65535);
561
562   return 0;
563 }
564
565 static const transport_proto_vft_t udp_proto = {
566   .enable = udp_enable_disable,
567   .start_listen = udp_session_bind,
568   .connect = udp_open_connection,
569   .stop_listen = udp_session_unbind,
570   .push_header = udp_push_header,
571   .get_connection = udp_session_get,
572   .get_listener = udp_session_get_listener,
573   .get_half_open = udp_session_get_half_open,
574   .close = udp_session_close,
575   .cleanup = udp_session_cleanup,
576   .send_params = udp_session_send_params,
577   .format_connection = format_udp_session,
578   .format_half_open = format_udp_half_open_session,
579   .format_listener = format_udp_listener_session,
580   .transport_options = {
581     .name = "udp",
582     .short_name = "U",
583     .tx_type = TRANSPORT_TX_DGRAM,
584     .service_type = TRANSPORT_SERVICE_CL,
585   },
586 };
587
588 static clib_error_t *
589 udp_init (vlib_main_t * vm)
590 {
591   udp_main_t *um = vnet_get_udp_main ();
592   ip_main_t *im = &ip_main;
593   vlib_thread_main_t *tm = vlib_get_thread_main ();
594   u32 num_threads;
595   ip_protocol_info_t *pi;
596
597   /*
598    * Registrations
599    */
600
601   /* IP registration */
602   pi = ip_get_protocol_info (im, IP_PROTOCOL_UDP);
603   if (pi == 0)
604     return clib_error_return (0, "UDP protocol info AWOL");
605   pi->format_header = format_udp_header;
606   pi->unformat_pg_edit = unformat_pg_udp_header;
607
608   /* Register as transport with session layer */
609   transport_register_protocol (TRANSPORT_PROTO_UDP, &udp_proto,
610                                FIB_PROTOCOL_IP4, udp4_output_node.index);
611   transport_register_protocol (TRANSPORT_PROTO_UDP, &udp_proto,
612                                FIB_PROTOCOL_IP6, udp6_output_node.index);
613
614   /*
615    * Initialize data structures
616    */
617
618   num_threads = 1 /* main thread */  + tm->n_threads;
619   vec_validate (um->wrk, num_threads - 1);
620
621   um->local_to_input_edge[UDP_IP4] =
622     vlib_node_add_next (vm, udp4_local_node.index, udp4_input_node.index);
623   um->local_to_input_edge[UDP_IP6] =
624     vlib_node_add_next (vm, udp6_local_node.index, udp6_input_node.index);
625
626   um->default_mtu = 1500;
627   um->csum_offload = 1;
628   return 0;
629 }
630
631 /* *INDENT-OFF* */
632 VLIB_INIT_FUNCTION (udp_init) =
633 {
634   .runs_after = VLIB_INITS("ip_main_init", "ip4_lookup_init",
635                            "ip6_lookup_init"),
636 };
637 /* *INDENT-ON* */
638
639 /*
640  * fd.io coding-style-patch-verification: ON
641  *
642  * Local Variables:
643  * eval: (c-set-style "gnu")
644  * End:
645  */