public inbox for passt-dev@passt.top
 help / color / mirror / code / Atom feed
blob a3d156558359dfffda3f0dfe9c224956d05cbe7b 26765 bytes (raw)

   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
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
 
// SPDX-License-Identifier: GPL-2.0-or-later

/* some parts from QEMU subprojects/libvhost-user/libvhost-user.c */

#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <assert.h>
#include <stdbool.h>
#include <inttypes.h>
#include <time.h>
#include <net/ethernet.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/mman.h>
#include <linux/vhost_types.h>
#include <linux/virtio_net.h>

#include "util.h"
#include "passt.h"
#include "tap.h"
#include "vhost_user.h"

#define VHOST_USER_VERSION 1

void vu_print_capabilities(void)
{
	printf("{\n");
	printf("  \"type\": \"net\"\n");
	printf("}\n");
	exit(EXIT_SUCCESS);
}

static const char *
vu_request_to_string(unsigned int req)
{
	if (req < VHOST_USER_MAX) {
#define REQ(req) [req] = #req
		static const char * const vu_request_str[] = {
			REQ(VHOST_USER_NONE),
			REQ(VHOST_USER_GET_FEATURES),
			REQ(VHOST_USER_SET_FEATURES),
			REQ(VHOST_USER_SET_OWNER),
			REQ(VHOST_USER_RESET_OWNER),
			REQ(VHOST_USER_SET_MEM_TABLE),
			REQ(VHOST_USER_SET_LOG_BASE),
			REQ(VHOST_USER_SET_LOG_FD),
			REQ(VHOST_USER_SET_VRING_NUM),
			REQ(VHOST_USER_SET_VRING_ADDR),
			REQ(VHOST_USER_SET_VRING_BASE),
			REQ(VHOST_USER_GET_VRING_BASE),
			REQ(VHOST_USER_SET_VRING_KICK),
			REQ(VHOST_USER_SET_VRING_CALL),
			REQ(VHOST_USER_SET_VRING_ERR),
			REQ(VHOST_USER_GET_PROTOCOL_FEATURES),
			REQ(VHOST_USER_SET_PROTOCOL_FEATURES),
			REQ(VHOST_USER_GET_QUEUE_NUM),
			REQ(VHOST_USER_SET_VRING_ENABLE),
			REQ(VHOST_USER_SEND_RARP),
			REQ(VHOST_USER_NET_SET_MTU),
			REQ(VHOST_USER_SET_BACKEND_REQ_FD),
			REQ(VHOST_USER_IOTLB_MSG),
			REQ(VHOST_USER_SET_VRING_ENDIAN),
			REQ(VHOST_USER_GET_CONFIG),
			REQ(VHOST_USER_SET_CONFIG),
			REQ(VHOST_USER_POSTCOPY_ADVISE),
			REQ(VHOST_USER_POSTCOPY_LISTEN),
			REQ(VHOST_USER_POSTCOPY_END),
			REQ(VHOST_USER_GET_INFLIGHT_FD),
			REQ(VHOST_USER_SET_INFLIGHT_FD),
			REQ(VHOST_USER_GPU_SET_SOCKET),
			REQ(VHOST_USER_VRING_KICK),
			REQ(VHOST_USER_GET_MAX_MEM_SLOTS),
			REQ(VHOST_USER_ADD_MEM_REG),
			REQ(VHOST_USER_REM_MEM_REG),
			REQ(VHOST_USER_MAX),
		};
#undef REQ
		return vu_request_str[req];
	}

	return "unknown";
}

/* Translate qemu virtual address to our virtual address.  */
static void *qva_to_va(VuDev *dev, uint64_t qemu_addr)
{
	unsigned int i;

	/* Find matching memory region.  */
	for (i = 0; i < dev->nregions; i++) {
		const VuDevRegion *r = &dev->regions[i];

		if ((qemu_addr >= r->qva) && (qemu_addr < (r->qva + r->size))) {
			/* NOLINTNEXTLINE(performance-no-int-to-ptr) */
			return (void *)(qemu_addr - r->qva + r->mmap_addr +
					r->mmap_offset);
		}
	}

	return NULL;
}

static void
vmsg_close_fds(const VhostUserMsg *vmsg)
{
	int i;

	for (i = 0; i < vmsg->fd_num; i++)
		close(vmsg->fds[i]);
}

static void vu_remove_watch(VuDev *vdev, int fd)
{
	const struct ctx *c = (struct ctx *) ((char *)vdev -
					      offsetof(struct ctx, vdev));

	epoll_ctl(c->epollfd, EPOLL_CTL_DEL, fd, NULL);
}

