1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30#define _FILE_OFFSET_BITS 64
31
32#include "qemu/osdep.h"
33#include "qemu/atomic.h"
34#include "qemu/ctype.h"
35#include "qemu/iov.h"
36#include "standard-headers/linux/virtio_net.h"
37#include "contrib/libvhost-user/libvhost-user.h"
38
39#define VHOST_USER_BRIDGE_DEBUG 1
40
41#define DPRINT(...) \
42 do { \
43 if (VHOST_USER_BRIDGE_DEBUG) { \
44 printf(__VA_ARGS__); \
45 } \
46 } while (0)
47
48enum {
49 VHOST_USER_BRIDGE_MAX_QUEUES = 8,
50};
51
52typedef void (*CallbackFunc)(int sock, void *ctx);
53
54typedef struct Event {
55 void *ctx;
56 CallbackFunc callback;
57} Event;
58
59typedef struct Dispatcher {
60 int max_sock;
61 fd_set fdset;
62 Event events[FD_SETSIZE];
63} Dispatcher;
64
65typedef struct VubrDev {
66 VuDev vudev;
67 Dispatcher dispatcher;
68 int backend_udp_sock;
69 struct sockaddr_in backend_udp_dest;
70 int hdrlen;
71 int sock;
72 int ready;
73 int quit;
74 struct {
75 int fd;
76 void *addr;
77 pthread_t thread;
78 } notifier;
79} VubrDev;
80
81static void
82vubr_die(const char *s)
83{
84 perror(s);
85 exit(1);
86}
87
88static int
89dispatcher_init(Dispatcher *dispr)
90{
91 FD_ZERO(&dispr->fdset);
92 dispr->max_sock = -1;
93 return 0;
94}
95
96static int
97dispatcher_add(Dispatcher *dispr, int sock, void *ctx, CallbackFunc cb)
98{
99 if (sock >= FD_SETSIZE) {
100 fprintf(stderr,
101 "Error: Failed to add new event. sock %d should be less than %d\n",
102 sock, FD_SETSIZE);
103 return -1;
104 }
105
106 dispr->events[sock].ctx = ctx;
107 dispr->events[sock].callback = cb;
108
109 FD_SET(sock, &dispr->fdset);
110 if (sock > dispr->max_sock) {
111 dispr->max_sock = sock;
112 }
113 DPRINT("Added sock %d for watching. max_sock: %d\n",
114 sock, dispr->max_sock);
115 return 0;
116}
117
118static int
119dispatcher_remove(Dispatcher *dispr, int sock)
120{
121 if (sock >= FD_SETSIZE) {
122 fprintf(stderr,
123 "Error: Failed to remove event. sock %d should be less than %d\n",
124 sock, FD_SETSIZE);
125 return -1;
126 }
127
128 FD_CLR(sock, &dispr->fdset);
129 DPRINT("Sock %d removed from dispatcher watch.\n", sock);
130 return 0;
131}
132
133
134static int
135dispatcher_wait(Dispatcher *dispr, uint32_t timeout)
136{
137 struct timeval tv;
138 tv.tv_sec = timeout / 1000000;
139 tv.tv_usec = timeout % 1000000;
140
141 fd_set fdset = dispr->fdset;
142
143
144 int rc = select(dispr->max_sock + 1, &fdset, 0, 0, &tv);
145
146 if (rc == -1) {
147 vubr_die("select");
148 }
149
150
151 if (rc == 0) {
152 return 0;
153 }
154
155
156
157 int sock;
158 for (sock = 0; sock < dispr->max_sock + 1; sock++) {
159
160
161
162
163 if (FD_ISSET(sock, &fdset) && FD_ISSET(sock, &dispr->fdset)) {
164 Event *e = &dispr->events[sock];
165 e->callback(sock, e->ctx);
166 }
167 }
168
169 return 0;
170}
171
172static void
173vubr_handle_tx(VuDev *dev, int qidx)
174{
175 VuVirtq *vq = vu_get_queue(dev, qidx);
176 VubrDev *vubr = container_of(dev, VubrDev, vudev);
177 int hdrlen = vubr->hdrlen;
178 VuVirtqElement *elem = NULL;
179
180 assert(qidx % 2);
181
182 for (;;) {
183 ssize_t ret;
184 unsigned int out_num;
185 struct iovec sg[VIRTQUEUE_MAX_SIZE], *out_sg;
186
187 elem = vu_queue_pop(dev, vq, sizeof(VuVirtqElement));
188 if (!elem) {
189 break;
190 }
191
192 out_num = elem->out_num;
193 out_sg = elem->out_sg;
194 if (out_num < 1) {
195 fprintf(stderr, "virtio-net header not in first element\n");
196 break;
197 }
198 if (VHOST_USER_BRIDGE_DEBUG) {
199 iov_hexdump(out_sg, out_num, stderr, "TX:", 1024);
200 }
201
202 if (hdrlen) {
203 unsigned sg_num = iov_copy(sg, ARRAY_SIZE(sg),
204 out_sg, out_num,
205 hdrlen, -1);
206 out_num = sg_num;
207 out_sg = sg;
208 }
209
210 struct msghdr msg = {
211 .msg_name = (struct sockaddr *) &vubr->backend_udp_dest,
212 .msg_namelen = sizeof(struct sockaddr_in),
213 .msg_iov = out_sg,
214 .msg_iovlen = out_num,
215 };
216 do {
217 ret = sendmsg(vubr->backend_udp_sock, &msg, 0);
218 } while (ret == -1 && (errno == EAGAIN || errno == EINTR));
219
220 if (ret == -1) {
221 vubr_die("sendmsg()");
222 }
223
224 vu_queue_push(dev, vq, elem, 0);
225 vu_queue_notify(dev, vq);
226
227 free(elem);
228 elem = NULL;
229 }
230
231 free(elem);
232}
233
234
235
236
237
238
239static void
240iov_restore_front(struct iovec *front, struct iovec *iov, size_t bytes)
241{
242 struct iovec *cur;
243
244 for (cur = front; cur != iov; cur++) {
245 assert(bytes >= cur->iov_len);
246 bytes -= cur->iov_len;
247 }
248
249 cur->iov_base -= bytes;
250 cur->iov_len += bytes;
251}
252
253static void
254iov_truncate(struct iovec *iov, unsigned iovc, size_t bytes)
255{
256 unsigned i;
257
258 for (i = 0; i < iovc; i++, iov++) {
259 if (bytes < iov->iov_len) {
260 iov->iov_len = bytes;
261 return;
262 }
263
264 bytes -= iov->iov_len;
265 }
266
267 assert(!"couldn't truncate iov");
268}
269
270static void
271vubr_backend_recv_cb(int sock, void *ctx)
272{
273 VubrDev *vubr = (VubrDev *) ctx;
274 VuDev *dev = &vubr->vudev;
275 VuVirtq *vq = vu_get_queue(dev, 0);
276 VuVirtqElement *elem = NULL;
277 struct iovec mhdr_sg[VIRTQUEUE_MAX_SIZE];
278 struct virtio_net_hdr_mrg_rxbuf mhdr;
279 unsigned mhdr_cnt = 0;
280 int hdrlen = vubr->hdrlen;
281 int i = 0;
282 struct virtio_net_hdr hdr = {
283 .flags = 0,
284 .gso_type = VIRTIO_NET_HDR_GSO_NONE
285 };
286
287 DPRINT("\n\n *** IN UDP RECEIVE CALLBACK ***\n\n");
288 DPRINT(" hdrlen = %d\n", hdrlen);
289
290 if (!vu_queue_enabled(dev, vq) ||
291 !vu_queue_started(dev, vq) ||
292 !vu_queue_avail_bytes(dev, vq, hdrlen, 0)) {
293 DPRINT("Got UDP packet, but no available descriptors on RX virtq.\n");
294 return;
295 }
296
297 while (1) {
298 struct iovec *sg;
299 ssize_t ret, total = 0;
300 unsigned int num;
301
302 elem = vu_queue_pop(dev, vq, sizeof(VuVirtqElement));
303 if (!elem) {
304 break;
305 }
306
307 if (elem->in_num < 1) {
308 fprintf(stderr, "virtio-net contains no in buffers\n");
309 break;
310 }
311
312 sg = elem->in_sg;
313 num = elem->in_num;
314 if (i == 0) {
315 if (hdrlen == 12) {
316 mhdr_cnt = iov_copy(mhdr_sg, ARRAY_SIZE(mhdr_sg),
317 sg, elem->in_num,
318 offsetof(typeof(mhdr), num_buffers),
319 sizeof(mhdr.num_buffers));
320 }
321 iov_from_buf(sg, elem->in_num, 0, &hdr, sizeof hdr);
322 total += hdrlen;
323 ret = iov_discard_front(&sg, &num, hdrlen);
324 assert(ret == hdrlen);
325 }
326
327 struct msghdr msg = {
328 .msg_name = (struct sockaddr *) &vubr->backend_udp_dest,
329 .msg_namelen = sizeof(struct sockaddr_in),
330 .msg_iov = sg,
331 .msg_iovlen = num,
332 .msg_flags = MSG_DONTWAIT,
333 };
334 do {
335 ret = recvmsg(vubr->backend_udp_sock, &msg, 0);
336 } while (ret == -1 && (errno == EINTR));
337
338 if (i == 0) {
339 iov_restore_front(elem->in_sg, sg, hdrlen);
340 }
341
342 if (ret == -1) {
343 if (errno == EWOULDBLOCK) {
344 vu_queue_rewind(dev, vq, 1);
345 break;
346 }
347
348 vubr_die("recvmsg()");
349 }
350
351 total += ret;
352 iov_truncate(elem->in_sg, elem->in_num, total);
353 vu_queue_fill(dev, vq, elem, total, i++);
354
355 free(elem);
356 elem = NULL;
357
358 break;
359 }
360
361 if (mhdr_cnt) {
362 mhdr.num_buffers = i;
363 iov_from_buf(mhdr_sg, mhdr_cnt,
364 0,
365 &mhdr.num_buffers, sizeof mhdr.num_buffers);
366 }
367
368 vu_queue_flush(dev, vq, i);
369 vu_queue_notify(dev, vq);
370
371 free(elem);
372}
373
374static void
375vubr_receive_cb(int sock, void *ctx)
376{
377 VubrDev *vubr = (VubrDev *)ctx;
378
379 if (!vu_dispatch(&vubr->vudev)) {
380 fprintf(stderr, "Error while dispatching\n");
381 }
382}
383
384typedef struct WatchData {
385 VuDev *dev;
386 vu_watch_cb cb;
387 void *data;
388} WatchData;
389
390static void
391watch_cb(int sock, void *ctx)
392{
393 struct WatchData *wd = ctx;
394
395 wd->cb(wd->dev, VU_WATCH_IN, wd->data);
396}
397
398static void
399vubr_set_watch(VuDev *dev, int fd, int condition,
400 vu_watch_cb cb, void *data)
401{
402 VubrDev *vubr = container_of(dev, VubrDev, vudev);
403 static WatchData watches[FD_SETSIZE];
404 struct WatchData *wd = &watches[fd];
405
406 wd->cb = cb;
407 wd->data = data;
408 wd->dev = dev;
409 dispatcher_add(&vubr->dispatcher, fd, wd, watch_cb);
410}
411
412static void
413vubr_remove_watch(VuDev *dev, int fd)
414{
415 VubrDev *vubr = container_of(dev, VubrDev, vudev);
416
417 dispatcher_remove(&vubr->dispatcher, fd);
418}
419
420static int
421vubr_send_rarp_exec(VuDev *dev, VhostUserMsg *vmsg)
422{
423 DPRINT("Function %s() not implemented yet.\n", __func__);
424 return 0;
425}
426
427static int
428vubr_process_msg(VuDev *dev, VhostUserMsg *vmsg, int *do_reply)
429{
430 switch (vmsg->request) {
431 case VHOST_USER_SEND_RARP:
432 *do_reply = vubr_send_rarp_exec(dev, vmsg);
433 return 1;
434 default:
435
436 return 0;
437 }
438
439 return 0;
440}
441
442static void
443vubr_set_features(VuDev *dev, uint64_t features)
444{
445 VubrDev *vubr = container_of(dev, VubrDev, vudev);
446
447 if ((features & (1ULL << VIRTIO_F_VERSION_1)) ||
448 (features & (1ULL << VIRTIO_NET_F_MRG_RXBUF))) {
449 vubr->hdrlen = 12;
450 } else {
451 vubr->hdrlen = 10;
452 }
453}
454
455static uint64_t
456vubr_get_features(VuDev *dev)
457{
458 return 1ULL << VIRTIO_NET_F_GUEST_ANNOUNCE |
459 1ULL << VIRTIO_NET_F_MRG_RXBUF |
460 1ULL << VIRTIO_F_VERSION_1;
461}
462
463static void
464vubr_queue_set_started(VuDev *dev, int qidx, bool started)
465{
466 VubrDev *vubr = container_of(dev, VubrDev, vudev);
467 VuVirtq *vq = vu_get_queue(dev, qidx);
468
469 if (started && vubr->notifier.fd >= 0) {
470 vu_set_queue_host_notifier(dev, vq, vubr->notifier.fd,
471 qemu_real_host_page_size,
472 qidx * qemu_real_host_page_size);
473 }
474
475 if (qidx % 2 == 1) {
476 vu_set_queue_handler(dev, vq, started ? vubr_handle_tx : NULL);
477 }
478}
479
480static void
481vubr_panic(VuDev *dev, const char *msg)
482{
483 VubrDev *vubr = container_of(dev, VubrDev, vudev);
484
485 fprintf(stderr, "PANIC: %s\n", msg);
486
487 dispatcher_remove(&vubr->dispatcher, dev->sock);
488 vubr->quit = 1;
489}
490
491static bool
492vubr_queue_is_processed_in_order(VuDev *dev, int qidx)
493{
494 return true;
495}
496
497static const VuDevIface vuiface = {
498 .get_features = vubr_get_features,
499 .set_features = vubr_set_features,
500 .process_msg = vubr_process_msg,
501 .queue_set_started = vubr_queue_set_started,
502 .queue_is_processed_in_order = vubr_queue_is_processed_in_order,
503};
504
505static void
506vubr_accept_cb(int sock, void *ctx)
507{
508 VubrDev *dev = (VubrDev *)ctx;
509 int conn_fd;
510 struct sockaddr_un un;
511 socklen_t len = sizeof(un);
512
513 conn_fd = accept(sock, (struct sockaddr *) &un, &len);
514 if (conn_fd == -1) {
515 vubr_die("accept()");
516 }
517 DPRINT("Got connection from remote peer on sock %d\n", conn_fd);
518
519 if (!vu_init(&dev->vudev,
520 VHOST_USER_BRIDGE_MAX_QUEUES,
521 conn_fd,
522 vubr_panic,
523 NULL,
524 vubr_set_watch,
525 vubr_remove_watch,
526 &vuiface)) {
527 fprintf(stderr, "Failed to initialize libvhost-user\n");
528 exit(1);
529 }
530
531 dispatcher_add(&dev->dispatcher, conn_fd, ctx, vubr_receive_cb);
532 dispatcher_remove(&dev->dispatcher, sock);
533}
534
535static VubrDev *
536vubr_new(const char *path, bool client)
537{
538 VubrDev *dev = (VubrDev *) calloc(1, sizeof(VubrDev));
539 struct sockaddr_un un;
540 CallbackFunc cb;
541 size_t len;
542
543
544 dev->sock = socket(AF_UNIX, SOCK_STREAM, 0);
545 if (dev->sock == -1) {
546 vubr_die("socket");
547 }
548
549 dev->notifier.fd = -1;
550
551 un.sun_family = AF_UNIX;
552 strcpy(un.sun_path, path);
553 len = sizeof(un.sun_family) + strlen(path);
554
555 if (!client) {
556 unlink(path);
557
558 if (bind(dev->sock, (struct sockaddr *) &un, len) == -1) {
559 vubr_die("bind");
560 }
561
562 if (listen(dev->sock, 1) == -1) {
563 vubr_die("listen");
564 }
565 cb = vubr_accept_cb;
566
567 DPRINT("Waiting for connections on UNIX socket %s ...\n", path);
568 } else {
569 if (connect(dev->sock, (struct sockaddr *)&un, len) == -1) {
570 vubr_die("connect");
571 }
572
573 if (!vu_init(&dev->vudev,
574 VHOST_USER_BRIDGE_MAX_QUEUES,
575 dev->sock,
576 vubr_panic,
577 NULL,
578 vubr_set_watch,
579 vubr_remove_watch,
580 &vuiface)) {
581 fprintf(stderr, "Failed to initialize libvhost-user\n");
582 exit(1);
583 }
584
585 cb = vubr_receive_cb;
586 }
587
588 dispatcher_init(&dev->dispatcher);
589
590 dispatcher_add(&dev->dispatcher, dev->sock, (void *)dev, cb);
591
592 return dev;
593}
594
595static void *notifier_thread(void *arg)
596{
597 VuDev *dev = (VuDev *)arg;
598 VubrDev *vubr = container_of(dev, VubrDev, vudev);
599 int pagesize = qemu_real_host_page_size;
600 int qidx;
601
602 while (true) {
603 for (qidx = 0; qidx < VHOST_USER_BRIDGE_MAX_QUEUES; qidx++) {
604 uint16_t *n = vubr->notifier.addr + pagesize * qidx;
605
606 if (*n == qidx) {
607 *n = 0xffff;
608
609
610 smp_mb();
611
612 DPRINT("Got a notification for queue%d via host notifier.\n",
613 qidx);
614
615 if (qidx % 2 == 1) {
616 vubr_handle_tx(dev, qidx);
617 }
618 }
619 usleep(1000);
620 }
621 }
622
623 return NULL;
624}
625
626static void
627vubr_host_notifier_setup(VubrDev *dev)
628{
629 char template[] = "/tmp/vubr-XXXXXX";
630 pthread_t thread;
631 size_t length;
632 void *addr;
633 int fd;
634
635 length = qemu_real_host_page_size * VHOST_USER_BRIDGE_MAX_QUEUES;
636
637 fd = mkstemp(template);
638 if (fd < 0) {
639 vubr_die("mkstemp()");
640 }
641
642 if (posix_fallocate(fd, 0, length) != 0) {
643 vubr_die("posix_fallocate()");
644 }
645
646 addr = mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
647 if (addr == MAP_FAILED) {
648 vubr_die("mmap()");
649 }
650
651 memset(addr, 0xff, length);
652
653 if (pthread_create(&thread, NULL, notifier_thread, &dev->vudev) != 0) {
654 vubr_die("pthread_create()");
655 }
656
657 dev->notifier.fd = fd;
658 dev->notifier.addr = addr;
659 dev->notifier.thread = thread;
660}
661
662static void
663vubr_set_host(struct sockaddr_in *saddr, const char *host)
664{
665 if (qemu_isdigit(host[0])) {
666 if (!inet_aton(host, &saddr->sin_addr)) {
667 fprintf(stderr, "inet_aton() failed.\n");
668 exit(1);
669 }
670 } else {
671 struct hostent *he = gethostbyname(host);
672
673 if (!he) {
674 fprintf(stderr, "gethostbyname() failed.\n");
675 exit(1);
676 }
677 saddr->sin_addr = *(struct in_addr *)he->h_addr;
678 }
679}
680
681static void
682vubr_backend_udp_setup(VubrDev *dev,
683 const char *local_host,
684 const char *local_port,
685 const char *remote_host,
686 const char *remote_port)
687{
688 int sock;
689 const char *r;
690
691 int lport, rport;
692
693 lport = strtol(local_port, (char **)&r, 0);
694 if (r == local_port) {
695 fprintf(stderr, "lport parsing failed.\n");
696 exit(1);
697 }
698
699 rport = strtol(remote_port, (char **)&r, 0);
700 if (r == remote_port) {
701 fprintf(stderr, "rport parsing failed.\n");
702 exit(1);
703 }
704
705 struct sockaddr_in si_local = {
706 .sin_family = AF_INET,
707 .sin_port = htons(lport),
708 };
709
710 vubr_set_host(&si_local, local_host);
711
712
713 dev->backend_udp_dest = (struct sockaddr_in) {
714 .sin_family = AF_INET,
715 .sin_port = htons(rport),
716 };
717 vubr_set_host(&dev->backend_udp_dest, remote_host);
718
719 sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
720 if (sock == -1) {
721 vubr_die("socket");
722 }
723
724 if (bind(sock, (struct sockaddr *)&si_local, sizeof(si_local)) == -1) {
725 vubr_die("bind");
726 }
727
728 dev->backend_udp_sock = sock;
729 dispatcher_add(&dev->dispatcher, sock, dev, vubr_backend_recv_cb);
730 DPRINT("Waiting for data from udp backend on %s:%d...\n",
731 local_host, lport);
732}
733
734static void
735vubr_run(VubrDev *dev)
736{
737 while (!dev->quit) {
738
739 dispatcher_wait(&dev->dispatcher, 200000);
740
741 }
742}
743
744static int
745vubr_parse_host_port(const char **host, const char **port, const char *buf)
746{
747 char *p = strchr(buf, ':');
748
749 if (!p) {
750 return -1;
751 }
752 *p = '\0';
753 *host = strdup(buf);
754 *port = strdup(p + 1);
755 return 0;
756}
757
758#define DEFAULT_UD_SOCKET "/tmp/vubr.sock"
759#define DEFAULT_LHOST "127.0.0.1"
760#define DEFAULT_LPORT "4444"
761#define DEFAULT_RHOST "127.0.0.1"
762#define DEFAULT_RPORT "5555"
763
764static const char *ud_socket_path = DEFAULT_UD_SOCKET;
765static const char *lhost = DEFAULT_LHOST;
766static const char *lport = DEFAULT_LPORT;
767static const char *rhost = DEFAULT_RHOST;
768static const char *rport = DEFAULT_RPORT;
769
770int
771main(int argc, char *argv[])
772{
773 VubrDev *dev;
774 int opt;
775 bool client = false;
776 bool host_notifier = false;
777
778 while ((opt = getopt(argc, argv, "l:r:u:cH")) != -1) {
779
780 switch (opt) {
781 case 'l':
782 if (vubr_parse_host_port(&lhost, &lport, optarg) < 0) {
783 goto out;
784 }
785 break;
786 case 'r':
787 if (vubr_parse_host_port(&rhost, &rport, optarg) < 0) {
788 goto out;
789 }
790 break;
791 case 'u':
792 ud_socket_path = strdup(optarg);
793 break;
794 case 'c':
795 client = true;
796 break;
797 case 'H':
798 host_notifier = true;
799 break;
800 default:
801 goto out;
802 }
803 }
804
805 DPRINT("ud socket: %s (%s)\n", ud_socket_path,
806 client ? "client" : "server");
807 DPRINT("local: %s:%s\n", lhost, lport);
808 DPRINT("remote: %s:%s\n", rhost, rport);
809
810 dev = vubr_new(ud_socket_path, client);
811 if (!dev) {
812 return 1;
813 }
814
815 if (host_notifier) {
816 vubr_host_notifier_setup(dev);
817 }
818
819 vubr_backend_udp_setup(dev, lhost, lport, rhost, rport);
820 vubr_run(dev);
821
822 vu_deinit(&dev->vudev);
823
824 return 0;
825
826out:
827 fprintf(stderr, "Usage: %s ", argv[0]);
828 fprintf(stderr, "[-c] [-H] [-u ud_socket_path] [-l lhost:lport] [-r rhost:rport]\n");
829 fprintf(stderr, "\t-u path to unix doman socket. default: %s\n",
830 DEFAULT_UD_SOCKET);
831 fprintf(stderr, "\t-l local host and port. default: %s:%s\n",
832 DEFAULT_LHOST, DEFAULT_LPORT);
833 fprintf(stderr, "\t-r remote host and port. default: %s:%s\n",
834 DEFAULT_RHOST, DEFAULT_RPORT);
835 fprintf(stderr, "\t-c client mode\n");
836 fprintf(stderr, "\t-H use host notifier\n");
837
838 return 1;
839}
840