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