/* Set reply payload.u64 and clear request flags and fd_num */
static void vmsg_set_reply_u64(struct VhostUserMsg *vmsg, uint64_t val)
{
	vmsg->hdr.flags = 0; /* defaults will be set by vu_send_reply() */
	vmsg->hdr.size = sizeof(vmsg->payload.u64);
	vmsg->payload.u64 = val;
	vmsg->fd_num = 0;
}

static ssize_t vu_message_read_default(VuDev *dev, int conn_fd, struct VhostUserMsg *vmsg)
{
	char control[CMSG_SPACE(VHOST_MEMORY_BASELINE_NREGIONS *
		     sizeof(int))] = { 0 };
	struct iovec iov = {
		.iov_base = (char *)vmsg,
		.iov_len = VHOST_USER_HDR_SIZE,
	};
	struct msghdr msg = {
		.msg_iov = &iov,
		.msg_iovlen = 1,
		.msg_control = control,
		.msg_controllen = sizeof(control),
	};
	size_t fd_size;
	struct cmsghdr *cmsg;
	ssize_t ret, sz_payload;

	ret = recvmsg(conn_fd, &msg, MSG_DONTWAIT);
	if (ret < 0) {
		if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
			return 0;
		vu_panic(dev, "Error while recvmsg: %s", strerror(errno));
		goto out;
	}

	vmsg->fd_num = 0;
	for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
	     cmsg = CMSG_NXTHDR(&msg, cmsg)) {
		if (cmsg->cmsg_level == SOL_SOCKET &&
		    cmsg->cmsg_type == SCM_RIGHTS) {
			fd_size = cmsg->cmsg_len - CMSG_LEN(0);
			vmsg->fd_num = fd_size / sizeof(int);
			memcpy(vmsg->fds, CMSG_DATA(cmsg), fd_size);
			break;
		}
	}

	sz_payload = vmsg->hdr.size;
	if ((size_t)sz_payload > sizeof(vmsg->payload)) {
		vu_panic(dev,
			 "Error: too big message request: %d, size: vmsg->size: %zd, "
			 "while sizeof(vmsg->payload) = %zu",
			 vmsg->hdr.request, sz_payload, sizeof(vmsg->payload));
		goto out;
	}

	if (sz_payload) {
		do {
			ret = recv(conn_fd, &vmsg->payload, sz_payload, 0);
		} while (ret < 0 && (errno == EINTR || errno == EAGAIN));

		if (ret < sz_payload) {
			vu_panic(dev, "Error while reading: %s", strerror(errno));
			goto out;
		}
	}

	return 1;
out:
	vmsg_close_fds(vmsg);

	return -ECONNRESET;
}

static int vu_message_write(VuDev *dev, int conn_fd, struct VhostUserMsg *vmsg)
{
	int rc;
	const uint8_t *p = (uint8_t *)vmsg;
	char control[CMSG_SPACE(VHOST_MEMORY_BASELINE_NREGIONS * sizeof(int))] = { 0 };
	struct iovec iov = {
		.iov_base = (char *)vmsg,
		.iov_len = VHOST_USER_HDR_SIZE,
	};
	struct msghdr msg = {
		.msg_iov = &iov,
		.msg_iovlen = 1,
		.msg_control = control,
	};

	memset(control, 0, sizeof(control));
	assert(vmsg->fd_num <= VHOST_MEMORY_BASELINE_NREGIONS);
	if (vmsg->fd_num > 0) {
		size_t fdsize = vmsg->fd_num * sizeof(int);
		struct cmsghdr *cmsg;

		msg.msg_controllen = CMSG_SPACE(fdsize);
		cmsg = CMSG_FIRSTHDR(&msg);
		cmsg->cmsg_len = CMSG_LEN(fdsize);
		cmsg->cmsg_level = SOL_SOCKET;
		cmsg->cmsg_type = SCM_RIGHTS;
		memcpy(CMSG_DATA(cmsg), vmsg->fds, fdsize);
	} else {
		msg.msg_controllen = 0;
	}

	do {
		rc = sendmsg(conn_fd, &msg, 0);
	} while (rc < 0 && (errno == EINTR || errno == EAGAIN));

	if (vmsg->hdr.size) {
		do {
			if (vmsg->data)
				rc = write(conn_fd, vmsg->data, vmsg->hdr.size);
			else
				rc = write(conn_fd, p + VHOST_USER_HDR_SIZE, vmsg->hdr.size);
		} while (rc < 0 && (errno == EINTR || errno == EAGAIN));
	}

	if (rc <= 0) {
		vu_panic(dev, "Error while writing: %s", strerror(errno));
		return false;
	}

	return true;
}

static int vu_send_reply(VuDev *dev, int conn_fd, struct VhostUserMsg *msg)
{
	msg->hdr.flags &= ~VHOST_USER_VERSION_MASK;
	msg->hdr.flags |= VHOST_USER_VERSION;
	msg->hdr.flags |= VHOST_USER_REPLY_MASK;

	return vu_message_write(dev, conn_fd, msg);
}

