nat: nat44-ed configuration refactor & cleanup
[vpp.git] / src / vnet / devices / tap / tap.c
1 /*
2  *------------------------------------------------------------------
3  * Copyright (c) 2017 Cisco and/or its affiliates.
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *------------------------------------------------------------------
16  */
17
18 #define _GNU_SOURCE
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/socket.h>
22 #include <fcntl.h>
23 #include <net/if.h>
24 #include <linux/if_tun.h>
25 #include <sys/ioctl.h>
26 #include <linux/ethtool.h>
27 #include <linux/sockios.h>
28 #include <sys/eventfd.h>
29 #include <net/if_arp.h>
30 #include <sched.h>
31 #include <limits.h>
32
33 #include <linux/netlink.h>
34 #include <linux/rtnetlink.h>
35
36 #include <vlib/vlib.h>
37 #include <vlib/physmem.h>
38 #include <vlib/unix/unix.h>
39 #include <vnet/ethernet/ethernet.h>
40 #include <vnet/ip/ip4_packet.h>
41 #include <vnet/ip/ip6_packet.h>
42 #include <vnet/devices/netlink.h>
43 #include <vnet/devices/virtio/virtio.h>
44 #include <vnet/devices/tap/tap.h>
45
46 tap_main_t tap_main;
47
48 #define tap_log_err(dev, f, ...)                        \
49   vlib_log (VLIB_LOG_LEVEL_ERR, tap_main.log_default, "tap%u: " f, dev->dev_instance, ## __VA_ARGS__)
50 #define tap_log_dbg(dev, f, ...)                        \
51   vlib_log (VLIB_LOG_LEVEL_DEBUG, tap_main.log_default, "tap%u: " f, dev->dev_instance, ## __VA_ARGS__)
52
53 #define _IOCTL(fd,a,...) \
54   if (ioctl (fd, a, __VA_ARGS__) < 0) \
55     { \
56       err = clib_error_return_unix (0, "ioctl(" #a ")"); \
57       tap_log_err (vif, "%U", format_clib_error, err); \
58       goto error; \
59     }
60
61   /* *INDENT-OFF* */
62 VNET_HW_INTERFACE_CLASS (tun_device_hw_interface_class, static) =
63 {
64   .name = "tun-device",
65   .flags = VNET_HW_INTERFACE_CLASS_FLAG_P2P,
66 };
67   /* *INDENT-ON* */
68
69 #define TUN_MAX_PACKET_BYTES     65355
70 #define TUN_MIN_PACKET_BYTES     64
71 #define TUN_DEFAULT_PACKET_BYTES 1500
72
73 static u32
74 virtio_eth_flag_change (vnet_main_t * vnm, vnet_hw_interface_t * hi,
75                         u32 flags)
76 {
77   /* nothing for now */
78   //TODO On MTU change call vnet_netlink_set_if_mtu
79   return 0;
80 }
81
82 static int
83 open_netns_fd (char *netns)
84 {
85   u8 *s = 0;
86   int fd;
87
88   if (strncmp (netns, "pid:", 4) == 0)
89     s = format (0, "/proc/%u/ns/net%c", atoi (netns + 4), 0);
90   else if (netns[0] == '/')
91     s = format (0, "%s%c", netns, 0);
92   else
93     s = format (0, "/var/run/netns/%s%c", netns, 0);
94
95   fd = open ((char *) s, O_RDONLY);
96   vec_free (s);
97   return fd;
98 }
99
100 #define TAP_MAX_INSTANCE 1024
101
102 static void
103 tap_free (vlib_main_t * vm, virtio_if_t * vif)
104 {
105   virtio_main_t *mm = &virtio_main;
106   tap_main_t *tm = &tap_main;
107   clib_error_t *err = 0;
108   int i;
109
110   /* *INDENT-OFF* */
111   vec_foreach_index (i, vif->vhost_fds) if (vif->vhost_fds[i] != -1)
112     close (vif->vhost_fds[i]);
113   vec_foreach_index (i, vif->rxq_vrings)
114     virtio_vring_free_rx (vm, vif, RX_QUEUE (i));
115   vec_foreach_index (i, vif->txq_vrings)
116     virtio_vring_free_tx (vm, vif, TX_QUEUE (i));
117   /* *INDENT-ON* */
118
119   if (vif->tap_fds)
120     {
121       _IOCTL (vif->tap_fds[0], TUNSETPERSIST, (void *) (uintptr_t) 0);
122       tap_log_dbg (vif, "TUNSETPERSIST: unset");
123     }
124 error:
125   vec_foreach_index (i, vif->tap_fds) close (vif->tap_fds[i]);
126
127   vec_free (vif->vhost_fds);
128   vec_free (vif->rxq_vrings);
129   vec_free (vif->txq_vrings);
130   vec_free (vif->host_if_name);
131   vec_free (vif->net_ns);
132   vec_free (vif->host_bridge);
133   clib_error_free (vif->error);
134
135   tm->tap_ids = clib_bitmap_set (tm->tap_ids, vif->id, 0);
136   clib_memset (vif, 0, sizeof (*vif));
137   pool_put (mm->interfaces, vif);
138 }
139
140 void
141 tap_create_if (vlib_main_t * vm, tap_create_if_args_t * args)
142 {
143   vlib_thread_main_t *thm = vlib_get_thread_main ();
144   vlib_physmem_main_t *vpm = &vm->physmem_main;
145   vnet_main_t *vnm = vnet_get_main ();
146   virtio_main_t *vim = &virtio_main;
147   tap_main_t *tm = &tap_main;
148   vnet_sw_interface_t *sw;
149   vnet_hw_interface_t *hw;
150   int i, num_vhost_queues;
151   int old_netns_fd = -1;
152   struct ifreq ifr = {.ifr_flags = IFF_NO_PI | IFF_VNET_HDR };
153   struct ifreq get_ifr = {.ifr_flags = 0 };
154   size_t hdrsz;
155   vhost_memory_t *vhost_mem = 0;
156   virtio_if_t *vif = 0;
157   clib_error_t *err = 0;
158   unsigned int tap_features;
159   int tfd = -1, qfd = -1, vfd = -1, nfd = -1;
160   char *host_if_name = 0;
161   unsigned int offload = 0;
162   int sndbuf = 0;
163
164   if (args->id != ~0)
165     {
166       if (clib_bitmap_get (tm->tap_ids, args->id))
167         {
168           args->rv = VNET_API_ERROR_INVALID_INTERFACE;
169           args->error = clib_error_return (0, "interface already exists");
170           return;
171         }
172     }
173   else
174     {
175       args->id = clib_bitmap_first_clear (tm->tap_ids);
176     }
177
178   if (args->id > TAP_MAX_INSTANCE)
179     {
180       args->rv = VNET_API_ERROR_UNSPECIFIED;
181       args->error = clib_error_return (0, "cannot find free interface id");
182       return;
183     }
184
185   pool_get_zero (vim->interfaces, vif);
186
187   if (args->tap_flags & TAP_FLAG_TUN)
188     {
189       vif->type = VIRTIO_IF_TYPE_TUN;
190       ifr.ifr_flags |= IFF_TUN;
191
192       /*
193        * From kernel 4.20, xdp support has been added in tun_sendmsg.
194        * If sndbuf == INT_MAX, vhost batches the packet and processes
195        * them using xdp data path for tun driver. It assumes packets
196        * are ethernet frames (It needs to be fixed).
197        * To avoid xdp data path in tun driver, sndbuf value should
198        * be < INT_MAX.
199        */
200       sndbuf = INT_MAX - 1;
201     }
202   else
203     {
204       vif->type = VIRTIO_IF_TYPE_TAP;
205       ifr.ifr_flags |= IFF_TAP;
206       sndbuf = INT_MAX;
207     }
208
209   vif->dev_instance = vif - vim->interfaces;
210   vif->id = args->id;
211   vif->num_txqs = thm->n_vlib_mains;
212   vif->num_rxqs = clib_max (args->num_rx_queues, 1);
213
214   if (args->tap_flags & TAP_FLAG_ATTACH)
215     {
216       if (args->host_if_name != NULL)
217         {
218           host_if_name = (char *) args->host_if_name;
219           clib_memcpy (ifr.ifr_name, host_if_name,
220                        clib_min (IFNAMSIZ, vec_len (host_if_name)));
221         }
222       else
223         {
224           args->rv = VNET_API_ERROR_NO_MATCHING_INTERFACE;
225           err = clib_error_return (0, "host_if_name is not provided");
226           goto error;
227         }
228       if (args->host_namespace)
229         {
230           old_netns_fd = open ("/proc/self/ns/net", O_RDONLY);
231           if ((nfd = open_netns_fd ((char *) args->host_namespace)) == -1)
232             {
233               args->rv = VNET_API_ERROR_SYSCALL_ERROR_2;
234               args->error = clib_error_return_unix (0, "open_netns_fd '%s'",
235                                                     args->host_namespace);
236               goto error;
237             }
238           if (setns (nfd, CLONE_NEWNET) == -1)
239             {
240               args->rv = VNET_API_ERROR_SYSCALL_ERROR_3;
241               args->error = clib_error_return_unix (0, "setns '%s'",
242                                                     args->host_namespace);
243               goto error;
244             }
245         }
246     }
247
248   if ((tfd = open ("/dev/net/tun", O_RDWR | O_NONBLOCK)) < 0)
249     {
250       args->rv = VNET_API_ERROR_SYSCALL_ERROR_2;
251       args->error = clib_error_return_unix (0, "open '/dev/net/tun'");
252       goto error;
253     }
254   vec_add1 (vif->tap_fds, tfd);
255   tap_log_dbg (vif, "open tap fd %d", tfd);
256
257   _IOCTL (tfd, TUNGETFEATURES, &tap_features);
258   tap_log_dbg (vif, "TUNGETFEATURES: features 0x%lx", tap_features);
259   if ((tap_features & IFF_VNET_HDR) == 0)
260     {
261       args->rv = VNET_API_ERROR_SYSCALL_ERROR_2;
262       args->error = clib_error_return (0, "vhost-net backend not available");
263       goto error;
264     }
265
266   if ((tap_features & IFF_MULTI_QUEUE) == 0)
267     {
268       if (vif->num_rxqs > 1)
269         {
270           args->rv = VNET_API_ERROR_SYSCALL_ERROR_2;
271           args->error = clib_error_return (0, "multiqueue not supported");
272           goto error;
273         }
274       vif->num_rxqs = vif->num_txqs = 1;
275     }
276   else
277     ifr.ifr_flags |= IFF_MULTI_QUEUE;
278
279   hdrsz = sizeof (virtio_net_hdr_v1_t);
280   if (args->tap_flags & TAP_FLAG_GSO)
281     {
282       offload = TUN_F_CSUM | TUN_F_TSO4 | TUN_F_TSO6;
283       vif->gso_enabled = 1;
284     }
285   else if (args->tap_flags & TAP_FLAG_CSUM_OFFLOAD)
286     {
287       offload = TUN_F_CSUM;
288       vif->csum_offload_enabled = 1;
289     }
290
291   _IOCTL (tfd, TUNSETIFF, (void *) &ifr);
292   tap_log_dbg (vif, "TUNSETIFF fd %d name %s flags 0x%x", tfd,
293                ifr.ifr_ifrn.ifrn_name, ifr.ifr_flags);
294
295   vif->ifindex = if_nametoindex (ifr.ifr_ifrn.ifrn_name);
296   tap_log_dbg (vif, "ifindex %d", vif->ifindex);
297
298   if (!args->host_if_name)
299     host_if_name = ifr.ifr_ifrn.ifrn_name;
300   else
301     host_if_name = (char *) args->host_if_name;
302
303   /*
304    * unset the persistence when attaching to existing
305    * interface
306    */
307   if (args->tap_flags & TAP_FLAG_ATTACH)
308     {
309       _IOCTL (tfd, TUNSETPERSIST, (void *) (uintptr_t) 0);
310       tap_log_dbg (vif, "TUNSETPERSIST: unset");
311     }
312
313   /* set the persistence */
314   if (args->tap_flags & TAP_FLAG_PERSIST)
315     {
316       _IOCTL (tfd, TUNSETPERSIST, (void *) (uintptr_t) 1);
317       tap_log_dbg (vif, "TUNSETPERSIST: set");
318
319       /* verify persistence is set, read the flags */
320       _IOCTL (tfd, TUNGETIFF, (void *) &get_ifr);
321       tap_log_dbg (vif, "TUNGETIFF: flags 0x%lx", get_ifr.ifr_flags);
322       if ((get_ifr.ifr_flags & IFF_PERSIST) == 0)
323         {
324           args->rv = VNET_API_ERROR_SYSCALL_ERROR_2;
325           args->error = clib_error_return (0, "persistence not supported");
326           goto error;
327         }
328     }
329
330   /* create additional queues on the linux side.
331    * we create as many linux queue pairs as we have rx queues
332    */
333   for (i = 1; i < vif->num_rxqs; i++)
334     {
335       if ((qfd = open ("/dev/net/tun", O_RDWR | O_NONBLOCK)) < 0)
336         {
337           args->rv = VNET_API_ERROR_SYSCALL_ERROR_2;
338           args->error = clib_error_return_unix (0, "open '/dev/net/tun'");
339           goto error;
340         }
341       _IOCTL (qfd, TUNSETIFF, (void *) &ifr);
342       tap_log_dbg (vif, "TUNSETIFF fd %d name %s flags 0x%x", qfd,
343                    ifr.ifr_ifrn.ifrn_name, ifr.ifr_flags);
344       vec_add1 (vif->tap_fds, qfd);
345     }
346
347   for (i = 0; i < vif->num_rxqs; i++)
348     {
349       tap_log_dbg (vif, "TUNSETVNETHDRSZ: fd %d vnet_hdr_sz %u",
350                    vif->tap_fds[i], hdrsz);
351       _IOCTL (vif->tap_fds[i], TUNSETVNETHDRSZ, &hdrsz);
352
353       tap_log_dbg (vif, "TUNSETSNDBUF: fd %d sndbuf %d", vif->tap_fds[i],
354                    sndbuf);
355       _IOCTL (vif->tap_fds[i], TUNSETSNDBUF, &sndbuf);
356
357       tap_log_dbg (vif, "TUNSETOFFLOAD: fd %d offload 0x%lx", vif->tap_fds[i],
358                    offload);
359       _IOCTL (vif->tap_fds[i], TUNSETOFFLOAD, offload);
360
361       if (fcntl (vif->tap_fds[i], F_SETFL, O_NONBLOCK) < 0)
362         {
363           err = clib_error_return_unix (0, "fcntl(tfd, F_SETFL, O_NONBLOCK)");
364           tap_log_err (vif, "set nonblocking: %U", format_clib_error, err);
365           goto error;
366         }
367     }
368
369   /* open as many vhost-net fds as required and set ownership */
370   num_vhost_queues = clib_max (vif->num_rxqs, vif->num_txqs);
371   for (i = 0; i < num_vhost_queues; i++)
372     {
373       if ((vfd = open ("/dev/vhost-net", O_RDWR | O_NONBLOCK)) < 0)
374         {
375           args->rv = VNET_API_ERROR_SYSCALL_ERROR_1;
376           args->error = clib_error_return_unix (0, "open '/dev/vhost-net'");
377           goto error;
378         }
379       vec_add1 (vif->vhost_fds, vfd);
380       virtio_log_debug (vif, "open vhost-net fd %d qpair %u", vfd, i);
381       _IOCTL (vfd, VHOST_SET_OWNER, 0);
382       virtio_log_debug (vif, "VHOST_SET_OWNER: fd %u", vfd);
383     }
384
385   _IOCTL (vif->vhost_fds[0], VHOST_GET_FEATURES, &vif->remote_features);
386   virtio_log_debug (vif, "VHOST_GET_FEATURES: features 0x%lx",
387                     vif->remote_features);
388
389   if ((vif->remote_features & VIRTIO_FEATURE (VIRTIO_NET_F_MRG_RXBUF)) == 0)
390     {
391       args->rv = VNET_API_ERROR_UNSUPPORTED;
392       args->error = clib_error_return (0, "vhost-net backend doesn't support "
393                                        "VIRTIO_NET_F_MRG_RXBUF feature");
394       goto error;
395     }
396
397   if ((vif->remote_features & VIRTIO_FEATURE (VIRTIO_RING_F_INDIRECT_DESC)) ==
398       0)
399     {
400       args->rv = VNET_API_ERROR_UNSUPPORTED;
401       args->error = clib_error_return (0, "vhost-net backend doesn't support "
402                                        "VIRTIO_RING_F_INDIRECT_DESC feature");
403       goto error;
404     }
405
406   if ((vif->remote_features & VIRTIO_FEATURE (VIRTIO_F_VERSION_1)) == 0)
407     {
408       args->rv = VNET_API_ERROR_UNSUPPORTED;
409       args->error = clib_error_return (0, "vhost-net backend doesn't support "
410                                        "VIRTIO_F_VERSION_1 features");
411       goto error;
412     }
413
414   vif->features |= VIRTIO_FEATURE (VIRTIO_NET_F_MRG_RXBUF);
415   vif->features |= VIRTIO_FEATURE (VIRTIO_F_VERSION_1);
416   vif->features |= VIRTIO_FEATURE (VIRTIO_RING_F_INDIRECT_DESC);
417
418   virtio_set_net_hdr_size (vif);
419
420   if (!(args->tap_flags & TAP_FLAG_ATTACH))
421     {
422       /* if namespace is specified, all further netlink messages should be executed
423          after we change our net namespace */
424       if (args->host_namespace)
425         {
426           old_netns_fd = open ("/proc/self/ns/net", O_RDONLY);
427           if ((nfd = open_netns_fd ((char *) args->host_namespace)) == -1)
428             {
429               args->rv = VNET_API_ERROR_SYSCALL_ERROR_2;
430               args->error = clib_error_return_unix (0, "open_netns_fd '%s'",
431                                                     args->host_namespace);
432               goto error;
433             }
434           args->error = vnet_netlink_set_link_netns (vif->ifindex, nfd,
435                                                      host_if_name);
436           if (args->error)
437             {
438               args->rv = VNET_API_ERROR_NETLINK_ERROR;
439               goto error;
440             }
441           if (setns (nfd, CLONE_NEWNET) == -1)
442             {
443               args->rv = VNET_API_ERROR_SYSCALL_ERROR_3;
444               args->error = clib_error_return_unix (0, "setns '%s'",
445                                                     args->host_namespace);
446               goto error;
447             }
448           if ((vif->ifindex = if_nametoindex (host_if_name)) == 0)
449             {
450               args->rv = VNET_API_ERROR_SYSCALL_ERROR_3;
451               args->error = clib_error_return_unix (0, "if_nametoindex '%s'",
452                                                     host_if_name);
453               goto error;
454             }
455         }
456       else if (host_if_name)
457         {
458           args->error =
459             vnet_netlink_set_link_name (vif->ifindex, host_if_name);
460           if (args->error)
461             {
462               args->rv = VNET_API_ERROR_NETLINK_ERROR;
463               goto error;
464             }
465         }
466     }
467
468   if (vif->type == VIRTIO_IF_TYPE_TAP)
469     {
470       if (ethernet_mac_address_is_zero (args->host_mac_addr.bytes))
471         ethernet_mac_address_generate (args->host_mac_addr.bytes);
472       args->error = vnet_netlink_set_link_addr (vif->ifindex,
473                                                 args->host_mac_addr.bytes);
474       if (args->error)
475         {
476           args->rv = VNET_API_ERROR_NETLINK_ERROR;
477           goto error;
478         }
479
480       if (args->host_bridge)
481         {
482           args->error = vnet_netlink_set_link_master (vif->ifindex,
483                                                       (char *)
484                                                       args->host_bridge);
485           if (args->error)
486             {
487               args->rv = VNET_API_ERROR_NETLINK_ERROR;
488               goto error;
489             }
490         }
491     }
492
493   if (args->host_ip4_prefix_len)
494     {
495       args->error = vnet_netlink_add_ip4_addr (vif->ifindex,
496                                                &args->host_ip4_addr,
497                                                args->host_ip4_prefix_len);
498       if (args->error)
499         {
500           args->rv = VNET_API_ERROR_NETLINK_ERROR;
501           goto error;
502         }
503     }
504
505   if (args->host_ip6_prefix_len)
506     {
507       args->error = vnet_netlink_add_ip6_addr (vif->ifindex,
508                                                &args->host_ip6_addr,
509                                                args->host_ip6_prefix_len);
510       if (args->error)
511         {
512           args->rv = VNET_API_ERROR_NETLINK_ERROR;
513           goto error;
514         }
515     }
516
517   args->error = vnet_netlink_set_link_state (vif->ifindex, 1 /* UP */ );
518   if (args->error)
519     {
520       args->rv = VNET_API_ERROR_NETLINK_ERROR;
521       goto error;
522     }
523
524   if (args->host_ip4_gw_set)
525     {
526       args->error = vnet_netlink_add_ip4_route (0, 0, &args->host_ip4_gw);
527       if (args->error)
528         {
529           args->rv = VNET_API_ERROR_NETLINK_ERROR;
530           goto error;
531         }
532     }
533
534   if (args->host_ip6_gw_set)
535     {
536       args->error = vnet_netlink_add_ip6_route (0, 0, &args->host_ip6_gw);
537       if (args->error)
538         {
539           args->rv = VNET_API_ERROR_NETLINK_ERROR;
540           goto error;
541         }
542     }
543
544   if (args->host_mtu_set)
545     {
546       args->error =
547         vnet_netlink_set_link_mtu (vif->ifindex, args->host_mtu_size);
548       if (args->error)
549         {
550           args->rv = VNET_API_ERROR_NETLINK_ERROR;
551           goto error;
552         }
553     }
554   else if (tm->host_mtu_size != 0)
555     {
556       args->error =
557         vnet_netlink_set_link_mtu (vif->ifindex, tm->host_mtu_size);
558       if (args->error)
559         {
560           args->rv = VNET_API_ERROR_NETLINK_ERROR;
561           goto error;
562         }
563       args->host_mtu_set = 1;
564       args->host_mtu_size = tm->host_mtu_size;
565     }
566
567   /* switch back to old net namespace */
568   if (args->host_namespace)
569     {
570       if (setns (old_netns_fd, CLONE_NEWNET) == -1)
571         {
572           args->rv = VNET_API_ERROR_SYSCALL_ERROR_2;
573           args->error = clib_error_return_unix (0, "setns '%s'",
574                                                 args->host_namespace);
575           goto error;
576         }
577     }
578
579   for (i = 0; i < num_vhost_queues; i++)
580     {
581       if (i < vif->num_rxqs && (args->error =
582                                 virtio_vring_init (vm, vif, RX_QUEUE (i),
583                                                    args->rx_ring_sz)))
584         {
585           args->rv = VNET_API_ERROR_INIT_FAILED;
586           goto error;
587         }
588
589       if (i < vif->num_txqs && (args->error =
590                                 virtio_vring_init (vm, vif, TX_QUEUE (i),
591                                                    args->tx_ring_sz)))
592         {
593           args->rv = VNET_API_ERROR_INIT_FAILED;
594           goto error;
595         }
596     }
597
598   /* setup features and memtable */
599   i = sizeof (vhost_memory_t) + sizeof (vhost_memory_region_t);
600   vhost_mem = clib_mem_alloc (i);
601   clib_memset (vhost_mem, 0, i);
602   vhost_mem->nregions = 1;
603   vhost_mem->regions[0].memory_size = vpm->max_size;
604   vhost_mem->regions[0].guest_phys_addr = vpm->base_addr;
605   vhost_mem->regions[0].userspace_addr =
606     vhost_mem->regions[0].guest_phys_addr;
607
608   for (i = 0; i < vhost_mem->nregions; i++)
609     virtio_log_debug (vif, "memtable region %u memory_size 0x%lx "
610                       "guest_phys_addr 0x%lx userspace_addr 0x%lx", i,
611                       vhost_mem->regions[0].memory_size,
612                       vhost_mem->regions[0].guest_phys_addr,
613                       vhost_mem->regions[0].userspace_addr);
614
615
616   for (i = 0; i < num_vhost_queues; i++)
617     {
618       int fd = vif->vhost_fds[i];
619       _IOCTL (fd, VHOST_SET_FEATURES, &vif->features);
620       virtio_log_debug (vif, "VHOST_SET_FEATURES: fd %u features 0x%lx",
621                         fd, vif->features);
622       _IOCTL (fd, VHOST_SET_MEM_TABLE, vhost_mem);
623       virtio_log_debug (vif, "VHOST_SET_MEM_TABLE: fd %u", fd);
624     }
625
626   /* finish initializing queue pair */
627   for (i = 0; i < num_vhost_queues * 2; i++)
628     {
629       vhost_vring_addr_t addr = { 0 };
630       vhost_vring_state_t state = { 0 };
631       vhost_vring_file_t file = { 0 };
632       virtio_vring_t *vring;
633       u16 qp = i >> 1;
634       int fd = vif->vhost_fds[qp];
635
636       if (i & 1)
637         {
638           if (qp >= vif->num_txqs)
639             continue;
640           vring = vec_elt_at_index (vif->txq_vrings, qp);
641         }
642       else
643         {
644           if (qp >= vif->num_rxqs)
645             continue;
646           vring = vec_elt_at_index (vif->rxq_vrings, qp);
647         }
648
649       addr.index = state.index = file.index = vring->queue_id & 1;
650       state.num = vring->size;
651       virtio_log_debug (vif, "VHOST_SET_VRING_NUM fd %d index %u num %u", fd,
652                         state.index, state.num);
653       _IOCTL (fd, VHOST_SET_VRING_NUM, &state);
654
655       addr.flags = 0;
656       addr.desc_user_addr = pointer_to_uword (vring->desc);
657       addr.avail_user_addr = pointer_to_uword (vring->avail);
658       addr.used_user_addr = pointer_to_uword (vring->used);
659
660       virtio_log_debug (vif, "VHOST_SET_VRING_ADDR fd %d index %u flags 0x%x "
661                         "desc_user_addr 0x%lx avail_user_addr 0x%lx "
662                         "used_user_addr 0x%lx", fd, addr.index,
663                         addr.flags, addr.desc_user_addr, addr.avail_user_addr,
664                         addr.used_user_addr);
665       _IOCTL (fd, VHOST_SET_VRING_ADDR, &addr);
666
667       file.fd = vring->call_fd;
668       virtio_log_debug (vif, "VHOST_SET_VRING_CALL fd %d index %u call_fd %d",
669                         fd, file.index, file.fd);
670       _IOCTL (fd, VHOST_SET_VRING_CALL, &file);
671
672       file.fd = vring->kick_fd;
673       virtio_log_debug (vif, "VHOST_SET_VRING_KICK fd %d index %u kick_fd %d",
674                         fd, file.index, file.fd);
675       _IOCTL (fd, VHOST_SET_VRING_KICK, &file);
676
677       file.fd = vif->tap_fds[qp % vif->num_rxqs];
678       virtio_log_debug (vif, "VHOST_NET_SET_BACKEND fd %d index %u tap_fd %d",
679                         fd, file.index, file.fd);
680       _IOCTL (fd, VHOST_NET_SET_BACKEND, &file);
681     }
682
683   if (vif->type == VIRTIO_IF_TYPE_TAP)
684     {
685       if (!args->mac_addr_set)
686         ethernet_mac_address_generate (args->mac_addr.bytes);
687
688       clib_memcpy (vif->mac_addr, args->mac_addr.bytes, 6);
689       vif->host_bridge = format (0, "%s%c", args->host_bridge, 0);
690     }
691   vif->host_if_name = format (0, "%s%c", host_if_name, 0);
692   vif->net_ns = format (0, "%s%c", args->host_namespace, 0);
693   vif->host_mtu_size = args->host_mtu_size;
694   vif->tap_flags = args->tap_flags;
695   clib_memcpy (vif->host_mac_addr, args->host_mac_addr.bytes, 6);
696   vif->host_ip4_prefix_len = args->host_ip4_prefix_len;
697   vif->host_ip6_prefix_len = args->host_ip6_prefix_len;
698   if (args->host_ip4_prefix_len)
699     clib_memcpy (&vif->host_ip4_addr, &args->host_ip4_addr, 4);
700   if (args->host_ip6_prefix_len)
701     clib_memcpy (&vif->host_ip6_addr, &args->host_ip6_addr, 16);
702
703   if (vif->type != VIRTIO_IF_TYPE_TUN)
704     {
705       args->error =
706         ethernet_register_interface (vnm, virtio_device_class.index,
707                                      vif->dev_instance, vif->mac_addr,
708                                      &vif->hw_if_index,
709                                      virtio_eth_flag_change);
710       if (args->error)
711         {
712           args->rv = VNET_API_ERROR_INVALID_REGISTRATION;
713           goto error;
714         }
715
716     }
717   else
718     {
719       vif->hw_if_index = vnet_register_interface
720         (vnm, virtio_device_class.index,
721          vif->dev_instance /* device instance */ ,
722          tun_device_hw_interface_class.index, vif->dev_instance);
723
724     }
725   tm->tap_ids = clib_bitmap_set (tm->tap_ids, vif->id, 1);
726   sw = vnet_get_hw_sw_interface (vnm, vif->hw_if_index);
727   vif->sw_if_index = sw->sw_if_index;
728   args->sw_if_index = vif->sw_if_index;
729   args->rv = 0;
730   hw = vnet_get_hw_interface (vnm, vif->hw_if_index);
731   hw->caps |= VNET_HW_INTERFACE_CAP_SUPPORTS_INT_MODE;
732   if (args->tap_flags & TAP_FLAG_GSO)
733     {
734       hw->caps |= VNET_HW_INTERFACE_CAP_SUPPORTS_TCP_GSO |
735                   VNET_HW_INTERFACE_CAP_SUPPORTS_TX_TCP_CKSUM |
736                   VNET_HW_INTERFACE_CAP_SUPPORTS_TX_UDP_CKSUM;
737     }
738   else if (args->tap_flags & TAP_FLAG_CSUM_OFFLOAD)
739     {
740       hw->caps |= VNET_HW_INTERFACE_CAP_SUPPORTS_TX_TCP_CKSUM |
741                   VNET_HW_INTERFACE_CAP_SUPPORTS_TX_UDP_CKSUM;
742     }
743   if ((args->tap_flags & TAP_FLAG_GSO)
744       && (args->tap_flags & TAP_FLAG_GRO_COALESCE))
745     {
746       virtio_set_packet_coalesce (vif);
747     }
748   if (vif->type == VIRTIO_IF_TYPE_TUN)
749     {
750       hw->max_supported_packet_bytes = TUN_MAX_PACKET_BYTES;
751       hw->min_packet_bytes = hw->min_supported_packet_bytes =
752         TUN_MIN_PACKET_BYTES;
753       hw->max_packet_bytes =
754         args->host_mtu_size ? args->host_mtu_size : TUN_DEFAULT_PACKET_BYTES;
755       vnet_sw_interface_set_mtu (vnm, hw->sw_if_index, hw->max_packet_bytes);
756     }
757
758   virtio_vring_set_rx_queues (vm, vif);
759
760   vif->per_interface_next_index = ~0;
761   vif->flags |= VIRTIO_IF_FLAG_ADMIN_UP;
762   vnet_hw_interface_set_flags (vnm, vif->hw_if_index,
763                                VNET_HW_INTERFACE_FLAG_LINK_UP);
764   /*
765    * Host tun/tap driver link carrier state is "up" at creation. The
766    * driver never changes this unless the backend (VPP) changes it using
767    * TUNSETCARRIER ioctl(). See tap_set_carrier().
768    */
769   vif->host_carrier_up = 1;
770   vif->cxq_vring = NULL;
771
772   goto done;
773
774 error:
775   if (err)
776     {
777       ASSERT (args->error == 0);
778       args->error = err;
779       args->rv = VNET_API_ERROR_SYSCALL_ERROR_3;
780     }
781
782   tap_log_err (vif, "%U", format_clib_error, args->error);
783   tap_free (vm, vif);
784 done:
785   if (vhost_mem)
786     clib_mem_free (vhost_mem);
787   if (old_netns_fd != -1)
788     close (old_netns_fd);
789   if (nfd != -1)
790     close (nfd);
791 }
792
793 int
794 tap_delete_if (vlib_main_t * vm, u32 sw_if_index)
795 {
796   vnet_main_t *vnm = vnet_get_main ();
797   virtio_main_t *mm = &virtio_main;
798   virtio_if_t *vif;
799   vnet_hw_interface_t *hw;
800
801   hw = vnet_get_sup_hw_interface_api_visible_or_null (vnm, sw_if_index);
802   if (hw == NULL || virtio_device_class.index != hw->dev_class_index)
803     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
804
805   vif = pool_elt_at_index (mm->interfaces, hw->dev_instance);
806
807   if ((vif->type != VIRTIO_IF_TYPE_TAP) && (vif->type != VIRTIO_IF_TYPE_TUN))
808     return VNET_API_ERROR_INVALID_INTERFACE;
809
810   /* bring down the interface */
811   vnet_hw_interface_set_flags (vnm, vif->hw_if_index, 0);
812   vnet_sw_interface_set_flags (vnm, vif->sw_if_index, 0);
813
814   if (vif->type == VIRTIO_IF_TYPE_TAP)
815     ethernet_delete_interface (vnm, vif->hw_if_index);
816   else                          /* VIRTIO_IF_TYPE_TUN */
817     vnet_delete_hw_interface (vnm, vif->hw_if_index);
818   vif->hw_if_index = ~0;
819
820   tap_free (vm, vif);
821
822   return 0;
823 }
824
825 int
826 tap_csum_offload_enable_disable (vlib_main_t * vm, u32 sw_if_index,
827                                  int enable_disable)
828 {
829   vnet_main_t *vnm = vnet_get_main ();
830   virtio_main_t *mm = &virtio_main;
831   virtio_if_t *vif;
832   vnet_hw_interface_t *hw;
833   clib_error_t *err = 0;
834   int i = 0;
835
836   hw = vnet_get_sup_hw_interface_api_visible_or_null (vnm, sw_if_index);
837
838   if (hw == NULL || virtio_device_class.index != hw->dev_class_index)
839     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
840
841   vif = pool_elt_at_index (mm->interfaces, hw->dev_instance);
842
843   const unsigned int csum_offload_on = TUN_F_CSUM;
844   const unsigned int csum_offload_off = 0;
845   unsigned int offload = enable_disable ? csum_offload_on : csum_offload_off;
846   vec_foreach_index (i, vif->tap_fds)
847     _IOCTL (vif->tap_fds[i], TUNSETOFFLOAD, offload);
848   vif->gso_enabled = 0;
849   vif->packet_coalesce = 0;
850   vif->csum_offload_enabled = enable_disable ? 1 : 0;
851
852   if ((hw->caps & VNET_HW_INTERFACE_CAP_SUPPORTS_TCP_GSO) != 0)
853     {
854       hw->caps &= ~VNET_HW_INTERFACE_CAP_SUPPORTS_TCP_GSO;
855     }
856
857   if (enable_disable)
858     {
859       hw->caps |= VNET_HW_INTERFACE_CAP_SUPPORTS_L4_TX_CKSUM;
860     }
861   else
862     {
863       hw->caps &= ~VNET_HW_INTERFACE_CAP_SUPPORTS_L4_TX_CKSUM;
864     }
865
866 error:
867   if (err)
868     {
869       clib_warning ("Error %s checksum offload on sw_if_index %d",
870                     enable_disable ? "enabling" : "disabling", sw_if_index);
871       return VNET_API_ERROR_SYSCALL_ERROR_3;
872     }
873   return 0;
874 }
875
876 int
877 tap_gso_enable_disable (vlib_main_t * vm, u32 sw_if_index, int enable_disable,
878                         int is_packet_coalesce)
879 {
880   vnet_main_t *vnm = vnet_get_main ();
881   virtio_main_t *mm = &virtio_main;
882   virtio_if_t *vif;
883   vnet_hw_interface_t *hw;
884   clib_error_t *err = 0;
885   int i = 0;
886
887   hw = vnet_get_sup_hw_interface_api_visible_or_null (vnm, sw_if_index);
888
889   if (hw == NULL || virtio_device_class.index != hw->dev_class_index)
890     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
891
892   vif = pool_elt_at_index (mm->interfaces, hw->dev_instance);
893
894   const unsigned int gso_on = TUN_F_CSUM | TUN_F_TSO4 | TUN_F_TSO6;
895   const unsigned int gso_off = 0;
896   unsigned int offload = enable_disable ? gso_on : gso_off;
897   vec_foreach_index (i, vif->tap_fds)
898     _IOCTL (vif->tap_fds[i], TUNSETOFFLOAD, offload);
899   vif->gso_enabled = enable_disable ? 1 : 0;
900   vif->csum_offload_enabled = 0;
901   if (enable_disable)
902     {
903       if ((hw->caps & VNET_HW_INTERFACE_CAP_SUPPORTS_TCP_GSO) == 0)
904         {
905           hw->caps |= VNET_HW_INTERFACE_CAP_SUPPORTS_TCP_GSO |
906                       VNET_HW_INTERFACE_CAP_SUPPORTS_L4_TX_CKSUM;
907         }
908       if (is_packet_coalesce)
909         {
910           virtio_set_packet_coalesce (vif);
911         }
912     }
913   else
914     {
915       if ((hw->caps & VNET_HW_INTERFACE_CAP_SUPPORTS_TCP_GSO) != 0)
916         {
917           hw->caps &= ~(VNET_HW_INTERFACE_CAP_SUPPORTS_TCP_GSO |
918                         VNET_HW_INTERFACE_CAP_SUPPORTS_L4_TX_CKSUM);
919         }
920       vif->packet_coalesce = 0;
921     }
922
923 error:
924   if (err)
925     {
926       clib_warning ("Error %s gso on sw_if_index %d",
927                     enable_disable ? "enabling" : "disabling", sw_if_index);
928       return VNET_API_ERROR_SYSCALL_ERROR_3;
929     }
930   return 0;
931 }
932
933 int
934 tap_dump_ifs (tap_interface_details_t ** out_tapids)
935 {
936   vnet_main_t *vnm = vnet_get_main ();
937   virtio_main_t *mm = &virtio_main;
938   virtio_if_t *vif;
939   virtio_vring_t *vring;
940   vnet_hw_interface_t *hi;
941   tap_interface_details_t *r_tapids = NULL;
942   tap_interface_details_t *tapid = NULL;
943
944   /* *INDENT-OFF* */
945   pool_foreach (vif, mm->interfaces) {
946     if ((vif->type != VIRTIO_IF_TYPE_TAP)
947       && (vif->type != VIRTIO_IF_TYPE_TUN))
948       continue;
949     vec_add2(r_tapids, tapid, 1);
950     clib_memset (tapid, 0, sizeof (*tapid));
951     tapid->id = vif->id;
952     tapid->sw_if_index = vif->sw_if_index;
953     hi = vnet_get_hw_interface (vnm, vif->hw_if_index);
954     clib_memcpy(tapid->dev_name, hi->name,
955                 MIN (ARRAY_LEN (tapid->dev_name) - 1, vec_len (hi->name)));
956     vring = vec_elt_at_index (vif->rxq_vrings, RX_QUEUE_ACCESS(0));
957     tapid->rx_ring_sz = vring->size;
958     vring = vec_elt_at_index (vif->txq_vrings, TX_QUEUE_ACCESS(0));
959     tapid->tx_ring_sz = vring->size;
960     tapid->tap_flags = vif->tap_flags;
961     clib_memcpy(&tapid->host_mac_addr, vif->host_mac_addr, 6);
962     if (vif->host_if_name)
963       {
964         clib_memcpy(tapid->host_if_name, vif->host_if_name,
965                     MIN (ARRAY_LEN (tapid->host_if_name) - 1,
966                     vec_len (vif->host_if_name)));
967       }
968     if (vif->net_ns)
969       {
970         clib_memcpy(tapid->host_namespace, vif->net_ns,
971                     MIN (ARRAY_LEN (tapid->host_namespace) - 1,
972                     vec_len (vif->net_ns)));
973       }
974     if (vif->host_bridge)
975       {
976         clib_memcpy(tapid->host_bridge, vif->host_bridge,
977                     MIN (ARRAY_LEN (tapid->host_bridge) - 1,
978                     vec_len (vif->host_bridge)));
979       }
980     if (vif->host_ip4_prefix_len)
981       clib_memcpy(tapid->host_ip4_addr.as_u8, &vif->host_ip4_addr, 4);
982     tapid->host_ip4_prefix_len = vif->host_ip4_prefix_len;
983     if (vif->host_ip6_prefix_len)
984       clib_memcpy(tapid->host_ip6_addr.as_u8, &vif->host_ip6_addr, 16);
985     tapid->host_ip6_prefix_len = vif->host_ip6_prefix_len;
986     tapid->host_mtu_size = vif->host_mtu_size;
987   }
988   /* *INDENT-ON* */
989
990   *out_tapids = r_tapids;
991
992   return 0;
993 }
994
995 /*
996  * Set host tap/tun interface carrier state so it will appear to host
997  * applications that the interface's link state changed.
998  *
999  * If the kernel we're building against does not have support for the
1000  * TUNSETCARRIER ioctl command, do nothing.
1001  */
1002 int
1003 tap_set_carrier (u32 hw_if_index, u32 carrier_up)
1004 {
1005   int ret = 0;
1006 #ifdef TUNSETCARRIER
1007   vnet_main_t *vnm = vnet_get_main ();
1008   vnet_hw_interface_t *hi = vnet_get_hw_interface (vnm, hw_if_index);
1009   virtio_main_t *mm = &virtio_main;
1010   virtio_if_t *vif;
1011   int *fd;
1012
1013   vif = pool_elt_at_index (mm->interfaces, hi->dev_instance);
1014   vec_foreach (fd, vif->tap_fds)
1015   {
1016     ret = ioctl (*fd, TUNSETCARRIER, &carrier_up);
1017     if (ret < 0)
1018       {
1019         clib_warning ("ioctl (TUNSETCARRIER) returned %d", ret);
1020         break;
1021       }
1022   }
1023   if (!ret)
1024     vif->host_carrier_up = (carrier_up != 0);
1025 #endif
1026
1027   return ret;
1028 }
1029
1030 static clib_error_t *
1031 tap_mtu_config (vlib_main_t * vm, unformat_input_t * input)
1032 {
1033   tap_main_t *tm = &tap_main;
1034
1035   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1036     {
1037       if (unformat (input, "host-mtu %d", &tm->host_mtu_size))
1038         ;
1039       else
1040         return clib_error_return (0, "unknown input `%U'",
1041                                   format_unformat_error, input);
1042     }
1043
1044   return 0;
1045 }
1046
1047 /*
1048  * Set host tap/tun interface speed in Mbps.
1049  */
1050 int
1051 tap_set_speed (u32 hw_if_index, u32 speed)
1052 {
1053   vnet_main_t *vnm = vnet_get_main ();
1054   vnet_hw_interface_t *hi = vnet_get_hw_interface (vnm, hw_if_index);
1055   virtio_main_t *mm = &virtio_main;
1056   virtio_if_t *vif;
1057   int old_netns_fd = -1;
1058   int nfd = -1;
1059   int ctl_fd = -1;
1060   struct ifreq ifr;
1061   struct ethtool_cmd ecmd;
1062   int ret = -1;
1063
1064   vif = pool_elt_at_index (mm->interfaces, hi->dev_instance);
1065
1066   if (vif->net_ns)
1067     {
1068       old_netns_fd = open ("/proc/self/ns/net", O_RDONLY);
1069       if ((nfd = open_netns_fd ((char *) vif->net_ns)) == -1)
1070         {
1071           clib_warning ("Cannot open netns");
1072           goto done;
1073         }
1074       if (setns (nfd, CLONE_NEWNET) == -1)
1075         {
1076           clib_warning ("Cannot set ns");
1077           goto done;
1078         }
1079     }
1080
1081   if ((ctl_fd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
1082     {
1083       clib_warning ("Cannot open control socket");
1084       goto done;
1085     }
1086
1087   ecmd.cmd = ETHTOOL_GSET;
1088   clib_memset (&ifr, 0, sizeof (ifr));
1089   clib_memcpy (ifr.ifr_name, vif->host_if_name,
1090                strlen ((const char *) vif->host_if_name));
1091   ifr.ifr_data = (void *) &ecmd;
1092   if ((ret = ioctl (ctl_fd, SIOCETHTOOL, &ifr)) < 0)
1093     {
1094       clib_warning ("Cannot get device settings");
1095       goto done;
1096     }
1097
1098   if (ethtool_cmd_speed (&ecmd) != speed)
1099     {
1100       ecmd.cmd = ETHTOOL_SSET;
1101       ethtool_cmd_speed_set (&ecmd, speed);
1102       if ((ret = ioctl (ctl_fd, SIOCETHTOOL, &ifr)) < 0)
1103         {
1104           clib_warning ("Cannot set device settings");
1105           goto done;
1106         }
1107     }
1108
1109 done:
1110   if (old_netns_fd != -1)
1111     {
1112       if (setns (old_netns_fd, CLONE_NEWNET) == -1)
1113         {
1114           clib_warning ("Cannot set old ns");
1115         }
1116       close (old_netns_fd);
1117     }
1118   if (nfd != -1)
1119     close (nfd);
1120   if (ctl_fd != -1)
1121     close (ctl_fd);
1122
1123   return ret;
1124 }
1125
1126 /* tap { host-mtu <size> } configuration. */
1127 VLIB_CONFIG_FUNCTION (tap_mtu_config, "tap");
1128
1129 static clib_error_t *
1130 tap_init (vlib_main_t * vm)
1131 {
1132   tap_main_t *tm = &tap_main;
1133   clib_error_t *error = 0;
1134
1135   tm->log_default = vlib_log_register_class ("tap", 0);
1136   vlib_log_debug (tm->log_default, "initialized");
1137
1138   tm->host_mtu_size = 0;
1139
1140   return error;
1141 }
1142
1143 VLIB_INIT_FUNCTION (tap_init);
1144
1145 /*
1146  * fd.io coding-style-patch-verification: ON
1147  *
1148  * Local Variables:
1149  * eval: (c-set-style "gnu")
1150  * End:
1151  */