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