linux-cp: Add VPP->Linux synchronization
[vpp.git] / src / plugins / linux-cp / lcp_interface.c
1 /*
2  * Copyright (c) 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 #define _GNU_SOURCE
17 #include <fcntl.h>
18 #include <ctype.h>
19 #include <sys/socket.h>
20 #include <net/if.h>
21
22 #include <linux-cp/lcp_interface.h>
23 #include <netlink/route/link/vlan.h>
24 #include <linux/if_ether.h>
25
26 #include <vnet/plugin/plugin.h>
27 #include <vnet/plugin/plugin.h>
28
29 #include <vppinfra/linux/netns.h>
30
31 #include <vnet/ip/ip_punt_drop.h>
32 #include <vnet/fib/fib_table.h>
33 #include <vnet/adj/adj_mcast.h>
34 #include <vnet/udp/udp.h>
35 #include <vnet/tcp/tcp.h>
36 #include <vnet/devices/tap/tap.h>
37 #include <vnet/devices/virtio/virtio.h>
38 #include <vnet/devices/netlink.h>
39 #include <vlibapi/api_helper_macros.h>
40 #include <vnet/ipsec/ipsec_punt.h>
41
42 vlib_log_class_t lcp_itf_pair_logger;
43
44 /**
45  * Pool of LIP objects
46  */
47 lcp_itf_pair_t *lcp_itf_pair_pool = NULL;
48
49 u32
50 lcp_itf_num_pairs (void)
51 {
52   return pool_elts (lcp_itf_pair_pool);
53 }
54
55 /**
56  * DBs of interface-pair objects:
57  *  - key'd by VIF (linux ID)
58  *  - key'd by VPP's physical interface
59  *  - number of shared uses of VPP's tap/host interface
60  */
61 static uword *lip_db_by_vif;
62 index_t *lip_db_by_phy;
63 u32 *lip_db_by_host;
64
65 /**
66  * vector of virtual function table
67  */
68 static lcp_itf_pair_vft_t *lcp_itf_vfts = NULL;
69
70 void
71 lcp_itf_pair_register_vft (lcp_itf_pair_vft_t *lcp_itf_vft)
72 {
73   vec_add1 (lcp_itf_vfts, *lcp_itf_vft);
74 }
75
76 u8 *
77 format_lcp_itf_pair (u8 *s, va_list *args)
78 {
79   vnet_main_t *vnm = vnet_get_main ();
80   lcp_itf_pair_t *lip = va_arg (*args, lcp_itf_pair_t *);
81   vnet_sw_interface_t *swif_phy;
82   vnet_sw_interface_t *swif_host;
83
84   s = format (s, "itf-pair: [%d]", lip - lcp_itf_pair_pool);
85
86   swif_phy = vnet_get_sw_interface_or_null (vnm, lip->lip_phy_sw_if_index);
87   if (!swif_phy)
88     s = format (s, " <no-phy-if>");
89   else
90     s = format (s, " %U", format_vnet_sw_interface_name, vnm, swif_phy);
91
92   swif_host = vnet_get_sw_interface_or_null (vnm, lip->lip_host_sw_if_index);
93   if (!swif_host)
94     s = format (s, " <no-host-if>");
95   else
96     s = format (s, " %U", format_vnet_sw_interface_name, vnm, swif_host);
97
98   s = format (s, " %v %d type %s", lip->lip_host_name, lip->lip_vif_index,
99               (lip->lip_host_type == LCP_ITF_HOST_TAP) ? "tap" : "tun");
100
101   if (lip->lip_namespace)
102     s = format (s, " netns %s", lip->lip_namespace);
103
104   return s;
105 }
106
107 static walk_rc_t
108 lcp_itf_pair_walk_show_cb (index_t api, void *ctx)
109 {
110   vlib_main_t *vm;
111   lcp_itf_pair_t *lip;
112
113   lip = lcp_itf_pair_get (api);
114   if (!lip)
115     return WALK_STOP;
116
117   vm = vlib_get_main ();
118   vlib_cli_output (vm, "%U\n", format_lcp_itf_pair, lip);
119
120   return WALK_CONTINUE;
121 }
122
123 void
124 lcp_itf_pair_show (u32 phy_sw_if_index)
125 {
126   vlib_main_t *vm;
127   u8 *ns;
128   index_t api;
129
130   vm = vlib_get_main ();
131   ns = lcp_get_default_ns ();
132   vlib_cli_output (vm, "lcp default netns '%s'\n",
133                    ns ? (char *) ns : "<unset>");
134   vlib_cli_output (vm, "lcp lcp-auto-subint %s\n",
135                    lcp_auto_subint () ? "on" : "off");
136   vlib_cli_output (vm, "lcp lcp-sync %s\n", lcp_sync () ? "on" : "off");
137
138   if (phy_sw_if_index == ~0)
139     {
140       lcp_itf_pair_walk (lcp_itf_pair_walk_show_cb, 0);
141     }
142   else
143     {
144       api = lcp_itf_pair_find_by_phy (phy_sw_if_index);
145       if (api != INDEX_INVALID)
146         lcp_itf_pair_walk_show_cb (api, 0);
147     }
148 }
149
150 lcp_itf_pair_t *
151 lcp_itf_pair_get (u32 index)
152 {
153   if (!lcp_itf_pair_pool)
154     return NULL;
155   if (index == INDEX_INVALID)
156     return NULL;
157
158   return pool_elt_at_index (lcp_itf_pair_pool, index);
159 }
160
161 index_t
162 lcp_itf_pair_find_by_vif (u32 vif_index)
163 {
164   uword *p;
165
166   p = hash_get (lip_db_by_vif, vif_index);
167
168   if (p)
169     return p[0];
170
171   return INDEX_INVALID;
172 }
173
174 const char *lcp_itf_l3_feat_names[N_LCP_ITF_HOST][N_AF] = {
175   [LCP_ITF_HOST_TAP] = {
176     [AF_IP4] = "linux-cp-xc-ip4",
177     [AF_IP6] = "linux-cp-xc-ip6",
178   },
179   [LCP_ITF_HOST_TUN] = {
180     [AF_IP4] = "linux-cp-xc-l3-ip4",
181     [AF_IP6] = "linux-cp-xc-l3-ip6",
182   },
183 };
184
185 const fib_route_path_flags_t lcp_itf_route_path_flags[N_LCP_ITF_HOST] = {
186   [LCP_ITF_HOST_TAP] = FIB_ROUTE_PATH_DVR,
187   [LCP_ITF_HOST_TUN] = FIB_ROUTE_PATH_FLAG_NONE,
188 };
189
190 static void
191 lcp_itf_unset_adjs (lcp_itf_pair_t *lip)
192 {
193   adj_unlock (lip->lip_phy_adjs.adj_index[AF_IP4]);
194   adj_unlock (lip->lip_phy_adjs.adj_index[AF_IP6]);
195 }
196
197 static void
198 lcp_itf_set_adjs (lcp_itf_pair_t *lip)
199 {
200   if (lip->lip_host_type == LCP_ITF_HOST_TUN)
201     {
202       lip->lip_phy_adjs.adj_index[AF_IP4] = adj_nbr_add_or_lock (
203         FIB_PROTOCOL_IP4, VNET_LINK_IP4, &zero_addr, lip->lip_phy_sw_if_index);
204       lip->lip_phy_adjs.adj_index[AF_IP6] = adj_nbr_add_or_lock (
205         FIB_PROTOCOL_IP6, VNET_LINK_IP6, &zero_addr, lip->lip_phy_sw_if_index);
206     }
207   else
208     {
209       lip->lip_phy_adjs.adj_index[AF_IP4] = adj_mcast_add_or_lock (
210         FIB_PROTOCOL_IP4, VNET_LINK_IP4, lip->lip_phy_sw_if_index);
211       lip->lip_phy_adjs.adj_index[AF_IP6] = adj_mcast_add_or_lock (
212         FIB_PROTOCOL_IP6, VNET_LINK_IP6, lip->lip_phy_sw_if_index);
213     }
214
215   ip_adjacency_t *adj;
216
217   adj = adj_get (lip->lip_phy_adjs.adj_index[AF_IP4]);
218
219   lip->lip_rewrite_len = adj->rewrite_header.data_bytes;
220 }
221
222 int
223 lcp_itf_pair_add (u32 host_sw_if_index, u32 phy_sw_if_index, u8 *host_name,
224                   u32 host_index, lip_host_type_t host_type, u8 *ns)
225 {
226   index_t lipi;
227   lcp_itf_pair_t *lip;
228
229   if (host_sw_if_index == ~0)
230     {
231       LCP_ITF_PAIR_ERR ("pair_add: Cannot add LIP - invalid host");
232       return VNET_API_ERROR_INVALID_SW_IF_INDEX;
233     }
234
235   lipi = lcp_itf_pair_find_by_phy (phy_sw_if_index);
236
237   if (lipi != INDEX_INVALID)
238     return VNET_API_ERROR_VALUE_EXIST;
239
240   LCP_ITF_PAIR_INFO ("add: host:%U phy:%U, host_if:%v vif:%d ns:%s",
241                      format_vnet_sw_if_index_name, vnet_get_main (),
242                      host_sw_if_index, format_vnet_sw_if_index_name,
243                      vnet_get_main (), phy_sw_if_index, host_name, host_index,
244                      ns);
245
246   /*
247    * Create a new pair.
248    */
249   pool_get (lcp_itf_pair_pool, lip);
250
251   lipi = lip - lcp_itf_pair_pool;
252
253   vec_validate_init_empty (lip_db_by_phy, phy_sw_if_index, INDEX_INVALID);
254   vec_validate_init_empty (lip_db_by_host, host_sw_if_index, INDEX_INVALID);
255   lip_db_by_phy[phy_sw_if_index] = lipi;
256   lip_db_by_host[host_sw_if_index] = lipi;
257   hash_set (lip_db_by_vif, host_index, lipi);
258
259   lip->lip_host_sw_if_index = host_sw_if_index;
260   lip->lip_phy_sw_if_index = phy_sw_if_index;
261   lip->lip_host_name = vec_dup (host_name);
262   lip->lip_host_type = host_type;
263   lip->lip_vif_index = host_index;
264   lip->lip_namespace = vec_dup (ns);
265
266   /*
267    * First use of this host interface.
268    * Enable the x-connect feature on the host to send
269    * all packets to the phy.
270    */
271   ip_address_family_t af;
272
273   FOR_EACH_IP_ADDRESS_FAMILY (af)
274   ip_feature_enable_disable (af, N_SAFI, IP_FEATURE_INPUT,
275                              lcp_itf_l3_feat_names[lip->lip_host_type][af],
276                              lip->lip_host_sw_if_index, 1, NULL, 0);
277
278   /*
279    * Configure passive punt to the host interface.
280    */
281   fib_route_path_t *rpaths = NULL, rpath = {
282     .frp_flags = lcp_itf_route_path_flags[lip->lip_host_type],
283     .frp_proto = DPO_PROTO_IP4,
284     .frp_sw_if_index = lip->lip_host_sw_if_index,
285     .frp_weight = 1,
286     .frp_fib_index = ~0,
287   };
288
289   vec_add1 (rpaths, rpath);
290
291   ip4_punt_redirect_add_paths (lip->lip_phy_sw_if_index, rpaths);
292
293   rpaths[0].frp_proto = DPO_PROTO_IP6;
294
295   ip6_punt_redirect_add_paths (lip->lip_phy_sw_if_index, rpaths);
296
297   vec_free (rpaths);
298
299   lcp_itf_set_adjs (lip);
300
301   /* enable ARP feature node for broadcast interfaces */
302   if (lip->lip_host_type != LCP_ITF_HOST_TUN)
303     {
304       vnet_feature_enable_disable ("arp", "linux-cp-arp-phy",
305                                    lip->lip_phy_sw_if_index, 1, NULL, 0);
306       vnet_feature_enable_disable ("arp", "linux-cp-arp-host",
307                                    lip->lip_host_sw_if_index, 1, NULL, 0);
308     }
309   else
310     {
311       vnet_feature_enable_disable ("ip4-punt", "linux-cp-punt-l3", 0, 1, NULL,
312                                    0);
313       vnet_feature_enable_disable ("ip6-punt", "linux-cp-punt-l3", 0, 1, NULL,
314                                    0);
315     }
316
317   /* invoke registered callbacks for pair addition */
318   lcp_itf_pair_vft_t *vft;
319
320   vec_foreach (vft, lcp_itf_vfts)
321     {
322       if (vft->pair_add_fn)
323         vft->pair_add_fn (lip);
324     }
325
326   /* set timestamp when pair entered service */
327   lip->lip_create_ts = vlib_time_now (vlib_get_main ());
328
329   return 0;
330 }
331
332 static clib_error_t *
333 lcp_netlink_add_link_vlan (int parent, u32 vlan, u16 proto, const char *name)
334 {
335   struct rtnl_link *link;
336   struct nl_sock *sk;
337   int err;
338
339   sk = nl_socket_alloc ();
340   if ((err = nl_connect (sk, NETLINK_ROUTE)) < 0)
341     {
342       LCP_ITF_PAIR_ERR ("netlink_add_link_vlan: connect error: %s",
343                         nl_geterror (err));
344       return clib_error_return (NULL, "Unable to connect socket: %d", err);
345     }
346
347   link = rtnl_link_vlan_alloc ();
348
349   rtnl_link_set_link (link, parent);
350   rtnl_link_set_name (link, name);
351   rtnl_link_vlan_set_id (link, vlan);
352   rtnl_link_vlan_set_protocol (link, htons (proto));
353
354   if ((err = rtnl_link_add (sk, link, NLM_F_CREATE)) < 0)
355     {
356       LCP_ITF_PAIR_ERR ("netlink_add_link_vlan: link add error: %s",
357                         nl_geterror (err));
358       return clib_error_return (NULL, "Unable to add link %s: %d", name, err);
359     }
360
361   rtnl_link_put (link);
362   nl_close (sk);
363
364   return NULL;
365 }
366
367 static clib_error_t *
368 lcp_netlink_del_link (const char *name)
369 {
370   struct rtnl_link *link;
371   struct nl_sock *sk;
372   int err;
373
374   sk = nl_socket_alloc ();
375   if ((err = nl_connect (sk, NETLINK_ROUTE)) < 0)
376     return clib_error_return (NULL, "Unable to connect socket: %d", err);
377
378   link = rtnl_link_alloc ();
379   rtnl_link_set_name (link, name);
380
381   if ((err = rtnl_link_delete (sk, link)) < 0)
382     return clib_error_return (NULL, "Unable to del link %s: %d", name, err);
383
384   rtnl_link_put (link);
385   nl_close (sk);
386
387   return NULL;
388 }
389
390 int
391 lcp_itf_pair_del (u32 phy_sw_if_index)
392 {
393   ip_address_family_t af;
394   lcp_itf_pair_t *lip;
395   u32 lipi;
396   lcp_itf_pair_vft_t *vft;
397
398   lipi = lcp_itf_pair_find_by_phy (phy_sw_if_index);
399
400   if (lipi == INDEX_INVALID)
401     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
402
403   lip = lcp_itf_pair_get (lipi);
404
405   LCP_ITF_PAIR_NOTICE (
406     "pair_del: host:%U phy:%U host_if:%s vif:%d ns:%s",
407     format_vnet_sw_if_index_name, vnet_get_main (), lip->lip_host_sw_if_index,
408     format_vnet_sw_if_index_name, vnet_get_main (), lip->lip_phy_sw_if_index,
409     lip->lip_host_name, lip->lip_vif_index, lip->lip_namespace);
410
411   /* invoke registered callbacks for pair deletion */
412   vec_foreach (vft, lcp_itf_vfts)
413     {
414       if (vft->pair_del_fn)
415         vft->pair_del_fn (lip);
416     }
417
418   FOR_EACH_IP_ADDRESS_FAMILY (af)
419   ip_feature_enable_disable (af, N_SAFI, IP_FEATURE_INPUT,
420                              lcp_itf_l3_feat_names[lip->lip_host_type][af],
421                              lip->lip_host_sw_if_index, 0, NULL, 0);
422
423   lcp_itf_unset_adjs (lip);
424
425   ip4_punt_redirect_del (lip->lip_phy_sw_if_index);
426   ip6_punt_redirect_del (lip->lip_phy_sw_if_index);
427
428   /* disable ARP feature node for broadcast interfaces */
429   if (lip->lip_host_type != LCP_ITF_HOST_TUN)
430     {
431       vnet_feature_enable_disable ("arp", "linux-cp-arp-phy",
432                                    lip->lip_phy_sw_if_index, 0, NULL, 0);
433       vnet_feature_enable_disable ("arp", "linux-cp-arp-host",
434                                    lip->lip_host_sw_if_index, 0, NULL, 0);
435     }
436   else
437     {
438       vnet_feature_enable_disable ("ip4-punt", "linux-cp-punt-l3", 0, 0, NULL,
439                                    0);
440       vnet_feature_enable_disable ("ip6-punt", "linux-cp-punt-l3", 0, 0, NULL,
441                                    0);
442     }
443
444   lip_db_by_phy[phy_sw_if_index] = INDEX_INVALID;
445   lip_db_by_host[lip->lip_host_sw_if_index] = INDEX_INVALID;
446   hash_unset (lip_db_by_vif, lip->lip_vif_index);
447
448   vec_free (lip->lip_host_name);
449   vec_free (lip->lip_namespace);
450   pool_put (lcp_itf_pair_pool, lip);
451
452   return 0;
453 }
454
455 static void
456 lcp_itf_pair_delete_by_index (index_t lipi)
457 {
458   u32 host_sw_if_index;
459   lcp_itf_pair_t *lip;
460   u8 *host_name, *ns;
461
462   lip = lcp_itf_pair_get (lipi);
463
464   host_name = vec_dup (lip->lip_host_name);
465   host_sw_if_index = lip->lip_host_sw_if_index;
466   ns = vec_dup (lip->lip_namespace);
467
468   lcp_itf_pair_del (lip->lip_phy_sw_if_index);
469
470   if (vnet_sw_interface_is_sub (vnet_get_main (), host_sw_if_index))
471     {
472       int curr_ns_fd = -1;
473       int vif_ns_fd = -1;
474       if (ns)
475         {
476           curr_ns_fd = clib_netns_open (NULL /* self */);
477           vif_ns_fd = clib_netns_open ((u8 *) ns);
478           if (vif_ns_fd != -1)
479             clib_setns (vif_ns_fd);
480         }
481
482       lcp_netlink_del_link ((const char *) host_name);
483       if (vif_ns_fd != -1)
484         close (vif_ns_fd);
485
486       if (curr_ns_fd != -1)
487         {
488           clib_setns (curr_ns_fd);
489           close (curr_ns_fd);
490         }
491
492       vnet_delete_sub_interface (host_sw_if_index);
493     }
494   else
495     tap_delete_if (vlib_get_main (), host_sw_if_index);
496
497   vec_free (host_name);
498   vec_free (ns);
499 }
500
501 int
502 lcp_itf_pair_delete (u32 phy_sw_if_index)
503 {
504   index_t lipi;
505
506   lipi = lcp_itf_pair_find_by_phy (phy_sw_if_index);
507
508   if (lipi == INDEX_INVALID)
509     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
510
511   lcp_itf_pair_delete_by_index (lipi);
512
513   return 0;
514 }
515
516 /**
517  * lcp_itf_interface_add_del
518  *
519  * Registered to receive interface Add and delete notifications
520  */
521 static clib_error_t *
522 lcp_itf_interface_add_del (vnet_main_t *vnm, u32 sw_if_index, u32 is_add)
523 {
524   if (!is_add)
525     /* remove any interface pair we have for this interface */
526     lcp_itf_pair_delete (sw_if_index);
527
528   return (NULL);
529 }
530
531 VNET_SW_INTERFACE_ADD_DEL_FUNCTION (lcp_itf_interface_add_del);
532
533 void
534 lcp_itf_pair_walk (lcp_itf_pair_walk_cb_t cb, void *ctx)
535 {
536   u32 api;
537
538   pool_foreach_index (api, lcp_itf_pair_pool)
539     {
540       if (!cb (api, ctx))
541         break;
542     };
543 }
544
545 static clib_error_t *
546 lcp_itf_pair_config (vlib_main_t *vm, unformat_input_t *input)
547 {
548   u8 *default_ns;
549
550   default_ns = NULL;
551
552   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
553     {
554       if (unformat (input, "default netns %v", &default_ns))
555         {
556           vec_add1 (default_ns, 0);
557           if (lcp_set_default_ns (default_ns) < 0)
558             {
559               return clib_error_return (0,
560                                         "linux-cp default namespace must"
561                                         " be less than %d characters",
562                                         LCP_NS_LEN);
563             }
564         }
565       else if (unformat (input, "lcp-auto-subint"))
566         lcp_set_auto_subint (1 /* is_auto */);
567       else if (unformat (input, "lcp-sync"))
568         lcp_set_sync (1 /* is_auto */);
569       else
570         return clib_error_return (0, "interfaces not found");
571     }
572
573   vec_free (default_ns);
574
575   return NULL;
576 }
577
578 VLIB_EARLY_CONFIG_FUNCTION (lcp_itf_pair_config, "linux-cp");
579
580 /*
581  * Returns 1 if the tap name is valid.
582  * Returns 0 if the tap name is invalid.
583  */
584 static int
585 lcp_validate_if_name (u8 *name)
586 {
587   int len;
588   char *p;
589
590   p = (char *) name;
591   len = clib_strnlen (p, IFNAMSIZ);
592   if (len >= IFNAMSIZ)
593     return 0;
594
595   for (; *p; ++p)
596     {
597       if (isalnum (*p))
598         continue;
599
600       switch (*p)
601         {
602         case '-':
603         case '_':
604         case '%':
605         case '@':
606         case ':':
607         case '.':
608           continue;
609         }
610
611       return 0;
612     }
613
614   return 1;
615 }
616
617 void
618 lcp_itf_set_link_state (const lcp_itf_pair_t *lip, u8 state)
619 {
620   int curr_ns_fd, vif_ns_fd;
621
622   if (!lip)
623     return;
624
625   curr_ns_fd = vif_ns_fd = -1;
626
627   if (lip->lip_namespace)
628     {
629       curr_ns_fd = clib_netns_open (NULL /* self */);
630       vif_ns_fd = clib_netns_open (lip->lip_namespace);
631       if (vif_ns_fd != -1)
632         clib_setns (vif_ns_fd);
633     }
634
635   /* Set the same link state on the netlink interface
636    */
637   vnet_netlink_set_link_state (lip->lip_vif_index, state);
638
639   if (vif_ns_fd != -1)
640     close (vif_ns_fd);
641
642   if (curr_ns_fd != -1)
643     {
644       clib_setns (curr_ns_fd);
645       close (curr_ns_fd);
646     }
647
648   return;
649 }
650
651 void
652 lcp_itf_set_interface_addr (const lcp_itf_pair_t *lip)
653 {
654   ip4_main_t *im4 = &ip4_main;
655   ip6_main_t *im6 = &ip6_main;
656   ip_lookup_main_t *lm4 = &im4->lookup_main;
657   ip_lookup_main_t *lm6 = &im6->lookup_main;
658   ip_interface_address_t *ia = 0;
659   int vif_ns_fd = -1;
660   int curr_ns_fd = -1;
661
662   if (!lip)
663     return;
664
665   if (lip->lip_namespace)
666     {
667       curr_ns_fd = clib_netns_open (NULL /* self */);
668       vif_ns_fd = clib_netns_open (lip->lip_namespace);
669       if (vif_ns_fd != -1)
670         clib_setns (vif_ns_fd);
671     }
672
673   /* Sync any IP4 addressing info into LCP */
674   foreach_ip_interface_address (
675     lm4, ia, lip->lip_phy_sw_if_index, 1 /* honor unnumbered */, ({
676       ip4_address_t *r4 = ip_interface_address_get_address (lm4, ia);
677       LCP_ITF_PAIR_NOTICE ("set_interface_addr: %U add ip4 %U/%d",
678                            format_lcp_itf_pair, lip, format_ip4_address, r4,
679                            ia->address_length);
680       vnet_netlink_add_ip4_addr (lip->lip_vif_index, r4, ia->address_length);
681     }));
682
683   /* Sync any IP6 addressing info into LCP */
684   foreach_ip_interface_address (
685     lm6, ia, lip->lip_phy_sw_if_index, 1 /* honor unnumbered */, ({
686       ip6_address_t *r6 = ip_interface_address_get_address (lm6, ia);
687       LCP_ITF_PAIR_NOTICE ("set_interface_addr: %U add ip6 %U/%d",
688                            format_lcp_itf_pair, lip, format_ip6_address, r6,
689                            ia->address_length);
690       vnet_netlink_add_ip6_addr (lip->lip_vif_index, r6, ia->address_length);
691     }));
692
693   if (vif_ns_fd != -1)
694     close (vif_ns_fd);
695
696   if (curr_ns_fd != -1)
697     {
698       clib_setns (curr_ns_fd);
699       close (curr_ns_fd);
700     }
701 }
702
703 typedef struct
704 {
705   u32 vlan;
706   bool dot1ad;
707
708   u32 matched_sw_if_index;
709 } lcp_itf_match_t;
710
711 static walk_rc_t
712 lcp_itf_pair_find_walk (vnet_main_t *vnm, u32 sw_if_index, void *arg)
713 {
714   lcp_itf_match_t *match = arg;
715   const vnet_sw_interface_t *sw;
716
717   sw = vnet_get_sw_interface (vnm, sw_if_index);
718   if (sw && (sw->sub.eth.inner_vlan_id == 0) &&
719       (sw->sub.eth.outer_vlan_id == match->vlan) &&
720       (sw->sub.eth.flags.dot1ad == match->dot1ad))
721     {
722       LCP_ITF_PAIR_DBG ("find_walk: found match outer %d dot1ad %d "
723                         "inner-dot1q %d: interface %U",
724                         sw->sub.eth.outer_vlan_id, sw->sub.eth.flags.dot1ad,
725                         sw->sub.eth.inner_vlan_id,
726                         format_vnet_sw_if_index_name, vnet_get_main (),
727                         sw->sw_if_index);
728       match->matched_sw_if_index = sw->sw_if_index;
729       return WALK_STOP;
730     }
731
732   return WALK_CONTINUE;
733 }
734
735 /* Return the index of the sub-int on the phy that has the given vlan and
736  * proto,
737  */
738 static index_t
739 lcp_itf_pair_find_by_outer_vlan (u32 sup_if_index, u16 vlan, bool dot1ad)
740 {
741   lcp_itf_match_t match;
742   const vnet_hw_interface_t *hw;
743
744   match.vlan = vlan;
745   match.dot1ad = dot1ad;
746   match.matched_sw_if_index = INDEX_INVALID;
747   hw = vnet_get_sup_hw_interface (vnet_get_main (), sup_if_index);
748
749   vnet_hw_interface_walk_sw (vnet_get_main (), hw->hw_if_index,
750                              lcp_itf_pair_find_walk, &match);
751
752   if (match.matched_sw_if_index >= vec_len (lip_db_by_phy))
753     return INDEX_INVALID;
754
755   return lip_db_by_phy[match.matched_sw_if_index];
756 }
757
758 int
759 lcp_itf_pair_create (u32 phy_sw_if_index, u8 *host_if_name,
760                      lip_host_type_t host_if_type, u8 *ns,
761                      u32 *host_sw_if_indexp)
762 {
763   vlib_main_t *vm;
764   vnet_main_t *vnm;
765   u32 vif_index = 0, host_sw_if_index;
766   const vnet_sw_interface_t *sw;
767   const vnet_hw_interface_t *hw;
768   const lcp_itf_pair_t *lip;
769
770   if (!vnet_sw_if_index_is_api_valid (phy_sw_if_index))
771     {
772       LCP_ITF_PAIR_ERR ("pair_create: invalid phy index %u", phy_sw_if_index);
773       return VNET_API_ERROR_INVALID_SW_IF_INDEX;
774     }
775
776   if (!lcp_validate_if_name (host_if_name))
777     {
778       LCP_ITF_PAIR_ERR ("pair_create: invalid host-if-name '%s'",
779                         host_if_name);
780       return VNET_API_ERROR_INVALID_ARGUMENT;
781     }
782
783   vnm = vnet_get_main ();
784   sw = vnet_get_sw_interface (vnm, phy_sw_if_index);
785   hw = vnet_get_sup_hw_interface (vnm, phy_sw_if_index);
786   if (!sw || !hw)
787     {
788       LCP_ITF_PAIR_ERR ("pair_create: invalid interface");
789       return VNET_API_ERROR_INVALID_SW_IF_INDEX;
790     }
791
792   /*
793    * Use interface-specific netns if supplied.
794    * Otherwise, use netns if defined, otherwise use the OS default.
795    */
796   if (ns == 0 || ns[0] == 0)
797     ns = lcp_get_default_ns ();
798
799   /* sub interfaces do not need a tap created */
800   if (vnet_sw_interface_is_sub (vnm, phy_sw_if_index))
801     {
802       index_t parent_if_index;
803       int orig_ns_fd, ns_fd;
804       clib_error_t *err;
805       u16 outer_vlan, inner_vlan;
806       u16 outer_proto, inner_proto;
807       u16 vlan, proto;
808       u32 parent_vif_index;
809
810       err = vnet_sw_interface_supports_addressing (vnm, phy_sw_if_index);
811       if (err)
812         {
813           LCP_ITF_PAIR_ERR ("pair_create: can't create LCP for a "
814                             "sub-interface without exact-match set");
815           return VNET_API_ERROR_INVALID_ARGUMENT;
816         }
817
818       outer_vlan = sw->sub.eth.outer_vlan_id;
819       inner_vlan = sw->sub.eth.inner_vlan_id;
820       outer_proto = inner_proto = ETH_P_8021Q;
821       if (1 == sw->sub.eth.flags.dot1ad)
822         outer_proto = ETH_P_8021AD;
823
824       LCP_ITF_PAIR_INFO ("pair_create: subif: dot1%s outer %d inner %d on %U",
825                          sw->sub.eth.flags.dot1ad ? "ad" : "q", outer_vlan,
826                          inner_vlan, format_vnet_sw_if_index_name, vnm,
827                          hw->sw_if_index);
828
829       parent_if_index = lcp_itf_pair_find_by_phy (sw->sup_sw_if_index);
830       if (INDEX_INVALID == parent_if_index)
831         {
832           LCP_ITF_PAIR_ERR ("pair_create: can't find LCP for %U",
833                             format_vnet_sw_if_index_name, vnet_get_main (),
834                             sw->sup_sw_if_index);
835           return VNET_API_ERROR_INVALID_SW_IF_INDEX;
836         }
837       lip = lcp_itf_pair_get (parent_if_index);
838       if (!lip)
839         {
840           LCP_ITF_PAIR_ERR ("pair_create: can't create LCP for a "
841                             "sub-interface without an LCP on the parent");
842           return VNET_API_ERROR_INVALID_ARGUMENT;
843         }
844       LCP_ITF_PAIR_DBG ("pair_create: parent %U", format_lcp_itf_pair, lip);
845       parent_vif_index = lip->lip_vif_index;
846
847       /*
848        * see if the requested host interface has already been created
849        */
850       orig_ns_fd = ns_fd = -1;
851       err = NULL;
852
853       if (ns && ns[0] != 0)
854         {
855           orig_ns_fd = clib_netns_open (NULL /* self */);
856           ns_fd = clib_netns_open (ns);
857           if (orig_ns_fd == -1 || ns_fd == -1)
858             goto socket_close;
859
860           clib_setns (ns_fd);
861         }
862
863       vif_index = if_nametoindex ((const char *) host_if_name);
864
865       if (!vif_index)
866         {
867           /*
868            * no existing host interface, create it now
869            */
870
871           /*
872            * Find the parent tap:
873            * - if this is an outer VLAN, use the pair from the parent phy
874            * - if this is an inner VLAN, find the pair from the outer sub-int,
875            * which must exist.
876            */
877           if (inner_vlan)
878             {
879               index_t linux_parent_if_index;
880               const lcp_itf_pair_t *llip;
881
882               vlan = inner_vlan;
883               proto = inner_proto;
884               linux_parent_if_index = lcp_itf_pair_find_by_outer_vlan (
885                 hw->sw_if_index, sw->sub.eth.outer_vlan_id,
886                 sw->sub.eth.flags.dot1ad);
887               if (INDEX_INVALID == linux_parent_if_index ||
888                   !(llip = lcp_itf_pair_get (linux_parent_if_index)))
889                 {
890                   LCP_ITF_PAIR_ERR (
891                     "pair_create: can't find LCP for outer vlan %d "
892                     "proto %s on %U",
893                     outer_vlan,
894                     outer_proto == ETH_P_8021AD ? "dot1ad" : "dot1q",
895                     format_vnet_sw_if_index_name, vnm, hw->sw_if_index);
896                   err = clib_error_return (0, "parent pair not found");
897                   goto socket_close;
898                 }
899
900               LCP_ITF_PAIR_DBG ("pair_create: linux parent %U",
901                                 format_lcp_itf_pair, llip);
902               parent_vif_index = llip->lip_vif_index;
903             }
904           else
905             {
906               vlan = outer_vlan;
907               proto = outer_proto;
908             }
909
910           err = lcp_netlink_add_link_vlan (parent_vif_index, vlan, proto,
911                                            (const char *) host_if_name);
912           if (err != 0)
913             {
914               LCP_ITF_PAIR_ERR ("pair_create: cannot create link "
915                                 "outer(proto:0x%04x,vlan:%u).inner(proto:0x%"
916                                 "04x,vlan:%u) name:'%s'",
917                                 outer_proto, outer_vlan, inner_proto,
918                                 inner_vlan, host_if_name);
919             }
920
921           if (!err)
922             vif_index = if_nametoindex ((char *) host_if_name);
923         }
924
925       /*
926        * create a sub-interface on the tap
927        */
928       if (!err &&
929           vnet_create_sub_interface (lip->lip_host_sw_if_index, sw->sub.id,
930                                      sw->sub.eth.raw_flags, inner_vlan,
931                                      outer_vlan, &host_sw_if_index))
932         {
933           LCP_ITF_PAIR_ERR (
934             "pair_create: failed to create tap subint: %d.%d on %U",
935             outer_vlan, inner_vlan, format_vnet_sw_if_index_name, vnm,
936             lip->lip_host_sw_if_index);
937           err = clib_error_return (
938             0, "failed to create tap subint: %d.%d. on %U", outer_vlan,
939             inner_vlan, format_vnet_sw_if_index_name, vnm,
940             lip->lip_host_sw_if_index);
941         }
942
943     socket_close:
944       if (orig_ns_fd != -1)
945         {
946           clib_setns (orig_ns_fd);
947           close (orig_ns_fd);
948         }
949       if (ns_fd != -1)
950         close (ns_fd);
951
952       if (err)
953         return VNET_API_ERROR_INVALID_ARGUMENT;
954     }
955   else
956     {
957       tap_create_if_args_t args = {
958         .num_rx_queues = clib_max (1, vlib_num_workers ()),
959         .num_tx_queues = 1,
960         .id = hw->hw_if_index,
961         .sw_if_index = ~0,
962         .rx_ring_sz = 256,
963         .tx_ring_sz = 256,
964         .host_if_name = host_if_name,
965         .host_namespace = 0,
966       };
967       ethernet_interface_t *ei;
968
969       if (host_if_type == LCP_ITF_HOST_TUN)
970         args.tap_flags |= TAP_FLAG_TUN;
971       else
972         {
973           ei = pool_elt_at_index (ethernet_main.interfaces, hw->hw_instance);
974           mac_address_copy (&args.host_mac_addr, &ei->address.mac);
975         }
976
977       if (sw->mtu[VNET_MTU_L3])
978         {
979           args.host_mtu_set = 1;
980           args.host_mtu_size = sw->mtu[VNET_MTU_L3];
981         }
982
983       if (ns && ns[0] != 0)
984         args.host_namespace = ns;
985
986       vm = vlib_get_main ();
987       tap_create_if (vm, &args);
988
989       if (args.rv < 0)
990         {
991           LCP_ITF_PAIR_ERR ("pair_create: could not create tap, retval:%d",
992                             args.rv);
993           return args.rv;
994         }
995
996       /*
997        * The TAP interface does copy forward the host MTU based on the VPP
998        * interface's L3 MTU, but it should also ensure that the VPP tap
999        * interface has an MTU that is greater-or-equal to those. Considering
1000        * users can set the interfaces at runtime (set interface mtu packet ...)
1001        * ensure that the tap MTU is large enough, taking the VPP interface L3
1002        * if it's set, and otherwise a sensible default.
1003        */
1004       if (sw->mtu[VNET_MTU_L3])
1005         vnet_sw_interface_set_mtu (vnm, args.sw_if_index,
1006                                    sw->mtu[VNET_MTU_L3]);
1007       else
1008         vnet_sw_interface_set_mtu (vnm, args.sw_if_index,
1009                                    ETHERNET_MAX_PACKET_BYTES);
1010
1011       /*
1012        * get the hw and ethernet of the tap
1013        */
1014       hw = vnet_get_sup_hw_interface (vnm, args.sw_if_index);
1015       virtio_main_t *mm = &virtio_main;
1016       virtio_if_t *vif = pool_elt_at_index (mm->interfaces, hw->dev_instance);
1017
1018       /*
1019        * Leave the TAP permanently up on the VPP side.
1020        * This TAP will be shared by many sub-interface.
1021        * Therefore we can't use it to manage admin state.
1022        * force the tap in promiscuous mode.
1023        */
1024       if (host_if_type == LCP_ITF_HOST_TAP)
1025         {
1026           ei = pool_elt_at_index (ethernet_main.interfaces, hw->hw_instance);
1027           ei->flags |= ETHERNET_INTERFACE_FLAG_STATUS_L3;
1028         }
1029
1030       vif_index = vif->ifindex;
1031       host_sw_if_index = args.sw_if_index;
1032     }
1033
1034   if (!vif_index)
1035     {
1036       LCP_ITF_PAIR_INFO ("failed pair add (no vif index): {%U, %U, %s}",
1037                          format_vnet_sw_if_index_name, vnet_get_main (),
1038                          phy_sw_if_index, format_vnet_sw_if_index_name,
1039                          vnet_get_main (), host_sw_if_index, host_if_name);
1040       return -1;
1041     }
1042
1043   LCP_ITF_PAIR_INFO ("pair create: {%U, %U, %s}", format_vnet_sw_if_index_name,
1044                      vnet_get_main (), phy_sw_if_index,
1045                      format_vnet_sw_if_index_name, vnet_get_main (),
1046                      host_sw_if_index, host_if_name);
1047   lcp_itf_pair_add (host_sw_if_index, phy_sw_if_index, host_if_name, vif_index,
1048                     host_if_type, ns);
1049
1050   /*
1051    * Copy the link state from VPP into the host side.
1052    * The TAP is shared by many interfaces, always keep it up.
1053    * This controls whether the host can RX/TX.
1054    */
1055
1056   lip = lcp_itf_pair_get (lcp_itf_pair_find_by_vif (vif_index));
1057   LCP_ITF_PAIR_INFO ("pair create: %U sw-flags %u hw-flags %u",
1058                      format_lcp_itf_pair, lip, sw->flags, hw->flags);
1059   vnet_sw_interface_admin_up (vnm, host_sw_if_index);
1060   lcp_itf_set_link_state (lip, sw->flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP);
1061
1062   if (host_sw_if_indexp)
1063     *host_sw_if_indexp = host_sw_if_index;
1064
1065   return 0;
1066 }
1067
1068 static walk_rc_t
1069 lcp_itf_pair_walk_mark (index_t lipi, void *ctx)
1070 {
1071   lcp_itf_pair_t *lip;
1072
1073   lip = lcp_itf_pair_get (lipi);
1074
1075   lip->lip_flags |= LIP_FLAG_STALE;
1076
1077   return (WALK_CONTINUE);
1078 }
1079
1080 int
1081 lcp_itf_pair_replace_begin (void)
1082 {
1083   lcp_itf_pair_walk (lcp_itf_pair_walk_mark, NULL);
1084
1085   return (0);
1086 }
1087
1088 typedef struct lcp_itf_pair_sweep_ctx_t_
1089 {
1090   index_t *indicies;
1091 } lcp_itf_pair_sweep_ctx_t;
1092
1093 static walk_rc_t
1094 lcp_itf_pair_walk_sweep (index_t lipi, void *arg)
1095 {
1096   lcp_itf_pair_sweep_ctx_t *ctx = arg;
1097   lcp_itf_pair_t *lip;
1098
1099   lip = lcp_itf_pair_get (lipi);
1100
1101   if (lip->lip_flags & LIP_FLAG_STALE)
1102     vec_add1 (ctx->indicies, lipi);
1103
1104   return (WALK_CONTINUE);
1105 }
1106
1107 int
1108 lcp_itf_pair_replace_end (void)
1109 {
1110   lcp_itf_pair_sweep_ctx_t ctx = {
1111     .indicies = NULL,
1112   };
1113   index_t *lipi;
1114
1115   lcp_itf_pair_walk (lcp_itf_pair_walk_sweep, &ctx);
1116
1117   vec_foreach (lipi, ctx.indicies)
1118     lcp_itf_pair_delete_by_index (*lipi);
1119
1120   vec_free (ctx.indicies);
1121   return (0);
1122 }
1123
1124 static clib_error_t *
1125 lcp_itf_pair_link_up_down (vnet_main_t *vnm, u32 hw_if_index, u32 flags)
1126 {
1127   vnet_hw_interface_t *hi;
1128   vnet_sw_interface_t *si;
1129   index_t lipi;
1130   lcp_itf_pair_t *lip;
1131
1132   hi = vnet_get_hw_interface_or_null (vnm, hw_if_index);
1133   if (!hi)
1134     return 0;
1135
1136   lipi = lcp_itf_pair_find_by_phy (hi->sw_if_index);
1137   if (lipi == INDEX_INVALID)
1138     return 0;
1139
1140   lip = lcp_itf_pair_get (lipi);
1141   si = vnet_get_sw_interface_or_null (vnm, lip->lip_host_sw_if_index);
1142   if (!si)
1143     return 0;
1144
1145   if (!lcp_main.test_mode)
1146     {
1147       tap_set_carrier (si->hw_if_index,
1148                        (flags & VNET_HW_INTERFACE_FLAG_LINK_UP));
1149
1150       if (flags & VNET_HW_INTERFACE_FLAG_LINK_UP)
1151         {
1152           tap_set_speed (si->hw_if_index, hi->link_speed / 1000);
1153         }
1154     }
1155
1156   return 0;
1157 }
1158
1159 VNET_HW_INTERFACE_LINK_UP_DOWN_FUNCTION (lcp_itf_pair_link_up_down);
1160
1161 static clib_error_t *
1162 lcp_itf_pair_init (vlib_main_t *vm)
1163 {
1164   vlib_punt_hdl_t punt_hdl = vlib_punt_client_register ("linux-cp");
1165
1166   /* punt IKE */
1167   vlib_punt_register (punt_hdl, ipsec_punt_reason[IPSEC_PUNT_IP4_SPI_UDP_0],
1168                       "linux-cp-punt");
1169
1170   /* punt all unknown ports */
1171   udp_punt_unknown (vm, 0, 1);
1172   udp_punt_unknown (vm, 1, 1);
1173   tcp_punt_unknown (vm, 0, 1);
1174   tcp_punt_unknown (vm, 1, 1);
1175
1176   lcp_itf_pair_logger = vlib_log_register_class ("linux-cp", "itf");
1177
1178   return NULL;
1179 }
1180
1181 VLIB_INIT_FUNCTION (lcp_itf_pair_init) = {
1182   .runs_after = VLIB_INITS ("vnet_interface_init", "tcp_init", "udp_init"),
1183 };
1184
1185 /*
1186  * fd.io coding-style-patch-verification: ON
1187  *
1188  * Local Variables:
1189  * eval: (c-set-style "gnu")
1190  * End:
1191  */