static bool vu_get_features_exec(struct VhostUserMsg *msg)
{
	uint64_t features =
		1ULL << VIRTIO_F_VERSION_1 |
		1ULL << VIRTIO_NET_F_MRG_RXBUF |
		1ULL << VHOST_USER_F_PROTOCOL_FEATURES;

	vmsg_set_reply_u64(msg, features);

	debug("Sending back to guest u64: 0x%016"PRIx64, msg->payload.u64);

	return true;
}

static void
vu_set_enable_all_rings(VuDev *vdev, bool enabled)
{
	uint16_t i;

	for (i = 0; i < VHOST_USER_MAX_QUEUES; i++)
		vdev->vq[i].enable = enabled;
}

static bool
vu_set_features_exec(VuDev *vdev, struct VhostUserMsg *msg)
{
	debug("u64: 0x%016"PRIx64, msg->payload.u64);

	vdev->features = msg->payload.u64;
	if (!vu_has_feature(vdev, VIRTIO_F_VERSION_1)) {
		/*
		 * We only support devices conforming to VIRTIO 1.0 or
		 * later
		 */
		vu_panic(vdev, "virtio legacy devices aren't supported by passt");
		return false;
	}

	if (!vu_has_feature(vdev, VHOST_USER_F_PROTOCOL_FEATURES))
		vu_set_enable_all_rings(vdev, true);

	/* virtio-net features */

	if (vu_has_feature(vdev, VIRTIO_F_VERSION_1) ||
	    vu_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF)) {
		vdev->hdrlen = sizeof(struct virtio_net_hdr_mrg_rxbuf);
	} else {
		vdev->hdrlen = sizeof(struct virtio_net_hdr);
	}

	return false;
}

static bool
vu_set_owner_exec(void)
{
	return false;
}

static bool map_ring(VuDev *vdev, VuVirtq *vq)
{
	vq->vring.desc = qva_to_va(vdev, vq->vra.desc_user_addr);
	vq->vring.used = qva_to_va(vdev, vq->vra.used_user_addr);
	vq->vring.avail = qva_to_va(vdev, vq->vra.avail_user_addr);

	debug("Setting virtq addresses:");
	debug("    vring_desc  at %p", (void *)vq->vring.desc);
	debug("    vring_used  at %p", (void *)vq->vring.used);
	debug("    vring_avail at %p", (void *)vq->vring.avail);

	return !(vq->vring.desc && vq->vring.used && vq->vring.avail);
}

int vu_packet_check_range(void *buf, size_t offset, size_t len, const char *start,
			  const char *func, int line)
{
	VuDevRegion *dev_region;

	for (dev_region = buf; dev_region->mmap_addr; dev_region++) {
		/* NOLINTNEXTLINE(performance-no-int-to-ptr) */
		char *m = (char *)dev_region->mmap_addr;

		if (m <= start &&
		    start + offset + len < m + dev_region->mmap_offset +
					       dev_region->size)
			return 0;
	}
	if (func)
		trace("cannot find region, %s:%i", func, line);

	return -1;
}

/*
 * #syscalls:passt mmap munmap
 */

static bool vu_set_mem_table_exec(VuDev *vdev,
				  struct VhostUserMsg *msg)
{
	unsigned int i;
	struct VhostUserMemory m = msg->payload.memory, *memory = &m;

	for (i = 0; i < vdev->nregions; i++) {
		VuDevRegion *r = &vdev->regions[i];
		/* NOLINTNEXTLINE(performance-no-int-to-ptr) */
		void *mm = (void *)r->mmap_addr;

		if (mm)
			munmap(mm, r->size + r->mmap_offset);
	}
	vdev->nregions = memory->nregions;

	debug("Nregions: %u", memory->nregions);
	for (i = 0; i < vdev->nregions; i++) {
		void *mmap_addr;
		VhostUserMemory_region *msg_region = &memory->regions[i];
		VuDevRegion *dev_region = &vdev->regions[i];

		debug("Region %d", i);
		debug("    guest_phys_addr: 0x%016"PRIx64,
		      msg_region->guest_phys_addr);
		debug("    memory_size:     0x%016"PRIx64,
		      msg_region->memory_size);
		debug("    userspace_addr   0x%016"PRIx64,
		      msg_region->userspace_addr);
		debug("    mmap_offset      0x%016"PRIx64,
		      msg_region->mmap_offset);

		dev_region->gpa = msg_region->guest_phys_addr;
		dev_region->size = msg_region->memory_size;
		dev_region->qva = msg_region->userspace_addr;
		dev_region->mmap_offset = msg_region->mmap_offset;

		/* We don't use offset argument of mmap() since the
		 * mapped address has to be page aligned, and we use huge
		 * pages.
		 */
		mmap_addr = mmap(0, dev_region->size + dev_region->mmap_offset,
				 PROT_READ | PROT_WRITE, MAP_SHARED | MAP_NORESERVE,
				 msg->fds[i], 0);

		if (mmap_addr == MAP_FAILED) {
			vu_panic(vdev, "region mmap error: %s", strerror(errno));
		} else {
			dev_region->mmap_addr = (uint64_t)(uintptr_t)mmap_addr;
			debug("    mmap_addr:       0x%016"PRIx64,
			      dev_region->mmap_addr);
		}

		close(msg->fds[i]);
	}

