forked from TheNewNormal/libxhyve
-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpci_virtio_sock.c
2458 lines (2047 loc) · 62.2 KB
/
pci_virtio_sock.c
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
// +build vsock
/*-
* Copyright (c) 2016 Docker, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer
* in this position and unchanged.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* virtio vsock emulation based on v4 specification
* http://markmail.org/message/porhou5zv3wqjz6h
* Tested against the Linux implementation at
* git@github.com:stefanha/linux.git#vsock @ 563d2a770dfa
* Backported to v4.1.19:
* git cherry-pick -x 11aa9c2 f6a835b 4ef7ea9 8566b86 \
* ea3803c a9f9df1 1bb5b77 0c734eb \
* 139bbcd 563d2a7
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <sys/time.h>
#include <sys/queue.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <fcntl.h>
#include <inttypes.h>
#include <strings.h>
#include <unistd.h>
#include <errno.h>
#include <xhyve/pci_emul.h>
#include <xhyve/virtio.h>
#include <xhyve/xhyve.h>
#define VTSOCK_RINGSZ 256
#define VTSOCK_QUEUE_RX 0
#define VTSOCK_QUEUE_TX 1
#define VTSOCK_QUEUE_EVT 2
#define VTSOCK_QUEUES 3
#define VTSOCK_MAXSEGS 32
#define VTSOCK_MAXSOCKS 1024
#define VTSOCK_MAXFWDS 4
/* Number of seconds to wait after sending an OP_SHUTDOWN flags == ALL before
* we RST the connection ourselves.
*/
#define SHUTDOWN_RST_DELAY 30
/*
* Host capabilities
*/
#define VTSOCK_S_HOSTCAPS 0
#if 0
(VIRTIO_RING_F_INDIRECT_DESC) /* indirect descriptors */
#endif
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpacked"
/*
* Config space "registers"
*/
struct vtsock_config {
uint64_t guest_cid;
} __packed;
/*
* Fixed-size block header
*/
struct virtio_sock_hdr {
uint64_t src_cid;
uint64_t dst_cid;
uint32_t src_port;
uint32_t dst_port;
uint32_t len;
#define VIRTIO_VSOCK_TYPE_STREAM 1
uint16_t type;
#define VIRTIO_VSOCK_OP_INVALID 0
/* Connect operations */
#define VIRTIO_VSOCK_OP_REQUEST 1
#define VIRTIO_VSOCK_OP_RESPONSE 2
#define VIRTIO_VSOCK_OP_RST 3
#define VIRTIO_VSOCK_OP_SHUTDOWN 4
/* To send payload */
#define VIRTIO_VSOCK_OP_RW 5
/* Tell the peer our credit info */
#define VIRTIO_VSOCK_OP_CREDIT_UPDATE 6
/* Request the peer to send the credit info to us */
#define VIRTIO_VSOCK_OP_CREDIT_REQUEST 7
uint16_t op;
uint32_t flags;
#define VIRTIO_VSOCK_FLAG_SHUTDOWN_RX (1U<<0) /* Peer will not receive any more data */
#define VIRTIO_VSOCK_FLAG_SHUTDOWN_TX (1U<<1) /* Peer will not transmit any more data */
#define VIRTIO_VSOCK_FLAG_SHUTDOWN_ALL (VIRTIO_VSOCK_FLAG_SHUTDOWN_RX|VIRTIO_VSOCK_FLAG_SHUTDOWN_TX)
uint32_t buf_alloc;
uint32_t fwd_cnt;
} __packed;
#pragma clang diagnostic pop
/*
* Debug printf
*/
static int pci_vtsock_debug = 0;
#define DPRINTF(params) do { if (pci_vtsock_debug) { printf params; fflush(stdout); } } while(0)
/* Protocol logging */
#define PPRINTF(params) do { if (0) { printf params; fflush(stdout); } } while(0)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
/* XXX need to use rx and tx more consistently */
struct vsock_addr {
uint64_t cid;
uint32_t port;
};
#define PRIcid "%08"PRIx64
#define PRIport "%08"PRIx32
#define SCNcid "%08"SCNx64
#define SCNport "%08"SCNx32
#define SCNaddr SCNcid "." SCNport
#ifdef PRI_ADDR_PREFIX
#define PRIaddr PRI_ADDR_PREFIX PRIcid "." PRIport
#else
#define PRIaddr PRIcid "." PRIport
#endif
#ifndef CONNECT_SOCKET_NAME
#define CONNECT_SOCKET_NAME "connect"
#endif
#define FMTADDR(a) a.cid, a.port
#define WRITE_BUF_LENGTH (128*1024)
struct pci_vtsock_sock {
pthread_mutex_t mtx;
/* Either on softc->free_list or softc->inuse_list */
LIST_ENTRY(pci_vtsock_sock) list;
/* For tx and rx thread local use respectively */
LIST_ENTRY(pci_vtsock_sock) tx_queue;
LIST_ENTRY(pci_vtsock_sock) rx_queue;
/*
* To allocate a sock:
*
* Take list_rwlock for writing
*
* Grab a sock from head of free_list
*
* If a FREE sock is found take its lock before removing it
* from the list and setting its state to CONNECTING.
*
* Add the sock to inuse_list.
*
* Drop list_rwlock
*
* To free a sock:
*
* Set state to CLOSING_TX and kick the tx thread[*].
*
* Then the following will happen:
*
* ,-TX thread:
* |
* | The TX loop will take list_rwlock for reading (as part of
* | its normal start of loop processing) and:
* |
* | Take the socket's lock and discover state == CLOSING_TX
* |
* | Set state == CLOSING_RX
* |
* | Note that an RX kick is needed
* |
* | Release list_rwlock
* |
* `-Kick the rx thread if required
*
* ,-RX thread:
* |
* | The RX loop will take list_rwlock for reading (as part of
* | its normal start of loop processing) and:
* |
* | Take the socket's lock and discover state == CLOSING_RX
* |
* | Put the socket on a local "to be closed" queue
* |
* | Release list_rwlock
* |
* | If there a sockets to be closed, take list_rwlock for
* | writing, and for each socket:
* |
* | close the fd, set state == FREE
* |
* | remove socket from inuse_list, add to free_list
* |
* | drop the socket's lock
* |
* `-Drop list_rwlock
*
* [*] Callers in the TX loop (only) may when closing a socket
* choose to skip the initial CLOSING_TX state (which exists
* only to ensure that the fd is not current in the tx select,
* which it cannot be if the TX thread is doing the close) and
* go straight to CLOSING_RX kicking the rx thread instead. If
* the close is initiated by the RX thread (or anywhere else)
* then it must go through the full
* CLOSING_TX->CLOSING_RX->FREE path.
*/
enum {
SOCK_FREE, /* Initial state */
SOCK_CONNECTING,
SOCK_CONNECTED,
SOCK_CLOSING_TX,
SOCK_CLOSING_RX,
} state;
/* fd is:
* >= 0 When state == CONNECTED,
* -1 Otherwise
*/
int fd;
uint16_t port_generation;
/* valid when SOCK_CONNECTED only */
uint32_t local_shutdown, peer_shutdown;
time_t rst_deadline; /* When local_shutdown==ALL, expect RST before */
struct vsock_addr local_addr;
struct vsock_addr peer_addr;
uint32_t buf_alloc;
uint32_t fwd_cnt;
bool credit_update_required;
uint32_t rx_cnt; /* Amount we have sent to the peer */
uint32_t peer_buf_alloc; /* From the peer */
uint32_t peer_fwd_cnt; /* From the peer */
/* Write buffer. We do not update fwd_cnt until we drain the _whole_ buffer */
uint8_t write_buf[WRITE_BUF_LENGTH];
unsigned int write_buf_head, write_buf_tail;
};
struct pci_vtsock_forward {
int listen_fd;
uint32_t port;
};
/*
* Per-device softc
*/
/*
* Lock order (outer most first): XXX more thought needed.
*
* vssc_mtx is taken by the core and is often held during callbacks
* (e.g. it is held during a vq_notify or pci cfg access). It
* protects virtio resources.
*
* list_rwlock, protects free and inuse lists (rdlock for traversal)
*
* sock->mtx protects the contents of the sock struct, including the
* state.
*
* reply_mtx protects reply_{ring,prod,cons}
*/
LIST_HEAD(sock_list_head, pci_vtsock_sock);
struct pci_vtsock_softc {
struct virtio_softc vssc_vs;
pthread_mutex_t vssc_mtx;
char *path;
struct vqueue_info vssc_vqs[VTSOCK_QUEUES];
struct vtsock_config vssc_cfg;
/* list_mtx protects free_list and inuse_list heads */
pthread_rwlock_t list_rwlock;
struct sock_list_head free_list, inuse_list;
struct pci_vtsock_sock socks[VTSOCK_MAXSOCKS];
struct pci_vtsock_forward fwds[VTSOCK_MAXFWDS];
int nr_fwds;
pthread_t tx_thread;
int tx_kick_fd, tx_wake_fd; /* Write to kick, select on wake */
bool rx_kick_pending;
int connect_fd; /* */
pthread_t rx_thread;
int rx_kick_fd, rx_wake_fd; /* Write to kick, select on wake */
pthread_mutex_t reply_mtx;
#define VTSOCK_REPLYRINGSZ (2*VTSOCK_RINGSZ)
struct virtio_sock_hdr reply_ring[VTSOCK_REPLYRINGSZ];
int reply_prod, reply_cons;
/*
* If reply_prod == reply_cons then the ring is empty,
* otherwise there is data in it.
*
* If the ring is not empty then there MUST always be a 1 slot
* buffer between the producer and the consumer pointers
* (i.e. the ring size is effectively one less than expected).
*
* If this invariant is violated and we consume the final free
* slot then reply_prod would have caught up to reply_cons and
* the ring would be considered empty rather than
* full. Therefore we consider the ring full when:
*
* (reply_prod + 1) % VTSOCK_REPLYRINGSZ == reply_cons.
*/
#define REPLY_RING_EMPTY(sc) (sc->reply_cons == sc->reply_prod)
//#define REPLY_RING_FULL(sc) ((sc->reply_prod + 1) % VTSOCK_REPLYRINGSZ == sc->reply_cons)
};
#pragma clang diagnostic pop
/* Protocol stuff */
/* Reserved CIDs */
#define VMADDR_CID_ANY -1U
//#define VMADDR_CID_HYPERVISOR 0
//#define VMADDR_CID_RESERVED 1
#define VMADDR_CID_HOST 2
#define VMADDR_CID_MAX UINT32_MAX /* Athough CID's are 64-bit in the protocol, we only support 32-bits */
static void pci_vtsock_reset(void *);
static void pci_vtsock_notify_tx(void *, struct vqueue_info *);
static void pci_vtsock_notify_rx(void *, struct vqueue_info *);
static int pci_vtsock_cfgread(void *, int, int, uint32_t *);
static int pci_vtsock_cfgwrite(void *, int, int, uint32_t);
static void *pci_vtsock_rx_thread(void *vssc);
static bool sock_is_buffering(struct pci_vtsock_sock *sock);
static struct virtio_consts vtsock_vi_consts = {
"vtsock", /* our name */
VTSOCK_QUEUES,
sizeof(struct vtsock_config), /* config reg size */
pci_vtsock_reset, /* reset */
NULL, /* no device-wide qnotify */
pci_vtsock_cfgread, /* read PCI config */
pci_vtsock_cfgwrite, /* write PCI config */
NULL, /* apply negotiated features */
VTSOCK_S_HOSTCAPS, /* our capabilities */
};
static void pci_vtsock_reset(void *vsc)
{
struct pci_vtsock_softc *sc = vsc;
DPRINTF(("vtsock: device reset requested !\n"));
vi_reset_dev(&sc->vssc_vs);
/* XXX TODO: close/reset all socks */
}
static const char * const opnames[] = {
[VIRTIO_VSOCK_OP_INVALID] = "INVALID",
[VIRTIO_VSOCK_OP_REQUEST] = "REQUEST",
[VIRTIO_VSOCK_OP_RESPONSE] = "RESPONSE",
[VIRTIO_VSOCK_OP_RST] = "RST",
[VIRTIO_VSOCK_OP_SHUTDOWN] = "SHUTDOWN",
[VIRTIO_VSOCK_OP_RW] = "RW",
[VIRTIO_VSOCK_OP_CREDIT_UPDATE] = "CREDIT_UPDATE",
[VIRTIO_VSOCK_OP_CREDIT_REQUEST] = "CREDIT_REQUEST"
};
static int max_fd(int a, int b)
{
if (a > b)
return a;
else
return b;
}
/*
* Returns >= 0 number of fds on success or -1 to indicate caller
* should retry. On any failure which cannot be retried logs and exits.
*/
static int xselect(const char *ctx,
int nfds, fd_set *readfds, fd_set *writefds,
fd_set *errorfds, struct timeval *timeout)
{
int rc = select(nfds, readfds, writefds, errorfds, timeout);
if (rc >= 0) return rc;
/*
* http://pubs.opengroup.org/onlinepubs/009695399/functions/select.html
* lists EINTR, EBADF and EINVAL. EINTR is recoverable and should be
* retried.
*/
if (errno == EINTR) return -1;
/*
* OSX select(2) man page lists EAGAIN in addition to the above.
* EAGAIN should be retried.
*/
if (errno == EAGAIN) return -1;
fprintf(stderr, "%s: select() failed %d: %s\n",
ctx, errno, strerror(errno));
abort();
}
static size_t iovec_clip(struct iovec **iov, int *iov_len, size_t bytes)
{
size_t ret = 0;
int i;
for (i = 0; i < *iov_len && ret < bytes; i++) {
if ((bytes-ret) < (*iov)[i].iov_len)
(*iov)[i].iov_len = bytes - ret;
ret += (*iov)[i].iov_len;
}
*iov_len = i;
return ret;
}
/* Pulls @bytes from @iov into @buf. @buf can be NULL, in which case this just discards @bytes */
static size_t iovec_pull(struct iovec **iov, int *iov_len, void *buf, size_t bytes)
{
size_t res = 0;
//DPRINTF(("iovec_pull %zd bytes into %p. iov=%p, iov_len=%d\n",
// bytes, (void *)buf, (void *)*iov, *iov_len));
while (res < bytes && *iov_len) {
size_t c = (bytes - res) < (*iov)[0].iov_len ? (bytes - res) : (*iov)[0].iov_len;
//DPRINTF(("Copy %zd/%zd bytes from base=%p to buf=%p\n",
// c, (*iov)[0].iov_len, (void*)(*iov)[0].iov_base, (void*)buf));
if (buf) memcpy(buf, (*iov)[0].iov_base, c);
(*iov)[0].iov_len -= c;
(*iov)[0].iov_base = (char *)(*iov)[0].iov_base + c;
//DPRINTF(("iov %p is now %zd bytes at %p\n", (void *)*iov,
// (*iov)[0].iov_len, (void *)(*iov)[0].iov_base));
if ((*iov)[0].iov_len == 0) {
(*iov)++;
(*iov_len)--;
//DPRINTF(("iov elem consumed, now iov=%p, iov_len=%d\n", (void *)*iov, *iov_len));
}
if (buf) buf = (char *)buf + c;
//DPRINTF(("buf now %p\n", (void *)buf));
res += c;
}
//DPRINTF(("iovec_pull pulled %zd/%zd bytes\n", res, bytes));
return res;
}
static size_t iovec_push(struct iovec **iov, int *iov_len, void *buf, size_t bytes)
{
size_t res = 0;
//DPRINTF(("iovec_push %zd bytes from %p. iov=%p, iov_len=%d\n",
// bytes, (void *)buf, (void *)*iov, *iov_len));
while (res < bytes && *iov_len) {
size_t c = (bytes - res) < (*iov)[0].iov_len ? (bytes - res) : (*iov)[0].iov_len;
//DPRINTF(("Copy %zd/%zd bytes from buf=%p to base=%p\n",
// c, (*iov)[0].iov_len, (void *)buf, (void *)(*iov)[0].iov_base));
memcpy((*iov)[0].iov_base, buf, c);
(*iov)[0].iov_len -= c;
(*iov)[0].iov_base = (char *)(*iov)[0].iov_base + c;
//DPRINTF(("iov %p is now %zd bytes at %p\n", (void *)*iov,
// (*iov)[0].iov_len, (void *)(*iov)[0].iov_base));
if ((*iov)[0].iov_len == 0) {
(*iov)++;
(*iov_len)--;
//DPRINTF(("iov elem consumed, now iov=%p, iov_len=%d\n", (void *)*iov, *iov_len));
}
buf = (char *)buf + c;
//DPRINTF(("buf now %p\n", (void *)buf));
res += c;
}
return res;
}
static void dprint_iovec(struct iovec *iov, int iovec_len, const char *ctx)
{
int i;
if (!pci_vtsock_debug) return;
DPRINTF(("%s: IOV:%p ELEMS:%d\n", ctx, (void *)iov, iovec_len));
for (i = 0; i < iovec_len; i++)
DPRINTF(("%s: %d = %zu @ %p\n",
ctx, i, iov[i].iov_len, (void *)iov[i].iov_base));
}
static void dprint_chain(struct iovec *iov, int iovec_len, const char *ctx)
{
int i;
if (!pci_vtsock_debug) return;
DPRINTF(("%s: CHAIN:%p ELEMS:%d\n", ctx, (void *)iov, iovec_len));
for (i = 0; i < iovec_len; i++)
DPRINTF(("%s: %d = %zu @ %p\n",
ctx, i, iov[i].iov_len, (void *)iov[i].iov_base));
}
static void dprint_header(struct virtio_sock_hdr *hdr, bool tx, const char *ctx)
{
if (!pci_vtsock_debug) return;
assert(hdr->op < nitems(opnames));
DPRINTF(("%s: %sSRC:"PRIaddr" DST:"PRIaddr"\n",
ctx, tx ? "<=" : "=>",
hdr->src_cid, hdr->src_port, hdr->dst_cid, hdr->dst_port));
DPRINTF(("%s: LEN:%08"PRIx32" TYPE:%04"PRIx16" OP:%"PRId16"=%s\n",
ctx, hdr->len, hdr->type, hdr->op,
opnames[hdr->op] ? opnames[hdr->op] : "<unknown>"));
DPRINTF(("%s: FLAGS:%08"PRIx32" BUF_ALLOC:%08"PRIx32" FWD_CNT:%08"PRIx32"\n",
ctx, hdr->flags, hdr->buf_alloc, hdr->fwd_cnt));
}
static void put_sock(struct pci_vtsock_sock *s)
{
int err = pthread_mutex_unlock(&s->mtx);
assert(err == 0);
}
static struct pci_vtsock_sock *get_sock(struct pci_vtsock_sock *s)
{
int err = pthread_mutex_lock(&s->mtx);
assert(err == 0);
return s;
}
/* Returns a locked sock */
static struct pci_vtsock_sock *lookup_sock(struct pci_vtsock_softc *sc,
uint16_t type,
struct vsock_addr local_addr,
struct vsock_addr peer_addr)
{
struct pci_vtsock_sock *s;
assert(type == VIRTIO_VSOCK_TYPE_STREAM);
pthread_rwlock_rdlock(&sc->list_rwlock);
LIST_FOREACH(s, &sc->inuse_list, list) {
get_sock(s);
if ((s->state == SOCK_CONNECTED || s->state == SOCK_CONNECTING) &&
s->peer_addr.cid == peer_addr.cid &&
s->peer_addr.port == peer_addr.port &&
s->local_addr.cid == local_addr.cid &&
s->local_addr.port == local_addr.port) {
goto found;
}
put_sock(s);
}
s = NULL;
found:
pthread_rwlock_unlock(&sc->list_rwlock);
return s;
}
/* Returns NULL on failure or a locked socket on success */
static struct pci_vtsock_sock *alloc_sock(struct pci_vtsock_softc *sc)
{
struct pci_vtsock_sock *s;
pthread_rwlock_wrlock(&sc->list_rwlock);
s = LIST_FIRST(&sc->free_list);
if (s) {
get_sock(s);
LIST_REMOVE(s, list);
LIST_INSERT_HEAD(&sc->inuse_list, s, list);
s->state = SOCK_CONNECTING;
}
pthread_rwlock_unlock(&sc->list_rwlock);
if (!s) return NULL;
s->buf_alloc = WRITE_BUF_LENGTH;
s->fwd_cnt = 0;
s->peer_buf_alloc = 0;
s->peer_fwd_cnt = 0;
s->rx_cnt = 0;
s->credit_update_required = false;
s->local_shutdown = 0;
s->peer_shutdown = 0;
s->write_buf_head = s->write_buf_tail = 0;
return s;
}
static int set_socket_options(struct pci_vtsock_sock *s)
{
int rc, buf_alloc = (int)s->buf_alloc;
socklen_t opt_len;
rc = setsockopt(s->fd, SOL_SOCKET, SO_SNDBUF,
&buf_alloc, sizeof(buf_alloc));
if ( rc < 0 ) {
DPRINTF(("Failed to set SO_SNDBUF on fd %d: %s\n",
s->fd, strerror(errno)));
return rc;
}
rc = setsockopt(s->fd, SOL_SOCKET, SO_RCVBUF,
&buf_alloc, sizeof(buf_alloc));
if ( rc < 0 ) {
DPRINTF(("Failed to set SO_RCVBUF on fd %d: %s\n",
s->fd, strerror(errno)));
return rc;
}
opt_len = sizeof(buf_alloc);
rc = getsockopt(s->fd, SOL_SOCKET, SO_SNDBUF,
&buf_alloc, &opt_len);
if ( rc < 0 ) {
DPRINTF(("Failed to get SO_SNDBUF on fd %d: %s\n",
s->fd, strerror(errno)));
return rc;
}
/* If we didn't get what we asked for then expose this to the other end */
if (buf_alloc < (int)s->buf_alloc) {
PPRINTF(("fd %d SO_SNDBUF is 0x%x not 0x%x as requested, clamping\n",
s->fd, buf_alloc, s->buf_alloc));
s->buf_alloc = (uint32_t)buf_alloc;
}
return 0;
}
static struct pci_vtsock_sock *connect_sock(struct pci_vtsock_softc *sc,
struct vsock_addr local_addr,
struct vsock_addr peer_addr,
uint32_t peer_buf_alloc,
uint32_t peer_fwd_cnt)
{
struct pci_vtsock_sock *s;
struct sockaddr_un un;
int rc, fd = -1;
s = alloc_sock(sc);
if (s == NULL) {
DPRINTF(("TX: No available socks\n"));
goto err;
}
DPRINTF(("TX: Assigned sock %ld at %p\n",
s - &sc->socks[0], (void *)s));
bzero(&un, sizeof(un));
un.sun_len = 0; /* Unused? */
un.sun_family = AF_UNIX;
rc = snprintf(un.sun_path, sizeof(un.sun_path),
"%s/"PRIaddr, sc->path, FMTADDR(local_addr));
if (rc < 0) {
DPRINTF(("TX: Failed to format socket path\n"));
goto err;
}
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
DPRINTF(("TX: socket failed for %s: %s\n",
un.sun_path, strerror(errno)));
goto err;
}
if (fd >= FD_SETSIZE) {
DPRINTF(("TX: socket fd %d > FD_SETSIZE %d\n", fd, FD_SETSIZE));
goto err;
}
rc = connect(fd, (struct sockaddr *)&un, sizeof(un));
if (rc < 0) {
DPRINTF(("TX: connect failed for %s: %s\n",
un.sun_path, strerror(errno)));
goto err;
}
rc = fcntl(fd, F_SETFL, O_NONBLOCK);
if (rc < 0) {
DPRINTF(("TX: O_NONBLOCK failed for %s: %s\n",
un.sun_path, strerror(errno)));
goto err;
}
DPRINTF(("TX: Socket path %s opened on fd %d\n", un.sun_path, fd));
s->fd = fd;
s->peer_addr = peer_addr;
s->local_addr = local_addr;
s->peer_buf_alloc = peer_buf_alloc;
s->peer_fwd_cnt = peer_fwd_cnt;
rc = set_socket_options(s);
if (rc < 0) goto err;
PPRINTF(("TX: SOCK connected (%d) "PRIaddr" <=> "PRIaddr"\n",
s->fd, FMTADDR(s->local_addr), FMTADDR(s->peer_addr)));
s->state = SOCK_CONNECTED;
put_sock(s);
return s;
err:
/* s is static, no need to free(), but do set state back to free */
if (fd >= 0) close(fd);
if (s) {
s->state = SOCK_FREE;
put_sock(s);
}
return NULL;
}
static void kick_rx(struct pci_vtsock_softc *sc, const char *why)
{
char dummy;
ssize_t nr;
sc->rx_kick_pending = false;
nr = write(sc->rx_kick_fd, &dummy, 1);
assert(nr == 1);
DPRINTF(("RX: kicked rx thread: %s\n", why));
}
static void kick_tx(struct pci_vtsock_softc *sc, const char *why)
{
char dummy;
ssize_t nr;
nr = write(sc->tx_kick_fd, &dummy, 1);
assert(nr == 1);
DPRINTF(("TX: kicked tx thread: %s\n", why));
}
/* Reflect peer_shutdown into local fd */
static void shutdown_peer_local_fd(struct pci_vtsock_sock *s, uint32_t mode,
const char *ctx)
{
int rc;
int how;
const char *how_str;
uint32_t new = mode | s->peer_shutdown;
uint32_t set = s->peer_shutdown ^ new;
uint32_t new_local = s->local_shutdown;
assert((mode & ~VIRTIO_VSOCK_FLAG_SHUTDOWN_ALL) == 0);
assert(mode != 0);
DPRINTF(("%s: PEER CUR %"PRIx32", MODE %"PRIx32", NEW %"PRIx32", SET %"PRIx32"\n",
ctx, s->peer_shutdown, mode, new, set));
switch (set) {
case 0:
return;
case VIRTIO_VSOCK_FLAG_SHUTDOWN_TX:
if (sock_is_buffering(s))
{
PPRINTF(("%s: fd: %d SHUT_WR while buffering, deferring local shutdown\n", ctx, s->fd));
how = 0;
how_str = "none";
} else {
how = SHUT_WR;
how_str = "SHUT_WR";
new_local |= VIRTIO_VSOCK_FLAG_SHUTDOWN_RX;
}
break;
case VIRTIO_VSOCK_FLAG_SHUTDOWN_RX:
how = SHUT_RD;
how_str = "SHUT_RD";
new_local = s->local_shutdown | VIRTIO_VSOCK_FLAG_SHUTDOWN_TX;
break;
case VIRTIO_VSOCK_FLAG_SHUTDOWN_ALL:
if (sock_is_buffering(s)) {
PPRINTF(("%s: fd: %d SHUT_RDWR while buffering, deferring local SHUT_WR\n", ctx, s->fd));
how = SHUT_RD;
how_str = "SHUT_RD";
new_local |= VIRTIO_VSOCK_FLAG_SHUTDOWN_TX;
} else {
how = SHUT_RDWR;
how_str = "SHUT_RDWR";
new_local |= VIRTIO_VSOCK_FLAG_SHUTDOWN_ALL;
}
break;
default:
abort();
}
if (how) {
rc = shutdown(s->fd, how);
DPRINTF(("%s: shutdown_peer: shutdown(%d, %s)\n", ctx, s->fd, how_str));
if (rc < 0 && errno != ENOTCONN) {
DPRINTF(("%s: shutdown(%d, %s) for peer shutdown failed: %s\n",
ctx, s->fd, how_str, strerror(errno)));
abort();
}
}
s->local_shutdown = new_local;
s->peer_shutdown = new;
}
/* The caller must have sent something (probably OP_RST, but perhaps
* OP_SHUTDOWN) to the peer already.
*/
static void close_sock(struct pci_vtsock_softc *sc, struct pci_vtsock_sock *s,
const char *ctx)
{
if (!s) return;
DPRINTF(("%s: Closing sock %p\n", ctx, (void *)s));
shutdown_peer_local_fd(s, VIRTIO_VSOCK_FLAG_SHUTDOWN_ALL, ctx);
s->state = SOCK_CLOSING_TX;
kick_tx(sc, "sock closed");
}
/*
* Caller should send OP_SHUTDOWN with flags == s->local_shutdown after calling this.
*/
static void shutdown_local_sock(const char *ctx,
struct pci_vtsock_sock *s,
uint32_t mode)
{
uint32_t new, set;
assert((mode & ~VIRTIO_VSOCK_FLAG_SHUTDOWN_ALL) == 0);
if (s->state != SOCK_CONNECTED) return;
assert(s->local_shutdown != VIRTIO_VSOCK_FLAG_SHUTDOWN_ALL);
DPRINTF(("%s: fd %d: LOCAL SHUTDOWN 0x%"PRIx32" (0x%"PRIx32")\n",
ctx, s->fd, mode, s->peer_shutdown));
new = mode | s->local_shutdown;
set = s->local_shutdown ^ new;
s->local_shutdown = new;
DPRINTF(("%s: setting 0x%"PRIx32" mode is now 0x%"PRIx32" (peer 0x%"PRIx32")\n",
ctx, set, s->local_shutdown, s->peer_shutdown));
if (s->local_shutdown & VIRTIO_VSOCK_FLAG_SHUTDOWN_RX && s->write_buf_tail > 0) {
PPRINTF(("%s: discarding %d bytes from buffer\n", ctx,
s->write_buf_tail - s->write_buf_head));
s->write_buf_tail = s->write_buf_head = 0;
}
if (s->local_shutdown == VIRTIO_VSOCK_FLAG_SHUTDOWN_ALL)
s->rst_deadline = time(NULL) + SHUTDOWN_RST_DELAY;
}
static void set_credit_update_required(struct pci_vtsock_softc *sc,
struct pci_vtsock_sock *sock)
{
if (sock->credit_update_required) return;
sock->credit_update_required = true;
sc->rx_kick_pending = true;
}
static void send_response_common(struct pci_vtsock_softc *sc,
struct vsock_addr local_addr,
struct vsock_addr peer_addr,
uint16_t op, uint16_t type, uint32_t flags,
uint32_t buf_alloc, uint32_t fwd_cnt)
{
struct virtio_sock_hdr *hdr;
int slot;
assert(op != VIRTIO_VSOCK_OP_RW);
assert(flags == 0 || op == VIRTIO_VSOCK_OP_SHUTDOWN);
pthread_mutex_lock(&sc->reply_mtx);
slot = sc->reply_prod++;
if (sc->reply_prod == VTSOCK_REPLYRINGSZ)
sc->reply_prod = 0;
DPRINTF(("TX: QUEUING REPLY IN SLOT %x (prod %x, cons %x)\n",
slot, sc->reply_prod, sc->reply_cons));
/*
* We have just incremented reply_prod above but we hold the
* lock so the consumer cannot have caught us up. Hence for
* the ring to appear empty it must actually have just overflowed.
*/
assert(!REPLY_RING_EMPTY(sc));
hdr = &sc->reply_ring[slot];
hdr->src_cid = local_addr.cid;
hdr->src_port = local_addr.port;
hdr->dst_cid = peer_addr.cid;
hdr->dst_port = peer_addr.port;
hdr->len = 0;
hdr->type = type;
hdr->op = op;
hdr->flags = flags;
hdr->buf_alloc = buf_alloc;
hdr->fwd_cnt = fwd_cnt;
dprint_header(hdr, 0, "TX");
pthread_mutex_unlock(&sc->reply_mtx);
sc->rx_kick_pending = true;
}
static void send_response_sock(struct pci_vtsock_softc *sc,
uint16_t op, uint32_t flags,
const struct pci_vtsock_sock *sock)
{
send_response_common(sc, sock->local_addr, sock->peer_addr,
op, VIRTIO_VSOCK_TYPE_STREAM, flags,
sock->buf_alloc, sock->fwd_cnt);
}
static void send_response_nosock(struct pci_vtsock_softc *sc, uint16_t op,
uint16_t type,
struct vsock_addr local_addr,
struct vsock_addr peer_addr)
{
send_response_common(sc, local_addr, peer_addr,
op, type, 0, 0, 0);
}
static bool sock_is_buffering(struct pci_vtsock_sock *sock)
{
return sock->write_buf_tail > 0;
}
static int buffer_write(struct pci_vtsock_sock *sock,
uint32_t len, struct iovec *iov, int iov_len)
{
size_t nr;
if (sock->write_buf_tail + len > WRITE_BUF_LENGTH) {
DPRINTF(("TX: fd %d unable to buffer write of 0x%"PRIx32" bytes,"
" buffer use 0x%x/0x%x, 0x%x remaining\n",
sock->fd, len, sock->write_buf_tail,
WRITE_BUF_LENGTH,
WRITE_BUF_LENGTH < sock->write_buf_tail));
return -1;
}
nr = iovec_pull(&iov, &iov_len,
&sock->write_buf[sock->write_buf_tail], len);
assert(nr == len);
assert(iov_len == 0);
sock->write_buf_tail += nr;
DPRINTF(("TX: fd %d buffered 0x%"PRIx32" bytes (0x%x/0x%x)\n",
sock->fd, len, sock->write_buf_tail, WRITE_BUF_LENGTH));
return 0;
}