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