	for (i = 0; i < VHOST_USER_MAX_QUEUES; i++) {
		if (vdev->vq[i].vring.desc) {
			if (map_ring(vdev, &vdev->vq[i]))
				vu_panic(vdev, "remapping queue %d during setmemtable", i);
		}
	}

	/* XXX */
	ASSERT(vdev->nregions < VHOST_USER_MAX_RAM_SLOTS - 1);
	vdev->regions[vdev->nregions].mmap_addr = 0; /* mark EOF for vu_packet_check_range() */

	tap_sock_update_buf(vdev->regions, 0);

	return false;
}

static bool vu_set_vring_num_exec(VuDev *vdev,
				  struct VhostUserMsg *msg)
{
	unsigned int idx = msg->payload.state.index;
	unsigned int num = msg->payload.state.num;

	debug("State.index: %u", idx);
	debug("State.num:   %u", num);
	vdev->vq[idx].vring.num = num;

	return false;
}

static bool vu_set_vring_addr_exec(VuDev *vdev,
				   struct VhostUserMsg *msg)
{
	struct vhost_vring_addr addr = msg->payload.addr, *vra = &addr;
	VuVirtq *vq = &vdev->vq[vra->index];

	debug("vhost_vring_addr:");
	debug("    index:  %d", vra->index);
	debug("    flags:  %d", vra->flags);
	debug("    desc_user_addr:   0x%016" PRIx64, (uint64_t)vra->desc_user_addr);
	debug("    used_user_addr:   0x%016" PRIx64, (uint64_t)vra->used_user_addr);
	debug("    avail_user_addr:  0x%016" PRIx64, (uint64_t)vra->avail_user_addr);
	debug("    log_guest_addr:   0x%016" PRIx64, (uint64_t)vra->log_guest_addr);

	vq->vra = *vra;
	vq->vring.flags = vra->flags;
	vq->vring.log_guest_addr = vra->log_guest_addr;

	if (map_ring(vdev, vq)) {
		vu_panic(vdev, "Invalid vring_addr message");
		return false;
	}

	vq->used_idx = le16toh(vq->vring.used->idx);

	if (vq->last_avail_idx != vq->used_idx) {
		debug("Last avail index != used index: %u != %u",
		      vq->last_avail_idx, vq->used_idx);
	}

	return false;
}

static bool vu_set_vring_base_exec(VuDev *vdev,
				   struct VhostUserMsg *msg)
{
	unsigned int idx = msg->payload.state.index;
	unsigned int num = msg->payload.state.num;

	debug("State.index: %u", idx);
	debug("State.num:   %u", num);
	vdev->vq[idx].shadow_avail_idx = vdev->vq[idx].last_avail_idx = num;

	return false;
}

static bool vu_get_vring_base_exec(VuDev *vdev,
				   struct VhostUserMsg *msg)
{
	unsigned int idx = msg->payload.state.index;

	debug("State.index: %u", idx);
	msg->payload.state.num = vdev->vq[idx].last_avail_idx;
	msg->hdr.size = sizeof(msg->payload.state);

	vdev->vq[idx].started = false;

	if (vdev->vq[idx].call_fd != -1) {
		close(vdev->vq[idx].call_fd);
		vdev->vq[idx].call_fd = -1;
	}
	if (vdev->vq[idx].kick_fd != -1) {
		vu_remove_watch(vdev,  vdev->vq[idx].kick_fd);
		close(vdev->vq[idx].kick_fd);
		vdev->vq[idx].kick_fd = -1;
	}

	return true;
}

static void vu_set_watch(VuDev *vdev, int fd)
{
	const struct ctx *c = (struct ctx *)
			      ((char *)vdev - offsetof(struct ctx, vdev));
	union epoll_ref ref = { .type = EPOLL_TYPE_VHOST_KICK, .fd = fd };
	struct epoll_event ev = { 0 };

	ev.data.u64 = ref.u64;
	ev.events = EPOLLIN;
	epoll_ctl(c->epollfd, EPOLL_CTL_ADD, fd, &ev);
}

