]> git.proxmox.com Git - mirror_qemu.git/blame - migration-rdma.c
rdma: validate RDMAControlHeader::len
[mirror_qemu.git] / migration-rdma.c
CommitLineData
2da776db
MH
1/*
2 * RDMA protocol and interfaces
3 *
4 * Copyright IBM, Corp. 2010-2013
5 *
6 * Authors:
7 * Michael R. Hines <mrhines@us.ibm.com>
8 * Jiuxing Liu <jl@us.ibm.com>
9 *
10 * This work is licensed under the terms of the GNU GPL, version 2 or
11 * later. See the COPYING file in the top-level directory.
12 *
13 */
14#include "qemu-common.h"
15#include "migration/migration.h"
16#include "migration/qemu-file.h"
17#include "exec/cpu-common.h"
18#include "qemu/main-loop.h"
19#include "qemu/sockets.h"
20#include "qemu/bitmap.h"
21#include "block/coroutine.h"
22#include <stdio.h>
23#include <sys/types.h>
24#include <sys/socket.h>
25#include <netdb.h>
26#include <arpa/inet.h>
27#include <string.h>
28#include <rdma/rdma_cma.h>
29
8cd31adc 30//#define DEBUG_RDMA
2da776db
MH
31//#define DEBUG_RDMA_VERBOSE
32//#define DEBUG_RDMA_REALLY_VERBOSE
33
34#ifdef DEBUG_RDMA
35#define DPRINTF(fmt, ...) \
36 do { printf("rdma: " fmt, ## __VA_ARGS__); } while (0)
37#else
38#define DPRINTF(fmt, ...) \
39 do { } while (0)
40#endif
41
42#ifdef DEBUG_RDMA_VERBOSE
43#define DDPRINTF(fmt, ...) \
44 do { printf("rdma: " fmt, ## __VA_ARGS__); } while (0)
45#else
46#define DDPRINTF(fmt, ...) \
47 do { } while (0)
48#endif
49
50#ifdef DEBUG_RDMA_REALLY_VERBOSE
51#define DDDPRINTF(fmt, ...) \
52 do { printf("rdma: " fmt, ## __VA_ARGS__); } while (0)
53#else
54#define DDDPRINTF(fmt, ...) \
55 do { } while (0)
56#endif
57
58/*
59 * Print and error on both the Monitor and the Log file.
60 */
61#define ERROR(errp, fmt, ...) \
62 do { \
66988941 63 fprintf(stderr, "RDMA ERROR: " fmt "\n", ## __VA_ARGS__); \
2da776db
MH
64 if (errp && (*(errp) == NULL)) { \
65 error_setg(errp, "RDMA ERROR: " fmt, ## __VA_ARGS__); \
66 } \
67 } while (0)
68
69#define RDMA_RESOLVE_TIMEOUT_MS 10000
70
71/* Do not merge data if larger than this. */
72#define RDMA_MERGE_MAX (2 * 1024 * 1024)
73#define RDMA_SIGNALED_SEND_MAX (RDMA_MERGE_MAX / 4096)
74
75#define RDMA_REG_CHUNK_SHIFT 20 /* 1 MB */
76
77/*
78 * This is only for non-live state being migrated.
79 * Instead of RDMA_WRITE messages, we use RDMA_SEND
80 * messages for that state, which requires a different
81 * delivery design than main memory.
82 */
83#define RDMA_SEND_INCREMENT 32768
84
85/*
86 * Maximum size infiniband SEND message
87 */
88#define RDMA_CONTROL_MAX_BUFFER (512 * 1024)
89#define RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE 4096
90
91#define RDMA_CONTROL_VERSION_CURRENT 1
92/*
93 * Capabilities for negotiation.
94 */
95#define RDMA_CAPABILITY_PIN_ALL 0x01
96
97/*
98 * Add the other flags above to this list of known capabilities
99 * as they are introduced.
100 */
101static uint32_t known_capabilities = RDMA_CAPABILITY_PIN_ALL;
102
103#define CHECK_ERROR_STATE() \
104 do { \
105 if (rdma->error_state) { \
106 if (!rdma->error_reported) { \
107 fprintf(stderr, "RDMA is in an error state waiting migration" \
108 " to abort!\n"); \
109 rdma->error_reported = 1; \
110 } \
111 return rdma->error_state; \
112 } \
113 } while (0);
114
115/*
116 * A work request ID is 64-bits and we split up these bits
117 * into 3 parts:
118 *
119 * bits 0-15 : type of control message, 2^16
120 * bits 16-29: ram block index, 2^14
121 * bits 30-63: ram block chunk number, 2^34
122 *
123 * The last two bit ranges are only used for RDMA writes,
124 * in order to track their completion and potentially
125 * also track unregistration status of the message.
126 */
127#define RDMA_WRID_TYPE_SHIFT 0UL
128#define RDMA_WRID_BLOCK_SHIFT 16UL
129#define RDMA_WRID_CHUNK_SHIFT 30UL
130
131#define RDMA_WRID_TYPE_MASK \
132 ((1UL << RDMA_WRID_BLOCK_SHIFT) - 1UL)
133
134#define RDMA_WRID_BLOCK_MASK \
135 (~RDMA_WRID_TYPE_MASK & ((1UL << RDMA_WRID_CHUNK_SHIFT) - 1UL))
136
137#define RDMA_WRID_CHUNK_MASK (~RDMA_WRID_BLOCK_MASK & ~RDMA_WRID_TYPE_MASK)
138
139/*
140 * RDMA migration protocol:
141 * 1. RDMA Writes (data messages, i.e. RAM)
142 * 2. IB Send/Recv (control channel messages)
143 */
144enum {
145 RDMA_WRID_NONE = 0,
146 RDMA_WRID_RDMA_WRITE = 1,
147 RDMA_WRID_SEND_CONTROL = 2000,
148 RDMA_WRID_RECV_CONTROL = 4000,
149};
150
151const char *wrid_desc[] = {
152 [RDMA_WRID_NONE] = "NONE",
153 [RDMA_WRID_RDMA_WRITE] = "WRITE RDMA",
154 [RDMA_WRID_SEND_CONTROL] = "CONTROL SEND",
155 [RDMA_WRID_RECV_CONTROL] = "CONTROL RECV",
156};
157
158/*
159 * Work request IDs for IB SEND messages only (not RDMA writes).
160 * This is used by the migration protocol to transmit
161 * control messages (such as device state and registration commands)
162 *
163 * We could use more WRs, but we have enough for now.
164 */
165enum {
166 RDMA_WRID_READY = 0,
167 RDMA_WRID_DATA,
168 RDMA_WRID_CONTROL,
169 RDMA_WRID_MAX,
170};
171
172/*
173 * SEND/RECV IB Control Messages.
174 */
175enum {
176 RDMA_CONTROL_NONE = 0,
177 RDMA_CONTROL_ERROR,
178 RDMA_CONTROL_READY, /* ready to receive */
179 RDMA_CONTROL_QEMU_FILE, /* QEMUFile-transmitted bytes */
180 RDMA_CONTROL_RAM_BLOCKS_REQUEST, /* RAMBlock synchronization */
181 RDMA_CONTROL_RAM_BLOCKS_RESULT, /* RAMBlock synchronization */
182 RDMA_CONTROL_COMPRESS, /* page contains repeat values */
183 RDMA_CONTROL_REGISTER_REQUEST, /* dynamic page registration */
184 RDMA_CONTROL_REGISTER_RESULT, /* key to use after registration */
185 RDMA_CONTROL_REGISTER_FINISHED, /* current iteration finished */
186 RDMA_CONTROL_UNREGISTER_REQUEST, /* dynamic UN-registration */
187 RDMA_CONTROL_UNREGISTER_FINISHED, /* unpinning finished */
188};
189
190const char *control_desc[] = {
191 [RDMA_CONTROL_NONE] = "NONE",
192 [RDMA_CONTROL_ERROR] = "ERROR",
193 [RDMA_CONTROL_READY] = "READY",
194 [RDMA_CONTROL_QEMU_FILE] = "QEMU FILE",
195 [RDMA_CONTROL_RAM_BLOCKS_REQUEST] = "RAM BLOCKS REQUEST",
196 [RDMA_CONTROL_RAM_BLOCKS_RESULT] = "RAM BLOCKS RESULT",
197 [RDMA_CONTROL_COMPRESS] = "COMPRESS",
198 [RDMA_CONTROL_REGISTER_REQUEST] = "REGISTER REQUEST",
199 [RDMA_CONTROL_REGISTER_RESULT] = "REGISTER RESULT",
200 [RDMA_CONTROL_REGISTER_FINISHED] = "REGISTER FINISHED",
201 [RDMA_CONTROL_UNREGISTER_REQUEST] = "UNREGISTER REQUEST",
202 [RDMA_CONTROL_UNREGISTER_FINISHED] = "UNREGISTER FINISHED",
203};
204
205/*
206 * Memory and MR structures used to represent an IB Send/Recv work request.
207 * This is *not* used for RDMA writes, only IB Send/Recv.
208 */
209typedef struct {
210 uint8_t control[RDMA_CONTROL_MAX_BUFFER]; /* actual buffer to register */
211 struct ibv_mr *control_mr; /* registration metadata */
212 size_t control_len; /* length of the message */
213 uint8_t *control_curr; /* start of unconsumed bytes */
214} RDMAWorkRequestData;
215
216/*
217 * Negotiate RDMA capabilities during connection-setup time.
218 */
219typedef struct {
220 uint32_t version;
221 uint32_t flags;
222} RDMACapabilities;
223
224static void caps_to_network(RDMACapabilities *cap)
225{
226 cap->version = htonl(cap->version);
227 cap->flags = htonl(cap->flags);
228}
229
230static void network_to_caps(RDMACapabilities *cap)
231{
232 cap->version = ntohl(cap->version);
233 cap->flags = ntohl(cap->flags);
234}
235
236/*
237 * Representation of a RAMBlock from an RDMA perspective.
238 * This is not transmitted, only local.
239 * This and subsequent structures cannot be linked lists
240 * because we're using a single IB message to transmit
241 * the information. It's small anyway, so a list is overkill.
242 */
243typedef struct RDMALocalBlock {
244 uint8_t *local_host_addr; /* local virtual address */
245 uint64_t remote_host_addr; /* remote virtual address */
246 uint64_t offset;
247 uint64_t length;
248 struct ibv_mr **pmr; /* MRs for chunk-level registration */
249 struct ibv_mr *mr; /* MR for non-chunk-level registration */
250 uint32_t *remote_keys; /* rkeys for chunk-level registration */
251 uint32_t remote_rkey; /* rkeys for non-chunk-level registration */
252 int index; /* which block are we */
253 bool is_ram_block;
254 int nb_chunks;
255 unsigned long *transit_bitmap;
256 unsigned long *unregister_bitmap;
257} RDMALocalBlock;
258
259/*
260 * Also represents a RAMblock, but only on the dest.
261 * This gets transmitted by the dest during connection-time
262 * to the source VM and then is used to populate the
263 * corresponding RDMALocalBlock with
264 * the information needed to perform the actual RDMA.
265 */
266typedef struct QEMU_PACKED RDMARemoteBlock {
267 uint64_t remote_host_addr;
268 uint64_t offset;
269 uint64_t length;
270 uint32_t remote_rkey;
271 uint32_t padding;
272} RDMARemoteBlock;
273
274static uint64_t htonll(uint64_t v)
275{
276 union { uint32_t lv[2]; uint64_t llv; } u;
277 u.lv[0] = htonl(v >> 32);
278 u.lv[1] = htonl(v & 0xFFFFFFFFULL);
279 return u.llv;
280}
281
282static uint64_t ntohll(uint64_t v) {
283 union { uint32_t lv[2]; uint64_t llv; } u;
284 u.llv = v;
285 return ((uint64_t)ntohl(u.lv[0]) << 32) | (uint64_t) ntohl(u.lv[1]);
286}
287
288static void remote_block_to_network(RDMARemoteBlock *rb)
289{
290 rb->remote_host_addr = htonll(rb->remote_host_addr);
291 rb->offset = htonll(rb->offset);
292 rb->length = htonll(rb->length);
293 rb->remote_rkey = htonl(rb->remote_rkey);
294}
295
296static void network_to_remote_block(RDMARemoteBlock *rb)
297{
298 rb->remote_host_addr = ntohll(rb->remote_host_addr);
299 rb->offset = ntohll(rb->offset);
300 rb->length = ntohll(rb->length);
301 rb->remote_rkey = ntohl(rb->remote_rkey);
302}
303
304/*
305 * Virtual address of the above structures used for transmitting
306 * the RAMBlock descriptions at connection-time.
307 * This structure is *not* transmitted.
308 */
309typedef struct RDMALocalBlocks {
310 int nb_blocks;
311 bool init; /* main memory init complete */
312 RDMALocalBlock *block;
313} RDMALocalBlocks;
314
315/*
316 * Main data structure for RDMA state.
317 * While there is only one copy of this structure being allocated right now,
318 * this is the place where one would start if you wanted to consider
319 * having more than one RDMA connection open at the same time.
320 */
321typedef struct RDMAContext {
322 char *host;
323 int port;
324
1f22364b 325 RDMAWorkRequestData wr_data[RDMA_WRID_MAX];
2da776db
MH
326
327 /*
328 * This is used by *_exchange_send() to figure out whether or not
329 * the initial "READY" message has already been received or not.
330 * This is because other functions may potentially poll() and detect
331 * the READY message before send() does, in which case we need to
332 * know if it completed.
333 */
334 int control_ready_expected;
335
336 /* number of outstanding writes */
337 int nb_sent;
338
339 /* store info about current buffer so that we can
340 merge it with future sends */
341 uint64_t current_addr;
342 uint64_t current_length;
343 /* index of ram block the current buffer belongs to */
344 int current_index;
345 /* index of the chunk in the current ram block */
346 int current_chunk;
347
348 bool pin_all;
349
350 /*
351 * infiniband-specific variables for opening the device
352 * and maintaining connection state and so forth.
353 *
354 * cm_id also has ibv_context, rdma_event_channel, and ibv_qp in
355 * cm_id->verbs, cm_id->channel, and cm_id->qp.
356 */
357 struct rdma_cm_id *cm_id; /* connection manager ID */
358 struct rdma_cm_id *listen_id;
359
360 struct ibv_context *verbs;
361 struct rdma_event_channel *channel;
362 struct ibv_qp *qp; /* queue pair */
363 struct ibv_comp_channel *comp_channel; /* completion channel */
364 struct ibv_pd *pd; /* protection domain */
365 struct ibv_cq *cq; /* completion queue */
366
367 /*
368 * If a previous write failed (perhaps because of a failed
369 * memory registration, then do not attempt any future work
370 * and remember the error state.
371 */
372 int error_state;
373 int error_reported;
374
375 /*
376 * Description of ram blocks used throughout the code.
377 */
378 RDMALocalBlocks local_ram_blocks;
379 RDMARemoteBlock *block;
380
381 /*
382 * Migration on *destination* started.
383 * Then use coroutine yield function.
384 * Source runs in a thread, so we don't care.
385 */
386 int migration_started_on_destination;
387
388 int total_registrations;
389 int total_writes;
390
391 int unregister_current, unregister_next;
392 uint64_t unregistrations[RDMA_SIGNALED_SEND_MAX];
393
394 GHashTable *blockmap;
b58c8552 395 bool ipv6;
2da776db
MH
396} RDMAContext;
397
398/*
399 * Interface to the rest of the migration call stack.
400 */
401typedef struct QEMUFileRDMA {
402 RDMAContext *rdma;
403 size_t len;
404 void *file;
405} QEMUFileRDMA;
406
407/*
408 * Main structure for IB Send/Recv control messages.
409 * This gets prepended at the beginning of every Send/Recv.
410 */
411typedef struct QEMU_PACKED {
412 uint32_t len; /* Total length of data portion */
413 uint32_t type; /* which control command to perform */
414 uint32_t repeat; /* number of commands in data portion of same type */
415 uint32_t padding;
416} RDMAControlHeader;
417
418static void control_to_network(RDMAControlHeader *control)
419{
420 control->type = htonl(control->type);
421 control->len = htonl(control->len);
422 control->repeat = htonl(control->repeat);
423}
424
425static void network_to_control(RDMAControlHeader *control)
426{
427 control->type = ntohl(control->type);
428 control->len = ntohl(control->len);
429 control->repeat = ntohl(control->repeat);
430}
431
432/*
433 * Register a single Chunk.
434 * Information sent by the source VM to inform the dest
435 * to register an single chunk of memory before we can perform
436 * the actual RDMA operation.
437 */
438typedef struct QEMU_PACKED {
439 union QEMU_PACKED {
440 uint64_t current_addr; /* offset into the ramblock of the chunk */
441 uint64_t chunk; /* chunk to lookup if unregistering */
442 } key;
443 uint32_t current_index; /* which ramblock the chunk belongs to */
444 uint32_t padding;
445 uint64_t chunks; /* how many sequential chunks to register */
446} RDMARegister;
447
448static void register_to_network(RDMARegister *reg)
449{
450 reg->key.current_addr = htonll(reg->key.current_addr);
451 reg->current_index = htonl(reg->current_index);
452 reg->chunks = htonll(reg->chunks);
453}
454
455static void network_to_register(RDMARegister *reg)
456{
457 reg->key.current_addr = ntohll(reg->key.current_addr);
458 reg->current_index = ntohl(reg->current_index);
459 reg->chunks = ntohll(reg->chunks);
460}
461
462typedef struct QEMU_PACKED {
463 uint32_t value; /* if zero, we will madvise() */
464 uint32_t block_idx; /* which ram block index */
465 uint64_t offset; /* where in the remote ramblock this chunk */
466 uint64_t length; /* length of the chunk */
467} RDMACompress;
468
469static void compress_to_network(RDMACompress *comp)
470{
471 comp->value = htonl(comp->value);
472 comp->block_idx = htonl(comp->block_idx);
473 comp->offset = htonll(comp->offset);
474 comp->length = htonll(comp->length);
475}
476
477static void network_to_compress(RDMACompress *comp)
478{
479 comp->value = ntohl(comp->value);
480 comp->block_idx = ntohl(comp->block_idx);
481 comp->offset = ntohll(comp->offset);
482 comp->length = ntohll(comp->length);
483}
484
485/*
486 * The result of the dest's memory registration produces an "rkey"
487 * which the source VM must reference in order to perform
488 * the RDMA operation.
489 */
490typedef struct QEMU_PACKED {
491 uint32_t rkey;
492 uint32_t padding;
493 uint64_t host_addr;
494} RDMARegisterResult;
495
496static void result_to_network(RDMARegisterResult *result)
497{
498 result->rkey = htonl(result->rkey);
499 result->host_addr = htonll(result->host_addr);
500};
501
502static void network_to_result(RDMARegisterResult *result)
503{
504 result->rkey = ntohl(result->rkey);
505 result->host_addr = ntohll(result->host_addr);
506};
507
508const char *print_wrid(int wrid);
509static int qemu_rdma_exchange_send(RDMAContext *rdma, RDMAControlHeader *head,
510 uint8_t *data, RDMAControlHeader *resp,
511 int *resp_idx,
512 int (*callback)(RDMAContext *rdma));
513
514static inline uint64_t ram_chunk_index(uint8_t *start, uint8_t *host)
515{
516 return ((uintptr_t) host - (uintptr_t) start) >> RDMA_REG_CHUNK_SHIFT;
517}
518
519static inline uint8_t *ram_chunk_start(RDMALocalBlock *rdma_ram_block,
520 uint64_t i)
521{
522 return (uint8_t *) (((uintptr_t) rdma_ram_block->local_host_addr)
523 + (i << RDMA_REG_CHUNK_SHIFT));
524}
525
526static inline uint8_t *ram_chunk_end(RDMALocalBlock *rdma_ram_block, uint64_t i)
527{
528 uint8_t *result = ram_chunk_start(rdma_ram_block, i) +
529 (1UL << RDMA_REG_CHUNK_SHIFT);
530
531 if (result > (rdma_ram_block->local_host_addr + rdma_ram_block->length)) {
532 result = rdma_ram_block->local_host_addr + rdma_ram_block->length;
533 }
534
535 return result;
536}
537
538static int __qemu_rdma_add_block(RDMAContext *rdma, void *host_addr,
539 ram_addr_t block_offset, uint64_t length)
540{
541 RDMALocalBlocks *local = &rdma->local_ram_blocks;
542 RDMALocalBlock *block = g_hash_table_lookup(rdma->blockmap,
543 (void *) block_offset);
544 RDMALocalBlock *old = local->block;
545
546 assert(block == NULL);
547
548 local->block = g_malloc0(sizeof(RDMALocalBlock) * (local->nb_blocks + 1));
549
550 if (local->nb_blocks) {
551 int x;
552
553 for (x = 0; x < local->nb_blocks; x++) {
554 g_hash_table_remove(rdma->blockmap, (void *)old[x].offset);
555 g_hash_table_insert(rdma->blockmap, (void *)old[x].offset,
556 &local->block[x]);
557 }
558 memcpy(local->block, old, sizeof(RDMALocalBlock) * local->nb_blocks);
559 g_free(old);
560 }
561
562 block = &local->block[local->nb_blocks];
563
564 block->local_host_addr = host_addr;
565 block->offset = block_offset;
566 block->length = length;
567 block->index = local->nb_blocks;
568 block->nb_chunks = ram_chunk_index(host_addr, host_addr + length) + 1UL;
569 block->transit_bitmap = bitmap_new(block->nb_chunks);
570 bitmap_clear(block->transit_bitmap, 0, block->nb_chunks);
571 block->unregister_bitmap = bitmap_new(block->nb_chunks);
572 bitmap_clear(block->unregister_bitmap, 0, block->nb_chunks);
573 block->remote_keys = g_malloc0(block->nb_chunks * sizeof(uint32_t));
574
575 block->is_ram_block = local->init ? false : true;
576
577 g_hash_table_insert(rdma->blockmap, (void *) block_offset, block);
578
579 DDPRINTF("Added Block: %d, addr: %" PRIu64 ", offset: %" PRIu64
580 " length: %" PRIu64 " end: %" PRIu64 " bits %" PRIu64 " chunks %d\n",
581 local->nb_blocks, (uint64_t) block->local_host_addr, block->offset,
582 block->length, (uint64_t) (block->local_host_addr + block->length),
583 BITS_TO_LONGS(block->nb_chunks) *
584 sizeof(unsigned long) * 8, block->nb_chunks);
585
586 local->nb_blocks++;
587
588 return 0;
589}
590
591/*
592 * Memory regions need to be registered with the device and queue pairs setup
593 * in advanced before the migration starts. This tells us where the RAM blocks
594 * are so that we can register them individually.
595 */
596static void qemu_rdma_init_one_block(void *host_addr,
597 ram_addr_t block_offset, ram_addr_t length, void *opaque)
598{
599 __qemu_rdma_add_block(opaque, host_addr, block_offset, length);
600}
601
602/*
603 * Identify the RAMBlocks and their quantity. They will be references to
604 * identify chunk boundaries inside each RAMBlock and also be referenced
605 * during dynamic page registration.
606 */
607static int qemu_rdma_init_ram_blocks(RDMAContext *rdma)
608{
609 RDMALocalBlocks *local = &rdma->local_ram_blocks;
610
611 assert(rdma->blockmap == NULL);
612 rdma->blockmap = g_hash_table_new(g_direct_hash, g_direct_equal);
613 memset(local, 0, sizeof *local);
614 qemu_ram_foreach_block(qemu_rdma_init_one_block, rdma);
615 DPRINTF("Allocated %d local ram block structures\n", local->nb_blocks);
616 rdma->block = (RDMARemoteBlock *) g_malloc0(sizeof(RDMARemoteBlock) *
617 rdma->local_ram_blocks.nb_blocks);
618 local->init = true;
619 return 0;
620}
621
622static int __qemu_rdma_delete_block(RDMAContext *rdma, ram_addr_t block_offset)
623{
624 RDMALocalBlocks *local = &rdma->local_ram_blocks;
625 RDMALocalBlock *block = g_hash_table_lookup(rdma->blockmap,
626 (void *) block_offset);
627 RDMALocalBlock *old = local->block;
628 int x;
629
630 assert(block);
631
632 if (block->pmr) {
633 int j;
634
635 for (j = 0; j < block->nb_chunks; j++) {
636 if (!block->pmr[j]) {
637 continue;
638 }
639 ibv_dereg_mr(block->pmr[j]);
640 rdma->total_registrations--;
641 }
642 g_free(block->pmr);
643 block->pmr = NULL;
644 }
645
646 if (block->mr) {
647 ibv_dereg_mr(block->mr);
648 rdma->total_registrations--;
649 block->mr = NULL;
650 }
651
652 g_free(block->transit_bitmap);
653 block->transit_bitmap = NULL;
654
655 g_free(block->unregister_bitmap);
656 block->unregister_bitmap = NULL;
657
658 g_free(block->remote_keys);
659 block->remote_keys = NULL;
660
661 for (x = 0; x < local->nb_blocks; x++) {
662 g_hash_table_remove(rdma->blockmap, (void *)old[x].offset);
663 }
664
665 if (local->nb_blocks > 1) {
666
667 local->block = g_malloc0(sizeof(RDMALocalBlock) *
668 (local->nb_blocks - 1));
669
670 if (block->index) {
671 memcpy(local->block, old, sizeof(RDMALocalBlock) * block->index);
672 }
673
674 if (block->index < (local->nb_blocks - 1)) {
675 memcpy(local->block + block->index, old + (block->index + 1),
676 sizeof(RDMALocalBlock) *
677 (local->nb_blocks - (block->index + 1)));
678 }
679 } else {
680 assert(block == local->block);
681 local->block = NULL;
682 }
683
684 DDPRINTF("Deleted Block: %d, addr: %" PRIu64 ", offset: %" PRIu64
685 " length: %" PRIu64 " end: %" PRIu64 " bits %" PRIu64 " chunks %d\n",
686 local->nb_blocks, (uint64_t) block->local_host_addr, block->offset,
687 block->length, (uint64_t) (block->local_host_addr + block->length),
688 BITS_TO_LONGS(block->nb_chunks) *
689 sizeof(unsigned long) * 8, block->nb_chunks);
690
691 g_free(old);
692
693 local->nb_blocks--;
694
695 if (local->nb_blocks) {
696 for (x = 0; x < local->nb_blocks; x++) {
697 g_hash_table_insert(rdma->blockmap, (void *)local->block[x].offset,
698 &local->block[x]);
699 }
700 }
701
702 return 0;
703}
704
705/*
706 * Put in the log file which RDMA device was opened and the details
707 * associated with that device.
708 */
709static void qemu_rdma_dump_id(const char *who, struct ibv_context *verbs)
710{
711 printf("%s RDMA Device opened: kernel name %s "
712 "uverbs device name %s, "
713 "infiniband_verbs class device path %s,"
714 " infiniband class device path %s\n",
715 who,
716 verbs->device->name,
717 verbs->device->dev_name,
718 verbs->device->dev_path,
719 verbs->device->ibdev_path);
720}
721
722/*
723 * Put in the log file the RDMA gid addressing information,
724 * useful for folks who have trouble understanding the
725 * RDMA device hierarchy in the kernel.
726 */
727static void qemu_rdma_dump_gid(const char *who, struct rdma_cm_id *id)
728{
729 char sgid[33];
730 char dgid[33];
731 inet_ntop(AF_INET6, &id->route.addr.addr.ibaddr.sgid, sgid, sizeof sgid);
732 inet_ntop(AF_INET6, &id->route.addr.addr.ibaddr.dgid, dgid, sizeof dgid);
733 DPRINTF("%s Source GID: %s, Dest GID: %s\n", who, sgid, dgid);
734}
735
736/*
737 * Figure out which RDMA device corresponds to the requested IP hostname
738 * Also create the initial connection manager identifiers for opening
739 * the connection.
740 */
741static int qemu_rdma_resolve_host(RDMAContext *rdma, Error **errp)
742{
743 int ret;
744 struct addrinfo *res;
745 char port_str[16];
746 struct rdma_cm_event *cm_event;
747 char ip[40] = "unknown";
b58c8552 748 int af = rdma->ipv6 ? PF_INET6 : PF_INET;
2da776db
MH
749
750 if (rdma->host == NULL || !strcmp(rdma->host, "")) {
66988941 751 ERROR(errp, "RDMA hostname has not been set");
2da776db
MH
752 return -1;
753 }
754
755 /* create CM channel */
756 rdma->channel = rdma_create_event_channel();
757 if (!rdma->channel) {
66988941 758 ERROR(errp, "could not create CM channel");
2da776db
MH
759 return -1;
760 }
761
762 /* create CM id */
763 ret = rdma_create_id(rdma->channel, &rdma->cm_id, NULL, RDMA_PS_TCP);
764 if (ret) {
66988941 765 ERROR(errp, "could not create channel id");
2da776db
MH
766 goto err_resolve_create_id;
767 }
768
769 snprintf(port_str, 16, "%d", rdma->port);
770 port_str[15] = '\0';
771
772 ret = getaddrinfo(rdma->host, port_str, NULL, &res);
773 if (ret < 0) {
66988941 774 ERROR(errp, "could not getaddrinfo address %s", rdma->host);
2da776db
MH
775 goto err_resolve_get_addr;
776 }
777
b58c8552 778 inet_ntop(af, &((struct sockaddr_in *) res->ai_addr)->sin_addr,
2da776db
MH
779 ip, sizeof ip);
780 DPRINTF("%s => %s\n", rdma->host, ip);
781
782 /* resolve the first address */
783 ret = rdma_resolve_addr(rdma->cm_id, NULL, res->ai_addr,
784 RDMA_RESOLVE_TIMEOUT_MS);
785 if (ret) {
66988941 786 ERROR(errp, "could not resolve address %s", rdma->host);
2da776db
MH
787 goto err_resolve_get_addr;
788 }
789
790 qemu_rdma_dump_gid("source_resolve_addr", rdma->cm_id);
791
792 ret = rdma_get_cm_event(rdma->channel, &cm_event);
793 if (ret) {
66988941 794 ERROR(errp, "could not perform event_addr_resolved");
2da776db
MH
795 goto err_resolve_get_addr;
796 }
797
798 if (cm_event->event != RDMA_CM_EVENT_ADDR_RESOLVED) {
66988941 799 ERROR(errp, "result not equal to event_addr_resolved %s",
2da776db
MH
800 rdma_event_str(cm_event->event));
801 perror("rdma_resolve_addr");
802 goto err_resolve_get_addr;
803 }
804 rdma_ack_cm_event(cm_event);
805
806 /* resolve route */
807 ret = rdma_resolve_route(rdma->cm_id, RDMA_RESOLVE_TIMEOUT_MS);
808 if (ret) {
66988941 809 ERROR(errp, "could not resolve rdma route");
2da776db
MH
810 goto err_resolve_get_addr;
811 }
812
813 ret = rdma_get_cm_event(rdma->channel, &cm_event);
814 if (ret) {
66988941 815 ERROR(errp, "could not perform event_route_resolved");
2da776db
MH
816 goto err_resolve_get_addr;
817 }
818 if (cm_event->event != RDMA_CM_EVENT_ROUTE_RESOLVED) {
66988941 819 ERROR(errp, "result not equal to event_route_resolved: %s",
2da776db
MH
820 rdma_event_str(cm_event->event));
821 rdma_ack_cm_event(cm_event);
822 goto err_resolve_get_addr;
823 }
824 rdma_ack_cm_event(cm_event);
825 rdma->verbs = rdma->cm_id->verbs;
826 qemu_rdma_dump_id("source_resolve_host", rdma->cm_id->verbs);
827 qemu_rdma_dump_gid("source_resolve_host", rdma->cm_id);
828 return 0;
829
830err_resolve_get_addr:
831 rdma_destroy_id(rdma->cm_id);
832 rdma->cm_id = NULL;
833err_resolve_create_id:
834 rdma_destroy_event_channel(rdma->channel);
835 rdma->channel = NULL;
836
837 return -1;
838}
839
840/*
841 * Create protection domain and completion queues
842 */
843static int qemu_rdma_alloc_pd_cq(RDMAContext *rdma)
844{
845 /* allocate pd */
846 rdma->pd = ibv_alloc_pd(rdma->verbs);
847 if (!rdma->pd) {
848 fprintf(stderr, "failed to allocate protection domain\n");
849 return -1;
850 }
851
852 /* create completion channel */
853 rdma->comp_channel = ibv_create_comp_channel(rdma->verbs);
854 if (!rdma->comp_channel) {
855 fprintf(stderr, "failed to allocate completion channel\n");
856 goto err_alloc_pd_cq;
857 }
858
859 /*
860 * Completion queue can be filled by both read and write work requests,
861 * so must reflect the sum of both possible queue sizes.
862 */
863 rdma->cq = ibv_create_cq(rdma->verbs, (RDMA_SIGNALED_SEND_MAX * 3),
864 NULL, rdma->comp_channel, 0);
865 if (!rdma->cq) {
866 fprintf(stderr, "failed to allocate completion queue\n");
867 goto err_alloc_pd_cq;
868 }
869
870 return 0;
871
872err_alloc_pd_cq:
873 if (rdma->pd) {
874 ibv_dealloc_pd(rdma->pd);
875 }
876 if (rdma->comp_channel) {
877 ibv_destroy_comp_channel(rdma->comp_channel);
878 }
879 rdma->pd = NULL;
880 rdma->comp_channel = NULL;
881 return -1;
882
883}
884
885/*
886 * Create queue pairs.
887 */
888static int qemu_rdma_alloc_qp(RDMAContext *rdma)
889{
890 struct ibv_qp_init_attr attr = { 0 };
891 int ret;
892
893 attr.cap.max_send_wr = RDMA_SIGNALED_SEND_MAX;
894 attr.cap.max_recv_wr = 3;
895 attr.cap.max_send_sge = 1;
896 attr.cap.max_recv_sge = 1;
897 attr.send_cq = rdma->cq;
898 attr.recv_cq = rdma->cq;
899 attr.qp_type = IBV_QPT_RC;
900
901 ret = rdma_create_qp(rdma->cm_id, rdma->pd, &attr);
902 if (ret) {
903 return -1;
904 }
905
906 rdma->qp = rdma->cm_id->qp;
907 return 0;
908}
909
910static int qemu_rdma_reg_whole_ram_blocks(RDMAContext *rdma)
911{
912 int i;
913 RDMALocalBlocks *local = &rdma->local_ram_blocks;
914
915 for (i = 0; i < local->nb_blocks; i++) {
916 local->block[i].mr =
917 ibv_reg_mr(rdma->pd,
918 local->block[i].local_host_addr,
919 local->block[i].length,
920 IBV_ACCESS_LOCAL_WRITE |
921 IBV_ACCESS_REMOTE_WRITE
922 );
923 if (!local->block[i].mr) {
924 perror("Failed to register local dest ram block!\n");
925 break;
926 }
927 rdma->total_registrations++;
928 }
929
930 if (i >= local->nb_blocks) {
931 return 0;
932 }
933
934 for (i--; i >= 0; i--) {
935 ibv_dereg_mr(local->block[i].mr);
936 rdma->total_registrations--;
937 }
938
939 return -1;
940
941}
942
943/*
944 * Find the ram block that corresponds to the page requested to be
945 * transmitted by QEMU.
946 *
947 * Once the block is found, also identify which 'chunk' within that
948 * block that the page belongs to.
949 *
950 * This search cannot fail or the migration will fail.
951 */
952static int qemu_rdma_search_ram_block(RDMAContext *rdma,
953 uint64_t block_offset,
954 uint64_t offset,
955 uint64_t length,
956 uint64_t *block_index,
957 uint64_t *chunk_index)
958{
959 uint64_t current_addr = block_offset + offset;
960 RDMALocalBlock *block = g_hash_table_lookup(rdma->blockmap,
961 (void *) block_offset);
962 assert(block);
963 assert(current_addr >= block->offset);
964 assert((current_addr + length) <= (block->offset + block->length));
965
966 *block_index = block->index;
967 *chunk_index = ram_chunk_index(block->local_host_addr,
968 block->local_host_addr + (current_addr - block->offset));
969
970 return 0;
971}
972
973/*
974 * Register a chunk with IB. If the chunk was already registered
975 * previously, then skip.
976 *
977 * Also return the keys associated with the registration needed
978 * to perform the actual RDMA operation.
979 */
980static int qemu_rdma_register_and_get_keys(RDMAContext *rdma,
981 RDMALocalBlock *block, uint8_t *host_addr,
982 uint32_t *lkey, uint32_t *rkey, int chunk,
983 uint8_t *chunk_start, uint8_t *chunk_end)
984{
985 if (block->mr) {
986 if (lkey) {
987 *lkey = block->mr->lkey;
988 }
989 if (rkey) {
990 *rkey = block->mr->rkey;
991 }
992 return 0;
993 }
994
995 /* allocate memory to store chunk MRs */
996 if (!block->pmr) {
997 block->pmr = g_malloc0(block->nb_chunks * sizeof(struct ibv_mr *));
998 if (!block->pmr) {
999 return -1;
1000 }
1001 }
1002
1003 /*
1004 * If 'rkey', then we're the destination, so grant access to the source.
1005 *
1006 * If 'lkey', then we're the source VM, so grant access only to ourselves.
1007 */
1008 if (!block->pmr[chunk]) {
1009 uint64_t len = chunk_end - chunk_start;
1010
1011 DDPRINTF("Registering %" PRIu64 " bytes @ %p\n",
1012 len, chunk_start);
1013
1014 block->pmr[chunk] = ibv_reg_mr(rdma->pd,
1015 chunk_start, len,
1016 (rkey ? (IBV_ACCESS_LOCAL_WRITE |
1017 IBV_ACCESS_REMOTE_WRITE) : 0));
1018
1019 if (!block->pmr[chunk]) {
1020 perror("Failed to register chunk!");
1021 fprintf(stderr, "Chunk details: block: %d chunk index %d"
1022 " start %" PRIu64 " end %" PRIu64 " host %" PRIu64
1023 " local %" PRIu64 " registrations: %d\n",
1024 block->index, chunk, (uint64_t) chunk_start,
1025 (uint64_t) chunk_end, (uint64_t) host_addr,
1026 (uint64_t) block->local_host_addr,
1027 rdma->total_registrations);
1028 return -1;
1029 }
1030 rdma->total_registrations++;
1031 }
1032
1033 if (lkey) {
1034 *lkey = block->pmr[chunk]->lkey;
1035 }
1036 if (rkey) {
1037 *rkey = block->pmr[chunk]->rkey;
1038 }
1039 return 0;
1040}
1041
1042/*
1043 * Register (at connection time) the memory used for control
1044 * channel messages.
1045 */
1046static int qemu_rdma_reg_control(RDMAContext *rdma, int idx)
1047{
1048 rdma->wr_data[idx].control_mr = ibv_reg_mr(rdma->pd,
1049 rdma->wr_data[idx].control, RDMA_CONTROL_MAX_BUFFER,
1050 IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE);
1051 if (rdma->wr_data[idx].control_mr) {
1052 rdma->total_registrations++;
1053 return 0;
1054 }
1055 fprintf(stderr, "qemu_rdma_reg_control failed!\n");
1056 return -1;
1057}
1058
1059const char *print_wrid(int wrid)
1060{
1061 if (wrid >= RDMA_WRID_RECV_CONTROL) {
1062 return wrid_desc[RDMA_WRID_RECV_CONTROL];
1063 }
1064 return wrid_desc[wrid];
1065}
1066
1067/*
1068 * RDMA requires memory registration (mlock/pinning), but this is not good for
1069 * overcommitment.
1070 *
1071 * In preparation for the future where LRU information or workload-specific
1072 * writable writable working set memory access behavior is available to QEMU
1073 * it would be nice to have in place the ability to UN-register/UN-pin
1074 * particular memory regions from the RDMA hardware when it is determine that
1075 * those regions of memory will likely not be accessed again in the near future.
1076 *
1077 * While we do not yet have such information right now, the following
1078 * compile-time option allows us to perform a non-optimized version of this
1079 * behavior.
1080 *
1081 * By uncommenting this option, you will cause *all* RDMA transfers to be
1082 * unregistered immediately after the transfer completes on both sides of the
1083 * connection. This has no effect in 'rdma-pin-all' mode, only regular mode.
1084 *
1085 * This will have a terrible impact on migration performance, so until future
1086 * workload information or LRU information is available, do not attempt to use
1087 * this feature except for basic testing.
1088 */
1089//#define RDMA_UNREGISTRATION_EXAMPLE
1090
1091/*
1092 * Perform a non-optimized memory unregistration after every transfer
1093 * for demonsration purposes, only if pin-all is not requested.
1094 *
1095 * Potential optimizations:
1096 * 1. Start a new thread to run this function continuously
1097 - for bit clearing
1098 - and for receipt of unregister messages
1099 * 2. Use an LRU.
1100 * 3. Use workload hints.
1101 */
1102static int qemu_rdma_unregister_waiting(RDMAContext *rdma)
1103{
1104 while (rdma->unregistrations[rdma->unregister_current]) {
1105 int ret;
1106 uint64_t wr_id = rdma->unregistrations[rdma->unregister_current];
1107 uint64_t chunk =
1108 (wr_id & RDMA_WRID_CHUNK_MASK) >> RDMA_WRID_CHUNK_SHIFT;
1109 uint64_t index =
1110 (wr_id & RDMA_WRID_BLOCK_MASK) >> RDMA_WRID_BLOCK_SHIFT;
1111 RDMALocalBlock *block =
1112 &(rdma->local_ram_blocks.block[index]);
1113 RDMARegister reg = { .current_index = index };
1114 RDMAControlHeader resp = { .type = RDMA_CONTROL_UNREGISTER_FINISHED,
1115 };
1116 RDMAControlHeader head = { .len = sizeof(RDMARegister),
1117 .type = RDMA_CONTROL_UNREGISTER_REQUEST,
1118 .repeat = 1,
1119 };
1120
1121 DDPRINTF("Processing unregister for chunk: %" PRIu64
1122 " at position %d\n", chunk, rdma->unregister_current);
1123
1124 rdma->unregistrations[rdma->unregister_current] = 0;
1125 rdma->unregister_current++;
1126
1127 if (rdma->unregister_current == RDMA_SIGNALED_SEND_MAX) {
1128 rdma->unregister_current = 0;
1129 }
1130
1131
1132 /*
1133 * Unregistration is speculative (because migration is single-threaded
1134 * and we cannot break the protocol's inifinband message ordering).
1135 * Thus, if the memory is currently being used for transmission,
1136 * then abort the attempt to unregister and try again
1137 * later the next time a completion is received for this memory.
1138 */
1139 clear_bit(chunk, block->unregister_bitmap);
1140
1141 if (test_bit(chunk, block->transit_bitmap)) {
1142 DDPRINTF("Cannot unregister inflight chunk: %" PRIu64 "\n", chunk);
1143 continue;
1144 }
1145
1146 DDPRINTF("Sending unregister for chunk: %" PRIu64 "\n", chunk);
1147
1148 ret = ibv_dereg_mr(block->pmr[chunk]);
1149 block->pmr[chunk] = NULL;
1150 block->remote_keys[chunk] = 0;
1151
1152 if (ret != 0) {
1153 perror("unregistration chunk failed");
1154 return -ret;
1155 }
1156 rdma->total_registrations--;
1157
1158 reg.key.chunk = chunk;
1159 register_to_network(&reg);
1160 ret = qemu_rdma_exchange_send(rdma, &head, (uint8_t *) &reg,
1161 &resp, NULL, NULL);
1162 if (ret < 0) {
1163 return ret;
1164 }
1165
1166 DDPRINTF("Unregister for chunk: %" PRIu64 " complete.\n", chunk);
1167 }
1168
1169 return 0;
1170}
1171
1172static uint64_t qemu_rdma_make_wrid(uint64_t wr_id, uint64_t index,
1173 uint64_t chunk)
1174{
1175 uint64_t result = wr_id & RDMA_WRID_TYPE_MASK;
1176
1177 result |= (index << RDMA_WRID_BLOCK_SHIFT);
1178 result |= (chunk << RDMA_WRID_CHUNK_SHIFT);
1179
1180 return result;
1181}
1182
1183/*
1184 * Set bit for unregistration in the next iteration.
1185 * We cannot transmit right here, but will unpin later.
1186 */
1187static void qemu_rdma_signal_unregister(RDMAContext *rdma, uint64_t index,
1188 uint64_t chunk, uint64_t wr_id)
1189{
1190 if (rdma->unregistrations[rdma->unregister_next] != 0) {
1191 fprintf(stderr, "rdma migration: queue is full!\n");
1192 } else {
1193 RDMALocalBlock *block = &(rdma->local_ram_blocks.block[index]);
1194
1195 if (!test_and_set_bit(chunk, block->unregister_bitmap)) {
1196 DDPRINTF("Appending unregister chunk %" PRIu64
1197 " at position %d\n", chunk, rdma->unregister_next);
1198
1199 rdma->unregistrations[rdma->unregister_next++] =
1200 qemu_rdma_make_wrid(wr_id, index, chunk);
1201
1202 if (rdma->unregister_next == RDMA_SIGNALED_SEND_MAX) {
1203 rdma->unregister_next = 0;
1204 }
1205 } else {
1206 DDPRINTF("Unregister chunk %" PRIu64 " already in queue.\n",
1207 chunk);
1208 }
1209 }
1210}
1211
1212/*
1213 * Consult the connection manager to see a work request
1214 * (of any kind) has completed.
1215 * Return the work request ID that completed.
1216 */
1217static uint64_t qemu_rdma_poll(RDMAContext *rdma, uint64_t *wr_id_out)
1218{
1219 int ret;
1220 struct ibv_wc wc;
1221 uint64_t wr_id;
1222
1223 ret = ibv_poll_cq(rdma->cq, 1, &wc);
1224
1225 if (!ret) {
1226 *wr_id_out = RDMA_WRID_NONE;
1227 return 0;
1228 }
1229
1230 if (ret < 0) {
1231 fprintf(stderr, "ibv_poll_cq return %d!\n", ret);
1232 return ret;
1233 }
1234
1235 wr_id = wc.wr_id & RDMA_WRID_TYPE_MASK;
1236
1237 if (wc.status != IBV_WC_SUCCESS) {
1238 fprintf(stderr, "ibv_poll_cq wc.status=%d %s!\n",
1239 wc.status, ibv_wc_status_str(wc.status));
1240 fprintf(stderr, "ibv_poll_cq wrid=%s!\n", wrid_desc[wr_id]);
1241
1242 return -1;
1243 }
1244
1245 if (rdma->control_ready_expected &&
1246 (wr_id >= RDMA_WRID_RECV_CONTROL)) {
1247 DDDPRINTF("completion %s #%" PRId64 " received (%" PRId64 ")"
1248 " left %d\n", wrid_desc[RDMA_WRID_RECV_CONTROL],
1249 wr_id - RDMA_WRID_RECV_CONTROL, wr_id, rdma->nb_sent);
1250 rdma->control_ready_expected = 0;
1251 }
1252
1253 if (wr_id == RDMA_WRID_RDMA_WRITE) {
1254 uint64_t chunk =
1255 (wc.wr_id & RDMA_WRID_CHUNK_MASK) >> RDMA_WRID_CHUNK_SHIFT;
1256 uint64_t index =
1257 (wc.wr_id & RDMA_WRID_BLOCK_MASK) >> RDMA_WRID_BLOCK_SHIFT;
1258 RDMALocalBlock *block = &(rdma->local_ram_blocks.block[index]);
1259
1260 DDDPRINTF("completions %s (%" PRId64 ") left %d, "
1261 "block %" PRIu64 ", chunk: %" PRIu64 " %p %p\n",
1262 print_wrid(wr_id), wr_id, rdma->nb_sent, index, chunk,
1263 block->local_host_addr, (void *)block->remote_host_addr);
1264
1265 clear_bit(chunk, block->transit_bitmap);
1266
1267 if (rdma->nb_sent > 0) {
1268 rdma->nb_sent--;
1269 }
1270
1271 if (!rdma->pin_all) {
1272 /*
1273 * FYI: If one wanted to signal a specific chunk to be unregistered
1274 * using LRU or workload-specific information, this is the function
1275 * you would call to do so. That chunk would then get asynchronously
1276 * unregistered later.
1277 */
1278#ifdef RDMA_UNREGISTRATION_EXAMPLE
1279 qemu_rdma_signal_unregister(rdma, index, chunk, wc.wr_id);
1280#endif
1281 }
1282 } else {
1283 DDDPRINTF("other completion %s (%" PRId64 ") received left %d\n",
1284 print_wrid(wr_id), wr_id, rdma->nb_sent);
1285 }
1286
1287 *wr_id_out = wc.wr_id;
1288
1289 return 0;
1290}
1291
1292/*
1293 * Block until the next work request has completed.
1294 *
1295 * First poll to see if a work request has already completed,
1296 * otherwise block.
1297 *
1298 * If we encounter completed work requests for IDs other than
1299 * the one we're interested in, then that's generally an error.
1300 *
1301 * The only exception is actual RDMA Write completions. These
1302 * completions only need to be recorded, but do not actually
1303 * need further processing.
1304 */
1305static int qemu_rdma_block_for_wrid(RDMAContext *rdma, int wrid_requested)
1306{
1307 int num_cq_events = 0, ret = 0;
1308 struct ibv_cq *cq;
1309 void *cq_ctx;
1310 uint64_t wr_id = RDMA_WRID_NONE, wr_id_in;
1311
1312 if (ibv_req_notify_cq(rdma->cq, 0)) {
1313 return -1;
1314 }
1315 /* poll cq first */
1316 while (wr_id != wrid_requested) {
1317 ret = qemu_rdma_poll(rdma, &wr_id_in);
1318 if (ret < 0) {
1319 return ret;
1320 }
1321
1322 wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
1323
1324 if (wr_id == RDMA_WRID_NONE) {
1325 break;
1326 }
1327 if (wr_id != wrid_requested) {
1328 DDDPRINTF("A Wanted wrid %s (%d) but got %s (%" PRIu64 ")\n",
1329 print_wrid(wrid_requested),
1330 wrid_requested, print_wrid(wr_id), wr_id);
1331 }
1332 }
1333
1334 if (wr_id == wrid_requested) {
1335 return 0;
1336 }
1337
1338 while (1) {
1339 /*
1340 * Coroutine doesn't start until process_incoming_migration()
1341 * so don't yield unless we know we're running inside of a coroutine.
1342 */
1343 if (rdma->migration_started_on_destination) {
1344 yield_until_fd_readable(rdma->comp_channel->fd);
1345 }
1346
1347 if (ibv_get_cq_event(rdma->comp_channel, &cq, &cq_ctx)) {
1348 perror("ibv_get_cq_event");
1349 goto err_block_for_wrid;
1350 }
1351
1352 num_cq_events++;
1353
1354 if (ibv_req_notify_cq(cq, 0)) {
1355 goto err_block_for_wrid;
1356 }
1357
1358 while (wr_id != wrid_requested) {
1359 ret = qemu_rdma_poll(rdma, &wr_id_in);
1360 if (ret < 0) {
1361 goto err_block_for_wrid;
1362 }
1363
1364 wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
1365
1366 if (wr_id == RDMA_WRID_NONE) {
1367 break;
1368 }
1369 if (wr_id != wrid_requested) {
1370 DDDPRINTF("B Wanted wrid %s (%d) but got %s (%" PRIu64 ")\n",
1371 print_wrid(wrid_requested), wrid_requested,
1372 print_wrid(wr_id), wr_id);
1373 }
1374 }
1375
1376 if (wr_id == wrid_requested) {
1377 goto success_block_for_wrid;
1378 }
1379 }
1380
1381success_block_for_wrid:
1382 if (num_cq_events) {
1383 ibv_ack_cq_events(cq, num_cq_events);
1384 }
1385 return 0;
1386
1387err_block_for_wrid:
1388 if (num_cq_events) {
1389 ibv_ack_cq_events(cq, num_cq_events);
1390 }
1391 return ret;
1392}
1393
1394/*
1395 * Post a SEND message work request for the control channel
1396 * containing some data and block until the post completes.
1397 */
1398static int qemu_rdma_post_send_control(RDMAContext *rdma, uint8_t *buf,
1399 RDMAControlHeader *head)
1400{
1401 int ret = 0;
1f22364b 1402 RDMAWorkRequestData *wr = &rdma->wr_data[RDMA_WRID_CONTROL];
2da776db
MH
1403 struct ibv_send_wr *bad_wr;
1404 struct ibv_sge sge = {
1405 .addr = (uint64_t)(wr->control),
1406 .length = head->len + sizeof(RDMAControlHeader),
1407 .lkey = wr->control_mr->lkey,
1408 };
1409 struct ibv_send_wr send_wr = {
1410 .wr_id = RDMA_WRID_SEND_CONTROL,
1411 .opcode = IBV_WR_SEND,
1412 .send_flags = IBV_SEND_SIGNALED,
1413 .sg_list = &sge,
1414 .num_sge = 1,
1415 };
1416
1417 DDDPRINTF("CONTROL: sending %s..\n", control_desc[head->type]);
1418
1419 /*
1420 * We don't actually need to do a memcpy() in here if we used
1421 * the "sge" properly, but since we're only sending control messages
1422 * (not RAM in a performance-critical path), then its OK for now.
1423 *
1424 * The copy makes the RDMAControlHeader simpler to manipulate
1425 * for the time being.
1426 */
6f1484ed 1427 assert(head->len <= RDMA_CONTROL_MAX_BUFFER - sizeof(*head));
2da776db
MH
1428 memcpy(wr->control, head, sizeof(RDMAControlHeader));
1429 control_to_network((void *) wr->control);
1430
1431 if (buf) {
1432 memcpy(wr->control + sizeof(RDMAControlHeader), buf, head->len);
1433 }
1434
1435
1436 if (ibv_post_send(rdma->qp, &send_wr, &bad_wr)) {
1437 return -1;
1438 }
1439
1440 if (ret < 0) {
1441 fprintf(stderr, "Failed to use post IB SEND for control!\n");
1442 return ret;
1443 }
1444
1445 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_SEND_CONTROL);
1446 if (ret < 0) {
1447 fprintf(stderr, "rdma migration: send polling control error!\n");
1448 }
1449
1450 return ret;
1451}
1452
1453/*
1454 * Post a RECV work request in anticipation of some future receipt
1455 * of data on the control channel.
1456 */
1457static int qemu_rdma_post_recv_control(RDMAContext *rdma, int idx)
1458{
1459 struct ibv_recv_wr *bad_wr;
1460 struct ibv_sge sge = {
1461 .addr = (uint64_t)(rdma->wr_data[idx].control),
1462 .length = RDMA_CONTROL_MAX_BUFFER,
1463 .lkey = rdma->wr_data[idx].control_mr->lkey,
1464 };
1465
1466 struct ibv_recv_wr recv_wr = {
1467 .wr_id = RDMA_WRID_RECV_CONTROL + idx,
1468 .sg_list = &sge,
1469 .num_sge = 1,
1470 };
1471
1472
1473 if (ibv_post_recv(rdma->qp, &recv_wr, &bad_wr)) {
1474 return -1;
1475 }
1476
1477 return 0;
1478}
1479
1480/*
1481 * Block and wait for a RECV control channel message to arrive.
1482 */
1483static int qemu_rdma_exchange_get_response(RDMAContext *rdma,
1484 RDMAControlHeader *head, int expecting, int idx)
1485{
1486 int ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RECV_CONTROL + idx);
1487
1488 if (ret < 0) {
1489 fprintf(stderr, "rdma migration: recv polling control error!\n");
1490 return ret;
1491 }
1492
1493 network_to_control((void *) rdma->wr_data[idx].control);
1494 memcpy(head, rdma->wr_data[idx].control, sizeof(RDMAControlHeader));
1495
1496 DDDPRINTF("CONTROL: %s receiving...\n", control_desc[expecting]);
1497
1498 if (expecting == RDMA_CONTROL_NONE) {
1499 DDDPRINTF("Surprise: got %s (%d)\n",
1500 control_desc[head->type], head->type);
1501 } else if (head->type != expecting || head->type == RDMA_CONTROL_ERROR) {
1502 fprintf(stderr, "Was expecting a %s (%d) control message"
1503 ", but got: %s (%d), length: %d\n",
1504 control_desc[expecting], expecting,
1505 control_desc[head->type], head->type, head->len);
1506 return -EIO;
1507 }
6f1484ed
IY
1508 if (head->len > RDMA_CONTROL_MAX_BUFFER - sizeof(*head)) {
1509 fprintf(stderr, "too long length: %d\n", head->len);
1510 return -EINVAL;
1511 }
2da776db
MH
1512
1513 return 0;
1514}
1515
1516/*
1517 * When a RECV work request has completed, the work request's
1518 * buffer is pointed at the header.
1519 *
1520 * This will advance the pointer to the data portion
1521 * of the control message of the work request's buffer that
1522 * was populated after the work request finished.
1523 */
1524static void qemu_rdma_move_header(RDMAContext *rdma, int idx,
1525 RDMAControlHeader *head)
1526{
1527 rdma->wr_data[idx].control_len = head->len;
1528 rdma->wr_data[idx].control_curr =
1529 rdma->wr_data[idx].control + sizeof(RDMAControlHeader);
1530}
1531
1532/*
1533 * This is an 'atomic' high-level operation to deliver a single, unified
1534 * control-channel message.
1535 *
1536 * Additionally, if the user is expecting some kind of reply to this message,
1537 * they can request a 'resp' response message be filled in by posting an
1538 * additional work request on behalf of the user and waiting for an additional
1539 * completion.
1540 *
1541 * The extra (optional) response is used during registration to us from having
1542 * to perform an *additional* exchange of message just to provide a response by
1543 * instead piggy-backing on the acknowledgement.
1544 */
1545static int qemu_rdma_exchange_send(RDMAContext *rdma, RDMAControlHeader *head,
1546 uint8_t *data, RDMAControlHeader *resp,
1547 int *resp_idx,
1548 int (*callback)(RDMAContext *rdma))
1549{
1550 int ret = 0;
1551
1552 /*
1553 * Wait until the dest is ready before attempting to deliver the message
1554 * by waiting for a READY message.
1555 */
1556 if (rdma->control_ready_expected) {
1557 RDMAControlHeader resp;
1558 ret = qemu_rdma_exchange_get_response(rdma,
1559 &resp, RDMA_CONTROL_READY, RDMA_WRID_READY);
1560 if (ret < 0) {
1561 return ret;
1562 }
1563 }
1564
1565 /*
1566 * If the user is expecting a response, post a WR in anticipation of it.
1567 */
1568 if (resp) {
1569 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_DATA);
1570 if (ret) {
1571 fprintf(stderr, "rdma migration: error posting"
1572 " extra control recv for anticipated result!");
1573 return ret;
1574 }
1575 }
1576
1577 /*
1578 * Post a WR to replace the one we just consumed for the READY message.
1579 */
1580 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
1581 if (ret) {
1582 fprintf(stderr, "rdma migration: error posting first control recv!");
1583 return ret;
1584 }
1585
1586 /*
1587 * Deliver the control message that was requested.
1588 */
1589 ret = qemu_rdma_post_send_control(rdma, data, head);
1590
1591 if (ret < 0) {
1592 fprintf(stderr, "Failed to send control buffer!\n");
1593 return ret;
1594 }
1595
1596 /*
1597 * If we're expecting a response, block and wait for it.
1598 */
1599 if (resp) {
1600 if (callback) {
1601 DDPRINTF("Issuing callback before receiving response...\n");
1602 ret = callback(rdma);
1603 if (ret < 0) {
1604 return ret;
1605 }
1606 }
1607
1608 DDPRINTF("Waiting for response %s\n", control_desc[resp->type]);
1609 ret = qemu_rdma_exchange_get_response(rdma, resp,
1610 resp->type, RDMA_WRID_DATA);
1611
1612 if (ret < 0) {
1613 return ret;
1614 }
1615
1616 qemu_rdma_move_header(rdma, RDMA_WRID_DATA, resp);
1617 if (resp_idx) {
1618 *resp_idx = RDMA_WRID_DATA;
1619 }
1620 DDPRINTF("Response %s received.\n", control_desc[resp->type]);
1621 }
1622
1623 rdma->control_ready_expected = 1;
1624
1625 return 0;
1626}
1627
1628/*
1629 * This is an 'atomic' high-level operation to receive a single, unified
1630 * control-channel message.
1631 */
1632static int qemu_rdma_exchange_recv(RDMAContext *rdma, RDMAControlHeader *head,
1633 int expecting)
1634{
1635 RDMAControlHeader ready = {
1636 .len = 0,
1637 .type = RDMA_CONTROL_READY,
1638 .repeat = 1,
1639 };
1640 int ret;
1641
1642 /*
1643 * Inform the source that we're ready to receive a message.
1644 */
1645 ret = qemu_rdma_post_send_control(rdma, NULL, &ready);
1646
1647 if (ret < 0) {
1648 fprintf(stderr, "Failed to send control buffer!\n");
1649 return ret;
1650 }
1651
1652 /*
1653 * Block and wait for the message.
1654 */
1655 ret = qemu_rdma_exchange_get_response(rdma, head,
1656 expecting, RDMA_WRID_READY);
1657
1658 if (ret < 0) {
1659 return ret;
1660 }
1661
1662 qemu_rdma_move_header(rdma, RDMA_WRID_READY, head);
1663
1664 /*
1665 * Post a new RECV work request to replace the one we just consumed.
1666 */
1667 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
1668 if (ret) {
1669 fprintf(stderr, "rdma migration: error posting second control recv!");
1670 return ret;
1671 }
1672
1673 return 0;
1674}
1675
1676/*
1677 * Write an actual chunk of memory using RDMA.
1678 *
1679 * If we're using dynamic registration on the dest-side, we have to
1680 * send a registration command first.
1681 */
1682static int qemu_rdma_write_one(QEMUFile *f, RDMAContext *rdma,
1683 int current_index, uint64_t current_addr,
1684 uint64_t length)
1685{
1686 struct ibv_sge sge;
1687 struct ibv_send_wr send_wr = { 0 };
1688 struct ibv_send_wr *bad_wr;
1689 int reg_result_idx, ret, count = 0;
1690 uint64_t chunk, chunks;
1691 uint8_t *chunk_start, *chunk_end;
1692 RDMALocalBlock *block = &(rdma->local_ram_blocks.block[current_index]);
1693 RDMARegister reg;
1694 RDMARegisterResult *reg_result;
1695 RDMAControlHeader resp = { .type = RDMA_CONTROL_REGISTER_RESULT };
1696 RDMAControlHeader head = { .len = sizeof(RDMARegister),
1697 .type = RDMA_CONTROL_REGISTER_REQUEST,
1698 .repeat = 1,
1699 };
1700
1701retry:
1702 sge.addr = (uint64_t)(block->local_host_addr +
1703 (current_addr - block->offset));
1704 sge.length = length;
1705
1706 chunk = ram_chunk_index(block->local_host_addr, (uint8_t *) sge.addr);
1707 chunk_start = ram_chunk_start(block, chunk);
1708
1709 if (block->is_ram_block) {
1710 chunks = length / (1UL << RDMA_REG_CHUNK_SHIFT);
1711
1712 if (chunks && ((length % (1UL << RDMA_REG_CHUNK_SHIFT)) == 0)) {
1713 chunks--;
1714 }
1715 } else {
1716 chunks = block->length / (1UL << RDMA_REG_CHUNK_SHIFT);
1717
1718 if (chunks && ((block->length % (1UL << RDMA_REG_CHUNK_SHIFT)) == 0)) {
1719 chunks--;
1720 }
1721 }
1722
1723 DDPRINTF("Writing %" PRIu64 " chunks, (%" PRIu64 " MB)\n",
1724 chunks + 1, (chunks + 1) * (1UL << RDMA_REG_CHUNK_SHIFT) / 1024 / 1024);
1725
1726 chunk_end = ram_chunk_end(block, chunk + chunks);
1727
1728 if (!rdma->pin_all) {
1729#ifdef RDMA_UNREGISTRATION_EXAMPLE
1730 qemu_rdma_unregister_waiting(rdma);
1731#endif
1732 }
1733
1734 while (test_bit(chunk, block->transit_bitmap)) {
1735 (void)count;
1736 DDPRINTF("(%d) Not clobbering: block: %d chunk %" PRIu64
1737 " current %" PRIu64 " len %" PRIu64 " %d %d\n",
1738 count++, current_index, chunk,
1739 sge.addr, length, rdma->nb_sent, block->nb_chunks);
1740
1741 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE);
1742
1743 if (ret < 0) {
1744 fprintf(stderr, "Failed to Wait for previous write to complete "
1745 "block %d chunk %" PRIu64
1746 " current %" PRIu64 " len %" PRIu64 " %d\n",
1747 current_index, chunk, sge.addr, length, rdma->nb_sent);
1748 return ret;
1749 }
1750 }
1751
1752 if (!rdma->pin_all || !block->is_ram_block) {
1753 if (!block->remote_keys[chunk]) {
1754 /*
1755 * This chunk has not yet been registered, so first check to see
1756 * if the entire chunk is zero. If so, tell the other size to
1757 * memset() + madvise() the entire chunk without RDMA.
1758 */
1759
1760 if (can_use_buffer_find_nonzero_offset((void *)sge.addr, length)
1761 && buffer_find_nonzero_offset((void *)sge.addr,
1762 length) == length) {
1763 RDMACompress comp = {
1764 .offset = current_addr,
1765 .value = 0,
1766 .block_idx = current_index,
1767 .length = length,
1768 };
1769
1770 head.len = sizeof(comp);
1771 head.type = RDMA_CONTROL_COMPRESS;
1772
1773 DDPRINTF("Entire chunk is zero, sending compress: %"
1774 PRIu64 " for %d "
1775 "bytes, index: %d, offset: %" PRId64 "...\n",
1776 chunk, sge.length, current_index, current_addr);
1777
1778 compress_to_network(&comp);
1779 ret = qemu_rdma_exchange_send(rdma, &head,
1780 (uint8_t *) &comp, NULL, NULL, NULL);
1781
1782 if (ret < 0) {
1783 return -EIO;
1784 }
1785
1786 acct_update_position(f, sge.length, true);
1787
1788 return 1;
1789 }
1790
1791 /*
1792 * Otherwise, tell other side to register.
1793 */
1794 reg.current_index = current_index;
1795 if (block->is_ram_block) {
1796 reg.key.current_addr = current_addr;
1797 } else {
1798 reg.key.chunk = chunk;
1799 }
1800 reg.chunks = chunks;
1801
1802 DDPRINTF("Sending registration request chunk %" PRIu64 " for %d "
1803 "bytes, index: %d, offset: %" PRId64 "...\n",
1804 chunk, sge.length, current_index, current_addr);
1805
1806 register_to_network(&reg);
1807 ret = qemu_rdma_exchange_send(rdma, &head, (uint8_t *) &reg,
1808 &resp, &reg_result_idx, NULL);
1809 if (ret < 0) {
1810 return ret;
1811 }
1812
1813 /* try to overlap this single registration with the one we sent. */
1814 if (qemu_rdma_register_and_get_keys(rdma, block,
1815 (uint8_t *) sge.addr,
1816 &sge.lkey, NULL, chunk,
1817 chunk_start, chunk_end)) {
1818 fprintf(stderr, "cannot get lkey!\n");
1819 return -EINVAL;
1820 }
1821
1822 reg_result = (RDMARegisterResult *)
1823 rdma->wr_data[reg_result_idx].control_curr;
1824
1825 network_to_result(reg_result);
1826
1827 DDPRINTF("Received registration result:"
1828 " my key: %x their key %x, chunk %" PRIu64 "\n",
1829 block->remote_keys[chunk], reg_result->rkey, chunk);
1830
1831 block->remote_keys[chunk] = reg_result->rkey;
1832 block->remote_host_addr = reg_result->host_addr;
1833 } else {
1834 /* already registered before */
1835 if (qemu_rdma_register_and_get_keys(rdma, block,
1836 (uint8_t *)sge.addr,
1837 &sge.lkey, NULL, chunk,
1838 chunk_start, chunk_end)) {
1839 fprintf(stderr, "cannot get lkey!\n");
1840 return -EINVAL;
1841 }
1842 }
1843
1844 send_wr.wr.rdma.rkey = block->remote_keys[chunk];
1845 } else {
1846 send_wr.wr.rdma.rkey = block->remote_rkey;
1847
1848 if (qemu_rdma_register_and_get_keys(rdma, block, (uint8_t *)sge.addr,
1849 &sge.lkey, NULL, chunk,
1850 chunk_start, chunk_end)) {
1851 fprintf(stderr, "cannot get lkey!\n");
1852 return -EINVAL;
1853 }
1854 }
1855
1856 /*
1857 * Encode the ram block index and chunk within this wrid.
1858 * We will use this information at the time of completion
1859 * to figure out which bitmap to check against and then which
1860 * chunk in the bitmap to look for.
1861 */
1862 send_wr.wr_id = qemu_rdma_make_wrid(RDMA_WRID_RDMA_WRITE,
1863 current_index, chunk);
1864
1865 send_wr.opcode = IBV_WR_RDMA_WRITE;
1866 send_wr.send_flags = IBV_SEND_SIGNALED;
1867 send_wr.sg_list = &sge;
1868 send_wr.num_sge = 1;
1869 send_wr.wr.rdma.remote_addr = block->remote_host_addr +
1870 (current_addr - block->offset);
1871
1872 DDDPRINTF("Posting chunk: %" PRIu64 ", addr: %lx"
1873 " remote: %lx, bytes %" PRIu32 "\n",
1874 chunk, sge.addr, send_wr.wr.rdma.remote_addr,
1875 sge.length);
1876
1877 /*
1878 * ibv_post_send() does not return negative error numbers,
1879 * per the specification they are positive - no idea why.
1880 */
1881 ret = ibv_post_send(rdma->qp, &send_wr, &bad_wr);
1882
1883 if (ret == ENOMEM) {
1884 DDPRINTF("send queue is full. wait a little....\n");
1885 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE);
1886 if (ret < 0) {
1887 fprintf(stderr, "rdma migration: failed to make "
1888 "room in full send queue! %d\n", ret);
1889 return ret;
1890 }
1891
1892 goto retry;
1893
1894 } else if (ret > 0) {
1895 perror("rdma migration: post rdma write failed");
1896 return -ret;
1897 }
1898
1899 set_bit(chunk, block->transit_bitmap);
1900 acct_update_position(f, sge.length, false);
1901 rdma->total_writes++;
1902
1903 return 0;
1904}
1905
1906/*
1907 * Push out any unwritten RDMA operations.
1908 *
1909 * We support sending out multiple chunks at the same time.
1910 * Not all of them need to get signaled in the completion queue.
1911 */
1912static int qemu_rdma_write_flush(QEMUFile *f, RDMAContext *rdma)
1913{
1914 int ret;
1915
1916 if (!rdma->current_length) {
1917 return 0;
1918 }
1919
1920 ret = qemu_rdma_write_one(f, rdma,
1921 rdma->current_index, rdma->current_addr, rdma->current_length);
1922
1923 if (ret < 0) {
1924 return ret;
1925 }
1926
1927 if (ret == 0) {
1928 rdma->nb_sent++;
1929 DDDPRINTF("sent total: %d\n", rdma->nb_sent);
1930 }
1931
1932 rdma->current_length = 0;
1933 rdma->current_addr = 0;
1934
1935 return 0;
1936}
1937
1938static inline int qemu_rdma_buffer_mergable(RDMAContext *rdma,
1939 uint64_t offset, uint64_t len)
1940{
44b59494
IY
1941 RDMALocalBlock *block;
1942 uint8_t *host_addr;
1943 uint8_t *chunk_end;
1944
1945 if (rdma->current_index < 0) {
1946 return 0;
1947 }
1948
1949 if (rdma->current_chunk < 0) {
1950 return 0;
1951 }
1952
1953 block = &(rdma->local_ram_blocks.block[rdma->current_index]);
1954 host_addr = block->local_host_addr + (offset - block->offset);
1955 chunk_end = ram_chunk_end(block, rdma->current_chunk);
2da776db
MH
1956
1957 if (rdma->current_length == 0) {
1958 return 0;
1959 }
1960
1961 /*
1962 * Only merge into chunk sequentially.
1963 */
1964 if (offset != (rdma->current_addr + rdma->current_length)) {
1965 return 0;
1966 }
1967
2da776db
MH
1968 if (offset < block->offset) {
1969 return 0;
1970 }
1971
1972 if ((offset + len) > (block->offset + block->length)) {
1973 return 0;
1974 }
1975
2da776db
MH
1976 if ((host_addr + len) > chunk_end) {
1977 return 0;
1978 }
1979
1980 return 1;
1981}
1982
1983/*
1984 * We're not actually writing here, but doing three things:
1985 *
1986 * 1. Identify the chunk the buffer belongs to.
1987 * 2. If the chunk is full or the buffer doesn't belong to the current
1988 * chunk, then start a new chunk and flush() the old chunk.
1989 * 3. To keep the hardware busy, we also group chunks into batches
1990 * and only require that a batch gets acknowledged in the completion
1991 * qeueue instead of each individual chunk.
1992 */
1993static int qemu_rdma_write(QEMUFile *f, RDMAContext *rdma,
1994 uint64_t block_offset, uint64_t offset,
1995 uint64_t len)
1996{
1997 uint64_t current_addr = block_offset + offset;
1998 uint64_t index = rdma->current_index;
1999 uint64_t chunk = rdma->current_chunk;
2000 int ret;
2001
2002 /* If we cannot merge it, we flush the current buffer first. */
2003 if (!qemu_rdma_buffer_mergable(rdma, current_addr, len)) {
2004 ret = qemu_rdma_write_flush(f, rdma);
2005 if (ret) {
2006 return ret;
2007 }
2008 rdma->current_length = 0;
2009 rdma->current_addr = current_addr;
2010
2011 ret = qemu_rdma_search_ram_block(rdma, block_offset,
2012 offset, len, &index, &chunk);
2013 if (ret) {
2014 fprintf(stderr, "ram block search failed\n");
2015 return ret;
2016 }
2017 rdma->current_index = index;
2018 rdma->current_chunk = chunk;
2019 }
2020
2021 /* merge it */
2022 rdma->current_length += len;
2023
2024 /* flush it if buffer is too large */
2025 if (rdma->current_length >= RDMA_MERGE_MAX) {
2026 return qemu_rdma_write_flush(f, rdma);
2027 }
2028
2029 return 0;
2030}
2031
2032static void qemu_rdma_cleanup(RDMAContext *rdma)
2033{
2034 struct rdma_cm_event *cm_event;
2035 int ret, idx;
2036
2037 if (rdma->cm_id) {
2038 if (rdma->error_state) {
2039 RDMAControlHeader head = { .len = 0,
2040 .type = RDMA_CONTROL_ERROR,
2041 .repeat = 1,
2042 };
2043 fprintf(stderr, "Early error. Sending error.\n");
2044 qemu_rdma_post_send_control(rdma, NULL, &head);
2045 }
2046
2047 ret = rdma_disconnect(rdma->cm_id);
2048 if (!ret) {
2049 DDPRINTF("waiting for disconnect\n");
2050 ret = rdma_get_cm_event(rdma->channel, &cm_event);
2051 if (!ret) {
2052 rdma_ack_cm_event(cm_event);
2053 }
2054 }
2055 DDPRINTF("Disconnected.\n");
2056 rdma->cm_id = NULL;
2057 }
2058
2059 g_free(rdma->block);
2060 rdma->block = NULL;
2061
1f22364b 2062 for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
2da776db
MH
2063 if (rdma->wr_data[idx].control_mr) {
2064 rdma->total_registrations--;
2065 ibv_dereg_mr(rdma->wr_data[idx].control_mr);
2066 }
2067 rdma->wr_data[idx].control_mr = NULL;
2068 }
2069
2070 if (rdma->local_ram_blocks.block) {
2071 while (rdma->local_ram_blocks.nb_blocks) {
2072 __qemu_rdma_delete_block(rdma,
2073 rdma->local_ram_blocks.block->offset);
2074 }
2075 }
2076
2077 if (rdma->qp) {
2078 ibv_destroy_qp(rdma->qp);
2079 rdma->qp = NULL;
2080 }
2081 if (rdma->cq) {
2082 ibv_destroy_cq(rdma->cq);
2083 rdma->cq = NULL;
2084 }
2085 if (rdma->comp_channel) {
2086 ibv_destroy_comp_channel(rdma->comp_channel);
2087 rdma->comp_channel = NULL;
2088 }
2089 if (rdma->pd) {
2090 ibv_dealloc_pd(rdma->pd);
2091 rdma->pd = NULL;
2092 }
2093 if (rdma->listen_id) {
2094 rdma_destroy_id(rdma->listen_id);
2095 rdma->listen_id = NULL;
2096 }
2097 if (rdma->cm_id) {
2098 rdma_destroy_id(rdma->cm_id);
2099 rdma->cm_id = NULL;
2100 }
2101 if (rdma->channel) {
2102 rdma_destroy_event_channel(rdma->channel);
2103 rdma->channel = NULL;
2104 }
e1d0fb37
IY
2105 g_free(rdma->host);
2106 rdma->host = NULL;
2da776db
MH
2107}
2108
2109
2110static int qemu_rdma_source_init(RDMAContext *rdma, Error **errp, bool pin_all)
2111{
2112 int ret, idx;
2113 Error *local_err = NULL, **temp = &local_err;
2114
2115 /*
2116 * Will be validated against destination's actual capabilities
2117 * after the connect() completes.
2118 */
2119 rdma->pin_all = pin_all;
2120
2121 ret = qemu_rdma_resolve_host(rdma, temp);
2122 if (ret) {
2123 goto err_rdma_source_init;
2124 }
2125
2126 ret = qemu_rdma_alloc_pd_cq(rdma);
2127 if (ret) {
2128 ERROR(temp, "rdma migration: error allocating pd and cq! Your mlock()"
2129 " limits may be too low. Please check $ ulimit -a # and "
66988941 2130 "search for 'ulimit -l' in the output");
2da776db
MH
2131 goto err_rdma_source_init;
2132 }
2133
2134 ret = qemu_rdma_alloc_qp(rdma);
2135 if (ret) {
66988941 2136 ERROR(temp, "rdma migration: error allocating qp!");
2da776db
MH
2137 goto err_rdma_source_init;
2138 }
2139
2140 ret = qemu_rdma_init_ram_blocks(rdma);
2141 if (ret) {
66988941 2142 ERROR(temp, "rdma migration: error initializing ram blocks!");
2da776db
MH
2143 goto err_rdma_source_init;
2144 }
2145
1f22364b 2146 for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
2da776db
MH
2147 ret = qemu_rdma_reg_control(rdma, idx);
2148 if (ret) {
66988941 2149 ERROR(temp, "rdma migration: error registering %d control!",
2da776db
MH
2150 idx);
2151 goto err_rdma_source_init;
2152 }
2153 }
2154
2155 return 0;
2156
2157err_rdma_source_init:
2158 error_propagate(errp, local_err);
2159 qemu_rdma_cleanup(rdma);
2160 return -1;
2161}
2162
2163static int qemu_rdma_connect(RDMAContext *rdma, Error **errp)
2164{
2165 RDMACapabilities cap = {
2166 .version = RDMA_CONTROL_VERSION_CURRENT,
2167 .flags = 0,
2168 };
2169 struct rdma_conn_param conn_param = { .initiator_depth = 2,
2170 .retry_count = 5,
2171 .private_data = &cap,
2172 .private_data_len = sizeof(cap),
2173 };
2174 struct rdma_cm_event *cm_event;
2175 int ret;
2176
2177 /*
2178 * Only negotiate the capability with destination if the user
2179 * on the source first requested the capability.
2180 */
2181 if (rdma->pin_all) {
2182 DPRINTF("Server pin-all memory requested.\n");
2183 cap.flags |= RDMA_CAPABILITY_PIN_ALL;
2184 }
2185
2186 caps_to_network(&cap);
2187
2188 ret = rdma_connect(rdma->cm_id, &conn_param);
2189 if (ret) {
2190 perror("rdma_connect");
66988941 2191 ERROR(errp, "connecting to destination!");
2da776db
MH
2192 rdma_destroy_id(rdma->cm_id);
2193 rdma->cm_id = NULL;
2194 goto err_rdma_source_connect;
2195 }
2196
2197 ret = rdma_get_cm_event(rdma->channel, &cm_event);
2198 if (ret) {
2199 perror("rdma_get_cm_event after rdma_connect");
66988941 2200 ERROR(errp, "connecting to destination!");
2da776db
MH
2201 rdma_ack_cm_event(cm_event);
2202 rdma_destroy_id(rdma->cm_id);
2203 rdma->cm_id = NULL;
2204 goto err_rdma_source_connect;
2205 }
2206
2207 if (cm_event->event != RDMA_CM_EVENT_ESTABLISHED) {
2208 perror("rdma_get_cm_event != EVENT_ESTABLISHED after rdma_connect");
66988941 2209 ERROR(errp, "connecting to destination!");
2da776db
MH
2210 rdma_ack_cm_event(cm_event);
2211 rdma_destroy_id(rdma->cm_id);
2212 rdma->cm_id = NULL;
2213 goto err_rdma_source_connect;
2214 }
2215
2216 memcpy(&cap, cm_event->param.conn.private_data, sizeof(cap));
2217 network_to_caps(&cap);
2218
2219 /*
2220 * Verify that the *requested* capabilities are supported by the destination
2221 * and disable them otherwise.
2222 */
2223 if (rdma->pin_all && !(cap.flags & RDMA_CAPABILITY_PIN_ALL)) {
2224 ERROR(errp, "Server cannot support pinning all memory. "
66988941 2225 "Will register memory dynamically.");
2da776db
MH
2226 rdma->pin_all = false;
2227 }
2228
2229 DPRINTF("Pin all memory: %s\n", rdma->pin_all ? "enabled" : "disabled");
2230
2231 rdma_ack_cm_event(cm_event);
2232
87772639 2233 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
2da776db 2234 if (ret) {
66988941 2235 ERROR(errp, "posting second control recv!");
2da776db
MH
2236 goto err_rdma_source_connect;
2237 }
2238
2239 rdma->control_ready_expected = 1;
2240 rdma->nb_sent = 0;
2241 return 0;
2242
2243err_rdma_source_connect:
2244 qemu_rdma_cleanup(rdma);
2245 return -1;
2246}
2247
2248static int qemu_rdma_dest_init(RDMAContext *rdma, Error **errp)
2249{
2250 int ret = -EINVAL, idx;
b58c8552 2251 int af = rdma->ipv6 ? PF_INET6 : PF_INET;
2da776db
MH
2252 struct sockaddr_in sin;
2253 struct rdma_cm_id *listen_id;
2254 char ip[40] = "unknown";
b58c8552
MH
2255 struct addrinfo *res;
2256 char port_str[16];
2da776db 2257
1f22364b 2258 for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
2da776db
MH
2259 rdma->wr_data[idx].control_len = 0;
2260 rdma->wr_data[idx].control_curr = NULL;
2261 }
2262
2263 if (rdma->host == NULL) {
66988941 2264 ERROR(errp, "RDMA host is not set!");
2da776db
MH
2265 rdma->error_state = -EINVAL;
2266 return -1;
2267 }
2268 /* create CM channel */
2269 rdma->channel = rdma_create_event_channel();
2270 if (!rdma->channel) {
66988941 2271 ERROR(errp, "could not create rdma event channel");
2da776db
MH
2272 rdma->error_state = -EINVAL;
2273 return -1;
2274 }
2275
2276 /* create CM id */
2277 ret = rdma_create_id(rdma->channel, &listen_id, NULL, RDMA_PS_TCP);
2278 if (ret) {
66988941 2279 ERROR(errp, "could not create cm_id!");
2da776db
MH
2280 goto err_dest_init_create_listen_id;
2281 }
2282
2283 memset(&sin, 0, sizeof(sin));
b58c8552 2284 sin.sin_family = af;
2da776db 2285 sin.sin_port = htons(rdma->port);
b58c8552
MH
2286 snprintf(port_str, 16, "%d", rdma->port);
2287 port_str[15] = '\0';
2da776db
MH
2288
2289 if (rdma->host && strcmp("", rdma->host)) {
b58c8552
MH
2290 ret = getaddrinfo(rdma->host, port_str, NULL, &res);
2291 if (ret < 0) {
66988941 2292 ERROR(errp, "could not getaddrinfo address %s", rdma->host);
2da776db
MH
2293 goto err_dest_init_bind_addr;
2294 }
b58c8552
MH
2295
2296
2297 inet_ntop(af, &((struct sockaddr_in *) res->ai_addr)->sin_addr,
2298 ip, sizeof ip);
2da776db 2299 } else {
66988941 2300 ERROR(errp, "migration host and port not specified!");
b58c8552
MH
2301 ret = -EINVAL;
2302 goto err_dest_init_bind_addr;
2da776db
MH
2303 }
2304
2305 DPRINTF("%s => %s\n", rdma->host, ip);
2306
b58c8552 2307 ret = rdma_bind_addr(listen_id, res->ai_addr);
2da776db 2308 if (ret) {
66988941 2309 ERROR(errp, "Error: could not rdma_bind_addr!");
2da776db
MH
2310 goto err_dest_init_bind_addr;
2311 }
2312
2313 rdma->listen_id = listen_id;
2314 qemu_rdma_dump_gid("dest_init", listen_id);
2315 return 0;
2316
2317err_dest_init_bind_addr:
2318 rdma_destroy_id(listen_id);
2319err_dest_init_create_listen_id:
2320 rdma_destroy_event_channel(rdma->channel);
2321 rdma->channel = NULL;
2322 rdma->error_state = ret;
2323 return ret;
2324
2325}
2326
2327static void *qemu_rdma_data_init(const char *host_port, Error **errp)
2328{
2329 RDMAContext *rdma = NULL;
2330 InetSocketAddress *addr;
2331
2332 if (host_port) {
2333 rdma = g_malloc0(sizeof(RDMAContext));
2334 memset(rdma, 0, sizeof(RDMAContext));
2335 rdma->current_index = -1;
2336 rdma->current_chunk = -1;
2337
2338 addr = inet_parse(host_port, NULL);
2339 if (addr != NULL) {
2340 rdma->port = atoi(addr->port);
2341 rdma->host = g_strdup(addr->host);
b58c8552 2342 rdma->ipv6 = addr->ipv6;
2da776db
MH
2343 } else {
2344 ERROR(errp, "bad RDMA migration address '%s'", host_port);
2345 g_free(rdma);
2346 return NULL;
2347 }
2348 }
2349
2350 return rdma;
2351}
2352
2353/*
2354 * QEMUFile interface to the control channel.
2355 * SEND messages for control only.
2356 * pc.ram is handled with regular RDMA messages.
2357 */
2358static int qemu_rdma_put_buffer(void *opaque, const uint8_t *buf,
2359 int64_t pos, int size)
2360{
2361 QEMUFileRDMA *r = opaque;
2362 QEMUFile *f = r->file;
2363 RDMAContext *rdma = r->rdma;
2364 size_t remaining = size;
2365 uint8_t * data = (void *) buf;
2366 int ret;
2367
2368 CHECK_ERROR_STATE();
2369
2370 /*
2371 * Push out any writes that
2372 * we're queued up for pc.ram.
2373 */
2374 ret = qemu_rdma_write_flush(f, rdma);
2375 if (ret < 0) {
2376 rdma->error_state = ret;
2377 return ret;
2378 }
2379
2380 while (remaining) {
2381 RDMAControlHeader head;
2382
2383 r->len = MIN(remaining, RDMA_SEND_INCREMENT);
2384 remaining -= r->len;
2385
2386 head.len = r->len;
2387 head.type = RDMA_CONTROL_QEMU_FILE;
2388
2389 ret = qemu_rdma_exchange_send(rdma, &head, data, NULL, NULL, NULL);
2390
2391 if (ret < 0) {
2392 rdma->error_state = ret;
2393 return ret;
2394 }
2395
2396 data += r->len;
2397 }
2398
2399 return size;
2400}
2401
2402static size_t qemu_rdma_fill(RDMAContext *rdma, uint8_t *buf,
2403 int size, int idx)
2404{
2405 size_t len = 0;
2406
2407 if (rdma->wr_data[idx].control_len) {
2408 DDDPRINTF("RDMA %" PRId64 " of %d bytes already in buffer\n",
2409 rdma->wr_data[idx].control_len, size);
2410
2411 len = MIN(size, rdma->wr_data[idx].control_len);
2412 memcpy(buf, rdma->wr_data[idx].control_curr, len);
2413 rdma->wr_data[idx].control_curr += len;
2414 rdma->wr_data[idx].control_len -= len;
2415 }
2416
2417 return len;
2418}
2419
2420/*
2421 * QEMUFile interface to the control channel.
2422 * RDMA links don't use bytestreams, so we have to
2423 * return bytes to QEMUFile opportunistically.
2424 */
2425static int qemu_rdma_get_buffer(void *opaque, uint8_t *buf,
2426 int64_t pos, int size)
2427{
2428 QEMUFileRDMA *r = opaque;
2429 RDMAContext *rdma = r->rdma;
2430 RDMAControlHeader head;
2431 int ret = 0;
2432
2433 CHECK_ERROR_STATE();
2434
2435 /*
2436 * First, we hold on to the last SEND message we
2437 * were given and dish out the bytes until we run
2438 * out of bytes.
2439 */
2440 r->len = qemu_rdma_fill(r->rdma, buf, size, 0);
2441 if (r->len) {
2442 return r->len;
2443 }
2444
2445 /*
2446 * Once we run out, we block and wait for another
2447 * SEND message to arrive.
2448 */
2449 ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_QEMU_FILE);
2450
2451 if (ret < 0) {
2452 rdma->error_state = ret;
2453 return ret;
2454 }
2455
2456 /*
2457 * SEND was received with new bytes, now try again.
2458 */
2459 return qemu_rdma_fill(r->rdma, buf, size, 0);
2460}
2461
2462/*
2463 * Block until all the outstanding chunks have been delivered by the hardware.
2464 */
2465static int qemu_rdma_drain_cq(QEMUFile *f, RDMAContext *rdma)
2466{
2467 int ret;
2468
2469 if (qemu_rdma_write_flush(f, rdma) < 0) {
2470 return -EIO;
2471 }
2472
2473 while (rdma->nb_sent) {
2474 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE);
2475 if (ret < 0) {
2476 fprintf(stderr, "rdma migration: complete polling error!\n");
2477 return -EIO;
2478 }
2479 }
2480
2481 qemu_rdma_unregister_waiting(rdma);
2482
2483 return 0;
2484}
2485
2486static int qemu_rdma_close(void *opaque)
2487{
2488 DPRINTF("Shutting down connection.\n");
2489 QEMUFileRDMA *r = opaque;
2490 if (r->rdma) {
2491 qemu_rdma_cleanup(r->rdma);
2492 g_free(r->rdma);
2493 }
2494 g_free(r);
2495 return 0;
2496}
2497
2498/*
2499 * Parameters:
2500 * @offset == 0 :
2501 * This means that 'block_offset' is a full virtual address that does not
2502 * belong to a RAMBlock of the virtual machine and instead
2503 * represents a private malloc'd memory area that the caller wishes to
2504 * transfer.
2505 *
2506 * @offset != 0 :
2507 * Offset is an offset to be added to block_offset and used
2508 * to also lookup the corresponding RAMBlock.
2509 *
2510 * @size > 0 :
2511 * Initiate an transfer this size.
2512 *
2513 * @size == 0 :
2514 * A 'hint' or 'advice' that means that we wish to speculatively
2515 * and asynchronously unregister this memory. In this case, there is no
52f35022 2516 * guarantee that the unregister will actually happen, for example,
2da776db
MH
2517 * if the memory is being actively transmitted. Additionally, the memory
2518 * may be re-registered at any future time if a write within the same
2519 * chunk was requested again, even if you attempted to unregister it
2520 * here.
2521 *
2522 * @size < 0 : TODO, not yet supported
2523 * Unregister the memory NOW. This means that the caller does not
2524 * expect there to be any future RDMA transfers and we just want to clean
2525 * things up. This is used in case the upper layer owns the memory and
2526 * cannot wait for qemu_fclose() to occur.
2527 *
2528 * @bytes_sent : User-specificed pointer to indicate how many bytes were
2529 * sent. Usually, this will not be more than a few bytes of
2530 * the protocol because most transfers are sent asynchronously.
2531 */
2532static size_t qemu_rdma_save_page(QEMUFile *f, void *opaque,
2533 ram_addr_t block_offset, ram_addr_t offset,
2534 size_t size, int *bytes_sent)
2535{
2536 QEMUFileRDMA *rfile = opaque;
2537 RDMAContext *rdma = rfile->rdma;
2538 int ret;
2539
2540 CHECK_ERROR_STATE();
2541
2542 qemu_fflush(f);
2543
2544 if (size > 0) {
2545 /*
2546 * Add this page to the current 'chunk'. If the chunk
2547 * is full, or the page doen't belong to the current chunk,
2548 * an actual RDMA write will occur and a new chunk will be formed.
2549 */
2550 ret = qemu_rdma_write(f, rdma, block_offset, offset, size);
2551 if (ret < 0) {
2552 fprintf(stderr, "rdma migration: write error! %d\n", ret);
2553 goto err;
2554 }
2555
2556 /*
2557 * We always return 1 bytes because the RDMA
2558 * protocol is completely asynchronous. We do not yet know
2559 * whether an identified chunk is zero or not because we're
2560 * waiting for other pages to potentially be merged with
2561 * the current chunk. So, we have to call qemu_update_position()
2562 * later on when the actual write occurs.
2563 */
2564 if (bytes_sent) {
2565 *bytes_sent = 1;
2566 }
2567 } else {
2568 uint64_t index, chunk;
2569
2570 /* TODO: Change QEMUFileOps prototype to be signed: size_t => long
2571 if (size < 0) {
2572 ret = qemu_rdma_drain_cq(f, rdma);
2573 if (ret < 0) {
2574 fprintf(stderr, "rdma: failed to synchronously drain"
2575 " completion queue before unregistration.\n");
2576 goto err;
2577 }
2578 }
2579 */
2580
2581 ret = qemu_rdma_search_ram_block(rdma, block_offset,
2582 offset, size, &index, &chunk);
2583
2584 if (ret) {
2585 fprintf(stderr, "ram block search failed\n");
2586 goto err;
2587 }
2588
2589 qemu_rdma_signal_unregister(rdma, index, chunk, 0);
2590
2591 /*
52f35022 2592 * TODO: Synchronous, guaranteed unregistration (should not occur during
2da776db
MH
2593 * fast-path). Otherwise, unregisters will process on the next call to
2594 * qemu_rdma_drain_cq()
2595 if (size < 0) {
2596 qemu_rdma_unregister_waiting(rdma);
2597 }
2598 */
2599 }
2600
2601 /*
2602 * Drain the Completion Queue if possible, but do not block,
2603 * just poll.
2604 *
2605 * If nothing to poll, the end of the iteration will do this
2606 * again to make sure we don't overflow the request queue.
2607 */
2608 while (1) {
2609 uint64_t wr_id, wr_id_in;
2610 int ret = qemu_rdma_poll(rdma, &wr_id_in);
2611 if (ret < 0) {
2612 fprintf(stderr, "rdma migration: polling error! %d\n", ret);
2613 goto err;
2614 }
2615
2616 wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
2617
2618 if (wr_id == RDMA_WRID_NONE) {
2619 break;
2620 }
2621 }
2622
2623 return RAM_SAVE_CONTROL_DELAYED;
2624err:
2625 rdma->error_state = ret;
2626 return ret;
2627}
2628
2629static int qemu_rdma_accept(RDMAContext *rdma)
2630{
2631 RDMACapabilities cap;
2632 struct rdma_conn_param conn_param = {
2633 .responder_resources = 2,
2634 .private_data = &cap,
2635 .private_data_len = sizeof(cap),
2636 };
2637 struct rdma_cm_event *cm_event;
2638 struct ibv_context *verbs;
2639 int ret = -EINVAL;
2640 int idx;
2641
2642 ret = rdma_get_cm_event(rdma->channel, &cm_event);
2643 if (ret) {
2644 goto err_rdma_dest_wait;
2645 }
2646
2647 if (cm_event->event != RDMA_CM_EVENT_CONNECT_REQUEST) {
2648 rdma_ack_cm_event(cm_event);
2649 goto err_rdma_dest_wait;
2650 }
2651
2652 memcpy(&cap, cm_event->param.conn.private_data, sizeof(cap));
2653
2654 network_to_caps(&cap);
2655
2656 if (cap.version < 1 || cap.version > RDMA_CONTROL_VERSION_CURRENT) {
2657 fprintf(stderr, "Unknown source RDMA version: %d, bailing...\n",
2658 cap.version);
2659 rdma_ack_cm_event(cm_event);
2660 goto err_rdma_dest_wait;
2661 }
2662
2663 /*
2664 * Respond with only the capabilities this version of QEMU knows about.
2665 */
2666 cap.flags &= known_capabilities;
2667
2668 /*
2669 * Enable the ones that we do know about.
2670 * Add other checks here as new ones are introduced.
2671 */
2672 if (cap.flags & RDMA_CAPABILITY_PIN_ALL) {
2673 rdma->pin_all = true;
2674 }
2675
2676 rdma->cm_id = cm_event->id;
2677 verbs = cm_event->id->verbs;
2678
2679 rdma_ack_cm_event(cm_event);
2680
2681 DPRINTF("Memory pin all: %s\n", rdma->pin_all ? "enabled" : "disabled");
2682
2683 caps_to_network(&cap);
2684
2685 DPRINTF("verbs context after listen: %p\n", verbs);
2686
2687 if (!rdma->verbs) {
2688 rdma->verbs = verbs;
2689 } else if (rdma->verbs != verbs) {
2690 fprintf(stderr, "ibv context not matching %p, %p!\n",
2691 rdma->verbs, verbs);
2692 goto err_rdma_dest_wait;
2693 }
2694
2695 qemu_rdma_dump_id("dest_init", verbs);
2696
2697 ret = qemu_rdma_alloc_pd_cq(rdma);
2698 if (ret) {
2699 fprintf(stderr, "rdma migration: error allocating pd and cq!\n");
2700 goto err_rdma_dest_wait;
2701 }
2702
2703 ret = qemu_rdma_alloc_qp(rdma);
2704 if (ret) {
2705 fprintf(stderr, "rdma migration: error allocating qp!\n");
2706 goto err_rdma_dest_wait;
2707 }
2708
2709 ret = qemu_rdma_init_ram_blocks(rdma);
2710 if (ret) {
2711 fprintf(stderr, "rdma migration: error initializing ram blocks!\n");
2712 goto err_rdma_dest_wait;
2713 }
2714
1f22364b 2715 for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
2da776db
MH
2716 ret = qemu_rdma_reg_control(rdma, idx);
2717 if (ret) {
2718 fprintf(stderr, "rdma: error registering %d control!\n", idx);
2719 goto err_rdma_dest_wait;
2720 }
2721 }
2722
2723 qemu_set_fd_handler2(rdma->channel->fd, NULL, NULL, NULL, NULL);
2724
2725 ret = rdma_accept(rdma->cm_id, &conn_param);
2726 if (ret) {
2727 fprintf(stderr, "rdma_accept returns %d!\n", ret);
2728 goto err_rdma_dest_wait;
2729 }
2730
2731 ret = rdma_get_cm_event(rdma->channel, &cm_event);
2732 if (ret) {
2733 fprintf(stderr, "rdma_accept get_cm_event failed %d!\n", ret);
2734 goto err_rdma_dest_wait;
2735 }
2736
2737 if (cm_event->event != RDMA_CM_EVENT_ESTABLISHED) {
2738 fprintf(stderr, "rdma_accept not event established!\n");
2739 rdma_ack_cm_event(cm_event);
2740 goto err_rdma_dest_wait;
2741 }
2742
2743 rdma_ack_cm_event(cm_event);
2744
87772639 2745 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
2da776db
MH
2746 if (ret) {
2747 fprintf(stderr, "rdma migration: error posting second control recv!\n");
2748 goto err_rdma_dest_wait;
2749 }
2750
2751 qemu_rdma_dump_gid("dest_connect", rdma->cm_id);
2752
2753 return 0;
2754
2755err_rdma_dest_wait:
2756 rdma->error_state = ret;
2757 qemu_rdma_cleanup(rdma);
2758 return ret;
2759}
2760
2761/*
2762 * During each iteration of the migration, we listen for instructions
2763 * by the source VM to perform dynamic page registrations before they
2764 * can perform RDMA operations.
2765 *
2766 * We respond with the 'rkey'.
2767 *
2768 * Keep doing this until the source tells us to stop.
2769 */
2770static int qemu_rdma_registration_handle(QEMUFile *f, void *opaque,
2771 uint64_t flags)
2772{
2773 RDMAControlHeader reg_resp = { .len = sizeof(RDMARegisterResult),
2774 .type = RDMA_CONTROL_REGISTER_RESULT,
2775 .repeat = 0,
2776 };
2777 RDMAControlHeader unreg_resp = { .len = 0,
2778 .type = RDMA_CONTROL_UNREGISTER_FINISHED,
2779 .repeat = 0,
2780 };
2781 RDMAControlHeader blocks = { .type = RDMA_CONTROL_RAM_BLOCKS_RESULT,
2782 .repeat = 1 };
2783 QEMUFileRDMA *rfile = opaque;
2784 RDMAContext *rdma = rfile->rdma;
2785 RDMALocalBlocks *local = &rdma->local_ram_blocks;
2786 RDMAControlHeader head;
2787 RDMARegister *reg, *registers;
2788 RDMACompress *comp;
2789 RDMARegisterResult *reg_result;
2790 static RDMARegisterResult results[RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE];
2791 RDMALocalBlock *block;
2792 void *host_addr;
2793 int ret = 0;
2794 int idx = 0;
2795 int count = 0;
2796 int i = 0;
2797
2798 CHECK_ERROR_STATE();
2799
2800 do {
2801 DDDPRINTF("Waiting for next request %" PRIu64 "...\n", flags);
2802
2803 ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_NONE);
2804
2805 if (ret < 0) {
2806 break;
2807 }
2808
2809 if (head.repeat > RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE) {
2810 fprintf(stderr, "rdma: Too many requests in this message (%d)."
2811 "Bailing.\n", head.repeat);
2812 ret = -EIO;
2813 break;
2814 }
2815
2816 switch (head.type) {
2817 case RDMA_CONTROL_COMPRESS:
2818 comp = (RDMACompress *) rdma->wr_data[idx].control_curr;
2819 network_to_compress(comp);
2820
2821 DDPRINTF("Zapping zero chunk: %" PRId64
2822 " bytes, index %d, offset %" PRId64 "\n",
2823 comp->length, comp->block_idx, comp->offset);
2824 block = &(rdma->local_ram_blocks.block[comp->block_idx]);
2825
2826 host_addr = block->local_host_addr +
2827 (comp->offset - block->offset);
2828
2829 ram_handle_compressed(host_addr, comp->value, comp->length);
2830 break;
2831
2832 case RDMA_CONTROL_REGISTER_FINISHED:
2833 DDDPRINTF("Current registrations complete.\n");
2834 goto out;
2835
2836 case RDMA_CONTROL_RAM_BLOCKS_REQUEST:
2837 DPRINTF("Initial setup info requested.\n");
2838
2839 if (rdma->pin_all) {
2840 ret = qemu_rdma_reg_whole_ram_blocks(rdma);
2841 if (ret) {
2842 fprintf(stderr, "rdma migration: error dest "
2843 "registering ram blocks!\n");
2844 goto out;
2845 }
2846 }
2847
2848 /*
2849 * Dest uses this to prepare to transmit the RAMBlock descriptions
2850 * to the source VM after connection setup.
2851 * Both sides use the "remote" structure to communicate and update
2852 * their "local" descriptions with what was sent.
2853 */
2854 for (i = 0; i < local->nb_blocks; i++) {
2855 rdma->block[i].remote_host_addr =
2856 (uint64_t)(local->block[i].local_host_addr);
2857
2858 if (rdma->pin_all) {
2859 rdma->block[i].remote_rkey = local->block[i].mr->rkey;
2860 }
2861
2862 rdma->block[i].offset = local->block[i].offset;
2863 rdma->block[i].length = local->block[i].length;
2864
2865 remote_block_to_network(&rdma->block[i]);
2866 }
2867
2868 blocks.len = rdma->local_ram_blocks.nb_blocks
2869 * sizeof(RDMARemoteBlock);
2870
2871
2872 ret = qemu_rdma_post_send_control(rdma,
2873 (uint8_t *) rdma->block, &blocks);
2874
2875 if (ret < 0) {
2876 fprintf(stderr, "rdma migration: error sending remote info!\n");
2877 goto out;
2878 }
2879
2880 break;
2881 case RDMA_CONTROL_REGISTER_REQUEST:
2882 DDPRINTF("There are %d registration requests\n", head.repeat);
2883
2884 reg_resp.repeat = head.repeat;
2885 registers = (RDMARegister *) rdma->wr_data[idx].control_curr;
2886
2887 for (count = 0; count < head.repeat; count++) {
2888 uint64_t chunk;
2889 uint8_t *chunk_start, *chunk_end;
2890
2891 reg = &registers[count];
2892 network_to_register(reg);
2893
2894 reg_result = &results[count];
2895
2896 DDPRINTF("Registration request (%d): index %d, current_addr %"
2897 PRIu64 " chunks: %" PRIu64 "\n", count,
2898 reg->current_index, reg->key.current_addr, reg->chunks);
2899
2900 block = &(rdma->local_ram_blocks.block[reg->current_index]);
2901 if (block->is_ram_block) {
2902 host_addr = (block->local_host_addr +
2903 (reg->key.current_addr - block->offset));
2904 chunk = ram_chunk_index(block->local_host_addr,
2905 (uint8_t *) host_addr);
2906 } else {
2907 chunk = reg->key.chunk;
2908 host_addr = block->local_host_addr +
2909 (reg->key.chunk * (1UL << RDMA_REG_CHUNK_SHIFT));
2910 }
2911 chunk_start = ram_chunk_start(block, chunk);
2912 chunk_end = ram_chunk_end(block, chunk + reg->chunks);
2913 if (qemu_rdma_register_and_get_keys(rdma, block,
2914 (uint8_t *)host_addr, NULL, &reg_result->rkey,
2915 chunk, chunk_start, chunk_end)) {
2916 fprintf(stderr, "cannot get rkey!\n");
2917 ret = -EINVAL;
2918 goto out;
2919 }
2920
2921 reg_result->host_addr = (uint64_t) block->local_host_addr;
2922
2923 DDPRINTF("Registered rkey for this request: %x\n",
2924 reg_result->rkey);
2925
2926 result_to_network(reg_result);
2927 }
2928
2929 ret = qemu_rdma_post_send_control(rdma,
2930 (uint8_t *) results, &reg_resp);
2931
2932 if (ret < 0) {
2933 fprintf(stderr, "Failed to send control buffer!\n");
2934 goto out;
2935 }
2936 break;
2937 case RDMA_CONTROL_UNREGISTER_REQUEST:
2938 DDPRINTF("There are %d unregistration requests\n", head.repeat);
2939 unreg_resp.repeat = head.repeat;
2940 registers = (RDMARegister *) rdma->wr_data[idx].control_curr;
2941
2942 for (count = 0; count < head.repeat; count++) {
2943 reg = &registers[count];
2944 network_to_register(reg);
2945
2946 DDPRINTF("Unregistration request (%d): "
2947 " index %d, chunk %" PRIu64 "\n",
2948 count, reg->current_index, reg->key.chunk);
2949
2950 block = &(rdma->local_ram_blocks.block[reg->current_index]);
2951
2952 ret = ibv_dereg_mr(block->pmr[reg->key.chunk]);
2953 block->pmr[reg->key.chunk] = NULL;
2954
2955 if (ret != 0) {
2956 perror("rdma unregistration chunk failed");
2957 ret = -ret;
2958 goto out;
2959 }
2960
2961 rdma->total_registrations--;
2962
2963 DDPRINTF("Unregistered chunk %" PRIu64 " successfully.\n",
2964 reg->key.chunk);
2965 }
2966
2967 ret = qemu_rdma_post_send_control(rdma, NULL, &unreg_resp);
2968
2969 if (ret < 0) {
2970 fprintf(stderr, "Failed to send control buffer!\n");
2971 goto out;
2972 }
2973 break;
2974 case RDMA_CONTROL_REGISTER_RESULT:
2975 fprintf(stderr, "Invalid RESULT message at dest.\n");
2976 ret = -EIO;
2977 goto out;
2978 default:
2979 fprintf(stderr, "Unknown control message %s\n",
2980 control_desc[head.type]);
2981 ret = -EIO;
2982 goto out;
2983 }
2984 } while (1);
2985out:
2986 if (ret < 0) {
2987 rdma->error_state = ret;
2988 }
2989 return ret;
2990}
2991
2992static int qemu_rdma_registration_start(QEMUFile *f, void *opaque,
2993 uint64_t flags)
2994{
2995 QEMUFileRDMA *rfile = opaque;
2996 RDMAContext *rdma = rfile->rdma;
2997
2998 CHECK_ERROR_STATE();
2999
3000 DDDPRINTF("start section: %" PRIu64 "\n", flags);
3001 qemu_put_be64(f, RAM_SAVE_FLAG_HOOK);
3002 qemu_fflush(f);
3003
3004 return 0;
3005}
3006
3007/*
3008 * Inform dest that dynamic registrations are done for now.
3009 * First, flush writes, if any.
3010 */
3011static int qemu_rdma_registration_stop(QEMUFile *f, void *opaque,
3012 uint64_t flags)
3013{
3014 Error *local_err = NULL, **errp = &local_err;
3015 QEMUFileRDMA *rfile = opaque;
3016 RDMAContext *rdma = rfile->rdma;
3017 RDMAControlHeader head = { .len = 0, .repeat = 1 };
3018 int ret = 0;
3019
3020 CHECK_ERROR_STATE();
3021
3022 qemu_fflush(f);
3023 ret = qemu_rdma_drain_cq(f, rdma);
3024
3025 if (ret < 0) {
3026 goto err;
3027 }
3028
3029 if (flags == RAM_CONTROL_SETUP) {
3030 RDMAControlHeader resp = {.type = RDMA_CONTROL_RAM_BLOCKS_RESULT };
3031 RDMALocalBlocks *local = &rdma->local_ram_blocks;
3032 int reg_result_idx, i, j, nb_remote_blocks;
3033
3034 head.type = RDMA_CONTROL_RAM_BLOCKS_REQUEST;
3035 DPRINTF("Sending registration setup for ram blocks...\n");
3036
3037 /*
3038 * Make sure that we parallelize the pinning on both sides.
3039 * For very large guests, doing this serially takes a really
3040 * long time, so we have to 'interleave' the pinning locally
3041 * with the control messages by performing the pinning on this
3042 * side before we receive the control response from the other
3043 * side that the pinning has completed.
3044 */
3045 ret = qemu_rdma_exchange_send(rdma, &head, NULL, &resp,
3046 &reg_result_idx, rdma->pin_all ?
3047 qemu_rdma_reg_whole_ram_blocks : NULL);
3048 if (ret < 0) {
66988941 3049 ERROR(errp, "receiving remote info!");
2da776db
MH
3050 return ret;
3051 }
3052
2da776db
MH
3053 nb_remote_blocks = resp.len / sizeof(RDMARemoteBlock);
3054
3055 /*
3056 * The protocol uses two different sets of rkeys (mutually exclusive):
3057 * 1. One key to represent the virtual address of the entire ram block.
3058 * (dynamic chunk registration disabled - pin everything with one rkey.)
3059 * 2. One to represent individual chunks within a ram block.
3060 * (dynamic chunk registration enabled - pin individual chunks.)
3061 *
3062 * Once the capability is successfully negotiated, the destination transmits
3063 * the keys to use (or sends them later) including the virtual addresses
3064 * and then propagates the remote ram block descriptions to his local copy.
3065 */
3066
3067 if (local->nb_blocks != nb_remote_blocks) {
3068 ERROR(errp, "ram blocks mismatch #1! "
3069 "Your QEMU command line parameters are probably "
66988941 3070 "not identical on both the source and destination.");
2da776db
MH
3071 return -EINVAL;
3072 }
3073
885e8f98
IY
3074 qemu_rdma_move_header(rdma, reg_result_idx, &resp);
3075 memcpy(rdma->block,
3076 rdma->wr_data[reg_result_idx].control_curr, resp.len);
2da776db
MH
3077 for (i = 0; i < nb_remote_blocks; i++) {
3078 network_to_remote_block(&rdma->block[i]);
3079
3080 /* search local ram blocks */
3081 for (j = 0; j < local->nb_blocks; j++) {
3082 if (rdma->block[i].offset != local->block[j].offset) {
3083 continue;
3084 }
3085
3086 if (rdma->block[i].length != local->block[j].length) {
3087 ERROR(errp, "ram blocks mismatch #2! "
3088 "Your QEMU command line parameters are probably "
66988941 3089 "not identical on both the source and destination.");
2da776db
MH
3090 return -EINVAL;
3091 }
3092 local->block[j].remote_host_addr =
3093 rdma->block[i].remote_host_addr;
3094 local->block[j].remote_rkey = rdma->block[i].remote_rkey;
3095 break;
3096 }
3097
3098 if (j >= local->nb_blocks) {
3099 ERROR(errp, "ram blocks mismatch #3! "
3100 "Your QEMU command line parameters are probably "
66988941 3101 "not identical on both the source and destination.");
2da776db
MH
3102 return -EINVAL;
3103 }
3104 }
3105 }
3106
3107 DDDPRINTF("Sending registration finish %" PRIu64 "...\n", flags);
3108
3109 head.type = RDMA_CONTROL_REGISTER_FINISHED;
3110 ret = qemu_rdma_exchange_send(rdma, &head, NULL, NULL, NULL, NULL);
3111
3112 if (ret < 0) {
3113 goto err;
3114 }
3115
3116 return 0;
3117err:
3118 rdma->error_state = ret;
3119 return ret;
3120}
3121
3122static int qemu_rdma_get_fd(void *opaque)
3123{
3124 QEMUFileRDMA *rfile = opaque;
3125 RDMAContext *rdma = rfile->rdma;
3126
3127 return rdma->comp_channel->fd;
3128}
3129
3130const QEMUFileOps rdma_read_ops = {
3131 .get_buffer = qemu_rdma_get_buffer,
3132 .get_fd = qemu_rdma_get_fd,
3133 .close = qemu_rdma_close,
3134 .hook_ram_load = qemu_rdma_registration_handle,
3135};
3136
3137const QEMUFileOps rdma_write_ops = {
3138 .put_buffer = qemu_rdma_put_buffer,
3139 .close = qemu_rdma_close,
3140 .before_ram_iterate = qemu_rdma_registration_start,
3141 .after_ram_iterate = qemu_rdma_registration_stop,
3142 .save_page = qemu_rdma_save_page,
3143};
3144
3145static void *qemu_fopen_rdma(RDMAContext *rdma, const char *mode)
3146{
3147 QEMUFileRDMA *r = g_malloc0(sizeof(QEMUFileRDMA));
3148
3149 if (qemu_file_mode_is_not_valid(mode)) {
3150 return NULL;
3151 }
3152
3153 r->rdma = rdma;
3154
3155 if (mode[0] == 'w') {
3156 r->file = qemu_fopen_ops(r, &rdma_write_ops);
3157 } else {
3158 r->file = qemu_fopen_ops(r, &rdma_read_ops);
3159 }
3160
3161 return r->file;
3162}
3163
3164static void rdma_accept_incoming_migration(void *opaque)
3165{
3166 RDMAContext *rdma = opaque;
3167 int ret;
3168 QEMUFile *f;
3169 Error *local_err = NULL, **errp = &local_err;
3170
3171 DPRINTF("Accepting rdma connection...\n");
3172 ret = qemu_rdma_accept(rdma);
3173
3174 if (ret) {
66988941 3175 ERROR(errp, "RDMA Migration initialization failed!");
2da776db
MH
3176 return;
3177 }
3178
3179 DPRINTF("Accepted migration\n");
3180
3181 f = qemu_fopen_rdma(rdma, "rb");
3182 if (f == NULL) {
66988941 3183 ERROR(errp, "could not qemu_fopen_rdma!");
2da776db
MH
3184 qemu_rdma_cleanup(rdma);
3185 return;
3186 }
3187
3188 rdma->migration_started_on_destination = 1;
3189 process_incoming_migration(f);
3190}
3191
3192void rdma_start_incoming_migration(const char *host_port, Error **errp)
3193{
3194 int ret;
3195 RDMAContext *rdma;
3196 Error *local_err = NULL;
3197
3198 DPRINTF("Starting RDMA-based incoming migration\n");
3199 rdma = qemu_rdma_data_init(host_port, &local_err);
3200
3201 if (rdma == NULL) {
3202 goto err;
3203 }
3204
3205 ret = qemu_rdma_dest_init(rdma, &local_err);
3206
3207 if (ret) {
3208 goto err;
3209 }
3210
3211 DPRINTF("qemu_rdma_dest_init success\n");
3212
3213 ret = rdma_listen(rdma->listen_id, 5);
3214
3215 if (ret) {
66988941 3216 ERROR(errp, "listening on socket!");
2da776db
MH
3217 goto err;
3218 }
3219
3220 DPRINTF("rdma_listen success\n");
3221
3222 qemu_set_fd_handler2(rdma->channel->fd, NULL,
3223 rdma_accept_incoming_migration, NULL,
3224 (void *)(intptr_t) rdma);
3225 return;
3226err:
3227 error_propagate(errp, local_err);
3228 g_free(rdma);
3229}
3230
3231void rdma_start_outgoing_migration(void *opaque,
3232 const char *host_port, Error **errp)
3233{
3234 MigrationState *s = opaque;
3235 Error *local_err = NULL, **temp = &local_err;
3236 RDMAContext *rdma = qemu_rdma_data_init(host_port, &local_err);
3237 int ret = 0;
3238
3239 if (rdma == NULL) {
66988941 3240 ERROR(temp, "Failed to initialize RDMA data structures! %d", ret);
2da776db
MH
3241 goto err;
3242 }
3243
3244 ret = qemu_rdma_source_init(rdma, &local_err,
3245 s->enabled_capabilities[MIGRATION_CAPABILITY_X_RDMA_PIN_ALL]);
3246
3247 if (ret) {
3248 goto err;
3249 }
3250
3251 DPRINTF("qemu_rdma_source_init success\n");
3252 ret = qemu_rdma_connect(rdma, &local_err);
3253
3254 if (ret) {
3255 goto err;
3256 }
3257
3258 DPRINTF("qemu_rdma_source_connect success\n");
3259
3260 s->file = qemu_fopen_rdma(rdma, "wb");
3261 migrate_fd_connect(s);
3262 return;
3263err:
3264 error_propagate(errp, local_err);
3265 g_free(rdma);
3266 migrate_fd_error(s);
3267}