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