xref: /openbmc/qemu/net/tap.c (revision b2580720)
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 "sysemu/sysemu.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 /* fd support */
333 
334 static NetClientInfo net_tap_info = {
335     .type = NET_CLIENT_DRIVER_TAP,
336     .size = sizeof(TAPState),
337     .receive = tap_receive,
338     .receive_iov = tap_receive_iov,
339     .poll = tap_poll,
340     .cleanup = tap_cleanup,
341     .has_ufo = tap_has_ufo,
342     .has_uso = tap_has_uso,
343     .has_vnet_hdr = tap_has_vnet_hdr,
344     .has_vnet_hdr_len = tap_has_vnet_hdr_len,
345     .set_offload = tap_set_offload,
346     .set_vnet_hdr_len = tap_set_vnet_hdr_len,
347     .set_vnet_le = tap_set_vnet_le,
348     .set_vnet_be = tap_set_vnet_be,
349     .set_steering_ebpf = tap_set_steering_ebpf,
350 };
351 
352 static TAPState *net_tap_fd_init(NetClientState *peer,
353                                  const char *model,
354                                  const char *name,
355                                  int fd,
356                                  int vnet_hdr)
357 {
358     NetClientState *nc;
359     TAPState *s;
360 
361     nc = qemu_new_net_client(&net_tap_info, peer, model, name);
362 
363     s = DO_UPCAST(TAPState, nc, nc);
364 
365     s->fd = fd;
366     s->host_vnet_hdr_len = vnet_hdr ? sizeof(struct virtio_net_hdr) : 0;
367     s->using_vnet_hdr = false;
368     s->has_ufo = tap_probe_has_ufo(s->fd);
369     s->has_uso = tap_probe_has_uso(s->fd);
370     s->enabled = true;
371     tap_set_offload(&s->nc, 0, 0, 0, 0, 0, 0, 0);
372     /*
373      * Make sure host header length is set correctly in tap:
374      * it might have been modified by another instance of qemu.
375      */
376     if (vnet_hdr) {
377         tap_fd_set_vnet_hdr_len(s->fd, s->host_vnet_hdr_len);
378     }
379     tap_read_poll(s, true);
380     s->vhost_net = NULL;
381 
382     s->exit.notify = tap_exit_notify;
383     qemu_add_exit_notifier(&s->exit);
384 
385     return s;
386 }
387 
388 static void launch_script(const char *setup_script, const char *ifname,
389                           int fd, Error **errp)
390 {
391     int pid, status;
392     char *args[3];
393     char **parg;
394 
395     /* try to launch network script */
396     pid = fork();
397     if (pid < 0) {
398         error_setg_errno(errp, errno, "could not launch network script %s",
399                          setup_script);
400         return;
401     }
402     if (pid == 0) {
403         int open_max = sysconf(_SC_OPEN_MAX), i;
404 
405         for (i = 3; i < open_max; i++) {
406             if (i != fd) {
407                 close(i);
408             }
409         }
410         parg = args;
411         *parg++ = (char *)setup_script;
412         *parg++ = (char *)ifname;
413         *parg = NULL;
414         execv(setup_script, args);
415         _exit(1);
416     } else {
417         while (waitpid(pid, &status, 0) != pid) {
418             /* loop */
419         }
420 
421         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
422             return;
423         }
424         error_setg(errp, "network script %s failed with status %d",
425                    setup_script, status);
426     }
427 }
428 
429 static int recv_fd(int c)
430 {
431     int fd;
432     uint8_t msgbuf[CMSG_SPACE(sizeof(fd))];
433     struct msghdr msg = {
434         .msg_control = msgbuf,
435         .msg_controllen = sizeof(msgbuf),
436     };
437     struct cmsghdr *cmsg;
438     struct iovec iov;
439     uint8_t req[1];
440     ssize_t len;
441 
442     cmsg = CMSG_FIRSTHDR(&msg);
443     cmsg->cmsg_level = SOL_SOCKET;
444     cmsg->cmsg_type = SCM_RIGHTS;
445     cmsg->cmsg_len = CMSG_LEN(sizeof(fd));
446     msg.msg_controllen = cmsg->cmsg_len;
447 
448     iov.iov_base = req;
449     iov.iov_len = sizeof(req);
450 
451     msg.msg_iov = &iov;
452     msg.msg_iovlen = 1;
453 
454     len = recvmsg(c, &msg, 0);
455     if (len > 0) {
456         memcpy(&fd, CMSG_DATA(cmsg), sizeof(fd));
457         return fd;
458     }
459 
460     return len;
461 }
462 
463 static int net_bridge_run_helper(const char *helper, const char *bridge,
464                                  Error **errp)
465 {
466     sigset_t oldmask, mask;
467     g_autofree char *default_helper = NULL;
468     int pid, status;
469     char *args[5];
470     char **parg;
471     int sv[2];
472 
473     sigemptyset(&mask);
474     sigaddset(&mask, SIGCHLD);
475     sigprocmask(SIG_BLOCK, &mask, &oldmask);
476 
477     if (!helper) {
478         helper = default_helper = get_relocated_path(DEFAULT_BRIDGE_HELPER);
479     }
480 
481     if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) == -1) {
482         error_setg_errno(errp, errno, "socketpair() failed");
483         return -1;
484     }
485 
486     /* try to launch bridge helper */
487     pid = fork();
488     if (pid < 0) {
489         error_setg_errno(errp, errno, "Can't fork bridge helper");
490         return -1;
491     }
492     if (pid == 0) {
493         int open_max = sysconf(_SC_OPEN_MAX), i;
494         char *fd_buf = NULL;
495         char *br_buf = NULL;
496         char *helper_cmd = NULL;
497 
498         for (i = 3; i < open_max; i++) {
499             if (i != sv[1]) {
500                 close(i);
501             }
502         }
503 
504         fd_buf = g_strdup_printf("%s%d", "--fd=", sv[1]);
505 
506         if (strrchr(helper, ' ') || strrchr(helper, '\t')) {
507             /* assume helper is a command */
508 
509             if (strstr(helper, "--br=") == NULL) {
510                 br_buf = g_strdup_printf("%s%s", "--br=", bridge);
511             }
512 
513             helper_cmd = g_strdup_printf("%s %s %s %s", helper,
514                             "--use-vnet", fd_buf, br_buf ? br_buf : "");
515 
516             parg = args;
517             *parg++ = (char *)"sh";
518             *parg++ = (char *)"-c";
519             *parg++ = helper_cmd;
520             *parg++ = NULL;
521 
522             execv("/bin/sh", args);
523             g_free(helper_cmd);
524         } else {
525             /* assume helper is just the executable path name */
526 
527             br_buf = g_strdup_printf("%s%s", "--br=", bridge);
528 
529             parg = args;
530             *parg++ = (char *)helper;
531             *parg++ = (char *)"--use-vnet";
532             *parg++ = fd_buf;
533             *parg++ = br_buf;
534             *parg++ = NULL;
535 
536             execv(helper, args);
537         }
538         g_free(fd_buf);
539         g_free(br_buf);
540         _exit(1);
541 
542     } else {
543         int fd;
544         int saved_errno;
545 
546         close(sv[1]);
547 
548         fd = RETRY_ON_EINTR(recv_fd(sv[0]));
549         saved_errno = errno;
550 
551         close(sv[0]);
552 
553         while (waitpid(pid, &status, 0) != pid) {
554             /* loop */
555         }
556         sigprocmask(SIG_SETMASK, &oldmask, NULL);
557         if (fd < 0) {
558             error_setg_errno(errp, saved_errno,
559                              "failed to recv file descriptor");
560             return -1;
561         }
562         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
563             error_setg(errp, "bridge helper failed");
564             return -1;
565         }
566         return fd;
567     }
568 }
569 
570 int net_init_bridge(const Netdev *netdev, const char *name,
571                     NetClientState *peer, Error **errp)
572 {
573     const NetdevBridgeOptions *bridge;
574     const char *helper, *br;
575     TAPState *s;
576     int fd, vnet_hdr;
577 
578     assert(netdev->type == NET_CLIENT_DRIVER_BRIDGE);
579     bridge = &netdev->u.bridge;
580     helper = bridge->helper;
581     br     = bridge->br ?: DEFAULT_BRIDGE_INTERFACE;
582 
583     fd = net_bridge_run_helper(helper, br, errp);
584     if (fd == -1) {
585         return -1;
586     }
587 
588     if (!g_unix_set_fd_nonblocking(fd, true, NULL)) {
589         error_setg_errno(errp, errno, "Failed to set FD nonblocking");
590         return -1;
591     }
592     vnet_hdr = tap_probe_vnet_hdr(fd, errp);
593     if (vnet_hdr < 0) {
594         close(fd);
595         return -1;
596     }
597     s = net_tap_fd_init(peer, "bridge", name, fd, vnet_hdr);
598 
599     qemu_set_info_str(&s->nc, "helper=%s,br=%s", helper, br);
600 
601     return 0;
602 }
603 
604 static int net_tap_init(const NetdevTapOptions *tap, int *vnet_hdr,
605                         const char *setup_script, char *ifname,
606                         size_t ifname_sz, int mq_required, Error **errp)
607 {
608     Error *err = NULL;
609     int fd, vnet_hdr_required;
610 
611     if (tap->has_vnet_hdr) {
612         *vnet_hdr = tap->vnet_hdr;
613         vnet_hdr_required = *vnet_hdr;
614     } else {
615         *vnet_hdr = 1;
616         vnet_hdr_required = 0;
617     }
618 
619     fd = RETRY_ON_EINTR(tap_open(ifname, ifname_sz, vnet_hdr, vnet_hdr_required,
620                       mq_required, errp));
621     if (fd < 0) {
622         return -1;
623     }
624 
625     if (setup_script &&
626         setup_script[0] != '\0' &&
627         strcmp(setup_script, "no") != 0) {
628         launch_script(setup_script, ifname, fd, &err);
629         if (err) {
630             error_propagate(errp, err);
631             close(fd);
632             return -1;
633         }
634     }
635 
636     return fd;
637 }
638 
639 #define MAX_TAP_QUEUES 1024
640 
641 static void net_init_tap_one(const NetdevTapOptions *tap, NetClientState *peer,
642                              const char *model, const char *name,
643                              const char *ifname, const char *script,
644                              const char *downscript, const char *vhostfdname,
645                              int vnet_hdr, int fd, Error **errp)
646 {
647     Error *err = NULL;
648     TAPState *s = net_tap_fd_init(peer, model, name, fd, vnet_hdr);
649     int vhostfd;
650 
651     tap_set_sndbuf(s->fd, tap, &err);
652     if (err) {
653         error_propagate(errp, err);
654         goto failed;
655     }
656 
657     if (tap->fd || tap->fds) {
658         qemu_set_info_str(&s->nc, "fd=%d", fd);
659     } else if (tap->helper) {
660         qemu_set_info_str(&s->nc, "helper=%s", tap->helper);
661     } else {
662         qemu_set_info_str(&s->nc, "ifname=%s,script=%s,downscript=%s", ifname,
663                           script, downscript);
664 
665         if (strcmp(downscript, "no") != 0) {
666             snprintf(s->down_script, sizeof(s->down_script), "%s", downscript);
667             snprintf(s->down_script_arg, sizeof(s->down_script_arg),
668                      "%s", ifname);
669         }
670     }
671 
672     if (tap->has_vhost ? tap->vhost :
673         vhostfdname || (tap->has_vhostforce && tap->vhostforce)) {
674         VhostNetOptions options;
675 
676         options.backend_type = VHOST_BACKEND_TYPE_KERNEL;
677         options.net_backend = &s->nc;
678         if (tap->has_poll_us) {
679             options.busyloop_timeout = tap->poll_us;
680         } else {
681             options.busyloop_timeout = 0;
682         }
683 
684         if (vhostfdname) {
685             vhostfd = monitor_fd_param(monitor_cur(), vhostfdname, &err);
686             if (vhostfd == -1) {
687                 error_propagate(errp, err);
688                 goto failed;
689             }
690             if (!g_unix_set_fd_nonblocking(vhostfd, true, NULL)) {
691                 error_setg_errno(errp, errno, "%s: Can't use file descriptor %d",
692                                  name, fd);
693                 goto failed;
694             }
695         } else {
696             vhostfd = open("/dev/vhost-net", O_RDWR);
697             if (vhostfd < 0) {
698                 error_setg_errno(errp, errno,
699                                  "tap: open vhost char device failed");
700                 goto failed;
701             }
702             if (!g_unix_set_fd_nonblocking(vhostfd, true, NULL)) {
703                 error_setg_errno(errp, errno, "Failed to set FD nonblocking");
704                 goto failed;
705             }
706         }
707         options.opaque = (void *)(uintptr_t)vhostfd;
708         options.nvqs = 2;
709 
710         s->vhost_net = vhost_net_init(&options);
711         if (!s->vhost_net) {
712             error_setg(errp,
713                        "vhost-net requested but could not be initialized");
714             goto failed;
715         }
716     } else if (vhostfdname) {
717         error_setg(errp, "vhostfd(s)= is not valid without vhost");
718         goto failed;
719     }
720 
721     return;
722 
723 failed:
724     qemu_del_net_client(&s->nc);
725 }
726 
727 static int get_fds(char *str, char *fds[], int max)
728 {
729     char *ptr = str, *this;
730     size_t len = strlen(str);
731     int i = 0;
732 
733     while (i < max && ptr < str + len) {
734         this = strchr(ptr, ':');
735 
736         if (this == NULL) {
737             fds[i] = g_strdup(ptr);
738         } else {
739             fds[i] = g_strndup(ptr, this - ptr);
740         }
741 
742         i++;
743         if (this == NULL) {
744             break;
745         } else {
746             ptr = this + 1;
747         }
748     }
749 
750     return i;
751 }
752 
753 int net_init_tap(const Netdev *netdev, const char *name,
754                  NetClientState *peer, Error **errp)
755 {
756     const NetdevTapOptions *tap;
757     int fd, vnet_hdr = 0, i = 0, queues;
758     /* for the no-fd, no-helper case */
759     const char *script;
760     const char *downscript;
761     Error *err = NULL;
762     const char *vhostfdname;
763     char ifname[128];
764     int ret = 0;
765 
766     assert(netdev->type == NET_CLIENT_DRIVER_TAP);
767     tap = &netdev->u.tap;
768     queues = tap->has_queues ? tap->queues : 1;
769     vhostfdname = tap->vhostfd;
770     script = tap->script;
771     downscript = tap->downscript;
772 
773     /* QEMU hubs do not support multiqueue tap, in this case peer is set.
774      * For -netdev, peer is always NULL. */
775     if (peer && (tap->has_queues || tap->fds || tap->vhostfds)) {
776         error_setg(errp, "Multiqueue tap cannot be used with hubs");
777         return -1;
778     }
779 
780     if (tap->fd) {
781         if (tap->ifname || tap->script || tap->downscript ||
782             tap->has_vnet_hdr || tap->helper || tap->has_queues ||
783             tap->fds || tap->vhostfds) {
784             error_setg(errp, "ifname=, script=, downscript=, vnet_hdr=, "
785                        "helper=, queues=, fds=, and vhostfds= "
786                        "are invalid with fd=");
787             return -1;
788         }
789 
790         fd = monitor_fd_param(monitor_cur(), tap->fd, errp);
791         if (fd == -1) {
792             return -1;
793         }
794 
795         if (!g_unix_set_fd_nonblocking(fd, true, NULL)) {
796             error_setg_errno(errp, errno, "%s: Can't use file descriptor %d",
797                              name, fd);
798             close(fd);
799             return -1;
800         }
801 
802         vnet_hdr = tap_probe_vnet_hdr(fd, errp);
803         if (vnet_hdr < 0) {
804             close(fd);
805             return -1;
806         }
807 
808         net_init_tap_one(tap, peer, "tap", name, NULL,
809                          script, downscript,
810                          vhostfdname, vnet_hdr, fd, &err);
811         if (err) {
812             error_propagate(errp, err);
813             close(fd);
814             return -1;
815         }
816     } else if (tap->fds) {
817         char **fds;
818         char **vhost_fds;
819         int nfds = 0, nvhosts = 0;
820 
821         if (tap->ifname || tap->script || tap->downscript ||
822             tap->has_vnet_hdr || tap->helper || tap->has_queues ||
823             tap->vhostfd) {
824             error_setg(errp, "ifname=, script=, downscript=, vnet_hdr=, "
825                        "helper=, queues=, and vhostfd= "
826                        "are invalid with fds=");
827             return -1;
828         }
829 
830         fds = g_new0(char *, MAX_TAP_QUEUES);
831         vhost_fds = g_new0(char *, MAX_TAP_QUEUES);
832 
833         nfds = get_fds(tap->fds, fds, MAX_TAP_QUEUES);
834         if (tap->vhostfds) {
835             nvhosts = get_fds(tap->vhostfds, vhost_fds, MAX_TAP_QUEUES);
836             if (nfds != nvhosts) {
837                 error_setg(errp, "The number of fds passed does not match "
838                            "the number of vhostfds passed");
839                 ret = -1;
840                 goto free_fail;
841             }
842         }
843 
844         for (i = 0; i < nfds; i++) {
845             fd = monitor_fd_param(monitor_cur(), fds[i], errp);
846             if (fd == -1) {
847                 ret = -1;
848                 goto free_fail;
849             }
850 
851             ret = g_unix_set_fd_nonblocking(fd, true, NULL);
852             if (!ret) {
853                 error_setg_errno(errp, errno, "%s: Can't use file descriptor %d",
854                                  name, fd);
855                 goto free_fail;
856             }
857 
858             if (i == 0) {
859                 vnet_hdr = tap_probe_vnet_hdr(fd, errp);
860                 if (vnet_hdr < 0) {
861                     ret = -1;
862                     goto free_fail;
863                 }
864             } else if (vnet_hdr != tap_probe_vnet_hdr(fd, NULL)) {
865                 error_setg(errp,
866                            "vnet_hdr not consistent across given tap fds");
867                 ret = -1;
868                 goto free_fail;
869             }
870 
871             net_init_tap_one(tap, peer, "tap", name, ifname,
872                              script, downscript,
873                              tap->vhostfds ? vhost_fds[i] : NULL,
874                              vnet_hdr, fd, &err);
875             if (err) {
876                 error_propagate(errp, err);
877                 ret = -1;
878                 goto free_fail;
879             }
880         }
881 
882 free_fail:
883         for (i = 0; i < nvhosts; i++) {
884             g_free(vhost_fds[i]);
885         }
886         for (i = 0; i < nfds; i++) {
887             g_free(fds[i]);
888         }
889         g_free(fds);
890         g_free(vhost_fds);
891         return ret;
892     } else if (tap->helper) {
893         if (tap->ifname || tap->script || tap->downscript ||
894             tap->has_vnet_hdr || tap->has_queues || tap->vhostfds) {
895             error_setg(errp, "ifname=, script=, downscript=, vnet_hdr=, "
896                        "queues=, and vhostfds= are invalid with helper=");
897             return -1;
898         }
899 
900         fd = net_bridge_run_helper(tap->helper,
901                                    tap->br ?: DEFAULT_BRIDGE_INTERFACE,
902                                    errp);
903         if (fd == -1) {
904             return -1;
905         }
906 
907         if (!g_unix_set_fd_nonblocking(fd, true, NULL)) {
908             error_setg_errno(errp, errno, "Failed to set FD nonblocking");
909             return -1;
910         }
911         vnet_hdr = tap_probe_vnet_hdr(fd, errp);
912         if (vnet_hdr < 0) {
913             close(fd);
914             return -1;
915         }
916 
917         net_init_tap_one(tap, peer, "bridge", name, ifname,
918                          script, downscript, vhostfdname,
919                          vnet_hdr, fd, &err);
920         if (err) {
921             error_propagate(errp, err);
922             close(fd);
923             return -1;
924         }
925     } else {
926         g_autofree char *default_script = NULL;
927         g_autofree char *default_downscript = NULL;
928         if (tap->vhostfds) {
929             error_setg(errp, "vhostfds= is invalid if fds= wasn't specified");
930             return -1;
931         }
932 
933         if (!script) {
934             script = default_script = get_relocated_path(DEFAULT_NETWORK_SCRIPT);
935         }
936         if (!downscript) {
937             downscript = default_downscript =
938                                  get_relocated_path(DEFAULT_NETWORK_DOWN_SCRIPT);
939         }
940 
941         if (tap->ifname) {
942             pstrcpy(ifname, sizeof ifname, tap->ifname);
943         } else {
944             ifname[0] = '\0';
945         }
946 
947         for (i = 0; i < queues; i++) {
948             fd = net_tap_init(tap, &vnet_hdr, i >= 1 ? "no" : script,
949                               ifname, sizeof ifname, queues > 1, errp);
950             if (fd == -1) {
951                 return -1;
952             }
953 
954             if (queues > 1 && i == 0 && !tap->ifname) {
955                 if (tap_fd_get_ifname(fd, ifname)) {
956                     error_setg(errp, "Fail to get ifname");
957                     close(fd);
958                     return -1;
959                 }
960             }
961 
962             net_init_tap_one(tap, peer, "tap", name, ifname,
963                              i >= 1 ? "no" : script,
964                              i >= 1 ? "no" : downscript,
965                              vhostfdname, vnet_hdr, fd, &err);
966             if (err) {
967                 error_propagate(errp, err);
968                 close(fd);
969                 return -1;
970             }
971         }
972     }
973 
974     return 0;
975 }
976 
977 VHostNetState *tap_get_vhost_net(NetClientState *nc)
978 {
979     TAPState *s = DO_UPCAST(TAPState, nc, nc);
980     assert(nc->info->type == NET_CLIENT_DRIVER_TAP);
981     return s->vhost_net;
982 }
983 
984 int tap_enable(NetClientState *nc)
985 {
986     TAPState *s = DO_UPCAST(TAPState, nc, nc);
987     int ret;
988 
989     if (s->enabled) {
990         return 0;
991     } else {
992         ret = tap_fd_enable(s->fd);
993         if (ret == 0) {
994             s->enabled = true;
995             tap_update_fd_handler(s);
996         }
997         return ret;
998     }
999 }
1000 
1001 int tap_disable(NetClientState *nc)
1002 {
1003     TAPState *s = DO_UPCAST(TAPState, nc, nc);
1004     int ret;
1005 
1006     if (s->enabled == 0) {
1007         return 0;
1008     } else {
1009         ret = tap_fd_disable(s->fd);
1010         if (ret == 0) {
1011             qemu_purge_queued_packets(nc);
1012             s->enabled = false;
1013             tap_update_fd_handler(s);
1014         }
1015         return ret;
1016     }
1017 }
1018