static int vu_wait_queue(const VuVirtq *vq)
{
	eventfd_t kick_data;
	ssize_t rc;
	int status;

	/* wait the kernel to put new entries in the queue */

	status = fcntl(vq->kick_fd, F_GETFL);
	if (status == -1)
		return -1;

	fcntl(vq->kick_fd, F_SETFL, status & ~O_NONBLOCK);
	rc =  eventfd_read(vq->kick_fd, &kick_data);
	fcntl(vq->kick_fd, F_SETFL, status);
	if (rc == -1)
		return -1;

	return 0;
}

int vu_send(const struct ctx *c, const void *buf, size_t size)
{
	VuDev *vdev = (VuDev *)&c->vdev;
	size_t hdrlen = vdev->hdrlen;
	VuVirtq *vq = &vdev->vq[VHOST_USER_RX_QUEUE];
	VuVirtqElement elem[VIRTQUEUE_MAX_SIZE];
	struct iovec in_sg[VIRTQUEUE_MAX_SIZE];
	size_t lens[VIRTQUEUE_MAX_SIZE];
	size_t offset;
	int i, j;
	__virtio16 *num_buffers_ptr;
	int in_sg_count;

	debug("vu_send size %zu hdrlen %zu", size, hdrlen);

	if (!vu_queue_enabled(vq) || !vu_queue_started(vq)) {
		err("Got packet, but no available descriptors on RX virtq.");
		return 0;
	}

	offset = 0;
	i = 0;
	num_buffers_ptr = NULL;
	in_sg_count = 0;
	while (offset < size) {
		size_t len;
		int total;
		int ret;

		total = 0;

		if (i == ARRAY_SIZE(elem) ||
		    in_sg_count == ARRAY_SIZE(in_sg)) {
			err("virtio-net unexpected long buffer chain");
			goto err;
		}

		elem[i].out_num = 0;
		elem[i].out_sg = NULL;
		elem[i].in_num = ARRAY_SIZE(in_sg) - in_sg_count;
		elem[i].in_sg = &in_sg[in_sg_count];

		ret = vu_queue_pop(vdev, vq, &elem[i]);
		if (ret < 0) {
			if (!vdev->broken) {
				if (vu_wait_queue(vq) != -1)
					continue;
			}
			if (i) {
				err("virtio-net unexpected empty queue: "
				    "i %d mergeable %d offset %zd, size %zd, "
				    "features 0x%" PRIx64,
				    i, vu_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF),
				    offset, size, vdev->features);
			}
			offset = -1;
			goto err;
		}
		in_sg_count += elem[i].in_num;

		if (elem[i].in_num < 1) {
			err("virtio-net receive queue contains no in buffers");
			vu_queue_detach_element(vdev, vq, elem[i].index, 0);
			offset = -1;
			goto err;
		}

		if (i == 0) {
			struct virtio_net_hdr hdr = {
				.flags = VIRTIO_NET_HDR_F_DATA_VALID,
				.gso_type = VIRTIO_NET_HDR_GSO_NONE,
			};

			ASSERT(offset == 0);
			ASSERT(elem[i].in_sg[0].iov_len >= hdrlen);

			len = iov_from_buf(elem[i].in_sg, elem[i].in_num, 0,
					   &hdr, sizeof(hdr));

			num_buffers_ptr = (__virtio16 *)((char *)elem[i].in_sg[0].iov_base +
							 len);

			total += hdrlen;
		}

		len = iov_from_buf(elem[i].in_sg, elem[i].in_num, total, (char *)buf + offset,
				   size - offset);

		total += len;
		offset += len;

		/* If buffers can't be merged, at this point we
		 * must have consumed the complete packet.
		 * Otherwise, drop it.
		 */
		if (!vu_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) && offset < size) {
			vu_queue_unpop(vdev, vq, elem[i].index, total);
			goto err;
		}

	lens[i] = total;
		i++;
	}

	if (num_buffers_ptr && vu_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
		*num_buffers_ptr = htole16(i);

	for (j = 0; j < i; j++) {
		debug("filling total %zd idx %d", lens[j], j);
		vu_queue_fill(vdev, vq, &elem[j], lens[j], j);
	}

	vu_queue_flush(vdev, vq, i);
	vu_queue_notify(vdev, vq);

	debug("sent %zu", offset);

	return offset;
err:
	for (j = 0; j < i; j++)
		vu_queue_detach_element(vdev, vq, elem[j].index, lens[j]);

	return offset;
}

