-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.c
157 lines (132 loc) · 2.33 KB
/
main.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
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <pthread.h>
#include <unistd.h>
#include "types.h"
#include "vhost.h"
#include "mbuf.h"
#include "tun.h"
static int sendto_peer(int fd, struct mbuf *m)
{
int rc;
rc = write(fd, m->data, m->len);
if (rc < 0) {
perror("write");
return 0;
}
return 1;
}
static int recvfrom_peer(int fd, struct mbuf **mbuf)
{
int rc;
struct mbuf *m;
m = vhost_new_mbuf();
if (!m) {
vhost_log("no mbuf\n");
exit(-1);
}
rc = read(fd, m->data, m->len);
if (rc < 0) {
perror("read");
vhost_free_mbuf(m);
return 0;
}
m->len = rc;
*mbuf = m;
return 1;
}
static int can_read(int fd)
{
fd_set fs;
struct timeval to;
int rc;
FD_ZERO(&fs);
FD_SET(fd, &fs);
to.tv_sec = to.tv_usec = 0;
rc = select(fd+1, &fs, NULL, NULL, &to);
if (rc > 0) {
if (FD_ISSET(fd, &fs))
return 1;
vhost_log("can_read: strange");
} else if (rc < 0) {
perror("select");
}
return 0;
}
/* data is tap name */
static void *worker_fn(void *data)
{
int i;
int np;
int fd;
struct virtio_dev *dev;
struct mbuf *m;
vhost_log("worker start...\n");
check:
/* make sure dev is running */
sleep(20);
dev = NULL;
while (!dev) {
dev = vhost_get_first_virtio();
sleep(1);
}
vhost_log("qemu comes...\n");
fd = tap_open(data);
if (fd < 0) {
perror("tap");
exit(-1);
}
/* data path is ready */
/* check dev running ? */
while (1) {
np = vhost_tx(dev, 1, &m, 1);
if (np > 0) {
np = sendto_peer(fd, m);
if (np > 0) {
//vhost_dump_mbuf(m);
vhost_log("tx to uds\n");
} else {
vhost_log("failed to send\n");
}
vhost_free_mbuf(m);
}
if (can_read(fd)) {
np = recvfrom_peer(fd, &m);
if (np > 0) {
//vhost_dump_mbuf(m);
vhost_log("rx from uds\n");
vhost_rx(dev, 0, &m, 1);
vhost_free_mbuf(m);
}
}
usleep(10);
}
}
static void vhost_user_worker_start(char *tap)
{
pthread_t t;
int rc;
rc = pthread_create(&t, NULL, worker_fn, tap);
if (rc) {
vhost_log("cannot start worker\n");
exit(-1);
}
rc = pthread_detach(t);
if (rc) {
vhost_log("cannot detach worker\n");
exit(-1);
}
}
int main(int argc, char **argv)
{
if (argc != 3) {
vhost_log("%s: [vhost-user socket path] [tap name]\n",
argv[0]);
exit(-1);
}
vhost_log("server start...\n");
vhost_user_worker_start(argv[2]);
vhost_user_start(argv[1]);
return 0;
}