6f4845b70e03898fea2a5aa47851de41ecd5955d
[deb_dpdk.git] / drivers / net / virtio / virtio_user / vhost_user.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2016 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include <sys/socket.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <unistd.h>
38 #include <fcntl.h>
39 #include <sys/un.h>
40 #include <string.h>
41 #include <errno.h>
42
43 #include "vhost.h"
44
45 static int
46 vhost_user_write(int fd, void *buf, int len, int *fds, int fd_num)
47 {
48         int r;
49         struct msghdr msgh;
50         struct iovec iov;
51         size_t fd_size = fd_num * sizeof(int);
52         char control[CMSG_SPACE(fd_size)];
53         struct cmsghdr *cmsg;
54
55         memset(&msgh, 0, sizeof(msgh));
56         memset(control, 0, sizeof(control));
57
58         iov.iov_base = (uint8_t *)buf;
59         iov.iov_len = len;
60
61         msgh.msg_iov = &iov;
62         msgh.msg_iovlen = 1;
63         msgh.msg_control = control;
64         msgh.msg_controllen = sizeof(control);
65
66         cmsg = CMSG_FIRSTHDR(&msgh);
67         cmsg->cmsg_len = CMSG_LEN(fd_size);
68         cmsg->cmsg_level = SOL_SOCKET;
69         cmsg->cmsg_type = SCM_RIGHTS;
70         memcpy(CMSG_DATA(cmsg), fds, fd_size);
71
72         do {
73                 r = sendmsg(fd, &msgh, 0);
74         } while (r < 0 && errno == EINTR);
75
76         return r;
77 }
78
79 static int
80 vhost_user_read(int fd, struct vhost_user_msg *msg)
81 {
82         uint32_t valid_flags = VHOST_USER_REPLY_MASK | VHOST_USER_VERSION;
83         int ret, sz_hdr = VHOST_USER_HDR_SIZE, sz_payload;
84
85         ret = recv(fd, (void *)msg, sz_hdr, 0);
86         if (ret < sz_hdr) {
87                 PMD_DRV_LOG(ERR, "Failed to recv msg hdr: %d instead of %d.",
88                             ret, sz_hdr);
89                 goto fail;
90         }
91
92         /* validate msg flags */
93         if (msg->flags != (valid_flags)) {
94                 PMD_DRV_LOG(ERR, "Failed to recv msg: flags %x instead of %x.",
95                             msg->flags, valid_flags);
96                 goto fail;
97         }
98
99         sz_payload = msg->size;
100
101         if ((size_t)sz_payload > sizeof(msg->payload))
102                 goto fail;
103
104         if (sz_payload) {
105                 ret = recv(fd, (void *)((char *)msg + sz_hdr), sz_payload, 0);
106                 if (ret < sz_payload) {
107                         PMD_DRV_LOG(ERR,
108                                 "Failed to recv msg payload: %d instead of %d.",
109                                 ret, msg->size);
110                         goto fail;
111                 }
112         }
113
114         return 0;
115
116 fail:
117         return -1;
118 }
119
120 struct hugepage_file_info {
121         uint64_t addr;            /**< virtual addr */
122         size_t   size;            /**< the file size */
123         char     path[PATH_MAX];  /**< path to backing file */
124 };
125
126 /* Two possible options:
127  * 1. Match HUGEPAGE_INFO_FMT to find the file storing struct hugepage_file
128  * array. This is simple but cannot be used in secondary process because
129  * secondary process will close and munmap that file.
130  * 2. Match HUGEFILE_FMT to find hugepage files directly.
131  *
132  * We choose option 2.
133  */
134 static int
135 get_hugepage_file_info(struct hugepage_file_info huges[], int max)
136 {
137         int idx;
138         FILE *f;
139         char buf[BUFSIZ], *tmp, *tail;
140         char *str_underline, *str_start;
141         int huge_index;
142         uint64_t v_start, v_end;
143
144         f = fopen("/proc/self/maps", "r");
145         if (!f) {
146                 PMD_DRV_LOG(ERR, "cannot open /proc/self/maps");
147                 return -1;
148         }
149
150         idx = 0;
151         while (fgets(buf, sizeof(buf), f) != NULL) {
152                 if (sscanf(buf, "%" PRIx64 "-%" PRIx64, &v_start, &v_end) < 2) {
153                         PMD_DRV_LOG(ERR, "Failed to parse address");
154                         goto error;
155                 }
156
157                 tmp = strchr(buf, ' ') + 1; /** skip address */
158                 tmp = strchr(tmp, ' ') + 1; /** skip perm */
159                 tmp = strchr(tmp, ' ') + 1; /** skip offset */
160                 tmp = strchr(tmp, ' ') + 1; /** skip dev */
161                 tmp = strchr(tmp, ' ') + 1; /** skip inode */
162                 while (*tmp == ' ')         /** skip spaces */
163                         tmp++;
164                 tail = strrchr(tmp, '\n');  /** remove newline if exists */
165                 if (tail)
166                         *tail = '\0';
167
168                 /* Match HUGEFILE_FMT, aka "%s/%smap_%d",
169                  * which is defined in eal_filesystem.h
170                  */
171                 str_underline = strrchr(tmp, '_');
172                 if (!str_underline)
173                         continue;
174
175                 str_start = str_underline - strlen("map");
176                 if (str_start < tmp)
177                         continue;
178
179                 if (sscanf(str_start, "map_%d", &huge_index) != 1)
180                         continue;
181
182                 if (idx >= max) {
183                         PMD_DRV_LOG(ERR, "Exceed maximum of %d", max);
184                         goto error;
185                 }
186                 huges[idx].addr = v_start;
187                 huges[idx].size = v_end - v_start;
188                 snprintf(huges[idx].path, PATH_MAX, "%s", tmp);
189                 idx++;
190         }
191
192         fclose(f);
193         return idx;
194
195 error:
196         fclose(f);
197         return -1;
198 }
199
200 static int
201 prepare_vhost_memory_user(struct vhost_user_msg *msg, int fds[])
202 {
203         int i, num;
204         struct hugepage_file_info huges[VHOST_MEMORY_MAX_NREGIONS];
205         struct vhost_memory_region *mr;
206
207         num = get_hugepage_file_info(huges, VHOST_MEMORY_MAX_NREGIONS);
208         if (num < 0) {
209                 PMD_INIT_LOG(ERR, "Failed to prepare memory for vhost-user");
210                 return -1;
211         }
212
213         for (i = 0; i < num; ++i) {
214                 mr = &msg->payload.memory.regions[i];
215                 mr->guest_phys_addr = huges[i].addr; /* use vaddr! */
216                 mr->userspace_addr = huges[i].addr;
217                 mr->memory_size = huges[i].size;
218                 mr->mmap_offset = 0;
219                 fds[i] = open(huges[i].path, O_RDWR);
220         }
221
222         msg->payload.memory.nregions = num;
223         msg->payload.memory.padding = 0;
224
225         return 0;
226 }
227
228 static struct vhost_user_msg m;
229
230 static const char * const vhost_msg_strings[] = {
231         [VHOST_USER_SET_OWNER] = "VHOST_USER_SET_OWNER",
232         [VHOST_USER_RESET_OWNER] = "VHOST_USER_RESET_OWNER",
233         [VHOST_USER_SET_FEATURES] = "VHOST_USER_SET_FEATURES",
234         [VHOST_USER_GET_FEATURES] = "VHOST_USER_GET_FEATURES",
235         [VHOST_USER_SET_VRING_CALL] = "VHOST_USER_SET_VRING_CALL",
236         [VHOST_USER_SET_VRING_NUM] = "VHOST_USER_SET_VRING_NUM",
237         [VHOST_USER_SET_VRING_BASE] = "VHOST_USER_SET_VRING_BASE",
238         [VHOST_USER_GET_VRING_BASE] = "VHOST_USER_GET_VRING_BASE",
239         [VHOST_USER_SET_VRING_ADDR] = "VHOST_USER_SET_VRING_ADDR",
240         [VHOST_USER_SET_VRING_KICK] = "VHOST_USER_SET_VRING_KICK",
241         [VHOST_USER_SET_MEM_TABLE] = "VHOST_USER_SET_MEM_TABLE",
242         [VHOST_USER_SET_VRING_ENABLE] = "VHOST_USER_SET_VRING_ENABLE",
243         NULL,
244 };
245
246 int
247 vhost_user_sock(int vhostfd, enum vhost_user_request req, void *arg)
248 {
249         struct vhost_user_msg msg;
250         struct vhost_vring_file *file = 0;
251         int need_reply = 0;
252         int fds[VHOST_MEMORY_MAX_NREGIONS];
253         int fd_num = 0;
254         int i, len;
255
256         RTE_SET_USED(m);
257         RTE_SET_USED(vhost_msg_strings);
258
259         PMD_DRV_LOG(INFO, "%s", vhost_msg_strings[req]);
260
261         msg.request = req;
262         msg.flags = VHOST_USER_VERSION;
263         msg.size = 0;
264
265         switch (req) {
266         case VHOST_USER_GET_FEATURES:
267                 need_reply = 1;
268                 break;
269
270         case VHOST_USER_SET_FEATURES:
271         case VHOST_USER_SET_LOG_BASE:
272                 msg.payload.u64 = *((__u64 *)arg);
273                 msg.size = sizeof(m.payload.u64);
274                 break;
275
276         case VHOST_USER_SET_OWNER:
277         case VHOST_USER_RESET_OWNER:
278                 break;
279
280         case VHOST_USER_SET_MEM_TABLE:
281                 if (prepare_vhost_memory_user(&msg, fds) < 0)
282                         return -1;
283                 fd_num = msg.payload.memory.nregions;
284                 msg.size = sizeof(m.payload.memory.nregions);
285                 msg.size += sizeof(m.payload.memory.padding);
286                 msg.size += fd_num * sizeof(struct vhost_memory_region);
287                 break;
288
289         case VHOST_USER_SET_LOG_FD:
290                 fds[fd_num++] = *((int *)arg);
291                 break;
292
293         case VHOST_USER_SET_VRING_NUM:
294         case VHOST_USER_SET_VRING_BASE:
295         case VHOST_USER_SET_VRING_ENABLE:
296                 memcpy(&msg.payload.state, arg, sizeof(msg.payload.state));
297                 msg.size = sizeof(m.payload.state);
298                 break;
299
300         case VHOST_USER_GET_VRING_BASE:
301                 memcpy(&msg.payload.state, arg, sizeof(msg.payload.state));
302                 msg.size = sizeof(m.payload.state);
303                 need_reply = 1;
304                 break;
305
306         case VHOST_USER_SET_VRING_ADDR:
307                 memcpy(&msg.payload.addr, arg, sizeof(msg.payload.addr));
308                 msg.size = sizeof(m.payload.addr);
309                 break;
310
311         case VHOST_USER_SET_VRING_KICK:
312         case VHOST_USER_SET_VRING_CALL:
313         case VHOST_USER_SET_VRING_ERR:
314                 file = arg;
315                 msg.payload.u64 = file->index & VHOST_USER_VRING_IDX_MASK;
316                 msg.size = sizeof(m.payload.u64);
317                 if (file->fd > 0)
318                         fds[fd_num++] = file->fd;
319                 else
320                         msg.payload.u64 |= VHOST_USER_VRING_NOFD_MASK;
321                 break;
322
323         default:
324                 PMD_DRV_LOG(ERR, "trying to send unhandled msg type");
325                 return -1;
326         }
327
328         len = VHOST_USER_HDR_SIZE + msg.size;
329         if (vhost_user_write(vhostfd, &msg, len, fds, fd_num) < 0) {
330                 PMD_DRV_LOG(ERR, "%s failed: %s",
331                             vhost_msg_strings[req], strerror(errno));
332                 return -1;
333         }
334
335         if (req == VHOST_USER_SET_MEM_TABLE)
336                 for (i = 0; i < fd_num; ++i)
337                         close(fds[i]);
338
339         if (need_reply) {
340                 if (vhost_user_read(vhostfd, &msg) < 0) {
341                         PMD_DRV_LOG(ERR, "Received msg failed: %s",
342                                     strerror(errno));
343                         return -1;
344                 }
345
346                 if (req != msg.request) {
347                         PMD_DRV_LOG(ERR, "Received unexpected msg type");
348                         return -1;
349                 }
350
351                 switch (req) {
352                 case VHOST_USER_GET_FEATURES:
353                         if (msg.size != sizeof(m.payload.u64)) {
354                                 PMD_DRV_LOG(ERR, "Received bad msg size");
355                                 return -1;
356                         }
357                         *((__u64 *)arg) = msg.payload.u64;
358                         break;
359                 case VHOST_USER_GET_VRING_BASE:
360                         if (msg.size != sizeof(m.payload.state)) {
361                                 PMD_DRV_LOG(ERR, "Received bad msg size");
362                                 return -1;
363                         }
364                         memcpy(arg, &msg.payload.state,
365                                sizeof(struct vhost_vring_state));
366                         break;
367                 default:
368                         PMD_DRV_LOG(ERR, "Received unexpected msg type");
369                         return -1;
370                 }
371         }
372
373         return 0;
374 }
375
376 /**
377  * Set up environment to talk with a vhost user backend.
378  * @param path
379  *   - The path to vhost user unix socket file.
380  *
381  * @return
382  *   - (-1) if fail to set up;
383  *   - (>=0) if successful, and it is the fd to vhostfd.
384  */
385 int
386 vhost_user_setup(const char *path)
387 {
388         int fd;
389         int flag;
390         struct sockaddr_un un;
391
392         fd = socket(AF_UNIX, SOCK_STREAM, 0);
393         if (fd < 0) {
394                 PMD_DRV_LOG(ERR, "socket() error, %s", strerror(errno));
395                 return -1;
396         }
397
398         flag = fcntl(fd, F_GETFD);
399         if (fcntl(fd, F_SETFD, flag | FD_CLOEXEC) < 0)
400                 PMD_DRV_LOG(WARNING, "fcntl failed, %s", strerror(errno));
401
402         memset(&un, 0, sizeof(un));
403         un.sun_family = AF_UNIX;
404         snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);
405         if (connect(fd, (struct sockaddr *)&un, sizeof(un)) < 0) {
406                 PMD_DRV_LOG(ERR, "connect error, %s", strerror(errno));
407                 close(fd);
408                 return -1;
409         }
410
411         return fd;
412 }
413
414 int
415 vhost_user_enable_queue_pair(int vhostfd, uint16_t pair_idx, int enable)
416 {
417         int i;
418
419         for (i = 0; i < 2; ++i) {
420                 struct vhost_vring_state state = {
421                         .index = pair_idx * 2 + i,
422                         .num   = enable,
423                 };
424
425                 if (vhost_user_sock(vhostfd,
426                                     VHOST_USER_SET_VRING_ENABLE, &state))
427                         return -1;
428         }
429
430         return 0;
431 }