static void vu_handle_tx(VuDev *vdev, int index)
{
	struct ctx *c = (struct ctx *) ((char *)vdev - offsetof(struct ctx, vdev));
	VuVirtq *vq = &vdev->vq[index];
	int hdrlen = vdev->hdrlen;
	struct timespec now;
	VuVirtqElement  elem[VIRTQUEUE_MAX_SIZE];
	struct iovec out_sg[VIRTQUEUE_MAX_SIZE];
	int out_sg_count;

	int count;

	if (index % 2 != VHOST_USER_TX_QUEUE) {
		debug("index %d is not an TX queue", index);
		return;
	}

	clock_gettime(CLOCK_MONOTONIC, &now);

	tap_flush_pools();

	count = 0;
	out_sg_count = 0;
	while (1) {
		int ret;

		ASSERT(index == VHOST_USER_TX_QUEUE);

		elem[count].out_num = 1;
		elem[count].out_sg = &out_sg[out_sg_count];
		elem[count].in_num = 0;
		elem[count].in_sg = NULL;
		ret = vu_queue_pop(vdev, vq, &elem[count]);
		if (ret < 0)
			break;
		out_sg_count += elem[count].out_num;

		if (elem[count].out_num < 1) {
			debug("virtio-net header not in first element");
			break;
		}
		ASSERT(elem[count].out_num == 1);

		tap_add_packet(c, elem[count].out_sg[0].iov_len - hdrlen,
			       (char *)elem[count].out_sg[0].iov_base + hdrlen);
		count++;
	}
	tap_handler(c, &now);

	if (count) {
		int i;

		for (i = 0; i < count; i++)
			vu_queue_fill(vdev, vq, &elem[i], 0, i);
		vu_queue_flush(vdev, vq, count);
		vu_queue_notify(vdev, vq);
	}
}

void vu_kick_cb(struct ctx *c, union epoll_ref ref)
{
	VuDev *vdev = &c->vdev;
	eventfd_t kick_data;
	ssize_t rc;
	int idx;

	for (idx = 0; idx < VHOST_USER_MAX_QUEUES; idx++)
		if (c->vdev.vq[idx].kick_fd == ref.fd)
			break;

	if (idx == VHOST_USER_MAX_QUEUES)
		return;

	rc =  eventfd_read(ref.fd, &kick_data);
	if (rc == -1) {
		vu_panic(vdev, "kick eventfd_read(): %s", strerror(errno));
		vu_remove_watch(vdev, ref.fd);
	} else {
		debug("Got kick_data: %016"PRIx64" idx:%d",
		      kick_data, idx);
		if (idx % 2 == VHOST_USER_TX_QUEUE)
			vu_handle_tx(vdev, idx);
	}
}

static bool vu_check_queue_msg_file(VuDev *vdev, struct VhostUserMsg *msg)
{
	int idx = msg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
	bool nofd = msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK;

	if (idx >= VHOST_USER_MAX_QUEUES) {
		vmsg_close_fds(msg);
		vu_panic(vdev, "Invalid queue index: %u", idx);
		return false;
	}

	if (nofd) {
		vmsg_close_fds(msg);
		return true;
	}

	if (msg->fd_num != 1) {
		vmsg_close_fds(msg);
		vu_panic(vdev, "Invalid fds in request: %d", msg->hdr.request);
		return false;
	}

	return true;
}

static bool vu_set_vring_kick_exec(VuDev *vdev,
				   struct VhostUserMsg *msg)
{
	int idx = msg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
	bool nofd = msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK;

	debug("u64: 0x%016"PRIx64, msg->payload.u64);

	if (!vu_check_queue_msg_file(vdev, msg))
		return false;

	if (vdev->vq[idx].kick_fd != -1) {
		vu_remove_watch(vdev, vdev->vq[idx].kick_fd);
		close(vdev->vq[idx].kick_fd);
		vdev->vq[idx].kick_fd = -1;
	}

	/* cppcheck-suppress redundantAssignment */
	vdev->vq[idx].kick_fd = nofd ? -1 : msg->fds[0];
	debug("Got kick_fd: %d for vq: %d", vdev->vq[idx].kick_fd, idx);

	vdev->vq[idx].started = true;

	if (vdev->vq[idx].kick_fd != -1 && idx % 2 == VHOST_USER_TX_QUEUE) {
		vu_set_watch(vdev, vdev->vq[idx].kick_fd);
		debug("Waiting for kicks on fd: %d for vq: %d",
		      vdev->vq[idx].kick_fd, idx);
	}

	return false;
}

static bool vu_set_vring_call_exec(VuDev *vdev,
				   struct VhostUserMsg *msg)
{
	int idx = msg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
	bool nofd = msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK;

	debug("u64: 0x%016"PRIx64, msg->payload.u64);

	if (!vu_check_queue_msg_file(vdev, msg))
		return false;

	if (vdev->vq[idx].call_fd != -1) {
		close(vdev->vq[idx].call_fd);
		vdev->vq[idx].call_fd = -1;
	}

	/* cppcheck-suppress redundantAssignment */
	vdev->vq[idx].call_fd = nofd ? -1 : msg->fds[0];

