xref: /openbmc/qemu/net/tap.c (revision 8f6e5c620a5b21c070eed93721236cad48b6f9d7)
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  * Copyright (c) 2009 Red Hat, Inc.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 
26 #include "qemu/osdep.h"
27 #include "tap_int.h"
28 
29 
30 #include <sys/ioctl.h>
31 #include <sys/wait.h>
32 #include <sys/socket.h>
33 #include <net/if.h>
34 
35 #include "net/eth.h"
36 #include "net/net.h"
37 #include "clients.h"
38 #include "monitor/monitor.h"
39 #include "system/system.h"
40 #include "qapi/error.h"
41 #include "qemu/cutils.h"
42 #include "qemu/error-report.h"
43 #include "qemu/main-loop.h"
44 #include "qemu/sockets.h"
45 
46 #include "net/tap.h"
47 
48 #include "net/vhost_net.h"
49 
50 typedef struct TAPState {
51     NetClientState nc;
52     int fd;
53     char down_script[1024];
54     char down_script_arg[128];
55     uint8_t buf[NET_BUFSIZE];
56     bool read_poll;
57     bool write_poll;
58     bool using_vnet_hdr;
59     bool has_ufo;
60     bool has_uso;
61     bool enabled;
62     VHostNetState *vhost_net;
63     unsigned host_vnet_hdr_len;
64     Notifier exit;
65 } TAPState;
66 
67 static void launch_script(const char *setup_script, const char *ifname,
68                           int fd, Error **errp);
69 
70 static void tap_send(void *opaque);
71 static void tap_writable(void *opaque);
72 
73 static void tap_update_fd_handler(TAPState *s)
74 {
75     qemu_set_fd_handler(s->fd,
76                         s->read_poll && s->enabled ? tap_send : NULL,
77                         s->write_poll && s->enabled ? tap_writable : NULL,
78                         s);
79 }
80 
81 static void tap_read_poll(TAPState *s, bool enable)
82 {
83     s->read_poll = enable;
84     tap_update_fd_handler(s);
85 }
86 
87 static void tap_write_poll(TAPState *s, bool enable)
88 {
89     s->write_poll = enable;
90     tap_update_fd_handler(s);
91 }
92 
93 static void tap_writable(void *opaque)
94 {
95     TAPState *s = opaque;
96 
97     tap_write_poll(s, false);
98 
99     qemu_flush_queued_packets(&s->nc);
100 }
101 
102 static ssize_t tap_write_packet(TAPState *s, const struct iovec *iov, int iovcnt)
103 {
104     ssize_t len;
105 
106     len = RETRY_ON_EINTR(writev(s->fd, iov, iovcnt));
107 
108     if (len == -1 && errno == EAGAIN) {
109         tap_write_poll(s, true);
110         return 0;
111     }
112 
113     return len;
114 }
115 
116 static ssize_t tap_receive_iov(NetClientState *nc, const struct iovec *iov,
117                                int iovcnt)
118 {
119     TAPState *s = DO_UPCAST(TAPState, nc, nc);
120     const struct iovec *iovp = iov;
121     g_autofree struct iovec *iov_copy = NULL;
122     struct virtio_net_hdr hdr = { };
123 
124     if (s->host_vnet_hdr_len && !s->using_vnet_hdr) {
125         iov_copy = g_new(struct iovec, iovcnt + 1);
126         iov_copy[0].iov_base = &hdr;
127         iov_copy[0].iov_len =  s->host_vnet_hdr_len;
128         memcpy(&iov_copy[1], iov, iovcnt * sizeof(*iov));
129         iovp = iov_copy;
130         iovcnt++;
131     }
132 
133     return tap_write_packet(s, iovp, iovcnt);
134 }
135 
136 static ssize_t tap_receive(NetClientState *nc, const uint8_t *buf, size_t size)
137 {
138     struct iovec iov = {
139         .iov_base = (void *)buf,
140         .iov_len = size
141     };
142 
143     return tap_receive_iov(nc, &iov, 1);
144 }
145 
146 #ifndef __sun__
147 ssize_t tap_read_packet(int tapfd, uint8_t *buf, int maxlen)
148 {
149     return read(tapfd, buf, maxlen);
150 }
151 #endif
152 
153 static void tap_send_completed(NetClientState *nc, ssize_t len)
154 {
155     TAPState *s = DO_UPCAST(TAPState, nc, nc);
156     tap_read_poll(s, true);
157 }
158 
159 static void tap_send(void *opaque)
160 {
161     TAPState *s = opaque;
162     int size;
163     int packets = 0;
164 
165     while (true) {
166         uint8_t *buf = s->buf;
167         uint8_t min_pkt[ETH_ZLEN];
168         size_t min_pktsz = sizeof(min_pkt);
169 
170         size = tap_read_packet(s->fd, s->buf, sizeof(s->buf));
171         if (size <= 0) {
172             break;
173         }
174 
175         if (s->host_vnet_hdr_len && !s->using_vnet_hdr) {
176             buf  += s->host_vnet_hdr_len;
177             size -= s->host_vnet_hdr_len;
178         }
179 
180         if (net_peer_needs_padding(&s->nc)) {
181             if (eth_pad_short_frame(min_pkt, &min_pktsz, buf, size)) {
182                 buf = min_pkt;
183                 size = min_pktsz;
184             }
185         }
186 
187         size = qemu_send_packet_async(&s->nc, buf, size, tap_send_completed);
188         if (size == 0) {
189             tap_read_poll(s, false);
190             break;
191         } else if (size < 0) {
192             break;
193         }
194 
195         /*
196          * When the host keeps receiving more packets while tap_send() is
197          * running we can hog the BQL.  Limit the number of
198          * packets that are processed per tap_send() callback to prevent
199          * stalling the guest.
200          */
201         packets++;
202         if (packets >= 50) {
203             break;
204         }
205     }
206 }
207 
208 static bool tap_has_ufo(NetClientState *nc)
209 {
210     TAPState *s = DO_UPCAST(TAPState, nc, nc);
211 
212     assert(nc->info->type == NET_CLIENT_DRIVER_TAP);
213 
214     return s->has_ufo;
215 }
216 
217 static bool tap_has_uso(NetClientState *nc)
218 {
219     TAPState *s = DO_UPCAST(TAPState, nc, nc);
220 
221     assert(nc->info->type == NET_CLIENT_DRIVER_TAP);
222 
223     return s->has_uso;
224 }
225 
226 static bool tap_has_vnet_hdr(NetClientState *nc)
227 {
228     TAPState *s = DO_UPCAST(TAPState, nc, nc);
229 
230     assert(nc->info->type == NET_CLIENT_DRIVER_TAP);
231 
232     return !!s->host_vnet_hdr_len;
233 }
234 
235 static bool tap_has_vnet_hdr_len(NetClientState *nc, int len)
236 {
237     return tap_has_vnet_hdr(nc);
238 }
239 
240 static void tap_set_vnet_hdr_len(NetClientState *nc, int len)
241 {
242     TAPState *s = DO_UPCAST(TAPState, nc, nc);
243 
244     assert(nc->info->type == NET_CLIENT_DRIVER_TAP);
245 
246     tap_fd_set_vnet_hdr_len(s->fd, len);
247     s->host_vnet_hdr_len = len;
248     s->using_vnet_hdr = true;
249 }
250 
251 static int tap_set_vnet_le(NetClientState *nc, bool is_le)
252 {
253     TAPState *s = DO_UPCAST(TAPState, nc, nc);
254 
255     return tap_fd_set_vnet_le(s->fd, is_le);
256 }
257 
258 static int tap_set_vnet_be(NetClientState *nc, bool is_be)
259 {
260     TAPState *s = DO_UPCAST(TAPState, nc, nc);
261 
262     return tap_fd_set_vnet_be(s->fd, is_be);
263 }
264 
265 static void tap_set_offload(NetClientState *nc, int csum, int tso4,
266                      int tso6, int ecn, int ufo, int uso4, int uso6)
267 {
268     TAPState *s = DO_UPCAST(TAPState, nc, nc);
269     if (s->fd < 0) {
270         return;
271     }
272 
273     tap_fd_set_offload(s->fd, csum, tso4, tso6, ecn, ufo, uso4, uso6);
274 }
275 
276 static void tap_exit_notify(Notifier *notifier, void *data)
277 {
278     TAPState *s = container_of(notifier, TAPState, exit);
279     Error *err = NULL;
280 
281     if (s->down_script[0]) {
282         launch_script(s->down_script, s->down_script_arg, s->fd, &err);
283         if (err) {
284             error_report_err(err);
285         }
286     }
287 }
288 
289 static void tap_cleanup(NetClientState *nc)
290 {
291     TAPState *s = DO_UPCAST(TAPState, nc, nc);
292 
293     if (s->vhost_net) {
294         vhost_net_cleanup(s->vhost_net);
295         g_free(s->vhost_net);
296         s->vhost_net = NULL;
297     }
298 
299     qemu_purge_queued_packets(nc);
300 
301     tap_exit_notify(&s->exit, NULL);
302     qemu_remove_exit_notifier(&s->exit);
303 
304     tap_read_poll(s, false);
305     tap_write_poll(s, false);
306     close(s->fd);
307     s->fd = -1;
308 }
309 
310 static void tap_poll(NetClientState *nc, bool enable)
311 {
312     TAPState *s = DO_UPCAST(TAPState, nc, nc);
313     tap_read_poll(s, enable);
314     tap_write_poll(s, enable);
315 }
316 
317 static bool tap_set_steering_ebpf(NetClientState *nc, int prog_fd)
318 {
319     TAPState *s = DO_UPCAST(TAPState, nc, nc);
320     assert(nc->info->type == NET_CLIENT_DRIVER_TAP);
321 
322     return tap_fd_set_steering_ebpf(s->fd, prog_fd) == 0;
323 }
324 
325 int tap_get_fd(NetClientState *nc)
326 {
327     TAPState *s = DO_UPCAST(TAPState, nc, nc);
328     assert(nc->info->type == NET_CLIENT_DRIVER_TAP);
329     return s->fd;
330 }
331 
332 /*
333  * tap_get_vhost_net() can return NULL if a tap net-device backend is
334  * created with 'vhost=off' option, 'vhostforce=off' or no vhost or
335  * vhostforce or vhostfd options at all. Please see net_init_tap_one().
336  */
337 static VHostNetState *tap_get_vhost_net(NetClientState *nc)
338 {
339     TAPState *s = DO_UPCAST(TAPState, nc, nc);
340     assert(nc->info->type == NET_CLIENT_DRIVER_TAP);
341     return s->vhost_net;
342 }
343 
344 /* fd support */
345 
346 static NetClientInfo net_tap_info = {
347     .type = NET_CLIENT_DRIVER_TAP,
348     .size = sizeof(TAPState),
349     .receive = tap_receive,
350     .receive_iov = tap_receive_iov,
351     .poll = tap_poll,
352     .cleanup = tap_cleanup,
353     .has_ufo = tap_has_ufo,
354     .has_uso = tap_has_uso,
355     .has_vnet_hdr = tap_has_vnet_hdr,
356     .has_vnet_hdr_len = tap_has_vnet_hdr_len,
357     .set_offload = tap_set_offload,
358     .set_vnet_hdr_len = tap_set_vnet_hdr_len,
359     .set_vnet_le = tap_set_vnet_le,
360     .set_vnet_be = tap_set_vnet_be,
361     .set_steering_ebpf = tap_set_steering_ebpf,
362     .get_vhost_net = tap_get_vhost_net,
363 };
364 
365 static TAPState *net_tap_fd_init(NetClientState *peer,
366                                  const char *model,
367                                  const char *name,
368                                  int fd,
369                                  int vnet_hdr)
370 {
371     NetClientState *nc;
372     TAPState *s;
373 
374     nc = qemu_new_net_client(&net_tap_info, peer, model, name);
375 
376     s = DO_UPCAST(TAPState, nc, nc);
377 
378     s->fd = fd;
379     s->host_vnet_hdr_len = vnet_hdr ? sizeof(struct virtio_net_hdr) : 0;
380     s->using_vnet_hdr = false;
381     s->has_ufo = tap_probe_has_ufo(s->fd);
382     s->has_uso = tap_probe_has_uso(s->fd);
383     s->enabled = true;
384     tap_set_offload(&s->nc, 0, 0, 0, 0, 0, 0, 0);
385     /*
386      * Make sure host header length is set correctly in tap:
387      * it might have been modified by another instance of qemu.
388      */
389     if (vnet_hdr) {
390         tap_fd_set_vnet_hdr_len(s->fd, s->host_vnet_hdr_len);
391     }
392     tap_read_poll(s, true);
393     s->vhost_net = NULL;
394 
395     s->exit.notify = tap_exit_notify;
396     qemu_add_exit_notifier(&s->exit);
397 
398     return s;
399 }
400 
401 static void close_all_fds_after_fork(int excluded_fd)
402 {
403     const int skip_fd[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO,
404                            excluded_fd};
405     unsigned int nskip = ARRAY_SIZE(skip_fd);
406 
407     /*
408      * skip_fd must be an ordered array of distinct fds, exclude
409      * excluded_fd if already included in the [STDIN_FILENO - STDERR_FILENO]
410      * range
411      */
412     if (excluded_fd <= STDERR_FILENO) {
413         nskip--;
414     }
415 
416     qemu_close_all_open_fd(skip_fd, nskip);
417 }
418 
419 static void launch_script(const char *setup_script, const char *ifname,
420                           int fd, Error **errp)
421 {
422     int pid, status;
423     char *args[3];
424     char **parg;
425 
426     /* try to launch network script */
427     pid = fork();
428     if (pid < 0) {
429         error_setg_errno(errp, errno, "could not launch network script %s",
430                          setup_script);
431         return;
432     }
433     if (pid == 0) {
434         close_all_fds_after_fork(fd);
435         parg = args;
436         *parg++ = (char *)setup_script;
437         *parg++ = (char *)ifname;
438         *parg = NULL;
439         execv(setup_script, args);
440         _exit(1);
441     } else {
442         while (waitpid(pid, &status, 0) != pid) {
443             /* loop */
444         }
445 
446         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
447             return;
448         }
449         error_setg(errp, "network script %s failed with status %d",
450                    setup_script, status);
451     }
452 }
453 
454 static int recv_fd(int c)
455 {
456     int fd;
457     uint8_t msgbuf[CMSG_SPACE(sizeof(fd))];
458     struct msghdr msg = {
459         .msg_control = msgbuf,
460         .msg_controllen = sizeof(msgbuf),
461     };
462     struct cmsghdr *cmsg;
463     struct iovec iov;
464     uint8_t req[1];
465     ssize_t len;
466 
467     cmsg = CMSG_FIRSTHDR(&msg);
468     cmsg->cmsg_level = SOL_SOCKET;
469     cmsg->cmsg_type = SCM_RIGHTS;
470     cmsg->cmsg_len = CMSG_LEN(sizeof(fd));
471     msg.msg_controllen = cmsg->cmsg_len;
472 
473     iov.iov_base = req;
474     iov.iov_len = sizeof(req);
475 
476     msg.msg_iov = &iov;
477     msg.msg_iovlen = 1;
478 
479     len = recvmsg(c, &msg, 0);
480     if (len > 0) {
481         memcpy(&fd, CMSG_DATA(cmsg), sizeof(fd));
482         return fd;
483     }
484 
485     return len;
486 }
487 
488 static int net_bridge_run_helper(const char *helper, const char *bridge,
489                                  Error **errp)
490 {
491     sigset_t oldmask, mask;
492     g_autofree char *default_helper = NULL;
493     int pid, status;
494     char *args[5];
495     char **parg;
496     int sv[2];
497 
498     sigemptyset(&mask);
499     sigaddset(&mask, SIGCHLD);
500     sigprocmask(SIG_BLOCK, &mask, &oldmask);
501 
502     if (!helper) {
503         helper = default_helper = get_relocated_path(DEFAULT_BRIDGE_HELPER);
504     }
505 
506     if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) == -1) {
507         error_setg_errno(errp, errno, "socketpair() failed");
508         return -1;
509     }
510 
511     /* try to launch bridge helper */
512     pid = fork();
513     if (pid < 0) {
514         error_setg_errno(errp, errno, "Can't fork bridge helper");
515         return -1;
516     }
517     if (pid == 0) {
518         char *fd_buf = NULL;
519         char *br_buf = NULL;
520         char *helper_cmd = NULL;
521 
522         close_all_fds_after_fork(sv[1]);
523         fd_buf = g_strdup_printf("%s%d", "--fd=", sv[1]);
524 
525         if (strrchr(helper, ' ') || strrchr(helper, '\t')) {
526             /* assume helper is a command */
527 
528             if (strstr(helper, "--br=") == NULL) {
529                 br_buf = g_strdup_printf("%s%s", "--br=", bridge);
530             }
531 
532             helper_cmd = g_strdup_printf("%s %s %s %s", helper,
533                             "--use-vnet", fd_buf, br_buf ? br_buf : "");
534 
535             parg = args;
536             *parg++ = (char *)"sh";
537             *parg++ = (char *)"-c";
538             *parg++ = helper_cmd;
539             *parg++ = NULL;
540 
541             execv("/bin/sh", args);
542             g_free(helper_cmd);
543         } else {
544             /* assume helper is just the executable path name */
545 
546             br_buf = g_strdup_printf("%s%s", "--br=", bridge);
547 
548             parg = args;
549             *parg++ = (char *)helper;
550             *parg++ = (char *)"--use-vnet";
551             *parg++ = fd_buf;
552             *parg++ = br_buf;
553             *parg++ = NULL;
554 
555             execv(helper, args);
556         }
557         g_free(fd_buf);
558         g_free(br_buf);
559         _exit(1);
560 
561     } else {
562         int fd;
563         int saved_errno;
564 
565         close(sv[1]);
566 
567         fd = RETRY_ON_EINTR(recv_fd(sv[0]));
568         saved_errno = errno;
569 
570         close(sv[0]);
571 
572         while (waitpid(pid, &status, 0) != pid) {
573             /* loop */
574         }
575         sigprocmask(SIG_SETMASK, &oldmask, NULL);
576         if (fd < 0) {
577             error_setg_errno(errp, saved_errno,
578                              "failed to recv file descriptor");
579             return -1;
580         }
581         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
582             error_setg(errp, "bridge helper failed");
583             return -1;
584         }
585         return fd;
586     }
587 }
588 
589 int net_init_bridge(const Netdev *netdev, const char *name,
590                     NetClientState *peer, Error **errp)
591 {
592     const NetdevBridgeOptions *bridge;
593     const char *helper, *br;
594     TAPState *s;
595     int fd, vnet_hdr;
596 
597     assert(netdev->type == NET_CLIENT_DRIVER_BRIDGE);
598     bridge = &netdev->u.bridge;
599     helper = bridge->helper;
600     br     = bridge->br ?: DEFAULT_BRIDGE_INTERFACE;
601 
602     fd = net_bridge_run_helper(helper, br, errp);
603     if (fd == -1) {
604         return -1;
605     }
606 
607     if (!g_unix_set_fd_nonblocking(fd, true, NULL)) {
608         error_setg_errno(errp, errno, "Failed to set FD nonblocking");
609         return -1;
610     }
611     vnet_hdr = tap_probe_vnet_hdr(fd, errp);
612     if (vnet_hdr < 0) {
613         close(fd);
614         return -1;
615     }
616     s = net_tap_fd_init(peer, "bridge", name, fd, vnet_hdr);
617 
618     qemu_set_info_str(&s->nc, "helper=%s,br=%s", helper, br);
619 
620     return 0;
621 }
622 
623 static int net_tap_init(const NetdevTapOptions *tap, int *vnet_hdr,
624                         const char *setup_script, char *ifname,
625                         size_t ifname_sz, int mq_required, Error **errp)
626 {
627     Error *err = NULL;
628     int fd, vnet_hdr_required;
629 
630     if (tap->has_vnet_hdr) {
631         *vnet_hdr = tap->vnet_hdr;
632         vnet_hdr_required = *vnet_hdr;
633     } else {
634         *vnet_hdr = 1;
635         vnet_hdr_required = 0;
636     }
637 
638     fd = RETRY_ON_EINTR(tap_open(ifname, ifname_sz, vnet_hdr, vnet_hdr_required,
639                       mq_required, errp));
640     if (fd < 0) {
641         return -1;
642     }
643 
644     if (setup_script &&
645         setup_script[0] != '\0' &&
646         strcmp(setup_script, "no") != 0) {
647         launch_script(setup_script, ifname, fd, &err);
648         if (err) {
649             error_propagate(errp, err);
650             close(fd);
651             return -1;
652         }
653     }
654 
655     return fd;
656 }
657 
658 #define MAX_TAP_QUEUES 1024
659 
660 static void net_init_tap_one(const NetdevTapOptions *tap, NetClientState *peer,
661                              const char *model, const char *name,
662                              const char *ifname, const char *script,
663                              const char *downscript, const char *vhostfdname,
664                              int vnet_hdr, int fd, Error **errp)
665 {
666     Error *err = NULL;
667     TAPState *s = net_tap_fd_init(peer, model, name, fd, vnet_hdr);
668     int vhostfd;
669 
670     tap_set_sndbuf(s->fd, tap, &err);
671     if (err) {
672         error_propagate(errp, err);
673         goto failed;
674     }
675 
676     if (tap->fd || tap->fds) {
677         qemu_set_info_str(&s->nc, "fd=%d", fd);
678     } else if (tap->helper) {
679         qemu_set_info_str(&s->nc, "helper=%s", tap->helper);
680     } else {
681         qemu_set_info_str(&s->nc, "ifname=%s,script=%s,downscript=%s", ifname,
682                           script, downscript);
683 
684         if (strcmp(downscript, "no") != 0) {
685             snprintf(s->down_script, sizeof(s->down_script), "%s", downscript);
686             snprintf(s->down_script_arg, sizeof(s->down_script_arg),
687                      "%s", ifname);
688         }
689     }
690 
691     if (tap->has_vhost ? tap->vhost :
692         vhostfdname || (tap->has_vhostforce && tap->vhostforce)) {
693         VhostNetOptions options;
694 
695         options.backend_type = VHOST_BACKEND_TYPE_KERNEL;
696         options.net_backend = &s->nc;
697         if (tap->has_poll_us) {
698             options.busyloop_timeout = tap->poll_us;
699         } else {
700             options.busyloop_timeout = 0;
701         }
702 
703         if (vhostfdname) {
704             vhostfd = monitor_fd_param(monitor_cur(), vhostfdname, &err);
705             if (vhostfd == -1) {
706                 error_propagate(errp, err);
707                 goto failed;
708             }
709             if (!g_unix_set_fd_nonblocking(vhostfd, true, NULL)) {
710                 error_setg_errno(errp, errno, "%s: Can't use file descriptor %d",
711                                  name, fd);
712                 goto failed;
713             }
714         } else {
715             vhostfd = open("/dev/vhost-net", O_RDWR);
716             if (vhostfd < 0) {
717                 error_setg_errno(errp, errno,
718                                  "tap: open vhost char device failed");
719                 goto failed;
720             }
721             if (!g_unix_set_fd_nonblocking(vhostfd, true, NULL)) {
722                 error_setg_errno(errp, errno, "Failed to set FD nonblocking");
723                 goto failed;
724             }
725         }
726         options.opaque = (void *)(uintptr_t)vhostfd;
727         options.nvqs = 2;
728 
729         s->vhost_net = vhost_net_init(&options);
730         if (!s->vhost_net) {
731             error_setg(errp,
732                        "vhost-net requested but could not be initialized");
733             goto failed;
734         }
735     } else if (vhostfdname) {
736         error_setg(errp, "vhostfd(s)= is not valid without vhost");
737         goto failed;
738     }
739 
740     return;
741 
742 failed:
743     qemu_del_net_client(&s->nc);
744 }
745 
746 static int get_fds(char *str, char *fds[], int max)
747 {
748     char *ptr = str, *this;
749     size_t len = strlen(str);
750     int i = 0;
751 
752     while (i < max && ptr < str + len) {
753         this = strchr(ptr, ':');
754 
755         if (this == NULL) {
756             fds[i] = g_strdup(ptr);
757         } else {
758             fds[i] = g_strndup(ptr, this - ptr);
759         }
760 
761         i++;
762         if (this == NULL) {
763             break;
764         } else {
765             ptr = this + 1;
766         }
767     }
768 
769     return i;
770 }
771 
772 int net_init_tap(const Netdev *netdev, const char *name,
773                  NetClientState *peer, Error **errp)
774 {
775     const NetdevTapOptions *tap;
776     int fd, vnet_hdr = 0, i = 0, queues;
777     /* for the no-fd, no-helper case */
778     const char *script;
779     const char *downscript;
780     Error *err = NULL;
781     const char *vhostfdname;
782     char ifname[128];
783     int ret = 0;
784 
785     assert(netdev->type == NET_CLIENT_DRIVER_TAP);
786     tap = &netdev->u.tap;
787     queues = tap->has_queues ? tap->queues : 1;
788     vhostfdname = tap->vhostfd;
789     script = tap->script;
790     downscript = tap->downscript;
791 
792     /* QEMU hubs do not support multiqueue tap, in this case peer is set.
793      * For -netdev, peer is always NULL. */
794     if (peer && (tap->has_queues || tap->fds || tap->vhostfds)) {
795         error_setg(errp, "Multiqueue tap cannot be used with hubs");
796         return -1;
797     }
798 
799     if (tap->fd) {
800         if (tap->ifname || tap->script || tap->downscript ||
801             tap->has_vnet_hdr || tap->helper || tap->has_queues ||
802             tap->fds || tap->vhostfds) {
803             error_setg(errp, "ifname=, script=, downscript=, vnet_hdr=, "
804                        "helper=, queues=, fds=, and vhostfds= "
805                        "are invalid with fd=");
806             return -1;
807         }
808 
809         fd = monitor_fd_param(monitor_cur(), tap->fd, errp);
810         if (fd == -1) {
811             return -1;
812         }
813 
814         if (!g_unix_set_fd_nonblocking(fd, true, NULL)) {
815             error_setg_errno(errp, errno, "%s: Can't use file descriptor %d",
816                              name, fd);
817             close(fd);
818             return -1;
819         }
820 
821         vnet_hdr = tap_probe_vnet_hdr(fd, errp);
822         if (vnet_hdr < 0) {
823             close(fd);
824             return -1;
825         }
826 
827         net_init_tap_one(tap, peer, "tap", name, NULL,
828                          script, downscript,
829                          vhostfdname, vnet_hdr, fd, &err);
830         if (err) {
831             error_propagate(errp, err);
832             close(fd);
833             return -1;
834         }
835     } else if (tap->fds) {
836         char **fds;
837         char **vhost_fds;
838         int nfds = 0, nvhosts = 0;
839 
840         if (tap->ifname || tap->script || tap->downscript ||
841             tap->has_vnet_hdr || tap->helper || tap->has_queues ||
842             tap->vhostfd) {
843             error_setg(errp, "ifname=, script=, downscript=, vnet_hdr=, "
844                        "helper=, queues=, and vhostfd= "
845                        "are invalid with fds=");
846             return -1;
847         }
848 
849         fds = g_new0(char *, MAX_TAP_QUEUES);
850         vhost_fds = g_new0(char *, MAX_TAP_QUEUES);
851 
852         nfds = get_fds(tap->fds, fds, MAX_TAP_QUEUES);
853         if (tap->vhostfds) {
854             nvhosts = get_fds(tap->vhostfds, vhost_fds, MAX_TAP_QUEUES);
855             if (nfds != nvhosts) {
856                 error_setg(errp, "The number of fds passed does not match "
857                            "the number of vhostfds passed");
858                 ret = -1;
859                 goto free_fail;
860             }
861         }
862 
863         for (i = 0; i < nfds; i++) {
864             fd = monitor_fd_param(monitor_cur(), fds[i], errp);
865             if (fd == -1) {
866                 ret = -1;
867                 goto free_fail;
868             }
869 
870             ret = g_unix_set_fd_nonblocking(fd, true, NULL);
871             if (!ret) {
872                 error_setg_errno(errp, errno, "%s: Can't use file descriptor %d",
873                                  name, fd);
874                 goto free_fail;
875             }
876 
877             if (i == 0) {
878                 vnet_hdr = tap_probe_vnet_hdr(fd, errp);
879                 if (vnet_hdr < 0) {
880                     ret = -1;
881                     goto free_fail;
882                 }
883             } else if (vnet_hdr != tap_probe_vnet_hdr(fd, NULL)) {
884                 error_setg(errp,
885                            "vnet_hdr not consistent across given tap fds");
886                 ret = -1;
887                 goto free_fail;
888             }
889 
890             net_init_tap_one(tap, peer, "tap", name, ifname,
891                              script, downscript,
892                              tap->vhostfds ? vhost_fds[i] : NULL,
893                              vnet_hdr, fd, &err);
894             if (err) {
895                 error_propagate(errp, err);
896                 ret = -1;
897                 goto free_fail;
898             }
899         }
900 
901 free_fail:
902         for (i = 0; i < nvhosts; i++) {
903             g_free(vhost_fds[i]);
904         }
905         for (i = 0; i < nfds; i++) {
906             g_free(fds[i]);
907         }
908         g_free(fds);
909         g_free(vhost_fds);
910         return ret;
911     } else if (tap->helper) {
912         if (tap->ifname || tap->script || tap->downscript ||
913             tap->has_vnet_hdr || tap->has_queues || tap->vhostfds) {
914             error_setg(errp, "ifname=, script=, downscript=, vnet_hdr=, "
915                        "queues=, and vhostfds= are invalid with helper=");
916             return -1;
917         }
918 
919         fd = net_bridge_run_helper(tap->helper,
920                                    tap->br ?: DEFAULT_BRIDGE_INTERFACE,
921                                    errp);
922         if (fd == -1) {
923             return -1;
924         }
925 
926         if (!g_unix_set_fd_nonblocking(fd, true, NULL)) {
927             error_setg_errno(errp, errno, "Failed to set FD nonblocking");
928             return -1;
929         }
930         vnet_hdr = tap_probe_vnet_hdr(fd, errp);
931         if (vnet_hdr < 0) {
932             close(fd);
933             return -1;
934         }
935 
936         net_init_tap_one(tap, peer, "bridge", name, ifname,
937                          script, downscript, vhostfdname,
938                          vnet_hdr, fd, &err);
939         if (err) {
940             error_propagate(errp, err);
941             close(fd);
942             return -1;
943         }
944     } else {
945         g_autofree char *default_script = NULL;
946         g_autofree char *default_downscript = NULL;
947         if (tap->vhostfds) {
948             error_setg(errp, "vhostfds= is invalid if fds= wasn't specified");
949             return -1;
950         }
951 
952         if (!script) {
953             script = default_script = get_relocated_path(DEFAULT_NETWORK_SCRIPT);
954         }
955         if (!downscript) {
956             downscript = default_downscript =
957                                  get_relocated_path(DEFAULT_NETWORK_DOWN_SCRIPT);
958         }
959 
960         if (tap->ifname) {
961             pstrcpy(ifname, sizeof ifname, tap->ifname);
962         } else {
963             ifname[0] = '\0';
964         }
965 
966         for (i = 0; i < queues; i++) {
967             fd = net_tap_init(tap, &vnet_hdr, i >= 1 ? "no" : script,
968                               ifname, sizeof ifname, queues > 1, errp);
969             if (fd == -1) {
970                 return -1;
971             }
972 
973             if (queues > 1 && i == 0 && !tap->ifname) {
974                 if (tap_fd_get_ifname(fd, ifname)) {
975                     error_setg(errp, "Fail to get ifname");
976                     close(fd);
977                     return -1;
978                 }
979             }
980 
981             net_init_tap_one(tap, peer, "tap", name, ifname,
982                              i >= 1 ? "no" : script,
983                              i >= 1 ? "no" : downscript,
984                              vhostfdname, vnet_hdr, fd, &err);
985             if (err) {
986                 error_propagate(errp, err);
987                 close(fd);
988                 return -1;
989             }
990         }
991     }
992 
993     return 0;
994 }
995 
996 int tap_enable(NetClientState *nc)
997 {
998     TAPState *s = DO_UPCAST(TAPState, nc, nc);
999     int ret;
1000 
1001     if (s->enabled) {
1002         return 0;
1003     } else {
1004         ret = tap_fd_enable(s->fd);
1005         if (ret == 0) {
1006             s->enabled = true;
1007             tap_update_fd_handler(s);
1008         }
1009         return ret;
1010     }
1011 }
1012 
1013 int tap_disable(NetClientState *nc)
1014 {
1015     TAPState *s = DO_UPCAST(TAPState, nc, nc);
1016     int ret;
1017 
1018     if (s->enabled == 0) {
1019         return 0;
1020     } else {
1021         ret = tap_fd_disable(s->fd);
1022         if (ret == 0) {
1023             qemu_purge_queued_packets(nc);
1024             s->enabled = false;
1025             tap_update_fd_handler(s);
1026         }
1027         return ret;
1028     }
1029 }
1030