vhost: fix leak of fds and mmaps
[dpdk.git] / lib / librte_vhost / vhost_user / virtio-net-user.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2014 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 <stdint.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 #include <sys/mman.h>
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #include <sys/ioctl.h>
43 #include <sys/socket.h>
44 #include <net/ethernet.h>
45 #include <netinet/in.h>
46 #include <netinet/if_ether.h>
47 #include <linux/if_packet.h>
48
49 #include <rte_common.h>
50 #include <rte_log.h>
51
52 #include "virtio-net.h"
53 #include "virtio-net-user.h"
54 #include "vhost-net-user.h"
55 #include "vhost-net.h"
56
57 struct orig_region_map {
58         int fd;
59         uint64_t mapped_address;
60         uint64_t mapped_size;
61         uint64_t blksz;
62 };
63
64 #define orig_region(ptr, nregions) \
65         ((struct orig_region_map *)RTE_PTR_ADD((ptr), \
66                 sizeof(struct virtio_memory) + \
67                 sizeof(struct virtio_memory_regions) * (nregions)))
68
69 static uint64_t
70 get_blk_size(int fd)
71 {
72         struct stat stat;
73
74         fstat(fd, &stat);
75         return (uint64_t)stat.st_blksize;
76 }
77
78 static void
79 free_mem_region(struct virtio_net *dev)
80 {
81         struct orig_region_map *region;
82         unsigned int idx;
83
84         if (!dev || !dev->mem)
85                 return;
86
87         region = orig_region(dev->mem, dev->mem->nregions);
88         for (idx = 0; idx < dev->mem->nregions; idx++) {
89                 if (region[idx].mapped_address) {
90                         munmap((void *)(uintptr_t)region[idx].mapped_address,
91                                         region[idx].mapped_size);
92                         close(region[idx].fd);
93                 }
94         }
95 }
96
97 void
98 vhost_backend_cleanup(struct virtio_net *dev)
99 {
100         if (dev->mem) {
101                 free_mem_region(dev);
102                 free(dev->mem);
103                 dev->mem = NULL;
104         }
105 }
106
107 int
108 user_set_mem_table(struct vhost_device_ctx ctx, struct VhostUserMsg *pmsg)
109 {
110         struct VhostUserMemory memory = pmsg->payload.memory;
111         struct virtio_memory_regions *pregion;
112         uint64_t mapped_address, mapped_size;
113         struct virtio_net *dev;
114         unsigned int idx = 0;
115         struct orig_region_map *pregion_orig;
116         uint64_t alignment;
117
118         /* unmap old memory regions one by one*/
119         dev = get_device(ctx);
120         if (dev == NULL)
121                 return -1;
122
123         /* Remove from the data plane. */
124         if (dev->flags & VIRTIO_DEV_RUNNING)
125                 notify_ops->destroy_device(dev);
126
127         if (dev->mem) {
128                 free_mem_region(dev);
129                 free(dev->mem);
130                 dev->mem = NULL;
131         }
132
133         dev->mem = calloc(1,
134                 sizeof(struct virtio_memory) +
135                 sizeof(struct virtio_memory_regions) * memory.nregions +
136                 sizeof(struct orig_region_map) * memory.nregions);
137         if (dev->mem == NULL) {
138                 RTE_LOG(ERR, VHOST_CONFIG,
139                         "(%"PRIu64") Failed to allocate memory for dev->mem\n",
140                         dev->device_fh);
141                 return -1;
142         }
143         dev->mem->nregions = memory.nregions;
144
145         pregion_orig = orig_region(dev->mem, memory.nregions);
146         for (idx = 0; idx < memory.nregions; idx++) {
147                 pregion = &dev->mem->regions[idx];
148                 pregion->guest_phys_address =
149                         memory.regions[idx].guest_phys_addr;
150                 pregion->guest_phys_address_end =
151                         memory.regions[idx].guest_phys_addr +
152                         memory.regions[idx].memory_size;
153                 pregion->memory_size =
154                         memory.regions[idx].memory_size;
155                 pregion->userspace_address =
156                         memory.regions[idx].userspace_addr;
157
158                 /* This is ugly */
159                 mapped_size = memory.regions[idx].memory_size +
160                         memory.regions[idx].mmap_offset;
161
162                 /* mmap() without flag of MAP_ANONYMOUS, should be called
163                  * with length argument aligned with hugepagesz at older
164                  * longterm version Linux, like 2.6.32 and 3.2.72, or
165                  * mmap() will fail with EINVAL.
166                  *
167                  * to avoid failure, make sure in caller to keep length
168                  * aligned.
169                  */
170                 alignment = get_blk_size(pmsg->fds[idx]);
171                 mapped_size = RTE_ALIGN_CEIL(mapped_size, alignment);
172
173                 mapped_address = (uint64_t)(uintptr_t)mmap(NULL,
174                         mapped_size,
175                         PROT_READ | PROT_WRITE, MAP_SHARED,
176                         pmsg->fds[idx],
177                         0);
178
179                 RTE_LOG(INFO, VHOST_CONFIG,
180                         "mapped region %d fd:%d to:%p sz:0x%"PRIx64" "
181                         "off:0x%"PRIx64" align:0x%"PRIx64"\n",
182                         idx, pmsg->fds[idx], (void *)(uintptr_t)mapped_address,
183                         mapped_size, memory.regions[idx].mmap_offset,
184                         alignment);
185
186                 if (mapped_address == (uint64_t)(uintptr_t)MAP_FAILED) {
187                         RTE_LOG(ERR, VHOST_CONFIG,
188                                 "mmap qemu guest failed.\n");
189                         goto err_mmap;
190                 }
191
192                 pregion_orig[idx].mapped_address = mapped_address;
193                 pregion_orig[idx].mapped_size = mapped_size;
194                 pregion_orig[idx].blksz = alignment;
195                 pregion_orig[idx].fd = pmsg->fds[idx];
196
197                 mapped_address +=  memory.regions[idx].mmap_offset;
198
199                 pregion->address_offset = mapped_address -
200                         pregion->guest_phys_address;
201
202                 if (memory.regions[idx].guest_phys_addr == 0) {
203                         dev->mem->base_address =
204                                 memory.regions[idx].userspace_addr;
205                         dev->mem->mapped_address =
206                                 pregion->address_offset;
207                 }
208
209                 LOG_DEBUG(VHOST_CONFIG,
210                         "REGION: %u GPA: %p QEMU VA: %p SIZE (%"PRIu64")\n",
211                         idx,
212                         (void *)(uintptr_t)pregion->guest_phys_address,
213                         (void *)(uintptr_t)pregion->userspace_address,
214                          pregion->memory_size);
215         }
216
217         return 0;
218
219 err_mmap:
220         while (idx--) {
221                 munmap((void *)(uintptr_t)pregion_orig[idx].mapped_address,
222                                 pregion_orig[idx].mapped_size);
223                 close(pregion_orig[idx].fd);
224         }
225         free(dev->mem);
226         dev->mem = NULL;
227         return -1;
228 }
229
230 static int
231 vq_is_ready(struct vhost_virtqueue *vq)
232 {
233         return vq && vq->desc   &&
234                vq->kickfd != -1 &&
235                vq->callfd != -1;
236 }
237
238 static int
239 virtio_is_ready(struct virtio_net *dev)
240 {
241         struct vhost_virtqueue *rvq, *tvq;
242         uint32_t i;
243
244         for (i = 0; i < dev->virt_qp_nb; i++) {
245                 rvq = dev->virtqueue[i * VIRTIO_QNUM + VIRTIO_RXQ];
246                 tvq = dev->virtqueue[i * VIRTIO_QNUM + VIRTIO_TXQ];
247
248                 if (!vq_is_ready(rvq) || !vq_is_ready(tvq)) {
249                         RTE_LOG(INFO, VHOST_CONFIG,
250                                 "virtio is not ready for processing.\n");
251                         return 0;
252                 }
253         }
254
255         RTE_LOG(INFO, VHOST_CONFIG,
256                 "virtio is now ready for processing.\n");
257         return 1;
258 }
259
260 void
261 user_set_vring_call(struct vhost_device_ctx ctx, struct VhostUserMsg *pmsg)
262 {
263         struct vhost_vring_file file;
264
265         file.index = pmsg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
266         if (pmsg->payload.u64 & VHOST_USER_VRING_NOFD_MASK)
267                 file.fd = -1;
268         else
269                 file.fd = pmsg->fds[0];
270         RTE_LOG(INFO, VHOST_CONFIG,
271                 "vring call idx:%d file:%d\n", file.index, file.fd);
272         ops->set_vring_call(ctx, &file);
273 }
274
275
276 /*
277  *  In vhost-user, when we receive kick message, will test whether virtio
278  *  device is ready for packet processing.
279  */
280 void
281 user_set_vring_kick(struct vhost_device_ctx ctx, struct VhostUserMsg *pmsg)
282 {
283         struct vhost_vring_file file;
284         struct virtio_net *dev = get_device(ctx);
285
286         file.index = pmsg->payload.u64 & VHOST_USER_VRING_IDX_MASK;
287         if (pmsg->payload.u64 & VHOST_USER_VRING_NOFD_MASK)
288                 file.fd = -1;
289         else
290                 file.fd = pmsg->fds[0];
291         RTE_LOG(INFO, VHOST_CONFIG,
292                 "vring kick idx:%d file:%d\n", file.index, file.fd);
293         ops->set_vring_kick(ctx, &file);
294
295         if (virtio_is_ready(dev) &&
296                 !(dev->flags & VIRTIO_DEV_RUNNING))
297                         notify_ops->new_device(dev);
298 }
299
300 /*
301  * when virtio is stopped, qemu will send us the GET_VRING_BASE message.
302  */
303 int
304 user_get_vring_base(struct vhost_device_ctx ctx,
305         struct vhost_vring_state *state)
306 {
307         struct virtio_net *dev = get_device(ctx);
308
309         if (dev == NULL)
310                 return -1;
311         /* We have to stop the queue (virtio) if it is running. */
312         if (dev->flags & VIRTIO_DEV_RUNNING)
313                 notify_ops->destroy_device(dev);
314
315         /* Here we are safe to get the last used index */
316         ops->get_vring_base(ctx, state->index, state);
317
318         RTE_LOG(INFO, VHOST_CONFIG,
319                 "vring base idx:%d file:%d\n", state->index, state->num);
320         /*
321          * Based on current qemu vhost-user implementation, this message is
322          * sent and only sent in vhost_vring_stop.
323          * TODO: cleanup the vring, it isn't usable since here.
324          */
325         if (dev->virtqueue[state->index]->kickfd >= 0) {
326                 close(dev->virtqueue[state->index]->kickfd);
327                 dev->virtqueue[state->index]->kickfd = -1;
328         }
329
330         return 0;
331 }
332
333 /*
334  * when virtio queues are ready to work, qemu will send us to
335  * enable the virtio queue pair.
336  */
337 int
338 user_set_vring_enable(struct vhost_device_ctx ctx,
339                       struct vhost_vring_state *state)
340 {
341         struct virtio_net *dev = get_device(ctx);
342         int enable = (int)state->num;
343
344         RTE_LOG(INFO, VHOST_CONFIG,
345                 "set queue enable: %d to qp idx: %d\n",
346                 enable, state->index);
347
348         if (notify_ops->vring_state_changed) {
349                 notify_ops->vring_state_changed(dev, state->index, enable);
350         }
351
352         dev->virtqueue[state->index]->enabled = enable;
353
354         return 0;
355 }
356
357 void
358 user_set_protocol_features(struct vhost_device_ctx ctx,
359                            uint64_t protocol_features)
360 {
361         struct virtio_net *dev;
362
363         dev = get_device(ctx);
364         if (dev == NULL || protocol_features & ~VHOST_USER_PROTOCOL_FEATURES)
365                 return;
366
367         dev->protocol_features = protocol_features;
368 }
369
370 int
371 user_set_log_base(struct vhost_device_ctx ctx,
372                  struct VhostUserMsg *msg)
373 {
374         struct virtio_net *dev;
375         int fd = msg->fds[0];
376         uint64_t size, off;
377         void *addr;
378
379         dev = get_device(ctx);
380         if (!dev)
381                 return -1;
382
383         if (fd < 0) {
384                 RTE_LOG(ERR, VHOST_CONFIG, "invalid log fd: %d\n", fd);
385                 return -1;
386         }
387
388         if (msg->size != sizeof(VhostUserLog)) {
389                 RTE_LOG(ERR, VHOST_CONFIG,
390                         "invalid log base msg size: %"PRId32" != %d\n",
391                         msg->size, (int)sizeof(VhostUserLog));
392                 return -1;
393         }
394
395         size = msg->payload.log.mmap_size;
396         off  = msg->payload.log.mmap_offset;
397         RTE_LOG(INFO, VHOST_CONFIG,
398                 "log mmap size: %"PRId64", offset: %"PRId64"\n",
399                 size, off);
400
401         /*
402          * mmap from 0 to workaround a hugepage mmap bug: mmap will
403          * fail when offset is not page size aligned.
404          */
405         addr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
406         if (addr == MAP_FAILED) {
407                 RTE_LOG(ERR, VHOST_CONFIG, "mmap log base failed!\n");
408                 return -1;
409         }
410
411         /* TODO: unmap on stop */
412         dev->log_base = (uint64_t)(uintptr_t)addr + off;
413         dev->log_size = size;
414
415         return 0;
416 }
417
418 #define RARP_BUF_SIZE   64
419
420 static void
421 make_rarp_packet(uint8_t *buf, uint8_t *mac)
422 {
423         struct ether_header *eth_hdr;
424         struct ether_arp *rarp;
425
426         /* Ethernet header. */
427         eth_hdr = (struct ether_header *)buf;
428         memset(&eth_hdr->ether_dhost, 0xff, ETH_ALEN);
429         memcpy(&eth_hdr->ether_shost, mac,  ETH_ALEN);
430         eth_hdr->ether_type = htons(ETH_P_RARP);
431
432         /* RARP header. */
433         rarp = (struct ether_arp *)(eth_hdr + 1);
434         rarp->ea_hdr.ar_hrd = htons(ARPHRD_ETHER);
435         rarp->ea_hdr.ar_pro = htons(ETHERTYPE_IP);
436         rarp->ea_hdr.ar_hln = ETH_ALEN;
437         rarp->ea_hdr.ar_pln = 4;
438         rarp->ea_hdr.ar_op  = htons(ARPOP_RREQUEST);
439
440         memcpy(&rarp->arp_sha, mac, ETH_ALEN);
441         memset(&rarp->arp_spa, 0x00, 4);
442         memcpy(&rarp->arp_tha, mac, 6);
443         memset(&rarp->arp_tpa, 0x00, 4);
444 }
445
446
447 static void
448 send_rarp(const char *ifname, uint8_t *rarp)
449 {
450         int fd;
451         struct ifreq ifr;
452         struct sockaddr_ll addr;
453
454         fd = socket(AF_PACKET, SOCK_RAW, 0);
455         if (fd < 0) {
456                 perror("socket failed");
457                 return;
458         }
459
460         memset(&ifr, 0, sizeof(struct ifreq));
461         strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
462         if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
463                 perror("failed to get interface index");
464                 close(fd);
465                 return;
466         }
467
468         addr.sll_ifindex = ifr.ifr_ifindex;
469         addr.sll_halen   = ETH_ALEN;
470
471         if (sendto(fd, rarp, RARP_BUF_SIZE, 0,
472                    (const struct sockaddr*)&addr, sizeof(addr)) < 0) {
473                 perror("send rarp packet failed");
474         }
475 }
476
477
478 /*
479  * Broadcast a RARP message to all interfaces, to update
480  * switch's mac table
481  */
482 int
483 user_send_rarp(struct VhostUserMsg *msg)
484 {
485         uint8_t *mac = (uint8_t *)&msg->payload.u64;
486         uint8_t rarp[RARP_BUF_SIZE];
487         struct ifconf ifc = {0, };
488         struct ifreq *ifr;
489         int nr = 16;
490         int fd;
491         uint32_t i;
492
493         RTE_LOG(DEBUG, VHOST_CONFIG,
494                 ":: mac: %02x:%02x:%02x:%02x:%02x:%02x\n",
495                 mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
496
497         make_rarp_packet(rarp, mac);
498
499         /*
500          * Get all interfaces
501          */
502         fd = socket(AF_INET, SOCK_DGRAM, 0);
503         if (fd < 0) {
504                 perror("failed to create AF_INET socket");
505                 return -1;
506         }
507
508 again:
509         ifc.ifc_len = sizeof(*ifr) * nr;
510         ifc.ifc_buf = realloc(ifc.ifc_buf, ifc.ifc_len);
511
512         if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) {
513                 perror("failed at SIOCGIFCONF");
514                 close(fd);
515                 return -1;
516         }
517
518         if (ifc.ifc_len == (int)sizeof(struct ifreq) * nr) {
519                 /*
520                  * current ifc_buf is not big enough to hold
521                  * all interfaces; double it and try again.
522                  */
523                 nr *= 2;
524                 goto again;
525         }
526
527         ifr = (struct ifreq *)ifc.ifc_buf;
528         for (i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++)
529                 send_rarp(ifr[i].ifr_name, rarp);
530
531         close(fd);
532
533         return 0;
534 }