	/* in case of I/O hang after reconnecting */
	if (vdev->vq[idx].call_fd != -1)
		eventfd_write(msg->fds[0], 1);

	debug("Got call_fd: %d for vq: %d", vdev->vq[idx].call_fd, idx);

	return false;
}

static bool vu_set_vring_err_exec(VuDev *vdev,
				  struct VhostUserMsg *msg)
{
	int idx = msg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
	bool nofd = msg->payload.u64 & VHOST_USER_VRING_NOFD_MASK;

	debug("u64: 0x%016"PRIx64, msg->payload.u64);

	if (!vu_check_queue_msg_file(vdev, msg))
		return false;

	if (vdev->vq[idx].err_fd != -1) {
		close(vdev->vq[idx].err_fd);
		vdev->vq[idx].err_fd = -1;
	}

	/* cppcheck-suppress redundantAssignment */
	vdev->vq[idx].err_fd = nofd ? -1 : msg->fds[0];

	return false;
}

static bool vu_get_protocol_features_exec(struct VhostUserMsg *msg)
{
	uint64_t features = 1ULL << VHOST_USER_PROTOCOL_F_REPLY_ACK;

	vmsg_set_reply_u64(msg, features);

	return true;
}

static bool vu_set_protocol_features_exec(VuDev *vdev, struct VhostUserMsg *msg)
{
	uint64_t features = msg->payload.u64;

	debug("u64: 0x%016"PRIx64, features);

	vdev->protocol_features = msg->payload.u64;

	if (vu_has_protocol_feature(vdev,
				    VHOST_USER_PROTOCOL_F_INBAND_NOTIFICATIONS) &&
	    (!vu_has_protocol_feature(vdev, VHOST_USER_PROTOCOL_F_BACKEND_REQ) ||
	     !vu_has_protocol_feature(vdev, VHOST_USER_PROTOCOL_F_REPLY_ACK))) {
		/*
		 * The use case for using messages for kick/call is simulation, to make
		 * the kick and call synchronous. To actually get that behaviour, both
		 * of the other features are required.
		 * Theoretically, one could use only kick messages, or do them without
		 * having F_REPLY_ACK, but too many (possibly pending) messages on the
		 * socket will eventually cause the master to hang, to avoid this in
		 * scenarios where not desired enforce that the settings are in a way
		 * that actually enables the simulation case.
		 */
		vu_panic(vdev,
			 "F_IN_BAND_NOTIFICATIONS requires F_BACKEND_REQ && F_REPLY_ACK");
		return false;
	}

	return false;
}


static bool vu_get_queue_num_exec(struct VhostUserMsg *msg)
{
	vmsg_set_reply_u64(msg, VHOST_USER_MAX_QUEUES);
	return true;
}

static bool vu_set_vring_enable_exec(VuDev *vdev, struct VhostUserMsg *msg)
{
	unsigned int idx = msg->payload.state.index;
	unsigned int enable = msg->payload.state.num;

	debug("State.index:  %u", idx);
	debug("State.enable: %u", enable);

	if (idx >= VHOST_USER_MAX_QUEUES) {
		vu_panic(vdev, "Invalid vring_enable index: %u", idx);
		return false;
	}

	vdev->vq[idx].enable = enable;
	return false;
}

void vu_init(struct ctx *c)
{
	int i;

	c->vdev.hdrlen = 0;
	for (i = 0; i < VHOST_USER_MAX_QUEUES; i++)
		c->vdev.vq[i] = (VuVirtq){
			.call_fd = -1,
			.kick_fd = -1,
			.err_fd = -1,
			.notification = true,
		};
}

static void vu_cleanup(VuDev *vdev)
{
	unsigned int i;

	for (i = 0; i < VHOST_USER_MAX_QUEUES; i++) {
		VuVirtq *vq = &vdev->vq[i];

		vq->started = false;
		vq->notification = true;

		if (vq->call_fd != -1) {
			close(vq->call_fd);
			vq->call_fd = -1;
		}
		if (vq->err_fd != -1) {
			close(vq->err_fd);
			vq->err_fd = -1;
		}
		if (vq->kick_fd != -1) {
			vu_remove_watch(vdev,  vq->kick_fd);
			close(vq->kick_fd);
			vq->kick_fd = -1;
		}

		vq->vring.desc = 0;
		vq->vring.used = 0;
		vq->vring.avail = 0;
	}
	vdev->hdrlen = 0;

	for (i = 0; i < vdev->nregions; i++) {
		const VuDevRegion *r = &vdev->regions[i];
		/* NOLINTNEXTLINE(performance-no-int-to-ptr) */
		void *m = (void *)r->mmap_addr;

		if (m)
			munmap(m, r->size + r->mmap_offset);
	}
	vdev->nregions = 0;
}

