xref: /openbmc/qemu/net/tap.c (revision 97d2b66d)
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 close_all_fds_after_fork(int excluded_fd)
389 {
390     const int skip_fd[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO,
391                            excluded_fd};
392     unsigned int nskip = ARRAY_SIZE(skip_fd);
393 
394     /*
395      * skip_fd must be an ordered array of distinct fds, exclude
396      * excluded_fd if already included in the [STDIN_FILENO - STDERR_FILENO]
397      * range
398      */
399     if (excluded_fd <= STDERR_FILENO) {
400         nskip--;
401     }
402 
403     qemu_close_all_open_fd(skip_fd, nskip);
404 }
405 
406 static void launch_script(const char *setup_script, const char *ifname,
407                           int fd, Error **errp)
408 {
409     int pid, status;
410     char *args[3];
411     char **parg;
412 
413     /* try to launch network script */
414     pid = fork();
415     if (pid < 0) {
416         error_setg_errno(errp, errno, "could not launch network script %s",
417                          setup_script);
418         return;
419     }
420     if (pid == 0) {
421         close_all_fds_after_fork(fd);
422         parg = args;
423         *parg++ = (char *)setup_script;
424         *parg++ = (char *)ifname;
425         *parg = NULL;
426         execv(setup_script, args);
427         _exit(1);
428     } else {
429         while (waitpid(pid, &status, 0) != pid) {
430             /* loop */
431         }
432 
433         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
434             return;
435         }
436         error_setg(errp, "network script %s failed with status %d",
437                    setup_script, status);
438     }
439 }
440 
441 static int recv_fd(int c)
442 {
443     int fd;
444     uint8_t msgbuf[CMSG_SPACE(sizeof(fd))];
445     struct msghdr msg = {
446         .msg_control = msgbuf,
447         .msg_controllen = sizeof(msgbuf),
448     };
449     struct cmsghdr *cmsg;
450     struct iovec iov;
451     uint8_t req[1];
452     ssize_t len;
453 
454     cmsg = CMSG_FIRSTHDR(&msg);
455     cmsg->cmsg_level = SOL_SOCKET;
456     cmsg->cmsg_type = SCM_RIGHTS;
457     cmsg->cmsg_len = CMSG_LEN(sizeof(fd));
458     msg.msg_controllen = cmsg->cmsg_len;
459 
460     iov.iov_base = req;
461     iov.iov_len = sizeof(req);
462 
463     msg.msg_iov = &iov;
464     msg.msg_iovlen = 1;
465 
466     len = recvmsg(c, &msg, 0);
467     if (len > 0) {
468         memcpy(&fd, CMSG_DATA(cmsg), sizeof(fd));
469         return fd;
470     }
471 
472     return len;
473 }
474 
475 static int net_bridge_run_helper(const char *helper, const char *bridge,
476                                  Error **errp)
477 {
478     sigset_t oldmask, mask;
479     g_autofree char *default_helper = NULL;
480     int pid, status;
481     char *args[5];
482     char **parg;
483     int sv[2];
484 
485     sigemptyset(&mask);
486     sigaddset(&mask, SIGCHLD);
487     sigprocmask(SIG_BLOCK, &mask, &oldmask);
488 
489     if (!helper) {
490         helper = default_helper = get_relocated_path(DEFAULT_BRIDGE_HELPER);
491     }
492 
493     if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) == -1) {
494         error_setg_errno(errp, errno, "socketpair() failed");
495         return -1;
496     }
497 
498     /* try to launch bridge helper */
499     pid = fork();
500     if (pid < 0) {
501         error_setg_errno(errp, errno, "Can't fork bridge helper");
502         return -1;
503     }
504     if (pid == 0) {
505         char *fd_buf = NULL;
506         char *br_buf = NULL;
507         char *helper_cmd = NULL;
508 
509         close_all_fds_after_fork(sv[1]);
510         fd_buf = g_strdup_printf("%s%d", "--fd=", sv[1]);
511 
512         if (strrchr(helper, ' ') || strrchr(helper, '\t')) {
513             /* assume helper is a command */
514 
515             if (strstr(helper, "--br=") == NULL) {
516                 br_buf = g_strdup_printf("%s%s", "--br=", bridge);
517             }
518 
519             helper_cmd = g_strdup_printf("%s %s %s %s", helper,
520                             "--use-vnet", fd_buf, br_buf ? br_buf : "");
521 
522             parg = args;
523             *parg++ = (char *)"sh";
524             *parg++ = (char *)"-c";
525             *parg++ = helper_cmd;
526             *parg++ = NULL;
527 
528             execv("/bin/sh", args);
529             g_free(helper_cmd);
530         } else {
531             /* assume helper is just the executable path name */
532 
533             br_buf = g_strdup_printf("%s%s", "--br=", bridge);
534 
535             parg = args;
536             *parg++ = (char *)helper;
537             *parg++ = (char *)"--use-vnet";
538             *parg++ = fd_buf;
539             *parg++ = br_buf;
540             *parg++ = NULL;
541 
542             execv(helper, args);
543         }
544         g_free(fd_buf);
545         g_free(br_buf);
546         _exit(1);
547 
548     } else {
549         int fd;
550         int saved_errno;
551 
552         close(sv[1]);
553 
554         fd = RETRY_ON_EINTR(recv_fd(sv[0]));
555         saved_errno = errno;
556 
557         close(sv[0]);
558 
559         while (waitpid(pid, &status, 0) != pid) {
560             /* loop */
561         }
562         sigprocmask(SIG_SETMASK, &oldmask, NULL);
563         if (fd < 0) {
564             error_setg_errno(errp, saved_errno,
565                              "failed to recv file descriptor");
566             return -1;
567         }
568         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
569             error_setg(errp, "bridge helper failed");
570             return -1;
571         }
572         return fd;
573     }
574 }
575 
576 int net_init_bridge(const Netdev *netdev, const char *name,
577                     NetClientState *peer, Error **errp)
578 {
579     const NetdevBridgeOptions *bridge;
580     const char *helper, *br;
581     TAPState *s;
582     int fd, vnet_hdr;
583 
584     assert(netdev->type == NET_CLIENT_DRIVER_BRIDGE);
585     bridge = &netdev->u.bridge;
586     helper = bridge->helper;
587     br     = bridge->br ?: DEFAULT_BRIDGE_INTERFACE;
588 
589     fd = net_bridge_run_helper(helper, br, errp);
590     if (fd == -1) {
591         return -1;
592     }
593 
594     if (!g_unix_set_fd_nonblocking(fd, true, NULL)) {
595         error_setg_errno(errp, errno, "Failed to set FD nonblocking");
596         return -1;
597     }
598     vnet_hdr = tap_probe_vnet_hdr(fd, errp);
599     if (vnet_hdr < 0) {
600         close(fd);
601         return -1;
602     }
603     s = net_tap_fd_init(peer, "bridge", name, fd, vnet_hdr);
604 
605     qemu_set_info_str(&s->nc, "helper=%s,br=%s", helper, 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     fd = RETRY_ON_EINTR(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         goto failed;
661     }
662 
663     if (tap->fd || tap->fds) {
664         qemu_set_info_str(&s->nc, "fd=%d", fd);
665     } else if (tap->helper) {
666         qemu_set_info_str(&s->nc, "helper=%s", tap->helper);
667     } else {
668         qemu_set_info_str(&s->nc, "ifname=%s,script=%s,downscript=%s", ifname,
669                           script, downscript);
670 
671         if (strcmp(downscript, "no") != 0) {
672             snprintf(s->down_script, sizeof(s->down_script), "%s", downscript);
673             snprintf(s->down_script_arg, sizeof(s->down_script_arg),
674                      "%s", ifname);
675         }
676     }
677 
678     if (tap->has_vhost ? tap->vhost :
679         vhostfdname || (tap->has_vhostforce && tap->vhostforce)) {
680         VhostNetOptions options;
681 
682         options.backend_type = VHOST_BACKEND_TYPE_KERNEL;
683         options.net_backend = &s->nc;
684         if (tap->has_poll_us) {
685             options.busyloop_timeout = tap->poll_us;
686         } else {
687             options.busyloop_timeout = 0;
688         }
689 
690         if (vhostfdname) {
691             vhostfd = monitor_fd_param(monitor_cur(), vhostfdname, &err);
692             if (vhostfd == -1) {
693                 error_propagate(errp, err);
694                 goto failed;
695             }
696             if (!g_unix_set_fd_nonblocking(vhostfd, true, NULL)) {
697                 error_setg_errno(errp, errno, "%s: Can't use file descriptor %d",
698                                  name, fd);
699                 goto failed;
700             }
701         } else {
702             vhostfd = open("/dev/vhost-net", O_RDWR);
703             if (vhostfd < 0) {
704                 error_setg_errno(errp, errno,
705                                  "tap: open vhost char device failed");
706                 goto failed;
707             }
708             if (!g_unix_set_fd_nonblocking(vhostfd, true, NULL)) {
709                 error_setg_errno(errp, errno, "Failed to set FD nonblocking");
710                 goto failed;
711             }
712         }
713         options.opaque = (void *)(uintptr_t)vhostfd;
714         options.nvqs = 2;
715 
716         s->vhost_net = vhost_net_init(&options);
717         if (!s->vhost_net) {
718             error_setg(errp,
719                        "vhost-net requested but could not be initialized");
720             goto failed;
721         }
722     } else if (vhostfdname) {
723         error_setg(errp, "vhostfd(s)= is not valid without vhost");
724         goto failed;
725     }
726 
727     return;
728 
729 failed:
730     qemu_del_net_client(&s->nc);
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;
766     const char *downscript;
767     Error *err = NULL;
768     const char *vhostfdname;
769     char ifname[128];
770     int ret = 0;
771 
772     assert(netdev->type == NET_CLIENT_DRIVER_TAP);
773     tap = &netdev->u.tap;
774     queues = tap->has_queues ? tap->queues : 1;
775     vhostfdname = tap->vhostfd;
776     script = tap->script;
777     downscript = tap->downscript;
778 
779     /* QEMU hubs do not support multiqueue tap, in this case peer is set.
780      * For -netdev, peer is always NULL. */
781     if (peer && (tap->has_queues || tap->fds || tap->vhostfds)) {
782         error_setg(errp, "Multiqueue tap cannot be used with hubs");
783         return -1;
784     }
785 
786     if (tap->fd) {
787         if (tap->ifname || tap->script || tap->downscript ||
788             tap->has_vnet_hdr || tap->helper || tap->has_queues ||
789             tap->fds || tap->vhostfds) {
790             error_setg(errp, "ifname=, script=, downscript=, vnet_hdr=, "
791                        "helper=, queues=, fds=, and vhostfds= "
792                        "are invalid with fd=");
793             return -1;
794         }
795 
796         fd = monitor_fd_param(monitor_cur(), tap->fd, errp);
797         if (fd == -1) {
798             return -1;
799         }
800 
801         if (!g_unix_set_fd_nonblocking(fd, true, NULL)) {
802             error_setg_errno(errp, errno, "%s: Can't use file descriptor %d",
803                              name, fd);
804             close(fd);
805             return -1;
806         }
807 
808         vnet_hdr = tap_probe_vnet_hdr(fd, errp);
809         if (vnet_hdr < 0) {
810             close(fd);
811             return -1;
812         }
813 
814         net_init_tap_one(tap, peer, "tap", name, NULL,
815                          script, downscript,
816                          vhostfdname, vnet_hdr, fd, &err);
817         if (err) {
818             error_propagate(errp, err);
819             close(fd);
820             return -1;
821         }
822     } else if (tap->fds) {
823         char **fds;
824         char **vhost_fds;
825         int nfds = 0, nvhosts = 0;
826 
827         if (tap->ifname || tap->script || tap->downscript ||
828             tap->has_vnet_hdr || tap->helper || tap->has_queues ||
829             tap->vhostfd) {
830             error_setg(errp, "ifname=, script=, downscript=, vnet_hdr=, "
831                        "helper=, queues=, and vhostfd= "
832                        "are invalid with fds=");
833             return -1;
834         }
835 
836         fds = g_new0(char *, MAX_TAP_QUEUES);
837         vhost_fds = g_new0(char *, MAX_TAP_QUEUES);
838 
839         nfds = get_fds(tap->fds, fds, MAX_TAP_QUEUES);
840         if (tap->vhostfds) {
841             nvhosts = get_fds(tap->vhostfds, vhost_fds, MAX_TAP_QUEUES);
842             if (nfds != nvhosts) {
843                 error_setg(errp, "The number of fds passed does not match "
844                            "the number of vhostfds passed");
845                 ret = -1;
846                 goto free_fail;
847             }
848         }
849 
850         for (i = 0; i < nfds; i++) {
851             fd = monitor_fd_param(monitor_cur(), fds[i], errp);
852             if (fd == -1) {
853                 ret = -1;
854                 goto free_fail;
855             }
856 
857             ret = g_unix_set_fd_nonblocking(fd, true, NULL);
858             if (!ret) {
859                 error_setg_errno(errp, errno, "%s: Can't use file descriptor %d",
860                                  name, fd);
861                 goto free_fail;
862             }
863 
864             if (i == 0) {
865                 vnet_hdr = tap_probe_vnet_hdr(fd, errp);
866                 if (vnet_hdr < 0) {
867                     ret = -1;
868                     goto free_fail;
869                 }
870             } else if (vnet_hdr != tap_probe_vnet_hdr(fd, NULL)) {
871                 error_setg(errp,
872                            "vnet_hdr not consistent across given tap fds");
873                 ret = -1;
874                 goto free_fail;
875             }
876 
877             net_init_tap_one(tap, peer, "tap", name, ifname,
878                              script, downscript,
879                              tap->vhostfds ? vhost_fds[i] : NULL,
880                              vnet_hdr, fd, &err);
881             if (err) {
882                 error_propagate(errp, err);
883                 ret = -1;
884                 goto free_fail;
885             }
886         }
887 
888 free_fail:
889         for (i = 0; i < nvhosts; i++) {
890             g_free(vhost_fds[i]);
891         }
892         for (i = 0; i < nfds; i++) {
893             g_free(fds[i]);
894         }
895         g_free(fds);
896         g_free(vhost_fds);
897         return ret;
898     } else if (tap->helper) {
899         if (tap->ifname || tap->script || tap->downscript ||
900             tap->has_vnet_hdr || tap->has_queues || tap->vhostfds) {
901             error_setg(errp, "ifname=, script=, downscript=, vnet_hdr=, "
902                        "queues=, and vhostfds= are invalid with helper=");
903             return -1;
904         }
905 
906         fd = net_bridge_run_helper(tap->helper,
907                                    tap->br ?: DEFAULT_BRIDGE_INTERFACE,
908                                    errp);
909         if (fd == -1) {
910             return -1;
911         }
912 
913         if (!g_unix_set_fd_nonblocking(fd, true, NULL)) {
914             error_setg_errno(errp, errno, "Failed to set FD nonblocking");
915             return -1;
916         }
917         vnet_hdr = tap_probe_vnet_hdr(fd, errp);
918         if (vnet_hdr < 0) {
919             close(fd);
920             return -1;
921         }
922 
923         net_init_tap_one(tap, peer, "bridge", name, ifname,
924                          script, downscript, vhostfdname,
925                          vnet_hdr, fd, &err);
926         if (err) {
927             error_propagate(errp, err);
928             close(fd);
929             return -1;
930         }
931     } else {
932         g_autofree char *default_script = NULL;
933         g_autofree char *default_downscript = NULL;
934         if (tap->vhostfds) {
935             error_setg(errp, "vhostfds= is invalid if fds= wasn't specified");
936             return -1;
937         }
938 
939         if (!script) {
940             script = default_script = get_relocated_path(DEFAULT_NETWORK_SCRIPT);
941         }
942         if (!downscript) {
943             downscript = default_downscript =
944                                  get_relocated_path(DEFAULT_NETWORK_DOWN_SCRIPT);
945         }
946 
947         if (tap->ifname) {
948             pstrcpy(ifname, sizeof ifname, tap->ifname);
949         } else {
950             ifname[0] = '\0';
951         }
952 
953         for (i = 0; i < queues; i++) {
954             fd = net_tap_init(tap, &vnet_hdr, i >= 1 ? "no" : script,
955                               ifname, sizeof ifname, queues > 1, errp);
956             if (fd == -1) {
957                 return -1;
958             }
959 
960             if (queues > 1 && i == 0 && !tap->ifname) {
961                 if (tap_fd_get_ifname(fd, ifname)) {
962                     error_setg(errp, "Fail to get ifname");
963                     close(fd);
964                     return -1;
965                 }
966             }
967 
968             net_init_tap_one(tap, peer, "tap", name, ifname,
969                              i >= 1 ? "no" : script,
970                              i >= 1 ? "no" : downscript,
971                              vhostfdname, vnet_hdr, fd, &err);
972             if (err) {
973                 error_propagate(errp, err);
974                 close(fd);
975                 return -1;
976             }
977         }
978     }
979 
980     return 0;
981 }
982 
983 VHostNetState *tap_get_vhost_net(NetClientState *nc)
984 {
985     TAPState *s = DO_UPCAST(TAPState, nc, nc);
986     assert(nc->info->type == NET_CLIENT_DRIVER_TAP);
987     return s->vhost_net;
988 }
989 
990 int tap_enable(NetClientState *nc)
991 {
992     TAPState *s = DO_UPCAST(TAPState, nc, nc);
993     int ret;
994 
995     if (s->enabled) {
996         return 0;
997     } else {
998         ret = tap_fd_enable(s->fd);
999         if (ret == 0) {
1000             s->enabled = true;
1001             tap_update_fd_handler(s);
1002         }
1003         return ret;
1004     }
1005 }
1006 
1007 int tap_disable(NetClientState *nc)
1008 {
1009     TAPState *s = DO_UPCAST(TAPState, nc, nc);
1010     int ret;
1011 
1012     if (s->enabled == 0) {
1013         return 0;
1014     } else {
1015         ret = tap_fd_disable(s->fd);
1016         if (ret == 0) {
1017             qemu_purge_queued_packets(nc);
1018             s->enabled = false;
1019             tap_update_fd_handler(s);
1020         }
1021         return ret;
1022     }
1023 }
1024