176d85de7771e553beae68650265b2f2ece6fe7a
[vpp.git] / src / plugins / linux-cp / lcp_nl.c
1 /*
2  * Copyright (c) 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 #define _GNU_SOURCE
17 #include <sched.h>
18 #include <fcntl.h>
19
20 #include <linux-cp/lcp_nl.h>
21
22 #include <netlink/route/rule.h>
23 #include <netlink/msg.h>
24 #include <netlink/netlink.h>
25 #include <netlink/socket.h>
26 #include <netlink/route/link.h>
27 #include <netlink/route/route.h>
28 #include <netlink/route/neighbour.h>
29 #include <netlink/route/addr.h>
30
31 #include <vlib/vlib.h>
32 #include <vlib/unix/unix.h>
33 #include <vppinfra/error.h>
34 #include <vppinfra/linux/netns.h>
35
36 #include <vnet/fib/fib_table.h>
37
38 #include <libmnl/libmnl.h>
39
40 #include <plugins/linux-cp/lcp_interface.h>
41
42 typedef enum nl_status_t_
43 {
44   NL_STATUS_NOTIF_PROC,
45   NL_STATUS_SYNC,
46 } nl_status_t;
47
48 typedef enum nl_sock_type_t_
49 {
50   NL_SOCK_TYPE_LINK,
51   NL_SOCK_TYPE_ADDR,
52   NL_SOCK_TYPE_NEIGH,
53   NL_SOCK_TYPE_ROUTE,
54 } nl_sock_type_t;
55
56 #define NL_SOCK_TYPES_N (NL_SOCK_TYPE_ROUTE + 1)
57
58 /* Socket type, message type, type name, function subname */
59 #define foreach_sock_type                                                     \
60   _ (NL_SOCK_TYPE_LINK, RTM_GETLINK, "link", link)                            \
61   _ (NL_SOCK_TYPE_ADDR, RTM_GETADDR, "address", link_addr)                    \
62   _ (NL_SOCK_TYPE_NEIGH, RTM_GETNEIGH, "neighbor", neigh)                     \
63   _ (NL_SOCK_TYPE_ROUTE, RTM_GETROUTE, "route", route)
64
65 typedef enum nl_event_type_t_
66 {
67   NL_EVENT_READ,
68   NL_EVENT_ERR,
69 } nl_event_type_t;
70
71 typedef struct nl_main
72 {
73
74   nl_status_t nl_status;
75
76   struct nl_sock *sk_route;
77   struct nl_sock *sk_route_sync[NL_SOCK_TYPES_N];
78   vlib_log_class_t nl_logger;
79   nl_vft_t *nl_vfts;
80   struct nl_cache *nl_caches[LCP_NL_N_OBJS];
81   nl_msg_info_t *nl_msg_queue;
82   uword clib_file_index;
83
84   u32 rx_buf_size;
85   u32 tx_buf_size;
86   u32 batch_size;
87   u32 batch_delay_ms;
88
89   u32 sync_batch_limit;
90   u32 sync_batch_delay_ms;
91   u32 sync_attempt_delay_ms;
92
93 } nl_main_t;
94
95 #define NL_RX_BUF_SIZE_DEF    (1 << 27) /* 128 MB */
96 #define NL_TX_BUF_SIZE_DEF    (1 << 18) /* 256 kB */
97 #define NL_BATCH_SIZE_DEF     (1 << 11) /* 2048 */
98 #define NL_BATCH_DELAY_MS_DEF 50        /* 50 ms, max 20 batch/s */
99
100 #define NL_SYNC_BATCH_LIMIT_DEF      (1 << 10) /* 1024 */
101 #define NL_SYNC_BATCH_DELAY_MS_DEF   20        /* 20ms, max 50 batch/s */
102 #define NL_SYNC_ATTEMPT_DELAY_MS_DEF 2000      /* 2s */
103
104 static nl_main_t nl_main = {
105   .rx_buf_size = NL_RX_BUF_SIZE_DEF,
106   .tx_buf_size = NL_TX_BUF_SIZE_DEF,
107   .batch_size = NL_BATCH_SIZE_DEF,
108   .batch_delay_ms = NL_BATCH_DELAY_MS_DEF,
109   .sync_batch_limit = NL_SYNC_BATCH_LIMIT_DEF,
110   .sync_batch_delay_ms = NL_SYNC_BATCH_DELAY_MS_DEF,
111   .sync_attempt_delay_ms = NL_SYNC_ATTEMPT_DELAY_MS_DEF,
112 };
113
114 /* #define foreach_nl_nft_proto  \ */
115 /*   _(IP4, "ip", AF_INT)  \ */
116 /*   _(IP6, "ip6", NFPROTO_IPV6) */
117
118 /* typedef enum nl_nft_proto_t_ */
119 /* { */
120 /* #define _(a,b,c) NL_NFT_PROTO_##a = c, */
121 /*   foreach_nl_nft_proto */
122 /* #undef _ */
123 /* } nl_nft_proto_t; */
124
125 #define FOREACH_VFT(__func, __arg)                                            \
126   {                                                                           \
127     nl_main_t *nm = &nl_main;                                                 \
128     nl_vft_t *__nv;                                                           \
129     vec_foreach (__nv, nm->nl_vfts)                                           \
130       {                                                                       \
131         if (!__nv->__func.cb)                                                 \
132           continue;                                                           \
133                                                                               \
134         if (!__nv->__func.is_mp_safe)                                         \
135           vlib_worker_thread_barrier_sync (vlib_get_main ());                 \
136                                                                               \
137         __nv->__func.cb (__arg);                                              \
138                                                                               \
139         if (!__nv->__func.is_mp_safe)                                         \
140           vlib_worker_thread_barrier_release (vlib_get_main ());              \
141       }                                                                       \
142   }
143
144 #define FOREACH_VFT_NO_ARG(__func)                                            \
145   {                                                                           \
146     nl_main_t *nm = &nl_main;                                                 \
147     nl_vft_t *__nv;                                                           \
148     vec_foreach (__nv, nm->nl_vfts)                                           \
149       {                                                                       \
150         if (!__nv->__func.cb)                                                 \
151           continue;                                                           \
152                                                                               \
153         if (!__nv->__func.is_mp_safe)                                         \
154           vlib_worker_thread_barrier_sync (vlib_get_main ());                 \
155                                                                               \
156         __nv->__func.cb ();                                                   \
157                                                                               \
158         if (!__nv->__func.is_mp_safe)                                         \
159           vlib_worker_thread_barrier_release (vlib_get_main ());              \
160       }                                                                       \
161   }
162
163 #define FOREACH_VFT_CTX(__func, __arg, __ctx)                                 \
164   {                                                                           \
165     nl_main_t *nm = &nl_main;                                                 \
166     nl_vft_t *__nv;                                                           \
167     vec_foreach (__nv, nm->nl_vfts)                                           \
168       {                                                                       \
169         if (!__nv->__func.cb)                                                 \
170           continue;                                                           \
171                                                                               \
172         if (!__nv->__func.is_mp_safe)                                         \
173           vlib_worker_thread_barrier_sync (vlib_get_main ());                 \
174                                                                               \
175         __nv->__func.cb (__arg, __ctx);                                       \
176                                                                               \
177         if (!__nv->__func.is_mp_safe)                                         \
178           vlib_worker_thread_barrier_release (vlib_get_main ());              \
179       }                                                                       \
180   }
181
182 void
183 nl_register_vft (const nl_vft_t *nv)
184 {
185   nl_main_t *nm = &nl_main;
186
187   vec_add1 (nm->nl_vfts, *nv);
188 }
189
190 #define NL_DBG(...)   vlib_log_debug (nl_main.nl_logger, __VA_ARGS__);
191 #define NL_INFO(...)  vlib_log_notice (nl_main.nl_logger, __VA_ARGS__);
192 #define NL_ERROR(...) vlib_log_err (nl_main.nl_logger, __VA_ARGS__);
193
194 static void lcp_nl_open_socket (void);
195 static void lcp_nl_close_socket (void);
196 static void lcp_nl_open_sync_socket (nl_sock_type_t sock_type);
197 static void lcp_nl_close_sync_socket (nl_sock_type_t sock_type);
198
199 static void
200 nl_route_del (struct rtnl_route *rr, void *arg)
201 {
202   FOREACH_VFT (nvl_rt_route_del, rr);
203 }
204
205 static void
206 nl_route_add (struct rtnl_route *rr, void *arg)
207 {
208   FOREACH_VFT (nvl_rt_route_add, rr);
209 }
210
211 static void
212 nl_route_sync_begin (void)
213 {
214   FOREACH_VFT_NO_ARG (nvl_rt_route_sync_begin);
215 }
216
217 static void
218 nl_route_sync_end (void)
219 {
220   FOREACH_VFT_NO_ARG (nvl_rt_route_sync_end);
221 }
222
223 static void
224 nl_neigh_del (struct rtnl_neigh *rn, void *arg)
225 {
226   FOREACH_VFT (nvl_rt_neigh_del, rn);
227 }
228
229 static void
230 nl_neigh_add (struct rtnl_neigh *rn, void *arg)
231 {
232   FOREACH_VFT (nvl_rt_neigh_add, rn);
233 }
234
235 static void
236 nl_neigh_sync_begin (void)
237 {
238   FOREACH_VFT_NO_ARG (nvl_rt_neigh_sync_begin);
239 }
240
241 static void
242 nl_neigh_sync_end (void)
243 {
244   FOREACH_VFT_NO_ARG (nvl_rt_neigh_sync_end);
245 }
246
247 static void
248 nl_link_addr_del (struct rtnl_addr *rla, void *arg)
249 {
250   FOREACH_VFT (nvl_rt_addr_del, rla);
251 }
252
253 static void
254 nl_link_addr_add (struct rtnl_addr *rla, void *arg)
255 {
256   FOREACH_VFT (nvl_rt_addr_add, rla);
257 }
258
259 static void
260 nl_link_addr_sync_begin (void)
261 {
262   FOREACH_VFT_NO_ARG (nvl_rt_addr_sync_begin);
263 }
264
265 static void
266 nl_link_addr_sync_end (void)
267 {
268   FOREACH_VFT_NO_ARG (nvl_rt_addr_sync_end);
269 }
270
271 static void
272 nl_link_del (struct rtnl_link *rl, void *arg)
273 {
274   FOREACH_VFT_CTX (nvl_rt_link_del, rl, arg);
275 }
276
277 static void
278 nl_link_add (struct rtnl_link *rl, void *arg)
279 {
280   FOREACH_VFT_CTX (nvl_rt_link_add, rl, arg);
281 }
282
283 static void
284 nl_link_sync_begin (void)
285 {
286   FOREACH_VFT_NO_ARG (nvl_rt_link_sync_begin);
287 }
288
289 static void
290 nl_link_sync_end (void)
291 {
292   FOREACH_VFT_NO_ARG (nvl_rt_link_sync_end);
293 }
294
295 static void
296 nl_route_dispatch (struct nl_object *obj, void *arg)
297 {
298   /* nothing can be done without interface mappings */
299   if (!lcp_itf_num_pairs ())
300     return;
301
302   switch (nl_object_get_msgtype (obj))
303     {
304     case RTM_NEWROUTE:
305       nl_route_add ((struct rtnl_route *) obj, arg);
306       break;
307     case RTM_DELROUTE:
308       nl_route_del ((struct rtnl_route *) obj, arg);
309       break;
310     case RTM_NEWNEIGH:
311       nl_neigh_add ((struct rtnl_neigh *) obj, arg);
312       break;
313     case RTM_DELNEIGH:
314       nl_neigh_del ((struct rtnl_neigh *) obj, arg);
315       break;
316     case RTM_NEWADDR:
317       nl_link_addr_add ((struct rtnl_addr *) obj, arg);
318       break;
319     case RTM_DELADDR:
320       nl_link_addr_del ((struct rtnl_addr *) obj, arg);
321       break;
322     case RTM_NEWLINK:
323       nl_link_add ((struct rtnl_link *) obj, arg);
324       break;
325     case RTM_DELLINK:
326       nl_link_del ((struct rtnl_link *) obj, arg);
327       break;
328     default:
329       NL_INFO ("unhandled: %s", nl_object_get_type (obj));
330       break;
331     }
332 }
333
334 static int
335 nl_route_process_msgs (void)
336 {
337   nl_main_t *nm = &nl_main;
338   nl_msg_info_t *msg_info;
339   int err, n_msgs = 0;
340
341   /* process a batch of messages. break if we hit our limit */
342   vec_foreach (msg_info, nm->nl_msg_queue)
343     {
344       if ((err = nl_msg_parse (msg_info->msg, nl_route_dispatch, msg_info)) <
345           0)
346         NL_ERROR ("Unable to parse object: %s", nl_geterror (err));
347       nlmsg_free (msg_info->msg);
348       if (++n_msgs >= nm->batch_size)
349         break;
350     }
351
352   /* remove the messages we processed from the head of the queue */
353   if (n_msgs)
354     vec_delete (nm->nl_msg_queue, n_msgs, 0);
355
356   NL_INFO ("Processed %u messages", n_msgs);
357
358   return n_msgs;
359 }
360
361 static int
362 lcp_nl_route_discard_msgs (void)
363 {
364   nl_main_t *nm = &nl_main;
365   nl_msg_info_t *msg_info;
366   int n_msgs;
367
368   n_msgs = vec_len (nm->nl_msg_queue);
369   if (n_msgs == 0)
370     return 0;
371
372   vec_foreach (msg_info, nm->nl_msg_queue)
373     {
374       nlmsg_free (msg_info->msg);
375     }
376
377   vec_reset_length (nm->nl_msg_queue);
378
379   NL_INFO ("Discarded %u messages", n_msgs);
380
381   return n_msgs;
382 }
383
384 static int
385 lcp_nl_route_send_dump_req (nl_sock_type_t sock_type, int msg_type)
386 {
387   nl_main_t *nm = &nl_main;
388   struct nl_sock *sk_route = nm->sk_route_sync[sock_type];
389   int err;
390   struct rtgenmsg rt_hdr = {
391     .rtgen_family = AF_UNSPEC,
392   };
393
394   err =
395     nl_send_simple (sk_route, msg_type, NLM_F_DUMP, &rt_hdr, sizeof (rt_hdr));
396
397   if (err < 0)
398     {
399       NL_ERROR ("Unable to send a dump request: %s", nl_geterror (err));
400     }
401   else
402     NL_INFO ("Dump request sent via socket %d of type %d",
403              nl_socket_get_fd (sk_route), sock_type);
404
405   return err;
406 }
407
408 static int
409 lcp_nl_route_dump_cb (struct nl_msg *msg, void *arg)
410 {
411   int err;
412
413   if ((err = nl_msg_parse (msg, nl_route_dispatch, NULL)) < 0)
414     NL_ERROR ("Unable to parse object: %s", nl_geterror (err));
415
416   return NL_OK;
417 }
418
419 static int
420 lcp_nl_recv_dump_replies (nl_sock_type_t sock_type, int msg_limit,
421                           int *is_done_rcvd)
422 {
423   nl_main_t *nm = &nl_main;
424   struct nl_sock *sk_route = nm->sk_route_sync[sock_type];
425   struct sockaddr_nl nla;
426   uint8_t *buf = NULL;
427   int n_bytes;
428   struct nlmsghdr *hdr;
429   struct nl_msg *msg = NULL;
430   int err = 0;
431   int done = 0;
432   int n_msgs = 0;
433
434 continue_reading:
435   n_bytes = nl_recv (sk_route, &nla, &buf, /* creds */ NULL);
436   if (n_bytes <= 0)
437     return n_bytes;
438
439   hdr = (struct nlmsghdr *) buf;
440   while (nlmsg_ok (hdr, n_bytes))
441     {
442       nlmsg_free (msg);
443       msg = nlmsg_convert (hdr);
444       if (!msg)
445         {
446           err = -NLE_NOMEM;
447           goto out;
448         }
449
450       n_msgs++;
451
452       nlmsg_set_proto (msg, NETLINK_ROUTE);
453       nlmsg_set_src (msg, &nla);
454
455       /* Message that terminates a multipart message. Finish parsing and signal
456        * the caller that all dump replies have been received
457        */
458       if (hdr->nlmsg_type == NLMSG_DONE)
459         {
460           done = 1;
461           goto out;
462         }
463       /* Message to be ignored. Continue parsing */
464       else if (hdr->nlmsg_type == NLMSG_NOOP)
465         ;
466       /* Message that indicates data was lost. Finish parsing and return an
467        * error
468        */
469       else if (hdr->nlmsg_type == NLMSG_OVERRUN)
470         {
471           err = -NLE_MSG_OVERFLOW;
472           goto out;
473         }
474       /* Message that indicates an error. Finish parsing, extract the error
475        * code, and return it */
476       else if (hdr->nlmsg_type == NLMSG_ERROR)
477         {
478           struct nlmsgerr *e = nlmsg_data (hdr);
479
480           if (hdr->nlmsg_len < nlmsg_size (sizeof (*e)))
481             {
482               err = -NLE_MSG_TRUNC;
483               goto out;
484             }
485           else if (e->error)
486             {
487               err = -nl_syserr2nlerr (e->error);
488               goto out;
489             }
490           /* Message is an acknowledgement (err_code = 0). Continue parsing */
491           else
492             ;
493         }
494       /* Message that contains the requested data. Pass it for processing and
495        * continue parsing
496        */
497       else
498         {
499           lcp_nl_route_dump_cb (msg, NULL);
500         }
501
502       hdr = nlmsg_next (hdr, &n_bytes);
503     }
504
505   nlmsg_free (msg);
506   free (buf);
507   msg = NULL;
508   buf = NULL;
509
510   if (!done && n_msgs < msg_limit)
511     goto continue_reading;
512
513 out:
514   nlmsg_free (msg);
515   free (buf);
516
517   if (err)
518     return err;
519
520   *is_done_rcvd = done;
521
522   return n_msgs;
523 }
524
525 #define DAY_F64 (1.0 * (24 * 60 * 60))
526
527 static uword
528 nl_route_process (vlib_main_t *vm, vlib_node_runtime_t *node,
529                   vlib_frame_t *frame)
530 {
531   nl_main_t *nm = &nl_main;
532   uword event_type;
533   uword *event_data = 0;
534   f64 wait_time = DAY_F64;
535   int n_msgs;
536   int is_done;
537
538   while (1)
539     {
540       if (nm->nl_status == NL_STATUS_NOTIF_PROC)
541         {
542           /* If we process a batch of messages and stop because we reached the
543            * batch size limit, we want to wake up after the batch delay and
544            * process more. Otherwise we just want to wait for a read event.
545            */
546           vlib_process_wait_for_event_or_clock (vm, wait_time);
547           event_type = vlib_process_get_events (vm, &event_data);
548           vec_reset_length (event_data);
549
550           switch (event_type)
551             {
552             /* Process batch of queued messages on timeout or read event
553              * signal
554              */
555             case ~0:
556             case NL_EVENT_READ:
557               nl_route_process_msgs ();
558               wait_time = (vec_len (nm->nl_msg_queue) != 0) ?
559                             nm->batch_delay_ms * 1e-3 :
560                             DAY_F64;
561               break;
562
563             /* Initiate synchronization if there was an error polling or
564              * reading the notification socket
565              */
566             case NL_EVENT_ERR:
567               nm->nl_status = NL_STATUS_SYNC;
568               break;
569
570             default:
571               NL_ERROR ("Unknown event type: %u", (u32) event_type);
572             }
573         }
574       else if (nm->nl_status == NL_STATUS_SYNC)
575         {
576           /* Stop processing notifications - close the notification socket and
577            * discard all messages that are currently in the queue
578            */
579           lcp_nl_close_socket ();
580           lcp_nl_route_discard_msgs ();
581
582           /* Wait some time before next synchronization attempt. Allows to
583            * reduce the number of failed attempts that stall the main thread by
584            * waiting out the notification storm
585            */
586           NL_INFO ("Wait before next synchronization attempt for %ums",
587                    nm->sync_attempt_delay_ms);
588           vlib_process_suspend (vm, nm->sync_attempt_delay_ms * 1e-3);
589
590           /* Open netlink synchronization socket, one for every data type of
591            * interest: link, address, neighbor, and route. That is needed to
592            * be able to send dump requests for every data type simultaneously.
593            * If send a dump request while the previous one is in progress,
594            * the request will fail and EBUSY returned
595            */
596 #define _(stype, mtype, tname, fn) lcp_nl_open_sync_socket (stype);
597           foreach_sock_type
598 #undef _
599
600           /* Start reading notifications and enqueueing them for further
601            * processing. The notifications will serve as a difference between
602            * the snapshot made after the dump request and the actual state at
603            * the moment. Once all the dump replies are processed, the
604            * notifications will be processed
605            */
606           lcp_nl_open_socket ();
607
608           /* Request the current entry set from the kernel for every data type
609            * of interest. Thus requesting a snapshot of the current routing
610            * state that the kernel will make and then reply with
611            */
612 #define _(stype, mtype, tname, fn) lcp_nl_route_send_dump_req (stype, mtype);
613           foreach_sock_type
614 #undef _
615
616           /* Process all the dump replies */
617 #define _(stype, mtype, tname, fn)                                            \
618   nl_##fn##_sync_begin ();                                                    \
619   is_done = 0;                                                                \
620   do                                                                          \
621     {                                                                         \
622       n_msgs =                                                                \
623         lcp_nl_recv_dump_replies (stype, nm->sync_batch_limit, &is_done);     \
624       if (n_msgs < 0)                                                         \
625         {                                                                     \
626           NL_ERROR ("Error receiving dump replies of type " tname             \
627                     ": %s (%d)",                                              \
628                     nl_geterror (n_msgs), n_msgs);                            \
629           break;                                                              \
630         }                                                                     \
631       else if (n_msgs == 0)                                                   \
632         {                                                                     \
633           NL_ERROR ("EOF while receiving dump replies of type " tname);       \
634           break;                                                              \
635         }                                                                     \
636       else                                                                    \
637         NL_INFO ("Processed %u dump replies of type " tname, n_msgs);         \
638                                                                               \
639       /* Suspend the processing loop and wait until event signal is           \
640        * received or timeout expires. During synchronization, only            \
641        * error event is expected because read event is suppressed.            \
642        * Allows not to stall the main thread and detect errors on the         \
643        * notification socket that will make synchronization                   \
644        * incomplete                                                           \
645        */                                                                     \
646       vlib_process_wait_for_event_or_clock (vm,                               \
647                                             nm->sync_batch_delay_ms * 1e-3);  \
648       event_type = vlib_process_get_events (vm, &event_data);                 \
649       vec_reset_length (event_data);                                          \
650                                                                               \
651       /* If error event received, stop synchronization and repeat an          \
652        * attempt later                                                        \
653        */                                                                     \
654       if (event_type == NL_EVENT_ERR)                                         \
655         goto sync_later;                                                      \
656     }                                                                         \
657   while (!is_done);                                                           \
658   nl_##fn##_sync_end ();
659
660             foreach_sock_type
661 #undef _
662
663               /* Start processing notifications */
664               nm->nl_status = NL_STATUS_NOTIF_PROC;
665
666           /* Trigger messages processing if there are notifications received
667            * during synchronization
668            */
669           wait_time = (vec_len (nm->nl_msg_queue) != 0) ? 1e-3 : DAY_F64;
670
671         sync_later:
672           /* Close netlink synchronization sockets */
673 #define _(stype, mtype, tname, fn) lcp_nl_close_sync_socket (stype);
674           foreach_sock_type
675 #undef _
676         }
677       else
678         NL_ERROR ("Unknown status: %d", nm->nl_status);
679     }
680   return frame->n_vectors;
681 }
682
683 VLIB_REGISTER_NODE (nl_route_process_node, static) = {
684   .function = nl_route_process,
685   .name = "linux-cp-netlink-process",
686   .type = VLIB_NODE_TYPE_PROCESS,
687   .process_log2_n_stack_bytes = 17,
688 };
689
690 static int
691 nl_route_cb (struct nl_msg *msg, void *arg)
692 {
693   nl_main_t *nm = &nl_main;
694   nl_msg_info_t *msg_info = 0;
695
696   /* delay processing - increment ref count and queue for later */
697   vec_add2 (nm->nl_msg_queue, msg_info, 1);
698
699   /* store a timestamp for the message */
700   msg_info->ts = vlib_time_now (vlib_get_main ());
701   msg_info->msg = msg;
702   nlmsg_get (msg);
703
704   return 0;
705 }
706
707 int
708 lcp_nl_drain_messages (void)
709 {
710   int err;
711   nl_main_t *nm = &nl_main;
712
713   /* Read until there's an error */
714   while ((err = nl_recvmsgs_default (nm->sk_route)) > -1)
715     ;
716
717   /* If there was an error other then EAGAIN, signal process node */
718   if (err != -NLE_AGAIN)
719     vlib_process_signal_event (vlib_get_main (), nl_route_process_node.index,
720                                NL_EVENT_ERR, 0);
721   else
722     {
723       /* If netlink notification processing is active, signal process node
724        * there were notifications read
725        */
726       if (nm->nl_status == NL_STATUS_NOTIF_PROC)
727         vlib_process_signal_event (
728           vlib_get_main (), nl_route_process_node.index, NL_EVENT_READ, 0);
729     }
730
731   return err;
732 }
733
734 void
735 lcp_nl_pair_add_cb (lcp_itf_pair_t *pair)
736 {
737   lcp_nl_drain_messages ();
738 }
739
740 static clib_error_t *
741 nl_route_read_cb (clib_file_t *f)
742 {
743   int err;
744   err = lcp_nl_drain_messages ();
745   if (err < 0 && err != -NLE_AGAIN)
746     NL_ERROR ("Error reading netlink socket (fd %d): %s (%d)",
747               f->file_descriptor, nl_geterror (err), err);
748
749   return 0;
750 }
751
752 static clib_error_t *
753 nl_route_error_cb (clib_file_t *f)
754 {
755   NL_ERROR ("Error polling netlink socket (fd %d)", f->file_descriptor);
756
757   /* notify process node */
758   vlib_process_signal_event (vlib_get_main (), nl_route_process_node.index,
759                              NL_EVENT_ERR, 0);
760
761   return clib_error_return (0, "Error polling netlink socket %d",
762                             f->file_descriptor);
763 }
764
765 struct nl_cache *
766 lcp_nl_get_cache (lcp_nl_obj_t t)
767 {
768   nl_main_t *nm = &nl_main;
769
770   return nm->nl_caches[t];
771 }
772
773 /* Set the RX buffer size to be used on the netlink socket */
774 void
775 lcp_nl_set_buffer_size (u32 buf_size)
776 {
777   nl_main_t *nm = &nl_main;
778
779   nm->rx_buf_size = buf_size;
780
781   if (nm->sk_route)
782     nl_socket_set_buffer_size (nm->sk_route, nm->rx_buf_size, nm->tx_buf_size);
783 }
784
785 /* Set the batch size - maximum netlink messages to process at one time */
786 void
787 lcp_nl_set_batch_size (u32 batch_size)
788 {
789   nl_main_t *nm = &nl_main;
790
791   nm->batch_size = batch_size;
792 }
793
794 /* Set the batch delay - how long to wait in ms between processing batches */
795 void
796 lcp_nl_set_batch_delay (u32 batch_delay_ms)
797 {
798   nl_main_t *nm = &nl_main;
799
800   nm->batch_delay_ms = batch_delay_ms;
801 }
802
803 static clib_error_t *
804 lcp_itf_pair_config (vlib_main_t *vm, unformat_input_t *input)
805 {
806   u32 buf_size, batch_size, batch_delay_ms;
807
808   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
809     {
810       if (unformat (input, "nl-rx-buffer-size %u", &buf_size))
811         lcp_nl_set_buffer_size (buf_size);
812       else if (unformat (input, "nl-batch-size %u", &batch_size))
813         lcp_nl_set_batch_size (batch_size);
814       else if (unformat (input, "nl-batch-delay-ms %u", &batch_delay_ms))
815         lcp_nl_set_batch_delay (batch_delay_ms);
816       else
817         return clib_error_return (0, "invalid netlink option: %U",
818                                   format_unformat_error, input);
819     }
820
821   return NULL;
822 }
823
824 VLIB_CONFIG_FUNCTION (lcp_itf_pair_config, "linux-nl");
825
826 static void
827 lcp_nl_close_socket (void)
828 {
829   nl_main_t *nm = &nl_main;
830
831   /* delete existing fd from epoll fd set */
832   if (nm->clib_file_index != ~0)
833     {
834       clib_file_main_t *fm = &file_main;
835       clib_file_t *f = clib_file_get (fm, nm->clib_file_index);
836
837       if (f)
838         {
839           NL_INFO ("Stopping poll of fd %u", f->file_descriptor);
840           fm->file_update (f, UNIX_FILE_UPDATE_DELETE);
841         }
842       else
843         /* stored index was not a valid file, reset stored index to ~0 */
844         nm->clib_file_index = ~0;
845     }
846
847   /* If we already created a socket, close/free it */
848   if (nm->sk_route)
849     {
850       NL_INFO ("Closing netlink socket %d", nl_socket_get_fd (nm->sk_route));
851       nl_socket_free (nm->sk_route);
852       nm->sk_route = NULL;
853     }
854 }
855
856 static void
857 lcp_nl_open_socket (void)
858 {
859   nl_main_t *nm = &nl_main;
860   int dest_ns_fd, curr_ns_fd;
861
862   /* Allocate a new socket for both routes and acls
863    * Notifications do not use sequence numbers, disable sequence number
864    * checking.
865    * Define a callback function, which will be called for each notification
866    * received
867    */
868   nm->sk_route = nl_socket_alloc ();
869   nl_socket_disable_seq_check (nm->sk_route);
870
871   dest_ns_fd = lcp_get_default_ns_fd ();
872   if (dest_ns_fd)
873     {
874       curr_ns_fd = open ("/proc/self/ns/net", O_RDONLY);
875       setns (dest_ns_fd, CLONE_NEWNET);
876     }
877
878   nl_connect (nm->sk_route, NETLINK_ROUTE);
879
880   if (dest_ns_fd && curr_ns_fd >= 0)
881     {
882       setns (curr_ns_fd, CLONE_NEWNET);
883       close (curr_ns_fd);
884     }
885
886   /* Subscribe to all the 'routing' notifications on the route socket */
887   nl_socket_add_memberships (nm->sk_route, RTNLGRP_LINK, RTNLGRP_IPV6_IFADDR,
888                              RTNLGRP_IPV4_IFADDR, RTNLGRP_IPV4_ROUTE,
889                              RTNLGRP_IPV6_ROUTE, RTNLGRP_NEIGH, RTNLGRP_NOTIFY,
890 #ifdef RTNLGRP_MPLS_ROUTE /* not defined on CentOS/RHEL 7 */
891                              RTNLGRP_MPLS_ROUTE,
892 #endif
893                              RTNLGRP_IPV4_RULE, RTNLGRP_IPV6_RULE, 0);
894
895   /* Set socket in nonblocking mode and increase buffer sizes */
896   nl_socket_set_nonblocking (nm->sk_route);
897   nl_socket_set_buffer_size (nm->sk_route, nm->rx_buf_size, nm->tx_buf_size);
898
899   if (nm->clib_file_index == ~0)
900     {
901       clib_file_t rt_file = {
902         .read_function = nl_route_read_cb,
903         .error_function = nl_route_error_cb,
904         .file_descriptor = nl_socket_get_fd (nm->sk_route),
905         .description = format (0, "linux-cp netlink route socket"),
906       };
907
908       nm->clib_file_index = clib_file_add (&file_main, &rt_file);
909       NL_INFO ("Added file %u", nm->clib_file_index);
910     }
911   else
912     /* clib file already created and socket was closed due to error */
913     {
914       clib_file_main_t *fm = &file_main;
915       clib_file_t *f = clib_file_get (fm, nm->clib_file_index);
916
917       f->file_descriptor = nl_socket_get_fd (nm->sk_route);
918       fm->file_update (f, UNIX_FILE_UPDATE_ADD);
919       NL_INFO ("Starting poll of %d", f->file_descriptor);
920     }
921
922   nl_socket_modify_cb (nm->sk_route, NL_CB_VALID, NL_CB_CUSTOM, nl_route_cb,
923                        NULL);
924   NL_INFO ("Opened netlink socket %d", nl_socket_get_fd (nm->sk_route));
925 }
926
927 static void
928 lcp_nl_open_sync_socket (nl_sock_type_t sock_type)
929 {
930   nl_main_t *nm = &nl_main;
931   int dest_ns_fd, curr_ns_fd;
932   struct nl_sock *sk_route;
933
934   /* Allocate a new blocking socket for routes that will be used for dump
935    * requests. Buffer sizes are left default because replies to dump requests
936    * are flow-controlled and the kernel will not overflow the socket by sending
937    * these
938    */
939
940   nm->sk_route_sync[sock_type] = sk_route = nl_socket_alloc ();
941
942   dest_ns_fd = lcp_get_default_ns_fd ();
943   if (dest_ns_fd > 0)
944     {
945       curr_ns_fd = clib_netns_open (NULL /* self */);
946       if (clib_setns (dest_ns_fd) == -1)
947         NL_ERROR ("Cannot set destination ns");
948     }
949
950   nl_connect (sk_route, NETLINK_ROUTE);
951
952   if (dest_ns_fd > 0)
953     {
954       if (curr_ns_fd == -1)
955         {
956           NL_ERROR ("No previous ns to set");
957         }
958       else
959         {
960           if (clib_setns (curr_ns_fd) == -1)
961             NL_ERROR ("Cannot set previous ns");
962           close (curr_ns_fd);
963         }
964     }
965
966   NL_INFO ("Opened netlink synchronization socket %d of type %d",
967            nl_socket_get_fd (sk_route), sock_type);
968 }
969
970 static void
971 lcp_nl_close_sync_socket (nl_sock_type_t sock_type)
972 {
973   nl_main_t *nm = &nl_main;
974   struct nl_sock *sk_route = nm->sk_route_sync[sock_type];
975
976   if (sk_route)
977     {
978       NL_INFO ("Closing netlink synchronization socket %d of type %d",
979                nl_socket_get_fd (sk_route), sock_type);
980       nl_socket_free (sk_route);
981       nm->sk_route_sync[sock_type] = NULL;
982     }
983 }
984
985 #include <vnet/plugin/plugin.h>
986 clib_error_t *
987 lcp_nl_init (vlib_main_t *vm)
988 {
989   nl_main_t *nm = &nl_main;
990   lcp_itf_pair_vft_t nl_itf_pair_vft = {
991     .pair_add_fn = lcp_nl_pair_add_cb,
992   };
993
994   nm->nl_status = NL_STATUS_NOTIF_PROC;
995   nm->clib_file_index = ~0;
996   nm->nl_logger = vlib_log_register_class ("nl", "nl");
997
998   lcp_nl_open_socket ();
999   lcp_itf_pair_register_vft (&nl_itf_pair_vft);
1000
1001   return (NULL);
1002 }
1003
1004 VLIB_INIT_FUNCTION (lcp_nl_init) = {
1005   .runs_after = VLIB_INITS ("lcp_interface_init", "tuntap_init",
1006                             "ip_neighbor_init"),
1007 };
1008
1009 #include <vpp/app/version.h>
1010 VLIB_PLUGIN_REGISTER () = {
1011   .version = VPP_BUILD_VER,
1012   .description = "linux Control Plane - Netlink listener",
1013   .default_disabled = 1,
1014 };
1015
1016 /*
1017  * fd.io coding-style-patch-verification: ON
1018  *
1019  * Local Variables:
1020  * eval: (c-set-style "gnu")
1021  * End:
1022  */