/**
 * tap_handler_vu() - Packet handler for vhost-user
 * @c:		Execution context
 * @events:	epoll events
 */
void tap_handler_vu(struct ctx *c, uint32_t events)
{
	VuDev *dev = &c->vdev;
	struct VhostUserMsg msg = { 0 };
	bool need_reply, reply_requested;
	int ret;

	if (events & (EPOLLRDHUP | EPOLLHUP | EPOLLERR)) {
		tap_sock_reset(c);
		return;
	}


	ret = vu_message_read_default(dev, c->fd_tap, &msg);
	if (ret <= 0) {
		if (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK)
			tap_sock_reset(c);
		return;
	}
	debug("================ Vhost user message ================");
	debug("Request: %s (%d)", vu_request_to_string(msg.hdr.request),
		msg.hdr.request);
	debug("Flags:   0x%x", msg.hdr.flags);
	debug("Size:    %u", msg.hdr.size);

	need_reply = msg.hdr.flags & VHOST_USER_NEED_REPLY_MASK;
	switch (msg.hdr.request) {
	case VHOST_USER_GET_FEATURES:
		reply_requested = vu_get_features_exec(&msg);
		break;
	case VHOST_USER_SET_FEATURES:
		reply_requested = vu_set_features_exec(dev, &msg);
		break;
	case VHOST_USER_GET_PROTOCOL_FEATURES:
		reply_requested = vu_get_protocol_features_exec(&msg);
		break;
	case VHOST_USER_SET_PROTOCOL_FEATURES:
		reply_requested = vu_set_protocol_features_exec(dev, &msg);
		break;
	case VHOST_USER_GET_QUEUE_NUM:
		reply_requested = vu_get_queue_num_exec(&msg);
		break;
	case VHOST_USER_SET_OWNER:
		reply_requested = vu_set_owner_exec();
		break;
	case VHOST_USER_SET_MEM_TABLE:
		reply_requested = vu_set_mem_table_exec(dev, &msg);
		break;
	case VHOST_USER_SET_VRING_NUM:
		reply_requested = vu_set_vring_num_exec(dev, &msg);
		break;
	case VHOST_USER_SET_VRING_ADDR:
		reply_requested = vu_set_vring_addr_exec(dev, &msg);
		break;
	case VHOST_USER_SET_VRING_BASE:
		reply_requested = vu_set_vring_base_exec(dev, &msg);
		break;
	case VHOST_USER_GET_VRING_BASE:
		reply_requested = vu_get_vring_base_exec(dev, &msg);
		break;
	case VHOST_USER_SET_VRING_KICK:
		reply_requested = vu_set_vring_kick_exec(dev, &msg);
		break;
	case VHOST_USER_SET_VRING_CALL:
		reply_requested = vu_set_vring_call_exec(dev, &msg);
		break;
	case VHOST_USER_SET_VRING_ERR:
		reply_requested = vu_set_vring_err_exec(dev, &msg);
		break;
	case VHOST_USER_SET_VRING_ENABLE:
		reply_requested = vu_set_vring_enable_exec(dev, &msg);
		break;
	case VHOST_USER_NONE:
		vu_cleanup(dev);
		return;
	default:
		vu_panic(dev, "Unhandled request: %d", msg.hdr.request);
		return;
	}

	if (!reply_requested && need_reply) {
		msg.payload.u64 = 0;
		msg.hdr.flags = 0;
		msg.hdr.size = sizeof(msg.payload.u64);
		msg.fd_num = 0;
		reply_requested = true;
	}

	if (reply_requested)
		vu_send_reply(dev, c->fd_tap, &msg);
	free(msg.data);
}

debug log:

solving a3d156558359 ...
found a3d156558359 in https://archives.passt.top/passt-dev/20240621145640.1914287-6-lvivier@redhat.com/
found 4ac0a3e53499 in https://archives.passt.top/passt-dev/20240621145640.1914287-4-lvivier@redhat.com/

applying [1/2] https://archives.passt.top/passt-dev/20240621145640.1914287-4-lvivier@redhat.com/
diff --git a/vhost_user.c b/vhost_user.c
new file mode 100644
index 000000000000..4ac0a3e53499


applying [2/2] https://archives.passt.top/passt-dev/20240621145640.1914287-6-lvivier@redhat.com/
diff --git a/vhost_user.c b/vhost_user.c
index 4ac0a3e53499..a3d156558359 100644

Checking patch vhost_user.c...
Applied patch vhost_user.c cleanly.
Checking patch vhost_user.c...
Applied patch vhost_user.c cleanly.

index at:
100644 a3d156558359dfffda3f0dfe9c224956d05cbe7b	vhost_user.c

Code repositories for project(s) associated with this public inbox

	https://passt.top/passt

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for IMAP folder(s).