migration/rdma: Silence qemu_rdma_resolve_host()
[qemu/armbru.git] / migration / rdma.c
blob3c7a407d25071608b2273ae3d0f57d777303032f
1 /*
2 * RDMA protocol and interfaces
4 * Copyright IBM, Corp. 2010-2013
5 * Copyright Red Hat, Inc. 2015-2016
7 * Authors:
8 * Michael R. Hines <mrhines@us.ibm.com>
9 * Jiuxing Liu <jl@us.ibm.com>
10 * Daniel P. Berrange <berrange@redhat.com>
12 * This work is licensed under the terms of the GNU GPL, version 2 or
13 * later. See the COPYING file in the top-level directory.
17 #include "qemu/osdep.h"
18 #include "qapi/error.h"
19 #include "qemu/cutils.h"
20 #include "exec/target_page.h"
21 #include "rdma.h"
22 #include "migration.h"
23 #include "migration-stats.h"
24 #include "qemu-file.h"
25 #include "ram.h"
26 #include "qemu/error-report.h"
27 #include "qemu/main-loop.h"
28 #include "qemu/module.h"
29 #include "qemu/rcu.h"
30 #include "qemu/sockets.h"
31 #include "qemu/bitmap.h"
32 #include "qemu/coroutine.h"
33 #include "exec/memory.h"
34 #include <sys/socket.h>
35 #include <netdb.h>
36 #include <arpa/inet.h>
37 #include <rdma/rdma_cma.h>
38 #include "trace.h"
39 #include "qom/object.h"
40 #include "options.h"
41 #include <poll.h>
43 #define RDMA_RESOLVE_TIMEOUT_MS 10000
45 /* Do not merge data if larger than this. */
46 #define RDMA_MERGE_MAX (2 * 1024 * 1024)
47 #define RDMA_SIGNALED_SEND_MAX (RDMA_MERGE_MAX / 4096)
49 #define RDMA_REG_CHUNK_SHIFT 20 /* 1 MB */
52 * This is only for non-live state being migrated.
53 * Instead of RDMA_WRITE messages, we use RDMA_SEND
54 * messages for that state, which requires a different
55 * delivery design than main memory.
57 #define RDMA_SEND_INCREMENT 32768
60 * Maximum size infiniband SEND message
62 #define RDMA_CONTROL_MAX_BUFFER (512 * 1024)
63 #define RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE 4096
65 #define RDMA_CONTROL_VERSION_CURRENT 1
67 * Capabilities for negotiation.
69 #define RDMA_CAPABILITY_PIN_ALL 0x01
72 * Add the other flags above to this list of known capabilities
73 * as they are introduced.
75 static uint32_t known_capabilities = RDMA_CAPABILITY_PIN_ALL;
78 * A work request ID is 64-bits and we split up these bits
79 * into 3 parts:
81 * bits 0-15 : type of control message, 2^16
82 * bits 16-29: ram block index, 2^14
83 * bits 30-63: ram block chunk number, 2^34
85 * The last two bit ranges are only used for RDMA writes,
86 * in order to track their completion and potentially
87 * also track unregistration status of the message.
89 #define RDMA_WRID_TYPE_SHIFT 0UL
90 #define RDMA_WRID_BLOCK_SHIFT 16UL
91 #define RDMA_WRID_CHUNK_SHIFT 30UL
93 #define RDMA_WRID_TYPE_MASK \
94 ((1UL << RDMA_WRID_BLOCK_SHIFT) - 1UL)
96 #define RDMA_WRID_BLOCK_MASK \
97 (~RDMA_WRID_TYPE_MASK & ((1UL << RDMA_WRID_CHUNK_SHIFT) - 1UL))
99 #define RDMA_WRID_CHUNK_MASK (~RDMA_WRID_BLOCK_MASK & ~RDMA_WRID_TYPE_MASK)
102 * RDMA migration protocol:
103 * 1. RDMA Writes (data messages, i.e. RAM)
104 * 2. IB Send/Recv (control channel messages)
106 enum {
107 RDMA_WRID_NONE = 0,
108 RDMA_WRID_RDMA_WRITE = 1,
109 RDMA_WRID_SEND_CONTROL = 2000,
110 RDMA_WRID_RECV_CONTROL = 4000,
114 * Work request IDs for IB SEND messages only (not RDMA writes).
115 * This is used by the migration protocol to transmit
116 * control messages (such as device state and registration commands)
118 * We could use more WRs, but we have enough for now.
120 enum {
121 RDMA_WRID_READY = 0,
122 RDMA_WRID_DATA,
123 RDMA_WRID_CONTROL,
124 RDMA_WRID_MAX,
128 * SEND/RECV IB Control Messages.
130 enum {
131 RDMA_CONTROL_NONE = 0,
132 RDMA_CONTROL_ERROR,
133 RDMA_CONTROL_READY, /* ready to receive */
134 RDMA_CONTROL_QEMU_FILE, /* QEMUFile-transmitted bytes */
135 RDMA_CONTROL_RAM_BLOCKS_REQUEST, /* RAMBlock synchronization */
136 RDMA_CONTROL_RAM_BLOCKS_RESULT, /* RAMBlock synchronization */
137 RDMA_CONTROL_COMPRESS, /* page contains repeat values */
138 RDMA_CONTROL_REGISTER_REQUEST, /* dynamic page registration */
139 RDMA_CONTROL_REGISTER_RESULT, /* key to use after registration */
140 RDMA_CONTROL_REGISTER_FINISHED, /* current iteration finished */
141 RDMA_CONTROL_UNREGISTER_REQUEST, /* dynamic UN-registration */
142 RDMA_CONTROL_UNREGISTER_FINISHED, /* unpinning finished */
147 * Memory and MR structures used to represent an IB Send/Recv work request.
148 * This is *not* used for RDMA writes, only IB Send/Recv.
150 typedef struct {
151 uint8_t control[RDMA_CONTROL_MAX_BUFFER]; /* actual buffer to register */
152 struct ibv_mr *control_mr; /* registration metadata */
153 size_t control_len; /* length of the message */
154 uint8_t *control_curr; /* start of unconsumed bytes */
155 } RDMAWorkRequestData;
158 * Negotiate RDMA capabilities during connection-setup time.
160 typedef struct {
161 uint32_t version;
162 uint32_t flags;
163 } RDMACapabilities;
165 static void caps_to_network(RDMACapabilities *cap)
167 cap->version = htonl(cap->version);
168 cap->flags = htonl(cap->flags);
171 static void network_to_caps(RDMACapabilities *cap)
173 cap->version = ntohl(cap->version);
174 cap->flags = ntohl(cap->flags);
178 * Representation of a RAMBlock from an RDMA perspective.
179 * This is not transmitted, only local.
180 * This and subsequent structures cannot be linked lists
181 * because we're using a single IB message to transmit
182 * the information. It's small anyway, so a list is overkill.
184 typedef struct RDMALocalBlock {
185 char *block_name;
186 uint8_t *local_host_addr; /* local virtual address */
187 uint64_t remote_host_addr; /* remote virtual address */
188 uint64_t offset;
189 uint64_t length;
190 struct ibv_mr **pmr; /* MRs for chunk-level registration */
191 struct ibv_mr *mr; /* MR for non-chunk-level registration */
192 uint32_t *remote_keys; /* rkeys for chunk-level registration */
193 uint32_t remote_rkey; /* rkeys for non-chunk-level registration */
194 int index; /* which block are we */
195 unsigned int src_index; /* (Only used on dest) */
196 bool is_ram_block;
197 int nb_chunks;
198 unsigned long *transit_bitmap;
199 unsigned long *unregister_bitmap;
200 } RDMALocalBlock;
203 * Also represents a RAMblock, but only on the dest.
204 * This gets transmitted by the dest during connection-time
205 * to the source VM and then is used to populate the
206 * corresponding RDMALocalBlock with
207 * the information needed to perform the actual RDMA.
209 typedef struct QEMU_PACKED RDMADestBlock {
210 uint64_t remote_host_addr;
211 uint64_t offset;
212 uint64_t length;
213 uint32_t remote_rkey;
214 uint32_t padding;
215 } RDMADestBlock;
217 static const char *control_desc(unsigned int rdma_control)
219 static const char *strs[] = {
220 [RDMA_CONTROL_NONE] = "NONE",
221 [RDMA_CONTROL_ERROR] = "ERROR",
222 [RDMA_CONTROL_READY] = "READY",
223 [RDMA_CONTROL_QEMU_FILE] = "QEMU FILE",
224 [RDMA_CONTROL_RAM_BLOCKS_REQUEST] = "RAM BLOCKS REQUEST",
225 [RDMA_CONTROL_RAM_BLOCKS_RESULT] = "RAM BLOCKS RESULT",
226 [RDMA_CONTROL_COMPRESS] = "COMPRESS",
227 [RDMA_CONTROL_REGISTER_REQUEST] = "REGISTER REQUEST",
228 [RDMA_CONTROL_REGISTER_RESULT] = "REGISTER RESULT",
229 [RDMA_CONTROL_REGISTER_FINISHED] = "REGISTER FINISHED",
230 [RDMA_CONTROL_UNREGISTER_REQUEST] = "UNREGISTER REQUEST",
231 [RDMA_CONTROL_UNREGISTER_FINISHED] = "UNREGISTER FINISHED",
234 if (rdma_control > RDMA_CONTROL_UNREGISTER_FINISHED) {
235 return "??BAD CONTROL VALUE??";
238 return strs[rdma_control];
241 static uint64_t htonll(uint64_t v)
243 union { uint32_t lv[2]; uint64_t llv; } u;
244 u.lv[0] = htonl(v >> 32);
245 u.lv[1] = htonl(v & 0xFFFFFFFFULL);
246 return u.llv;
249 static uint64_t ntohll(uint64_t v)
251 union { uint32_t lv[2]; uint64_t llv; } u;
252 u.llv = v;
253 return ((uint64_t)ntohl(u.lv[0]) << 32) | (uint64_t) ntohl(u.lv[1]);
256 static void dest_block_to_network(RDMADestBlock *db)
258 db->remote_host_addr = htonll(db->remote_host_addr);
259 db->offset = htonll(db->offset);
260 db->length = htonll(db->length);
261 db->remote_rkey = htonl(db->remote_rkey);
264 static void network_to_dest_block(RDMADestBlock *db)
266 db->remote_host_addr = ntohll(db->remote_host_addr);
267 db->offset = ntohll(db->offset);
268 db->length = ntohll(db->length);
269 db->remote_rkey = ntohl(db->remote_rkey);
273 * Virtual address of the above structures used for transmitting
274 * the RAMBlock descriptions at connection-time.
275 * This structure is *not* transmitted.
277 typedef struct RDMALocalBlocks {
278 int nb_blocks;
279 bool init; /* main memory init complete */
280 RDMALocalBlock *block;
281 } RDMALocalBlocks;
284 * Main data structure for RDMA state.
285 * While there is only one copy of this structure being allocated right now,
286 * this is the place where one would start if you wanted to consider
287 * having more than one RDMA connection open at the same time.
289 typedef struct RDMAContext {
290 char *host;
291 int port;
292 char *host_port;
294 RDMAWorkRequestData wr_data[RDMA_WRID_MAX];
297 * This is used by *_exchange_send() to figure out whether or not
298 * the initial "READY" message has already been received or not.
299 * This is because other functions may potentially poll() and detect
300 * the READY message before send() does, in which case we need to
301 * know if it completed.
303 int control_ready_expected;
305 /* number of outstanding writes */
306 int nb_sent;
308 /* store info about current buffer so that we can
309 merge it with future sends */
310 uint64_t current_addr;
311 uint64_t current_length;
312 /* index of ram block the current buffer belongs to */
313 int current_index;
314 /* index of the chunk in the current ram block */
315 int current_chunk;
317 bool pin_all;
320 * infiniband-specific variables for opening the device
321 * and maintaining connection state and so forth.
323 * cm_id also has ibv_context, rdma_event_channel, and ibv_qp in
324 * cm_id->verbs, cm_id->channel, and cm_id->qp.
326 struct rdma_cm_id *cm_id; /* connection manager ID */
327 struct rdma_cm_id *listen_id;
328 bool connected;
330 struct ibv_context *verbs;
331 struct rdma_event_channel *channel;
332 struct ibv_qp *qp; /* queue pair */
333 struct ibv_comp_channel *recv_comp_channel; /* recv completion channel */
334 struct ibv_comp_channel *send_comp_channel; /* send completion channel */
335 struct ibv_pd *pd; /* protection domain */
336 struct ibv_cq *recv_cq; /* recvieve completion queue */
337 struct ibv_cq *send_cq; /* send completion queue */
340 * If a previous write failed (perhaps because of a failed
341 * memory registration, then do not attempt any future work
342 * and remember the error state.
344 bool errored;
345 bool error_reported;
346 bool received_error;
349 * Description of ram blocks used throughout the code.
351 RDMALocalBlocks local_ram_blocks;
352 RDMADestBlock *dest_blocks;
354 /* Index of the next RAMBlock received during block registration */
355 unsigned int next_src_index;
358 * Migration on *destination* started.
359 * Then use coroutine yield function.
360 * Source runs in a thread, so we don't care.
362 int migration_started_on_destination;
364 int total_registrations;
365 int total_writes;
367 int unregister_current, unregister_next;
368 uint64_t unregistrations[RDMA_SIGNALED_SEND_MAX];
370 GHashTable *blockmap;
372 /* the RDMAContext for return path */
373 struct RDMAContext *return_path;
374 bool is_return_path;
375 } RDMAContext;
377 #define TYPE_QIO_CHANNEL_RDMA "qio-channel-rdma"
378 OBJECT_DECLARE_SIMPLE_TYPE(QIOChannelRDMA, QIO_CHANNEL_RDMA)
382 struct QIOChannelRDMA {
383 QIOChannel parent;
384 RDMAContext *rdmain;
385 RDMAContext *rdmaout;
386 QEMUFile *file;
387 bool blocking; /* XXX we don't actually honour this yet */
391 * Main structure for IB Send/Recv control messages.
392 * This gets prepended at the beginning of every Send/Recv.
394 typedef struct QEMU_PACKED {
395 uint32_t len; /* Total length of data portion */
396 uint32_t type; /* which control command to perform */
397 uint32_t repeat; /* number of commands in data portion of same type */
398 uint32_t padding;
399 } RDMAControlHeader;
401 static void control_to_network(RDMAControlHeader *control)
403 control->type = htonl(control->type);
404 control->len = htonl(control->len);
405 control->repeat = htonl(control->repeat);
408 static void network_to_control(RDMAControlHeader *control)
410 control->type = ntohl(control->type);
411 control->len = ntohl(control->len);
412 control->repeat = ntohl(control->repeat);
416 * Register a single Chunk.
417 * Information sent by the source VM to inform the dest
418 * to register an single chunk of memory before we can perform
419 * the actual RDMA operation.
421 typedef struct QEMU_PACKED {
422 union QEMU_PACKED {
423 uint64_t current_addr; /* offset into the ram_addr_t space */
424 uint64_t chunk; /* chunk to lookup if unregistering */
425 } key;
426 uint32_t current_index; /* which ramblock the chunk belongs to */
427 uint32_t padding;
428 uint64_t chunks; /* how many sequential chunks to register */
429 } RDMARegister;
431 static bool rdma_errored(RDMAContext *rdma)
433 if (rdma->errored && !rdma->error_reported) {
434 error_report("RDMA is in an error state waiting migration"
435 " to abort!");
436 rdma->error_reported = true;
438 return rdma->errored;
441 static void register_to_network(RDMAContext *rdma, RDMARegister *reg)
443 RDMALocalBlock *local_block;
444 local_block = &rdma->local_ram_blocks.block[reg->current_index];
446 if (local_block->is_ram_block) {
448 * current_addr as passed in is an address in the local ram_addr_t
449 * space, we need to translate this for the destination
451 reg->key.current_addr -= local_block->offset;
452 reg->key.current_addr += rdma->dest_blocks[reg->current_index].offset;
454 reg->key.current_addr = htonll(reg->key.current_addr);
455 reg->current_index = htonl(reg->current_index);
456 reg->chunks = htonll(reg->chunks);
459 static void network_to_register(RDMARegister *reg)
461 reg->key.current_addr = ntohll(reg->key.current_addr);
462 reg->current_index = ntohl(reg->current_index);
463 reg->chunks = ntohll(reg->chunks);
466 typedef struct QEMU_PACKED {
467 uint32_t value; /* if zero, we will madvise() */
468 uint32_t block_idx; /* which ram block index */
469 uint64_t offset; /* Address in remote ram_addr_t space */
470 uint64_t length; /* length of the chunk */
471 } RDMACompress;
473 static void compress_to_network(RDMAContext *rdma, RDMACompress *comp)
475 comp->value = htonl(comp->value);
477 * comp->offset as passed in is an address in the local ram_addr_t
478 * space, we need to translate this for the destination
480 comp->offset -= rdma->local_ram_blocks.block[comp->block_idx].offset;
481 comp->offset += rdma->dest_blocks[comp->block_idx].offset;
482 comp->block_idx = htonl(comp->block_idx);
483 comp->offset = htonll(comp->offset);
484 comp->length = htonll(comp->length);
487 static void network_to_compress(RDMACompress *comp)
489 comp->value = ntohl(comp->value);
490 comp->block_idx = ntohl(comp->block_idx);
491 comp->offset = ntohll(comp->offset);
492 comp->length = ntohll(comp->length);
496 * The result of the dest's memory registration produces an "rkey"
497 * which the source VM must reference in order to perform
498 * the RDMA operation.
500 typedef struct QEMU_PACKED {
501 uint32_t rkey;
502 uint32_t padding;
503 uint64_t host_addr;
504 } RDMARegisterResult;
506 static void result_to_network(RDMARegisterResult *result)
508 result->rkey = htonl(result->rkey);
509 result->host_addr = htonll(result->host_addr);
512 static void network_to_result(RDMARegisterResult *result)
514 result->rkey = ntohl(result->rkey);
515 result->host_addr = ntohll(result->host_addr);
518 static int qemu_rdma_exchange_send(RDMAContext *rdma, RDMAControlHeader *head,
519 uint8_t *data, RDMAControlHeader *resp,
520 int *resp_idx,
521 int (*callback)(RDMAContext *rdma,
522 Error **errp),
523 Error **errp);
525 static inline uint64_t ram_chunk_index(const uint8_t *start,
526 const uint8_t *host)
528 return ((uintptr_t) host - (uintptr_t) start) >> RDMA_REG_CHUNK_SHIFT;
531 static inline uint8_t *ram_chunk_start(const RDMALocalBlock *rdma_ram_block,
532 uint64_t i)
534 return (uint8_t *)(uintptr_t)(rdma_ram_block->local_host_addr +
535 (i << RDMA_REG_CHUNK_SHIFT));
538 static inline uint8_t *ram_chunk_end(const RDMALocalBlock *rdma_ram_block,
539 uint64_t i)
541 uint8_t *result = ram_chunk_start(rdma_ram_block, i) +
542 (1UL << RDMA_REG_CHUNK_SHIFT);
544 if (result > (rdma_ram_block->local_host_addr + rdma_ram_block->length)) {
545 result = rdma_ram_block->local_host_addr + rdma_ram_block->length;
548 return result;
551 static void rdma_add_block(RDMAContext *rdma, const char *block_name,
552 void *host_addr,
553 ram_addr_t block_offset, uint64_t length)
555 RDMALocalBlocks *local = &rdma->local_ram_blocks;
556 RDMALocalBlock *block;
557 RDMALocalBlock *old = local->block;
559 local->block = g_new0(RDMALocalBlock, local->nb_blocks + 1);
561 if (local->nb_blocks) {
562 int x;
564 if (rdma->blockmap) {
565 for (x = 0; x < local->nb_blocks; x++) {
566 g_hash_table_remove(rdma->blockmap,
567 (void *)(uintptr_t)old[x].offset);
568 g_hash_table_insert(rdma->blockmap,
569 (void *)(uintptr_t)old[x].offset,
570 &local->block[x]);
573 memcpy(local->block, old, sizeof(RDMALocalBlock) * local->nb_blocks);
574 g_free(old);
577 block = &local->block[local->nb_blocks];
579 block->block_name = g_strdup(block_name);
580 block->local_host_addr = host_addr;
581 block->offset = block_offset;
582 block->length = length;
583 block->index = local->nb_blocks;
584 block->src_index = ~0U; /* Filled in by the receipt of the block list */
585 block->nb_chunks = ram_chunk_index(host_addr, host_addr + length) + 1UL;
586 block->transit_bitmap = bitmap_new(block->nb_chunks);
587 bitmap_clear(block->transit_bitmap, 0, block->nb_chunks);
588 block->unregister_bitmap = bitmap_new(block->nb_chunks);
589 bitmap_clear(block->unregister_bitmap, 0, block->nb_chunks);
590 block->remote_keys = g_new0(uint32_t, block->nb_chunks);
592 block->is_ram_block = local->init ? false : true;
594 if (rdma->blockmap) {
595 g_hash_table_insert(rdma->blockmap, (void *)(uintptr_t)block_offset, block);
598 trace_rdma_add_block(block_name, local->nb_blocks,
599 (uintptr_t) block->local_host_addr,
600 block->offset, block->length,
601 (uintptr_t) (block->local_host_addr + block->length),
602 BITS_TO_LONGS(block->nb_chunks) *
603 sizeof(unsigned long) * 8,
604 block->nb_chunks);
606 local->nb_blocks++;
610 * Memory regions need to be registered with the device and queue pairs setup
611 * in advanced before the migration starts. This tells us where the RAM blocks
612 * are so that we can register them individually.
614 static int qemu_rdma_init_one_block(RAMBlock *rb, void *opaque)
616 const char *block_name = qemu_ram_get_idstr(rb);
617 void *host_addr = qemu_ram_get_host_addr(rb);
618 ram_addr_t block_offset = qemu_ram_get_offset(rb);
619 ram_addr_t length = qemu_ram_get_used_length(rb);
620 rdma_add_block(opaque, block_name, host_addr, block_offset, length);
621 return 0;
625 * Identify the RAMBlocks and their quantity. They will be references to
626 * identify chunk boundaries inside each RAMBlock and also be referenced
627 * during dynamic page registration.
629 static void qemu_rdma_init_ram_blocks(RDMAContext *rdma)
631 RDMALocalBlocks *local = &rdma->local_ram_blocks;
632 int ret;
634 assert(rdma->blockmap == NULL);
635 memset(local, 0, sizeof *local);
636 ret = foreach_not_ignored_block(qemu_rdma_init_one_block, rdma);
637 assert(!ret);
638 trace_qemu_rdma_init_ram_blocks(local->nb_blocks);
639 rdma->dest_blocks = g_new0(RDMADestBlock,
640 rdma->local_ram_blocks.nb_blocks);
641 local->init = true;
645 * Note: If used outside of cleanup, the caller must ensure that the destination
646 * block structures are also updated
648 static void rdma_delete_block(RDMAContext *rdma, RDMALocalBlock *block)
650 RDMALocalBlocks *local = &rdma->local_ram_blocks;
651 RDMALocalBlock *old = local->block;
652 int x;
654 if (rdma->blockmap) {
655 g_hash_table_remove(rdma->blockmap, (void *)(uintptr_t)block->offset);
657 if (block->pmr) {
658 int j;
660 for (j = 0; j < block->nb_chunks; j++) {
661 if (!block->pmr[j]) {
662 continue;
664 ibv_dereg_mr(block->pmr[j]);
665 rdma->total_registrations--;
667 g_free(block->pmr);
668 block->pmr = NULL;
671 if (block->mr) {
672 ibv_dereg_mr(block->mr);
673 rdma->total_registrations--;
674 block->mr = NULL;
677 g_free(block->transit_bitmap);
678 block->transit_bitmap = NULL;
680 g_free(block->unregister_bitmap);
681 block->unregister_bitmap = NULL;
683 g_free(block->remote_keys);
684 block->remote_keys = NULL;
686 g_free(block->block_name);
687 block->block_name = NULL;
689 if (rdma->blockmap) {
690 for (x = 0; x < local->nb_blocks; x++) {
691 g_hash_table_remove(rdma->blockmap,
692 (void *)(uintptr_t)old[x].offset);
696 if (local->nb_blocks > 1) {
698 local->block = g_new0(RDMALocalBlock, local->nb_blocks - 1);
700 if (block->index) {
701 memcpy(local->block, old, sizeof(RDMALocalBlock) * block->index);
704 if (block->index < (local->nb_blocks - 1)) {
705 memcpy(local->block + block->index, old + (block->index + 1),
706 sizeof(RDMALocalBlock) *
707 (local->nb_blocks - (block->index + 1)));
708 for (x = block->index; x < local->nb_blocks - 1; x++) {
709 local->block[x].index--;
712 } else {
713 assert(block == local->block);
714 local->block = NULL;
717 trace_rdma_delete_block(block, (uintptr_t)block->local_host_addr,
718 block->offset, block->length,
719 (uintptr_t)(block->local_host_addr + block->length),
720 BITS_TO_LONGS(block->nb_chunks) *
721 sizeof(unsigned long) * 8, block->nb_chunks);
723 g_free(old);
725 local->nb_blocks--;
727 if (local->nb_blocks && rdma->blockmap) {
728 for (x = 0; x < local->nb_blocks; x++) {
729 g_hash_table_insert(rdma->blockmap,
730 (void *)(uintptr_t)local->block[x].offset,
731 &local->block[x]);
737 * Put in the log file which RDMA device was opened and the details
738 * associated with that device.
740 static void qemu_rdma_dump_id(const char *who, struct ibv_context *verbs)
742 struct ibv_port_attr port;
744 if (ibv_query_port(verbs, 1, &port)) {
745 error_report("Failed to query port information");
746 return;
749 printf("%s RDMA Device opened: kernel name %s "
750 "uverbs device name %s, "
751 "infiniband_verbs class device path %s, "
752 "infiniband class device path %s, "
753 "transport: (%d) %s\n",
754 who,
755 verbs->device->name,
756 verbs->device->dev_name,
757 verbs->device->dev_path,
758 verbs->device->ibdev_path,
759 port.link_layer,
760 (port.link_layer == IBV_LINK_LAYER_INFINIBAND) ? "Infiniband" :
761 ((port.link_layer == IBV_LINK_LAYER_ETHERNET)
762 ? "Ethernet" : "Unknown"));
766 * Put in the log file the RDMA gid addressing information,
767 * useful for folks who have trouble understanding the
768 * RDMA device hierarchy in the kernel.
770 static void qemu_rdma_dump_gid(const char *who, struct rdma_cm_id *id)
772 char sgid[33];
773 char dgid[33];
774 inet_ntop(AF_INET6, &id->route.addr.addr.ibaddr.sgid, sgid, sizeof sgid);
775 inet_ntop(AF_INET6, &id->route.addr.addr.ibaddr.dgid, dgid, sizeof dgid);
776 trace_qemu_rdma_dump_gid(who, sgid, dgid);
780 * As of now, IPv6 over RoCE / iWARP is not supported by linux.
781 * We will try the next addrinfo struct, and fail if there are
782 * no other valid addresses to bind against.
784 * If user is listening on '[::]', then we will not have a opened a device
785 * yet and have no way of verifying if the device is RoCE or not.
787 * In this case, the source VM will throw an error for ALL types of
788 * connections (both IPv4 and IPv6) if the destination machine does not have
789 * a regular infiniband network available for use.
791 * The only way to guarantee that an error is thrown for broken kernels is
792 * for the management software to choose a *specific* interface at bind time
793 * and validate what time of hardware it is.
795 * Unfortunately, this puts the user in a fix:
797 * If the source VM connects with an IPv4 address without knowing that the
798 * destination has bound to '[::]' the migration will unconditionally fail
799 * unless the management software is explicitly listening on the IPv4
800 * address while using a RoCE-based device.
802 * If the source VM connects with an IPv6 address, then we're OK because we can
803 * throw an error on the source (and similarly on the destination).
805 * But in mixed environments, this will be broken for a while until it is fixed
806 * inside linux.
808 * We do provide a *tiny* bit of help in this function: We can list all of the
809 * devices in the system and check to see if all the devices are RoCE or
810 * Infiniband.
812 * If we detect that we have a *pure* RoCE environment, then we can safely
813 * thrown an error even if the management software has specified '[::]' as the
814 * bind address.
816 * However, if there is are multiple hetergeneous devices, then we cannot make
817 * this assumption and the user just has to be sure they know what they are
818 * doing.
820 * Patches are being reviewed on linux-rdma.
822 static int qemu_rdma_broken_ipv6_kernel(struct ibv_context *verbs, Error **errp)
824 /* This bug only exists in linux, to our knowledge. */
825 #ifdef CONFIG_LINUX
826 struct ibv_port_attr port_attr;
829 * Verbs are only NULL if management has bound to '[::]'.
831 * Let's iterate through all the devices and see if there any pure IB
832 * devices (non-ethernet).
834 * If not, then we can safely proceed with the migration.
835 * Otherwise, there are no guarantees until the bug is fixed in linux.
837 if (!verbs) {
838 int num_devices, x;
839 struct ibv_device **dev_list = ibv_get_device_list(&num_devices);
840 bool roce_found = false;
841 bool ib_found = false;
843 for (x = 0; x < num_devices; x++) {
844 verbs = ibv_open_device(dev_list[x]);
846 * ibv_open_device() is not documented to set errno. If
847 * it does, it's somebody else's doc bug. If it doesn't,
848 * the use of errno below is wrong.
849 * TODO Find out whether ibv_open_device() sets errno.
851 if (!verbs) {
852 if (errno == EPERM) {
853 continue;
854 } else {
855 error_setg_errno(errp, errno,
856 "could not open RDMA device context");
857 return -1;
861 if (ibv_query_port(verbs, 1, &port_attr)) {
862 ibv_close_device(verbs);
863 error_setg(errp,
864 "RDMA ERROR: Could not query initial IB port");
865 return -1;
868 if (port_attr.link_layer == IBV_LINK_LAYER_INFINIBAND) {
869 ib_found = true;
870 } else if (port_attr.link_layer == IBV_LINK_LAYER_ETHERNET) {
871 roce_found = true;
874 ibv_close_device(verbs);
878 if (roce_found) {
879 if (ib_found) {
880 fprintf(stderr, "WARN: migrations may fail:"
881 " IPv6 over RoCE / iWARP in linux"
882 " is broken. But since you appear to have a"
883 " mixed RoCE / IB environment, be sure to only"
884 " migrate over the IB fabric until the kernel "
885 " fixes the bug.\n");
886 } else {
887 error_setg(errp, "RDMA ERROR: "
888 "You only have RoCE / iWARP devices in your systems"
889 " and your management software has specified '[::]'"
890 ", but IPv6 over RoCE / iWARP is not supported in Linux.");
891 return -1;
895 return 0;
899 * If we have a verbs context, that means that some other than '[::]' was
900 * used by the management software for binding. In which case we can
901 * actually warn the user about a potentially broken kernel.
904 /* IB ports start with 1, not 0 */
905 if (ibv_query_port(verbs, 1, &port_attr)) {
906 error_setg(errp, "RDMA ERROR: Could not query initial IB port");
907 return -1;
910 if (port_attr.link_layer == IBV_LINK_LAYER_ETHERNET) {
911 error_setg(errp, "RDMA ERROR: "
912 "Linux kernel's RoCE / iWARP does not support IPv6 "
913 "(but patches on linux-rdma in progress)");
914 return -1;
917 #endif
919 return 0;
923 * Figure out which RDMA device corresponds to the requested IP hostname
924 * Also create the initial connection manager identifiers for opening
925 * the connection.
927 static int qemu_rdma_resolve_host(RDMAContext *rdma, Error **errp)
929 Error *err = NULL;
930 int ret;
931 struct rdma_addrinfo *res;
932 char port_str[16];
933 struct rdma_cm_event *cm_event;
934 char ip[40] = "unknown";
935 struct rdma_addrinfo *e;
937 if (rdma->host == NULL || !strcmp(rdma->host, "")) {
938 error_setg(errp, "RDMA ERROR: RDMA hostname has not been set");
939 return -1;
942 /* create CM channel */
943 rdma->channel = rdma_create_event_channel();
944 if (!rdma->channel) {
945 error_setg(errp, "RDMA ERROR: could not create CM channel");
946 return -1;
949 /* create CM id */
950 ret = rdma_create_id(rdma->channel, &rdma->cm_id, NULL, RDMA_PS_TCP);
951 if (ret < 0) {
952 error_setg(errp, "RDMA ERROR: could not create channel id");
953 goto err_resolve_create_id;
956 snprintf(port_str, 16, "%d", rdma->port);
957 port_str[15] = '\0';
959 ret = rdma_getaddrinfo(rdma->host, port_str, NULL, &res);
960 if (ret) {
961 error_setg(errp, "RDMA ERROR: could not rdma_getaddrinfo address %s",
962 rdma->host);
963 goto err_resolve_get_addr;
966 /* Try all addresses, saving the first error in @err */
967 for (e = res; e != NULL; e = e->ai_next) {
968 Error **local_errp = err ? NULL : &err;
970 inet_ntop(e->ai_family,
971 &((struct sockaddr_in *) e->ai_dst_addr)->sin_addr, ip, sizeof ip);
972 trace_qemu_rdma_resolve_host_trying(rdma->host, ip);
974 ret = rdma_resolve_addr(rdma->cm_id, NULL, e->ai_dst_addr,
975 RDMA_RESOLVE_TIMEOUT_MS);
976 if (ret >= 0) {
977 if (e->ai_family == AF_INET6) {
978 ret = qemu_rdma_broken_ipv6_kernel(rdma->cm_id->verbs,
979 local_errp);
980 if (ret < 0) {
981 continue;
984 error_free(err);
985 goto route;
989 rdma_freeaddrinfo(res);
990 if (err) {
991 error_propagate(errp, err);
992 } else {
993 error_setg(errp, "RDMA ERROR: could not resolve address %s",
994 rdma->host);
996 goto err_resolve_get_addr;
998 route:
999 rdma_freeaddrinfo(res);
1000 qemu_rdma_dump_gid("source_resolve_addr", rdma->cm_id);
1002 ret = rdma_get_cm_event(rdma->channel, &cm_event);
1003 if (ret < 0) {
1004 error_setg(errp, "RDMA ERROR: could not perform event_addr_resolved");
1005 goto err_resolve_get_addr;
1008 if (cm_event->event != RDMA_CM_EVENT_ADDR_RESOLVED) {
1009 error_setg(errp,
1010 "RDMA ERROR: result not equal to event_addr_resolved %s",
1011 rdma_event_str(cm_event->event));
1012 rdma_ack_cm_event(cm_event);
1013 goto err_resolve_get_addr;
1015 rdma_ack_cm_event(cm_event);
1017 /* resolve route */
1018 ret = rdma_resolve_route(rdma->cm_id, RDMA_RESOLVE_TIMEOUT_MS);
1019 if (ret < 0) {
1020 error_setg(errp, "RDMA ERROR: could not resolve rdma route");
1021 goto err_resolve_get_addr;
1024 ret = rdma_get_cm_event(rdma->channel, &cm_event);
1025 if (ret < 0) {
1026 error_setg(errp, "RDMA ERROR: could not perform event_route_resolved");
1027 goto err_resolve_get_addr;
1029 if (cm_event->event != RDMA_CM_EVENT_ROUTE_RESOLVED) {
1030 error_setg(errp, "RDMA ERROR: "
1031 "result not equal to event_route_resolved: %s",
1032 rdma_event_str(cm_event->event));
1033 rdma_ack_cm_event(cm_event);
1034 goto err_resolve_get_addr;
1036 rdma_ack_cm_event(cm_event);
1037 rdma->verbs = rdma->cm_id->verbs;
1038 qemu_rdma_dump_id("source_resolve_host", rdma->cm_id->verbs);
1039 qemu_rdma_dump_gid("source_resolve_host", rdma->cm_id);
1040 return 0;
1042 err_resolve_get_addr:
1043 rdma_destroy_id(rdma->cm_id);
1044 rdma->cm_id = NULL;
1045 err_resolve_create_id:
1046 rdma_destroy_event_channel(rdma->channel);
1047 rdma->channel = NULL;
1048 return -1;
1052 * Create protection domain and completion queues
1054 static int qemu_rdma_alloc_pd_cq(RDMAContext *rdma, Error **errp)
1056 /* allocate pd */
1057 rdma->pd = ibv_alloc_pd(rdma->verbs);
1058 if (!rdma->pd) {
1059 error_setg(errp, "failed to allocate protection domain");
1060 return -1;
1063 /* create receive completion channel */
1064 rdma->recv_comp_channel = ibv_create_comp_channel(rdma->verbs);
1065 if (!rdma->recv_comp_channel) {
1066 error_setg(errp, "failed to allocate receive completion channel");
1067 goto err_alloc_pd_cq;
1071 * Completion queue can be filled by read work requests.
1073 rdma->recv_cq = ibv_create_cq(rdma->verbs, (RDMA_SIGNALED_SEND_MAX * 3),
1074 NULL, rdma->recv_comp_channel, 0);
1075 if (!rdma->recv_cq) {
1076 error_setg(errp, "failed to allocate receive completion queue");
1077 goto err_alloc_pd_cq;
1080 /* create send completion channel */
1081 rdma->send_comp_channel = ibv_create_comp_channel(rdma->verbs);
1082 if (!rdma->send_comp_channel) {
1083 error_setg(errp, "failed to allocate send completion channel");
1084 goto err_alloc_pd_cq;
1087 rdma->send_cq = ibv_create_cq(rdma->verbs, (RDMA_SIGNALED_SEND_MAX * 3),
1088 NULL, rdma->send_comp_channel, 0);
1089 if (!rdma->send_cq) {
1090 error_setg(errp, "failed to allocate send completion queue");
1091 goto err_alloc_pd_cq;
1094 return 0;
1096 err_alloc_pd_cq:
1097 if (rdma->pd) {
1098 ibv_dealloc_pd(rdma->pd);
1100 if (rdma->recv_comp_channel) {
1101 ibv_destroy_comp_channel(rdma->recv_comp_channel);
1103 if (rdma->send_comp_channel) {
1104 ibv_destroy_comp_channel(rdma->send_comp_channel);
1106 if (rdma->recv_cq) {
1107 ibv_destroy_cq(rdma->recv_cq);
1108 rdma->recv_cq = NULL;
1110 rdma->pd = NULL;
1111 rdma->recv_comp_channel = NULL;
1112 rdma->send_comp_channel = NULL;
1113 return -1;
1118 * Create queue pairs.
1120 static int qemu_rdma_alloc_qp(RDMAContext *rdma)
1122 struct ibv_qp_init_attr attr = { 0 };
1123 int ret;
1125 attr.cap.max_send_wr = RDMA_SIGNALED_SEND_MAX;
1126 attr.cap.max_recv_wr = 3;
1127 attr.cap.max_send_sge = 1;
1128 attr.cap.max_recv_sge = 1;
1129 attr.send_cq = rdma->send_cq;
1130 attr.recv_cq = rdma->recv_cq;
1131 attr.qp_type = IBV_QPT_RC;
1133 ret = rdma_create_qp(rdma->cm_id, rdma->pd, &attr);
1134 if (ret < 0) {
1135 return -1;
1138 rdma->qp = rdma->cm_id->qp;
1139 return 0;
1142 /* Check whether On-Demand Paging is supported by RDAM device */
1143 static bool rdma_support_odp(struct ibv_context *dev)
1145 struct ibv_device_attr_ex attr = {0};
1146 int ret = ibv_query_device_ex(dev, NULL, &attr);
1147 if (ret) {
1148 return false;
1151 if (attr.odp_caps.general_caps & IBV_ODP_SUPPORT) {
1152 return true;
1155 return false;
1159 * ibv_advise_mr to avoid RNR NAK error as far as possible.
1160 * The responder mr registering with ODP will sent RNR NAK back to
1161 * the requester in the face of the page fault.
1163 static void qemu_rdma_advise_prefetch_mr(struct ibv_pd *pd, uint64_t addr,
1164 uint32_t len, uint32_t lkey,
1165 const char *name, bool wr)
1167 #ifdef HAVE_IBV_ADVISE_MR
1168 int ret;
1169 int advice = wr ? IBV_ADVISE_MR_ADVICE_PREFETCH_WRITE :
1170 IBV_ADVISE_MR_ADVICE_PREFETCH;
1171 struct ibv_sge sg_list = {.lkey = lkey, .addr = addr, .length = len};
1173 ret = ibv_advise_mr(pd, advice,
1174 IBV_ADVISE_MR_FLAG_FLUSH, &sg_list, 1);
1175 /* ignore the error */
1176 trace_qemu_rdma_advise_mr(name, len, addr, strerror(ret));
1177 #endif
1180 static int qemu_rdma_reg_whole_ram_blocks(RDMAContext *rdma, Error **errp)
1182 int i;
1183 RDMALocalBlocks *local = &rdma->local_ram_blocks;
1185 for (i = 0; i < local->nb_blocks; i++) {
1186 int access = IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE;
1188 local->block[i].mr =
1189 ibv_reg_mr(rdma->pd,
1190 local->block[i].local_host_addr,
1191 local->block[i].length, access
1194 * ibv_reg_mr() is not documented to set errno. If it does,
1195 * it's somebody else's doc bug. If it doesn't, the use of
1196 * errno below is wrong.
1197 * TODO Find out whether ibv_reg_mr() sets errno.
1199 if (!local->block[i].mr &&
1200 errno == ENOTSUP && rdma_support_odp(rdma->verbs)) {
1201 access |= IBV_ACCESS_ON_DEMAND;
1202 /* register ODP mr */
1203 local->block[i].mr =
1204 ibv_reg_mr(rdma->pd,
1205 local->block[i].local_host_addr,
1206 local->block[i].length, access);
1207 trace_qemu_rdma_register_odp_mr(local->block[i].block_name);
1209 if (local->block[i].mr) {
1210 qemu_rdma_advise_prefetch_mr(rdma->pd,
1211 (uintptr_t)local->block[i].local_host_addr,
1212 local->block[i].length,
1213 local->block[i].mr->lkey,
1214 local->block[i].block_name,
1215 true);
1219 if (!local->block[i].mr) {
1220 error_setg_errno(errp, errno,
1221 "Failed to register local dest ram block!");
1222 goto err;
1224 rdma->total_registrations++;
1227 return 0;
1229 err:
1230 for (i--; i >= 0; i--) {
1231 ibv_dereg_mr(local->block[i].mr);
1232 local->block[i].mr = NULL;
1233 rdma->total_registrations--;
1236 return -1;
1241 * Find the ram block that corresponds to the page requested to be
1242 * transmitted by QEMU.
1244 * Once the block is found, also identify which 'chunk' within that
1245 * block that the page belongs to.
1247 static void qemu_rdma_search_ram_block(RDMAContext *rdma,
1248 uintptr_t block_offset,
1249 uint64_t offset,
1250 uint64_t length,
1251 uint64_t *block_index,
1252 uint64_t *chunk_index)
1254 uint64_t current_addr = block_offset + offset;
1255 RDMALocalBlock *block = g_hash_table_lookup(rdma->blockmap,
1256 (void *) block_offset);
1257 assert(block);
1258 assert(current_addr >= block->offset);
1259 assert((current_addr + length) <= (block->offset + block->length));
1261 *block_index = block->index;
1262 *chunk_index = ram_chunk_index(block->local_host_addr,
1263 block->local_host_addr + (current_addr - block->offset));
1267 * Register a chunk with IB. If the chunk was already registered
1268 * previously, then skip.
1270 * Also return the keys associated with the registration needed
1271 * to perform the actual RDMA operation.
1273 static int qemu_rdma_register_and_get_keys(RDMAContext *rdma,
1274 RDMALocalBlock *block, uintptr_t host_addr,
1275 uint32_t *lkey, uint32_t *rkey, int chunk,
1276 uint8_t *chunk_start, uint8_t *chunk_end)
1278 if (block->mr) {
1279 if (lkey) {
1280 *lkey = block->mr->lkey;
1282 if (rkey) {
1283 *rkey = block->mr->rkey;
1285 return 0;
1288 /* allocate memory to store chunk MRs */
1289 if (!block->pmr) {
1290 block->pmr = g_new0(struct ibv_mr *, block->nb_chunks);
1294 * If 'rkey', then we're the destination, so grant access to the source.
1296 * If 'lkey', then we're the source VM, so grant access only to ourselves.
1298 if (!block->pmr[chunk]) {
1299 uint64_t len = chunk_end - chunk_start;
1300 int access = rkey ? IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE :
1303 trace_qemu_rdma_register_and_get_keys(len, chunk_start);
1305 block->pmr[chunk] = ibv_reg_mr(rdma->pd, chunk_start, len, access);
1307 * ibv_reg_mr() is not documented to set errno. If it does,
1308 * it's somebody else's doc bug. If it doesn't, the use of
1309 * errno below is wrong.
1310 * TODO Find out whether ibv_reg_mr() sets errno.
1312 if (!block->pmr[chunk] &&
1313 errno == ENOTSUP && rdma_support_odp(rdma->verbs)) {
1314 access |= IBV_ACCESS_ON_DEMAND;
1315 /* register ODP mr */
1316 block->pmr[chunk] = ibv_reg_mr(rdma->pd, chunk_start, len, access);
1317 trace_qemu_rdma_register_odp_mr(block->block_name);
1319 if (block->pmr[chunk]) {
1320 qemu_rdma_advise_prefetch_mr(rdma->pd, (uintptr_t)chunk_start,
1321 len, block->pmr[chunk]->lkey,
1322 block->block_name, rkey);
1327 if (!block->pmr[chunk]) {
1328 perror("Failed to register chunk!");
1329 fprintf(stderr, "Chunk details: block: %d chunk index %d"
1330 " start %" PRIuPTR " end %" PRIuPTR
1331 " host %" PRIuPTR
1332 " local %" PRIuPTR " registrations: %d\n",
1333 block->index, chunk, (uintptr_t)chunk_start,
1334 (uintptr_t)chunk_end, host_addr,
1335 (uintptr_t)block->local_host_addr,
1336 rdma->total_registrations);
1337 return -1;
1339 rdma->total_registrations++;
1341 if (lkey) {
1342 *lkey = block->pmr[chunk]->lkey;
1344 if (rkey) {
1345 *rkey = block->pmr[chunk]->rkey;
1347 return 0;
1351 * Register (at connection time) the memory used for control
1352 * channel messages.
1354 static int qemu_rdma_reg_control(RDMAContext *rdma, int idx)
1356 rdma->wr_data[idx].control_mr = ibv_reg_mr(rdma->pd,
1357 rdma->wr_data[idx].control, RDMA_CONTROL_MAX_BUFFER,
1358 IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE);
1359 if (rdma->wr_data[idx].control_mr) {
1360 rdma->total_registrations++;
1361 return 0;
1363 error_report("qemu_rdma_reg_control failed");
1364 return -1;
1368 * Perform a non-optimized memory unregistration after every transfer
1369 * for demonstration purposes, only if pin-all is not requested.
1371 * Potential optimizations:
1372 * 1. Start a new thread to run this function continuously
1373 - for bit clearing
1374 - and for receipt of unregister messages
1375 * 2. Use an LRU.
1376 * 3. Use workload hints.
1378 static int qemu_rdma_unregister_waiting(RDMAContext *rdma)
1380 Error *err = NULL;
1382 while (rdma->unregistrations[rdma->unregister_current]) {
1383 int ret;
1384 uint64_t wr_id = rdma->unregistrations[rdma->unregister_current];
1385 uint64_t chunk =
1386 (wr_id & RDMA_WRID_CHUNK_MASK) >> RDMA_WRID_CHUNK_SHIFT;
1387 uint64_t index =
1388 (wr_id & RDMA_WRID_BLOCK_MASK) >> RDMA_WRID_BLOCK_SHIFT;
1389 RDMALocalBlock *block =
1390 &(rdma->local_ram_blocks.block[index]);
1391 RDMARegister reg = { .current_index = index };
1392 RDMAControlHeader resp = { .type = RDMA_CONTROL_UNREGISTER_FINISHED,
1394 RDMAControlHeader head = { .len = sizeof(RDMARegister),
1395 .type = RDMA_CONTROL_UNREGISTER_REQUEST,
1396 .repeat = 1,
1399 trace_qemu_rdma_unregister_waiting_proc(chunk,
1400 rdma->unregister_current);
1402 rdma->unregistrations[rdma->unregister_current] = 0;
1403 rdma->unregister_current++;
1405 if (rdma->unregister_current == RDMA_SIGNALED_SEND_MAX) {
1406 rdma->unregister_current = 0;
1411 * Unregistration is speculative (because migration is single-threaded
1412 * and we cannot break the protocol's inifinband message ordering).
1413 * Thus, if the memory is currently being used for transmission,
1414 * then abort the attempt to unregister and try again
1415 * later the next time a completion is received for this memory.
1417 clear_bit(chunk, block->unregister_bitmap);
1419 if (test_bit(chunk, block->transit_bitmap)) {
1420 trace_qemu_rdma_unregister_waiting_inflight(chunk);
1421 continue;
1424 trace_qemu_rdma_unregister_waiting_send(chunk);
1426 ret = ibv_dereg_mr(block->pmr[chunk]);
1427 block->pmr[chunk] = NULL;
1428 block->remote_keys[chunk] = 0;
1430 if (ret != 0) {
1432 * FIXME perror() is problematic, bcause ibv_dereg_mr() is
1433 * not documented to set errno. Will go away later in
1434 * this series.
1436 perror("unregistration chunk failed");
1437 return -1;
1439 rdma->total_registrations--;
1441 reg.key.chunk = chunk;
1442 register_to_network(rdma, &reg);
1443 ret = qemu_rdma_exchange_send(rdma, &head, (uint8_t *) &reg,
1444 &resp, NULL, NULL, &err);
1445 if (ret < 0) {
1446 error_report_err(err);
1447 return -1;
1450 trace_qemu_rdma_unregister_waiting_complete(chunk);
1453 return 0;
1456 static uint64_t qemu_rdma_make_wrid(uint64_t wr_id, uint64_t index,
1457 uint64_t chunk)
1459 uint64_t result = wr_id & RDMA_WRID_TYPE_MASK;
1461 result |= (index << RDMA_WRID_BLOCK_SHIFT);
1462 result |= (chunk << RDMA_WRID_CHUNK_SHIFT);
1464 return result;
1468 * Consult the connection manager to see a work request
1469 * (of any kind) has completed.
1470 * Return the work request ID that completed.
1472 static int qemu_rdma_poll(RDMAContext *rdma, struct ibv_cq *cq,
1473 uint64_t *wr_id_out, uint32_t *byte_len)
1475 int ret;
1476 struct ibv_wc wc;
1477 uint64_t wr_id;
1479 ret = ibv_poll_cq(cq, 1, &wc);
1481 if (!ret) {
1482 *wr_id_out = RDMA_WRID_NONE;
1483 return 0;
1486 if (ret < 0) {
1487 error_report("ibv_poll_cq failed");
1488 return -1;
1491 wr_id = wc.wr_id & RDMA_WRID_TYPE_MASK;
1493 if (wc.status != IBV_WC_SUCCESS) {
1494 fprintf(stderr, "ibv_poll_cq wc.status=%d %s!\n",
1495 wc.status, ibv_wc_status_str(wc.status));
1496 fprintf(stderr, "ibv_poll_cq wrid=%" PRIu64 "!\n", wr_id);
1498 return -1;
1501 if (rdma->control_ready_expected &&
1502 (wr_id >= RDMA_WRID_RECV_CONTROL)) {
1503 trace_qemu_rdma_poll_recv(wr_id - RDMA_WRID_RECV_CONTROL, wr_id,
1504 rdma->nb_sent);
1505 rdma->control_ready_expected = 0;
1508 if (wr_id == RDMA_WRID_RDMA_WRITE) {
1509 uint64_t chunk =
1510 (wc.wr_id & RDMA_WRID_CHUNK_MASK) >> RDMA_WRID_CHUNK_SHIFT;
1511 uint64_t index =
1512 (wc.wr_id & RDMA_WRID_BLOCK_MASK) >> RDMA_WRID_BLOCK_SHIFT;
1513 RDMALocalBlock *block = &(rdma->local_ram_blocks.block[index]);
1515 trace_qemu_rdma_poll_write(wr_id, rdma->nb_sent,
1516 index, chunk, block->local_host_addr,
1517 (void *)(uintptr_t)block->remote_host_addr);
1519 clear_bit(chunk, block->transit_bitmap);
1521 if (rdma->nb_sent > 0) {
1522 rdma->nb_sent--;
1524 } else {
1525 trace_qemu_rdma_poll_other(wr_id, rdma->nb_sent);
1528 *wr_id_out = wc.wr_id;
1529 if (byte_len) {
1530 *byte_len = wc.byte_len;
1533 return 0;
1536 /* Wait for activity on the completion channel.
1537 * Returns 0 on success, none-0 on error.
1539 static int qemu_rdma_wait_comp_channel(RDMAContext *rdma,
1540 struct ibv_comp_channel *comp_channel)
1542 struct rdma_cm_event *cm_event;
1543 int ret;
1546 * Coroutine doesn't start until migration_fd_process_incoming()
1547 * so don't yield unless we know we're running inside of a coroutine.
1549 if (rdma->migration_started_on_destination &&
1550 migration_incoming_get_current()->state == MIGRATION_STATUS_ACTIVE) {
1551 yield_until_fd_readable(comp_channel->fd);
1552 } else {
1553 /* This is the source side, we're in a separate thread
1554 * or destination prior to migration_fd_process_incoming()
1555 * after postcopy, the destination also in a separate thread.
1556 * we can't yield; so we have to poll the fd.
1557 * But we need to be able to handle 'cancel' or an error
1558 * without hanging forever.
1560 while (!rdma->errored && !rdma->received_error) {
1561 GPollFD pfds[2];
1562 pfds[0].fd = comp_channel->fd;
1563 pfds[0].events = G_IO_IN | G_IO_HUP | G_IO_ERR;
1564 pfds[0].revents = 0;
1566 pfds[1].fd = rdma->channel->fd;
1567 pfds[1].events = G_IO_IN | G_IO_HUP | G_IO_ERR;
1568 pfds[1].revents = 0;
1570 /* 0.1s timeout, should be fine for a 'cancel' */
1571 switch (qemu_poll_ns(pfds, 2, 100 * 1000 * 1000)) {
1572 case 2:
1573 case 1: /* fd active */
1574 if (pfds[0].revents) {
1575 return 0;
1578 if (pfds[1].revents) {
1579 ret = rdma_get_cm_event(rdma->channel, &cm_event);
1580 if (ret < 0) {
1581 error_report("failed to get cm event while wait "
1582 "completion channel");
1583 return -1;
1586 error_report("receive cm event while wait comp channel,"
1587 "cm event is %d", cm_event->event);
1588 if (cm_event->event == RDMA_CM_EVENT_DISCONNECTED ||
1589 cm_event->event == RDMA_CM_EVENT_DEVICE_REMOVAL) {
1590 rdma_ack_cm_event(cm_event);
1591 return -1;
1593 rdma_ack_cm_event(cm_event);
1595 break;
1597 case 0: /* Timeout, go around again */
1598 break;
1600 default: /* Error of some type -
1601 * I don't trust errno from qemu_poll_ns
1603 error_report("%s: poll failed", __func__);
1604 return -1;
1607 if (migrate_get_current()->state == MIGRATION_STATUS_CANCELLING) {
1608 /* Bail out and let the cancellation happen */
1609 return -1;
1614 if (rdma->received_error) {
1615 return -1;
1617 return -rdma->errored;
1620 static struct ibv_comp_channel *to_channel(RDMAContext *rdma, uint64_t wrid)
1622 return wrid < RDMA_WRID_RECV_CONTROL ? rdma->send_comp_channel :
1623 rdma->recv_comp_channel;
1626 static struct ibv_cq *to_cq(RDMAContext *rdma, uint64_t wrid)
1628 return wrid < RDMA_WRID_RECV_CONTROL ? rdma->send_cq : rdma->recv_cq;
1632 * Block until the next work request has completed.
1634 * First poll to see if a work request has already completed,
1635 * otherwise block.
1637 * If we encounter completed work requests for IDs other than
1638 * the one we're interested in, then that's generally an error.
1640 * The only exception is actual RDMA Write completions. These
1641 * completions only need to be recorded, but do not actually
1642 * need further processing.
1644 static int qemu_rdma_block_for_wrid(RDMAContext *rdma,
1645 uint64_t wrid_requested,
1646 uint32_t *byte_len)
1648 int num_cq_events = 0, ret;
1649 struct ibv_cq *cq;
1650 void *cq_ctx;
1651 uint64_t wr_id = RDMA_WRID_NONE, wr_id_in;
1652 struct ibv_comp_channel *ch = to_channel(rdma, wrid_requested);
1653 struct ibv_cq *poll_cq = to_cq(rdma, wrid_requested);
1655 if (ibv_req_notify_cq(poll_cq, 0)) {
1656 return -1;
1658 /* poll cq first */
1659 while (wr_id != wrid_requested) {
1660 ret = qemu_rdma_poll(rdma, poll_cq, &wr_id_in, byte_len);
1661 if (ret < 0) {
1662 return -1;
1665 wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
1667 if (wr_id == RDMA_WRID_NONE) {
1668 break;
1670 if (wr_id != wrid_requested) {
1671 trace_qemu_rdma_block_for_wrid_miss(wrid_requested, wr_id);
1675 if (wr_id == wrid_requested) {
1676 return 0;
1679 while (1) {
1680 ret = qemu_rdma_wait_comp_channel(rdma, ch);
1681 if (ret < 0) {
1682 goto err_block_for_wrid;
1685 ret = ibv_get_cq_event(ch, &cq, &cq_ctx);
1686 if (ret < 0) {
1688 * FIXME perror() is problematic, because ibv_reg_mr() is
1689 * not documented to set errno. Will go away later in
1690 * this series.
1692 perror("ibv_get_cq_event");
1693 goto err_block_for_wrid;
1696 num_cq_events++;
1698 if (ibv_req_notify_cq(cq, 0)) {
1699 goto err_block_for_wrid;
1702 while (wr_id != wrid_requested) {
1703 ret = qemu_rdma_poll(rdma, poll_cq, &wr_id_in, byte_len);
1704 if (ret < 0) {
1705 goto err_block_for_wrid;
1708 wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
1710 if (wr_id == RDMA_WRID_NONE) {
1711 break;
1713 if (wr_id != wrid_requested) {
1714 trace_qemu_rdma_block_for_wrid_miss(wrid_requested, wr_id);
1718 if (wr_id == wrid_requested) {
1719 goto success_block_for_wrid;
1723 success_block_for_wrid:
1724 if (num_cq_events) {
1725 ibv_ack_cq_events(cq, num_cq_events);
1727 return 0;
1729 err_block_for_wrid:
1730 if (num_cq_events) {
1731 ibv_ack_cq_events(cq, num_cq_events);
1734 rdma->errored = true;
1735 return -1;
1739 * Post a SEND message work request for the control channel
1740 * containing some data and block until the post completes.
1742 static int qemu_rdma_post_send_control(RDMAContext *rdma, uint8_t *buf,
1743 RDMAControlHeader *head,
1744 Error **errp)
1746 int ret;
1747 RDMAWorkRequestData *wr = &rdma->wr_data[RDMA_WRID_CONTROL];
1748 struct ibv_send_wr *bad_wr;
1749 struct ibv_sge sge = {
1750 .addr = (uintptr_t)(wr->control),
1751 .length = head->len + sizeof(RDMAControlHeader),
1752 .lkey = wr->control_mr->lkey,
1754 struct ibv_send_wr send_wr = {
1755 .wr_id = RDMA_WRID_SEND_CONTROL,
1756 .opcode = IBV_WR_SEND,
1757 .send_flags = IBV_SEND_SIGNALED,
1758 .sg_list = &sge,
1759 .num_sge = 1,
1762 trace_qemu_rdma_post_send_control(control_desc(head->type));
1765 * We don't actually need to do a memcpy() in here if we used
1766 * the "sge" properly, but since we're only sending control messages
1767 * (not RAM in a performance-critical path), then its OK for now.
1769 * The copy makes the RDMAControlHeader simpler to manipulate
1770 * for the time being.
1772 assert(head->len <= RDMA_CONTROL_MAX_BUFFER - sizeof(*head));
1773 memcpy(wr->control, head, sizeof(RDMAControlHeader));
1774 control_to_network((void *) wr->control);
1776 if (buf) {
1777 memcpy(wr->control + sizeof(RDMAControlHeader), buf, head->len);
1781 ret = ibv_post_send(rdma->qp, &send_wr, &bad_wr);
1783 if (ret > 0) {
1784 error_setg(errp, "Failed to use post IB SEND for control");
1785 return -1;
1788 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_SEND_CONTROL, NULL);
1789 if (ret < 0) {
1790 error_setg(errp, "rdma migration: send polling control error");
1791 return -1;
1794 return 0;
1798 * Post a RECV work request in anticipation of some future receipt
1799 * of data on the control channel.
1801 static int qemu_rdma_post_recv_control(RDMAContext *rdma, int idx,
1802 Error **errp)
1804 struct ibv_recv_wr *bad_wr;
1805 struct ibv_sge sge = {
1806 .addr = (uintptr_t)(rdma->wr_data[idx].control),
1807 .length = RDMA_CONTROL_MAX_BUFFER,
1808 .lkey = rdma->wr_data[idx].control_mr->lkey,
1811 struct ibv_recv_wr recv_wr = {
1812 .wr_id = RDMA_WRID_RECV_CONTROL + idx,
1813 .sg_list = &sge,
1814 .num_sge = 1,
1818 if (ibv_post_recv(rdma->qp, &recv_wr, &bad_wr)) {
1819 error_setg(errp, "error posting control recv");
1820 return -1;
1823 return 0;
1827 * Block and wait for a RECV control channel message to arrive.
1829 static int qemu_rdma_exchange_get_response(RDMAContext *rdma,
1830 RDMAControlHeader *head, uint32_t expecting, int idx,
1831 Error **errp)
1833 uint32_t byte_len;
1834 int ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RECV_CONTROL + idx,
1835 &byte_len);
1837 if (ret < 0) {
1838 error_setg(errp, "rdma migration: recv polling control error!");
1839 return -1;
1842 network_to_control((void *) rdma->wr_data[idx].control);
1843 memcpy(head, rdma->wr_data[idx].control, sizeof(RDMAControlHeader));
1845 trace_qemu_rdma_exchange_get_response_start(control_desc(expecting));
1847 if (expecting == RDMA_CONTROL_NONE) {
1848 trace_qemu_rdma_exchange_get_response_none(control_desc(head->type),
1849 head->type);
1850 } else if (head->type != expecting || head->type == RDMA_CONTROL_ERROR) {
1851 error_setg(errp, "Was expecting a %s (%d) control message"
1852 ", but got: %s (%d), length: %d",
1853 control_desc(expecting), expecting,
1854 control_desc(head->type), head->type, head->len);
1855 if (head->type == RDMA_CONTROL_ERROR) {
1856 rdma->received_error = true;
1858 return -1;
1860 if (head->len > RDMA_CONTROL_MAX_BUFFER - sizeof(*head)) {
1861 error_setg(errp, "too long length: %d", head->len);
1862 return -1;
1864 if (sizeof(*head) + head->len != byte_len) {
1865 error_setg(errp, "Malformed length: %d byte_len %d",
1866 head->len, byte_len);
1867 return -1;
1870 return 0;
1874 * When a RECV work request has completed, the work request's
1875 * buffer is pointed at the header.
1877 * This will advance the pointer to the data portion
1878 * of the control message of the work request's buffer that
1879 * was populated after the work request finished.
1881 static void qemu_rdma_move_header(RDMAContext *rdma, int idx,
1882 RDMAControlHeader *head)
1884 rdma->wr_data[idx].control_len = head->len;
1885 rdma->wr_data[idx].control_curr =
1886 rdma->wr_data[idx].control + sizeof(RDMAControlHeader);
1890 * This is an 'atomic' high-level operation to deliver a single, unified
1891 * control-channel message.
1893 * Additionally, if the user is expecting some kind of reply to this message,
1894 * they can request a 'resp' response message be filled in by posting an
1895 * additional work request on behalf of the user and waiting for an additional
1896 * completion.
1898 * The extra (optional) response is used during registration to us from having
1899 * to perform an *additional* exchange of message just to provide a response by
1900 * instead piggy-backing on the acknowledgement.
1902 static int qemu_rdma_exchange_send(RDMAContext *rdma, RDMAControlHeader *head,
1903 uint8_t *data, RDMAControlHeader *resp,
1904 int *resp_idx,
1905 int (*callback)(RDMAContext *rdma,
1906 Error **errp),
1907 Error **errp)
1909 int ret;
1912 * Wait until the dest is ready before attempting to deliver the message
1913 * by waiting for a READY message.
1915 if (rdma->control_ready_expected) {
1916 RDMAControlHeader resp_ignored;
1918 ret = qemu_rdma_exchange_get_response(rdma, &resp_ignored,
1919 RDMA_CONTROL_READY,
1920 RDMA_WRID_READY, errp);
1921 if (ret < 0) {
1922 return -1;
1927 * If the user is expecting a response, post a WR in anticipation of it.
1929 if (resp) {
1930 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_DATA, errp);
1931 if (ret < 0) {
1932 return -1;
1937 * Post a WR to replace the one we just consumed for the READY message.
1939 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY, errp);
1940 if (ret < 0) {
1941 return -1;
1945 * Deliver the control message that was requested.
1947 ret = qemu_rdma_post_send_control(rdma, data, head, errp);
1949 if (ret < 0) {
1950 return -1;
1954 * If we're expecting a response, block and wait for it.
1956 if (resp) {
1957 if (callback) {
1958 trace_qemu_rdma_exchange_send_issue_callback();
1959 ret = callback(rdma, errp);
1960 if (ret < 0) {
1961 return -1;
1965 trace_qemu_rdma_exchange_send_waiting(control_desc(resp->type));
1966 ret = qemu_rdma_exchange_get_response(rdma, resp,
1967 resp->type, RDMA_WRID_DATA,
1968 errp);
1970 if (ret < 0) {
1971 return -1;
1974 qemu_rdma_move_header(rdma, RDMA_WRID_DATA, resp);
1975 if (resp_idx) {
1976 *resp_idx = RDMA_WRID_DATA;
1978 trace_qemu_rdma_exchange_send_received(control_desc(resp->type));
1981 rdma->control_ready_expected = 1;
1983 return 0;
1987 * This is an 'atomic' high-level operation to receive a single, unified
1988 * control-channel message.
1990 static int qemu_rdma_exchange_recv(RDMAContext *rdma, RDMAControlHeader *head,
1991 uint32_t expecting, Error **errp)
1993 RDMAControlHeader ready = {
1994 .len = 0,
1995 .type = RDMA_CONTROL_READY,
1996 .repeat = 1,
1998 int ret;
2001 * Inform the source that we're ready to receive a message.
2003 ret = qemu_rdma_post_send_control(rdma, NULL, &ready, errp);
2005 if (ret < 0) {
2006 return -1;
2010 * Block and wait for the message.
2012 ret = qemu_rdma_exchange_get_response(rdma, head,
2013 expecting, RDMA_WRID_READY, errp);
2015 if (ret < 0) {
2016 return -1;
2019 qemu_rdma_move_header(rdma, RDMA_WRID_READY, head);
2022 * Post a new RECV work request to replace the one we just consumed.
2024 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY, errp);
2025 if (ret < 0) {
2026 return -1;
2029 return 0;
2033 * Write an actual chunk of memory using RDMA.
2035 * If we're using dynamic registration on the dest-side, we have to
2036 * send a registration command first.
2038 static int qemu_rdma_write_one(RDMAContext *rdma,
2039 int current_index, uint64_t current_addr,
2040 uint64_t length, Error **errp)
2042 struct ibv_sge sge;
2043 struct ibv_send_wr send_wr = { 0 };
2044 struct ibv_send_wr *bad_wr;
2045 int reg_result_idx, ret, count = 0;
2046 uint64_t chunk, chunks;
2047 uint8_t *chunk_start, *chunk_end;
2048 RDMALocalBlock *block = &(rdma->local_ram_blocks.block[current_index]);
2049 RDMARegister reg;
2050 RDMARegisterResult *reg_result;
2051 RDMAControlHeader resp = { .type = RDMA_CONTROL_REGISTER_RESULT };
2052 RDMAControlHeader head = { .len = sizeof(RDMARegister),
2053 .type = RDMA_CONTROL_REGISTER_REQUEST,
2054 .repeat = 1,
2057 retry:
2058 sge.addr = (uintptr_t)(block->local_host_addr +
2059 (current_addr - block->offset));
2060 sge.length = length;
2062 chunk = ram_chunk_index(block->local_host_addr,
2063 (uint8_t *)(uintptr_t)sge.addr);
2064 chunk_start = ram_chunk_start(block, chunk);
2066 if (block->is_ram_block) {
2067 chunks = length / (1UL << RDMA_REG_CHUNK_SHIFT);
2069 if (chunks && ((length % (1UL << RDMA_REG_CHUNK_SHIFT)) == 0)) {
2070 chunks--;
2072 } else {
2073 chunks = block->length / (1UL << RDMA_REG_CHUNK_SHIFT);
2075 if (chunks && ((block->length % (1UL << RDMA_REG_CHUNK_SHIFT)) == 0)) {
2076 chunks--;
2080 trace_qemu_rdma_write_one_top(chunks + 1,
2081 (chunks + 1) *
2082 (1UL << RDMA_REG_CHUNK_SHIFT) / 1024 / 1024);
2084 chunk_end = ram_chunk_end(block, chunk + chunks);
2087 while (test_bit(chunk, block->transit_bitmap)) {
2088 (void)count;
2089 trace_qemu_rdma_write_one_block(count++, current_index, chunk,
2090 sge.addr, length, rdma->nb_sent, block->nb_chunks);
2092 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL);
2094 if (ret < 0) {
2095 error_setg(errp, "Failed to Wait for previous write to complete "
2096 "block %d chunk %" PRIu64
2097 " current %" PRIu64 " len %" PRIu64 " %d",
2098 current_index, chunk, sge.addr, length, rdma->nb_sent);
2099 return -1;
2103 if (!rdma->pin_all || !block->is_ram_block) {
2104 if (!block->remote_keys[chunk]) {
2106 * This chunk has not yet been registered, so first check to see
2107 * if the entire chunk is zero. If so, tell the other size to
2108 * memset() + madvise() the entire chunk without RDMA.
2111 if (buffer_is_zero((void *)(uintptr_t)sge.addr, length)) {
2112 RDMACompress comp = {
2113 .offset = current_addr,
2114 .value = 0,
2115 .block_idx = current_index,
2116 .length = length,
2119 head.len = sizeof(comp);
2120 head.type = RDMA_CONTROL_COMPRESS;
2122 trace_qemu_rdma_write_one_zero(chunk, sge.length,
2123 current_index, current_addr);
2125 compress_to_network(rdma, &comp);
2126 ret = qemu_rdma_exchange_send(rdma, &head,
2127 (uint8_t *) &comp, NULL, NULL, NULL, errp);
2129 if (ret < 0) {
2130 return -1;
2134 * TODO: Here we are sending something, but we are not
2135 * accounting for anything transferred. The following is wrong:
2137 * stat64_add(&mig_stats.rdma_bytes, sge.length);
2139 * because we are using some kind of compression. I
2140 * would think that head.len would be the more similar
2141 * thing to a correct value.
2143 stat64_add(&mig_stats.zero_pages,
2144 sge.length / qemu_target_page_size());
2145 return 1;
2149 * Otherwise, tell other side to register.
2151 reg.current_index = current_index;
2152 if (block->is_ram_block) {
2153 reg.key.current_addr = current_addr;
2154 } else {
2155 reg.key.chunk = chunk;
2157 reg.chunks = chunks;
2159 trace_qemu_rdma_write_one_sendreg(chunk, sge.length, current_index,
2160 current_addr);
2162 register_to_network(rdma, &reg);
2163 ret = qemu_rdma_exchange_send(rdma, &head, (uint8_t *) &reg,
2164 &resp, &reg_result_idx, NULL, errp);
2165 if (ret < 0) {
2166 return -1;
2169 /* try to overlap this single registration with the one we sent. */
2170 if (qemu_rdma_register_and_get_keys(rdma, block, sge.addr,
2171 &sge.lkey, NULL, chunk,
2172 chunk_start, chunk_end)) {
2173 error_setg(errp, "cannot get lkey");
2174 return -1;
2177 reg_result = (RDMARegisterResult *)
2178 rdma->wr_data[reg_result_idx].control_curr;
2180 network_to_result(reg_result);
2182 trace_qemu_rdma_write_one_recvregres(block->remote_keys[chunk],
2183 reg_result->rkey, chunk);
2185 block->remote_keys[chunk] = reg_result->rkey;
2186 block->remote_host_addr = reg_result->host_addr;
2187 } else {
2188 /* already registered before */
2189 if (qemu_rdma_register_and_get_keys(rdma, block, sge.addr,
2190 &sge.lkey, NULL, chunk,
2191 chunk_start, chunk_end)) {
2192 error_setg(errp, "cannot get lkey!");
2193 return -1;
2197 send_wr.wr.rdma.rkey = block->remote_keys[chunk];
2198 } else {
2199 send_wr.wr.rdma.rkey = block->remote_rkey;
2201 if (qemu_rdma_register_and_get_keys(rdma, block, sge.addr,
2202 &sge.lkey, NULL, chunk,
2203 chunk_start, chunk_end)) {
2204 error_setg(errp, "cannot get lkey!");
2205 return -1;
2210 * Encode the ram block index and chunk within this wrid.
2211 * We will use this information at the time of completion
2212 * to figure out which bitmap to check against and then which
2213 * chunk in the bitmap to look for.
2215 send_wr.wr_id = qemu_rdma_make_wrid(RDMA_WRID_RDMA_WRITE,
2216 current_index, chunk);
2218 send_wr.opcode = IBV_WR_RDMA_WRITE;
2219 send_wr.send_flags = IBV_SEND_SIGNALED;
2220 send_wr.sg_list = &sge;
2221 send_wr.num_sge = 1;
2222 send_wr.wr.rdma.remote_addr = block->remote_host_addr +
2223 (current_addr - block->offset);
2225 trace_qemu_rdma_write_one_post(chunk, sge.addr, send_wr.wr.rdma.remote_addr,
2226 sge.length);
2229 * ibv_post_send() does not return negative error numbers,
2230 * per the specification they are positive - no idea why.
2232 ret = ibv_post_send(rdma->qp, &send_wr, &bad_wr);
2234 if (ret == ENOMEM) {
2235 trace_qemu_rdma_write_one_queue_full();
2236 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL);
2237 if (ret < 0) {
2238 error_setg(errp, "rdma migration: failed to make "
2239 "room in full send queue!");
2240 return -1;
2243 goto retry;
2245 } else if (ret > 0) {
2246 error_setg_errno(errp, ret,
2247 "rdma migration: post rdma write failed");
2248 return -1;
2251 set_bit(chunk, block->transit_bitmap);
2252 stat64_add(&mig_stats.normal_pages, sge.length / qemu_target_page_size());
2254 * We are adding to transferred the amount of data written, but no
2255 * overhead at all. I will asume that RDMA is magicaly and don't
2256 * need to transfer (at least) the addresses where it wants to
2257 * write the pages. Here it looks like it should be something
2258 * like:
2259 * sizeof(send_wr) + sge.length
2260 * but this being RDMA, who knows.
2262 stat64_add(&mig_stats.rdma_bytes, sge.length);
2263 ram_transferred_add(sge.length);
2264 rdma->total_writes++;
2266 return 0;
2270 * Push out any unwritten RDMA operations.
2272 * We support sending out multiple chunks at the same time.
2273 * Not all of them need to get signaled in the completion queue.
2275 static int qemu_rdma_write_flush(RDMAContext *rdma, Error **errp)
2277 int ret;
2279 if (!rdma->current_length) {
2280 return 0;
2283 ret = qemu_rdma_write_one(rdma, rdma->current_index, rdma->current_addr,
2284 rdma->current_length, errp);
2286 if (ret < 0) {
2287 return -1;
2290 if (ret == 0) {
2291 rdma->nb_sent++;
2292 trace_qemu_rdma_write_flush(rdma->nb_sent);
2295 rdma->current_length = 0;
2296 rdma->current_addr = 0;
2298 return 0;
2301 static inline bool qemu_rdma_buffer_mergeable(RDMAContext *rdma,
2302 uint64_t offset, uint64_t len)
2304 RDMALocalBlock *block;
2305 uint8_t *host_addr;
2306 uint8_t *chunk_end;
2308 if (rdma->current_index < 0) {
2309 return false;
2312 if (rdma->current_chunk < 0) {
2313 return false;
2316 block = &(rdma->local_ram_blocks.block[rdma->current_index]);
2317 host_addr = block->local_host_addr + (offset - block->offset);
2318 chunk_end = ram_chunk_end(block, rdma->current_chunk);
2320 if (rdma->current_length == 0) {
2321 return false;
2325 * Only merge into chunk sequentially.
2327 if (offset != (rdma->current_addr + rdma->current_length)) {
2328 return false;
2331 if (offset < block->offset) {
2332 return false;
2335 if ((offset + len) > (block->offset + block->length)) {
2336 return false;
2339 if ((host_addr + len) > chunk_end) {
2340 return false;
2343 return true;
2347 * We're not actually writing here, but doing three things:
2349 * 1. Identify the chunk the buffer belongs to.
2350 * 2. If the chunk is full or the buffer doesn't belong to the current
2351 * chunk, then start a new chunk and flush() the old chunk.
2352 * 3. To keep the hardware busy, we also group chunks into batches
2353 * and only require that a batch gets acknowledged in the completion
2354 * queue instead of each individual chunk.
2356 static int qemu_rdma_write(RDMAContext *rdma,
2357 uint64_t block_offset, uint64_t offset,
2358 uint64_t len, Error **errp)
2360 uint64_t current_addr = block_offset + offset;
2361 uint64_t index = rdma->current_index;
2362 uint64_t chunk = rdma->current_chunk;
2363 int ret;
2365 /* If we cannot merge it, we flush the current buffer first. */
2366 if (!qemu_rdma_buffer_mergeable(rdma, current_addr, len)) {
2367 ret = qemu_rdma_write_flush(rdma, errp);
2368 if (ret < 0) {
2369 return -1;
2371 rdma->current_length = 0;
2372 rdma->current_addr = current_addr;
2374 qemu_rdma_search_ram_block(rdma, block_offset,
2375 offset, len, &index, &chunk);
2376 rdma->current_index = index;
2377 rdma->current_chunk = chunk;
2380 /* merge it */
2381 rdma->current_length += len;
2383 /* flush it if buffer is too large */
2384 if (rdma->current_length >= RDMA_MERGE_MAX) {
2385 return qemu_rdma_write_flush(rdma, errp);
2388 return 0;
2391 static void qemu_rdma_cleanup(RDMAContext *rdma)
2393 Error *err = NULL;
2394 int idx;
2396 if (rdma->cm_id && rdma->connected) {
2397 if ((rdma->errored ||
2398 migrate_get_current()->state == MIGRATION_STATUS_CANCELLING) &&
2399 !rdma->received_error) {
2400 RDMAControlHeader head = { .len = 0,
2401 .type = RDMA_CONTROL_ERROR,
2402 .repeat = 1,
2404 error_report("Early error. Sending error.");
2405 if (qemu_rdma_post_send_control(rdma, NULL, &head, &err) < 0) {
2406 error_report_err(err);
2410 rdma_disconnect(rdma->cm_id);
2411 trace_qemu_rdma_cleanup_disconnect();
2412 rdma->connected = false;
2415 if (rdma->channel) {
2416 qemu_set_fd_handler(rdma->channel->fd, NULL, NULL, NULL);
2418 g_free(rdma->dest_blocks);
2419 rdma->dest_blocks = NULL;
2421 for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
2422 if (rdma->wr_data[idx].control_mr) {
2423 rdma->total_registrations--;
2424 ibv_dereg_mr(rdma->wr_data[idx].control_mr);
2426 rdma->wr_data[idx].control_mr = NULL;
2429 if (rdma->local_ram_blocks.block) {
2430 while (rdma->local_ram_blocks.nb_blocks) {
2431 rdma_delete_block(rdma, &rdma->local_ram_blocks.block[0]);
2435 if (rdma->qp) {
2436 rdma_destroy_qp(rdma->cm_id);
2437 rdma->qp = NULL;
2439 if (rdma->recv_cq) {
2440 ibv_destroy_cq(rdma->recv_cq);
2441 rdma->recv_cq = NULL;
2443 if (rdma->send_cq) {
2444 ibv_destroy_cq(rdma->send_cq);
2445 rdma->send_cq = NULL;
2447 if (rdma->recv_comp_channel) {
2448 ibv_destroy_comp_channel(rdma->recv_comp_channel);
2449 rdma->recv_comp_channel = NULL;
2451 if (rdma->send_comp_channel) {
2452 ibv_destroy_comp_channel(rdma->send_comp_channel);
2453 rdma->send_comp_channel = NULL;
2455 if (rdma->pd) {
2456 ibv_dealloc_pd(rdma->pd);
2457 rdma->pd = NULL;
2459 if (rdma->cm_id) {
2460 rdma_destroy_id(rdma->cm_id);
2461 rdma->cm_id = NULL;
2464 /* the destination side, listen_id and channel is shared */
2465 if (rdma->listen_id) {
2466 if (!rdma->is_return_path) {
2467 rdma_destroy_id(rdma->listen_id);
2469 rdma->listen_id = NULL;
2471 if (rdma->channel) {
2472 if (!rdma->is_return_path) {
2473 rdma_destroy_event_channel(rdma->channel);
2475 rdma->channel = NULL;
2479 if (rdma->channel) {
2480 rdma_destroy_event_channel(rdma->channel);
2481 rdma->channel = NULL;
2483 g_free(rdma->host);
2484 g_free(rdma->host_port);
2485 rdma->host = NULL;
2486 rdma->host_port = NULL;
2490 static int qemu_rdma_source_init(RDMAContext *rdma, bool pin_all, Error **errp)
2492 int ret, idx;
2495 * Will be validated against destination's actual capabilities
2496 * after the connect() completes.
2498 rdma->pin_all = pin_all;
2500 ret = qemu_rdma_resolve_host(rdma, errp);
2501 if (ret < 0) {
2502 goto err_rdma_source_init;
2505 ret = qemu_rdma_alloc_pd_cq(rdma, errp);
2506 if (ret < 0) {
2507 goto err_rdma_source_init;
2510 ret = qemu_rdma_alloc_qp(rdma);
2511 if (ret < 0) {
2512 error_setg(errp, "RDMA ERROR: rdma migration: error allocating qp!");
2513 goto err_rdma_source_init;
2516 qemu_rdma_init_ram_blocks(rdma);
2518 /* Build the hash that maps from offset to RAMBlock */
2519 rdma->blockmap = g_hash_table_new(g_direct_hash, g_direct_equal);
2520 for (idx = 0; idx < rdma->local_ram_blocks.nb_blocks; idx++) {
2521 g_hash_table_insert(rdma->blockmap,
2522 (void *)(uintptr_t)rdma->local_ram_blocks.block[idx].offset,
2523 &rdma->local_ram_blocks.block[idx]);
2526 for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
2527 ret = qemu_rdma_reg_control(rdma, idx);
2528 if (ret < 0) {
2529 error_setg(errp,
2530 "RDMA ERROR: rdma migration: error registering %d control!",
2531 idx);
2532 goto err_rdma_source_init;
2536 return 0;
2538 err_rdma_source_init:
2539 qemu_rdma_cleanup(rdma);
2540 return -1;
2543 static int qemu_get_cm_event_timeout(RDMAContext *rdma,
2544 struct rdma_cm_event **cm_event,
2545 long msec, Error **errp)
2547 int ret;
2548 struct pollfd poll_fd = {
2549 .fd = rdma->channel->fd,
2550 .events = POLLIN,
2551 .revents = 0
2554 do {
2555 ret = poll(&poll_fd, 1, msec);
2556 } while (ret < 0 && errno == EINTR);
2558 if (ret == 0) {
2559 error_setg(errp, "RDMA ERROR: poll cm event timeout");
2560 return -1;
2561 } else if (ret < 0) {
2562 error_setg(errp, "RDMA ERROR: failed to poll cm event, errno=%i",
2563 errno);
2564 return -1;
2565 } else if (poll_fd.revents & POLLIN) {
2566 if (rdma_get_cm_event(rdma->channel, cm_event) < 0) {
2567 error_setg(errp, "RDMA ERROR: failed to get cm event");
2568 return -1;
2570 return 0;
2571 } else {
2572 error_setg(errp, "RDMA ERROR: no POLLIN event, revent=%x",
2573 poll_fd.revents);
2574 return -1;
2578 static int qemu_rdma_connect(RDMAContext *rdma, bool return_path,
2579 Error **errp)
2581 RDMACapabilities cap = {
2582 .version = RDMA_CONTROL_VERSION_CURRENT,
2583 .flags = 0,
2585 struct rdma_conn_param conn_param = { .initiator_depth = 2,
2586 .retry_count = 5,
2587 .private_data = &cap,
2588 .private_data_len = sizeof(cap),
2590 struct rdma_cm_event *cm_event;
2591 int ret;
2594 * Only negotiate the capability with destination if the user
2595 * on the source first requested the capability.
2597 if (rdma->pin_all) {
2598 trace_qemu_rdma_connect_pin_all_requested();
2599 cap.flags |= RDMA_CAPABILITY_PIN_ALL;
2602 caps_to_network(&cap);
2604 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY, errp);
2605 if (ret < 0) {
2606 goto err_rdma_source_connect;
2609 ret = rdma_connect(rdma->cm_id, &conn_param);
2610 if (ret < 0) {
2611 perror("rdma_connect");
2612 error_setg(errp, "RDMA ERROR: connecting to destination!");
2613 goto err_rdma_source_connect;
2616 if (return_path) {
2617 ret = qemu_get_cm_event_timeout(rdma, &cm_event, 5000, errp);
2618 } else {
2619 ret = rdma_get_cm_event(rdma->channel, &cm_event);
2620 if (ret < 0) {
2621 error_setg(errp, "RDMA ERROR: failed to get cm event");
2624 if (ret < 0) {
2626 * FIXME perror() is wrong, because
2627 * qemu_get_cm_event_timeout() can fail without setting errno.
2628 * Will go away later in this series.
2630 perror("rdma_get_cm_event after rdma_connect");
2631 goto err_rdma_source_connect;
2634 if (cm_event->event != RDMA_CM_EVENT_ESTABLISHED) {
2635 error_report("rdma_get_cm_event != EVENT_ESTABLISHED after rdma_connect");
2636 error_setg(errp, "RDMA ERROR: connecting to destination!");
2637 rdma_ack_cm_event(cm_event);
2638 goto err_rdma_source_connect;
2640 rdma->connected = true;
2642 memcpy(&cap, cm_event->param.conn.private_data, sizeof(cap));
2643 network_to_caps(&cap);
2646 * Verify that the *requested* capabilities are supported by the destination
2647 * and disable them otherwise.
2649 if (rdma->pin_all && !(cap.flags & RDMA_CAPABILITY_PIN_ALL)) {
2650 warn_report("RDMA: Server cannot support pinning all memory. "
2651 "Will register memory dynamically.");
2652 rdma->pin_all = false;
2655 trace_qemu_rdma_connect_pin_all_outcome(rdma->pin_all);
2657 rdma_ack_cm_event(cm_event);
2659 rdma->control_ready_expected = 1;
2660 rdma->nb_sent = 0;
2661 return 0;
2663 err_rdma_source_connect:
2664 qemu_rdma_cleanup(rdma);
2665 return -1;
2668 static int qemu_rdma_dest_init(RDMAContext *rdma, Error **errp)
2670 Error *err = NULL;
2671 int ret, idx;
2672 struct rdma_cm_id *listen_id;
2673 char ip[40] = "unknown";
2674 struct rdma_addrinfo *res, *e;
2675 char port_str[16];
2676 int reuse = 1;
2678 for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
2679 rdma->wr_data[idx].control_len = 0;
2680 rdma->wr_data[idx].control_curr = NULL;
2683 if (!rdma->host || !rdma->host[0]) {
2684 error_setg(errp, "RDMA ERROR: RDMA host is not set!");
2685 rdma->errored = true;
2686 return -1;
2688 /* create CM channel */
2689 rdma->channel = rdma_create_event_channel();
2690 if (!rdma->channel) {
2691 error_setg(errp, "RDMA ERROR: could not create rdma event channel");
2692 rdma->errored = true;
2693 return -1;
2696 /* create CM id */
2697 ret = rdma_create_id(rdma->channel, &listen_id, NULL, RDMA_PS_TCP);
2698 if (ret < 0) {
2699 error_setg(errp, "RDMA ERROR: could not create cm_id!");
2700 goto err_dest_init_create_listen_id;
2703 snprintf(port_str, 16, "%d", rdma->port);
2704 port_str[15] = '\0';
2706 ret = rdma_getaddrinfo(rdma->host, port_str, NULL, &res);
2707 if (ret) {
2708 error_setg(errp, "RDMA ERROR: could not rdma_getaddrinfo address %s",
2709 rdma->host);
2710 goto err_dest_init_bind_addr;
2713 ret = rdma_set_option(listen_id, RDMA_OPTION_ID, RDMA_OPTION_ID_REUSEADDR,
2714 &reuse, sizeof reuse);
2715 if (ret < 0) {
2716 error_setg(errp, "RDMA ERROR: Error: could not set REUSEADDR option");
2717 goto err_dest_init_bind_addr;
2720 /* Try all addresses, saving the first error in @err */
2721 for (e = res; e != NULL; e = e->ai_next) {
2722 Error **local_errp = err ? NULL : &err;
2724 inet_ntop(e->ai_family,
2725 &((struct sockaddr_in *) e->ai_dst_addr)->sin_addr, ip, sizeof ip);
2726 trace_qemu_rdma_dest_init_trying(rdma->host, ip);
2727 ret = rdma_bind_addr(listen_id, e->ai_dst_addr);
2728 if (ret < 0) {
2729 continue;
2731 if (e->ai_family == AF_INET6) {
2732 ret = qemu_rdma_broken_ipv6_kernel(listen_id->verbs,
2733 local_errp);
2734 if (ret < 0) {
2735 continue;
2738 error_free(err);
2739 break;
2742 rdma_freeaddrinfo(res);
2743 if (!e) {
2744 if (err) {
2745 error_propagate(errp, err);
2746 } else {
2747 error_setg(errp, "RDMA ERROR: Error: could not rdma_bind_addr!");
2749 goto err_dest_init_bind_addr;
2752 rdma->listen_id = listen_id;
2753 qemu_rdma_dump_gid("dest_init", listen_id);
2754 return 0;
2756 err_dest_init_bind_addr:
2757 rdma_destroy_id(listen_id);
2758 err_dest_init_create_listen_id:
2759 rdma_destroy_event_channel(rdma->channel);
2760 rdma->channel = NULL;
2761 rdma->errored = true;
2762 return -1;
2766 static void qemu_rdma_return_path_dest_init(RDMAContext *rdma_return_path,
2767 RDMAContext *rdma)
2769 int idx;
2771 for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
2772 rdma_return_path->wr_data[idx].control_len = 0;
2773 rdma_return_path->wr_data[idx].control_curr = NULL;
2776 /*the CM channel and CM id is shared*/
2777 rdma_return_path->channel = rdma->channel;
2778 rdma_return_path->listen_id = rdma->listen_id;
2780 rdma->return_path = rdma_return_path;
2781 rdma_return_path->return_path = rdma;
2782 rdma_return_path->is_return_path = true;
2785 static RDMAContext *qemu_rdma_data_init(const char *host_port, Error **errp)
2787 RDMAContext *rdma = NULL;
2788 InetSocketAddress *addr;
2790 rdma = g_new0(RDMAContext, 1);
2791 rdma->current_index = -1;
2792 rdma->current_chunk = -1;
2794 addr = g_new(InetSocketAddress, 1);
2795 if (!inet_parse(addr, host_port, NULL)) {
2796 rdma->port = atoi(addr->port);
2797 rdma->host = g_strdup(addr->host);
2798 rdma->host_port = g_strdup(host_port);
2799 } else {
2800 error_setg(errp, "RDMA ERROR: bad RDMA migration address '%s'",
2801 host_port);
2802 g_free(rdma);
2803 rdma = NULL;
2806 qapi_free_InetSocketAddress(addr);
2807 return rdma;
2811 * QEMUFile interface to the control channel.
2812 * SEND messages for control only.
2813 * VM's ram is handled with regular RDMA messages.
2815 static ssize_t qio_channel_rdma_writev(QIOChannel *ioc,
2816 const struct iovec *iov,
2817 size_t niov,
2818 int *fds,
2819 size_t nfds,
2820 int flags,
2821 Error **errp)
2823 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
2824 RDMAContext *rdma;
2825 int ret;
2826 ssize_t done = 0;
2827 size_t i, len;
2829 RCU_READ_LOCK_GUARD();
2830 rdma = qatomic_rcu_read(&rioc->rdmaout);
2832 if (!rdma) {
2833 error_setg(errp, "RDMA control channel output is not set");
2834 return -1;
2837 if (rdma->errored) {
2838 error_setg(errp,
2839 "RDMA is in an error state waiting migration to abort!");
2840 return -1;
2844 * Push out any writes that
2845 * we're queued up for VM's ram.
2847 ret = qemu_rdma_write_flush(rdma, errp);
2848 if (ret < 0) {
2849 rdma->errored = true;
2850 return -1;
2853 for (i = 0; i < niov; i++) {
2854 size_t remaining = iov[i].iov_len;
2855 uint8_t * data = (void *)iov[i].iov_base;
2856 while (remaining) {
2857 RDMAControlHeader head = {};
2859 len = MIN(remaining, RDMA_SEND_INCREMENT);
2860 remaining -= len;
2862 head.len = len;
2863 head.type = RDMA_CONTROL_QEMU_FILE;
2865 ret = qemu_rdma_exchange_send(rdma, &head,
2866 data, NULL, NULL, NULL, errp);
2868 if (ret < 0) {
2869 rdma->errored = true;
2870 return -1;
2873 data += len;
2874 done += len;
2878 return done;
2881 static size_t qemu_rdma_fill(RDMAContext *rdma, uint8_t *buf,
2882 size_t size, int idx)
2884 size_t len = 0;
2886 if (rdma->wr_data[idx].control_len) {
2887 trace_qemu_rdma_fill(rdma->wr_data[idx].control_len, size);
2889 len = MIN(size, rdma->wr_data[idx].control_len);
2890 memcpy(buf, rdma->wr_data[idx].control_curr, len);
2891 rdma->wr_data[idx].control_curr += len;
2892 rdma->wr_data[idx].control_len -= len;
2895 return len;
2899 * QEMUFile interface to the control channel.
2900 * RDMA links don't use bytestreams, so we have to
2901 * return bytes to QEMUFile opportunistically.
2903 static ssize_t qio_channel_rdma_readv(QIOChannel *ioc,
2904 const struct iovec *iov,
2905 size_t niov,
2906 int **fds,
2907 size_t *nfds,
2908 int flags,
2909 Error **errp)
2911 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
2912 RDMAContext *rdma;
2913 RDMAControlHeader head;
2914 int ret;
2915 ssize_t done = 0;
2916 size_t i, len;
2918 RCU_READ_LOCK_GUARD();
2919 rdma = qatomic_rcu_read(&rioc->rdmain);
2921 if (!rdma) {
2922 error_setg(errp, "RDMA control channel input is not set");
2923 return -1;
2926 if (rdma->errored) {
2927 error_setg(errp,
2928 "RDMA is in an error state waiting migration to abort!");
2929 return -1;
2932 for (i = 0; i < niov; i++) {
2933 size_t want = iov[i].iov_len;
2934 uint8_t *data = (void *)iov[i].iov_base;
2937 * First, we hold on to the last SEND message we
2938 * were given and dish out the bytes until we run
2939 * out of bytes.
2941 len = qemu_rdma_fill(rdma, data, want, 0);
2942 done += len;
2943 want -= len;
2944 /* Got what we needed, so go to next iovec */
2945 if (want == 0) {
2946 continue;
2949 /* If we got any data so far, then don't wait
2950 * for more, just return what we have */
2951 if (done > 0) {
2952 break;
2956 /* We've got nothing at all, so lets wait for
2957 * more to arrive
2959 ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_QEMU_FILE,
2960 errp);
2962 if (ret < 0) {
2963 rdma->errored = true;
2964 return -1;
2968 * SEND was received with new bytes, now try again.
2970 len = qemu_rdma_fill(rdma, data, want, 0);
2971 done += len;
2972 want -= len;
2974 /* Still didn't get enough, so lets just return */
2975 if (want) {
2976 if (done == 0) {
2977 return QIO_CHANNEL_ERR_BLOCK;
2978 } else {
2979 break;
2983 return done;
2987 * Block until all the outstanding chunks have been delivered by the hardware.
2989 static int qemu_rdma_drain_cq(RDMAContext *rdma)
2991 Error *err = NULL;
2992 int ret;
2994 if (qemu_rdma_write_flush(rdma, &err) < 0) {
2995 error_report_err(err);
2996 return -1;
2999 while (rdma->nb_sent) {
3000 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL);
3001 if (ret < 0) {
3002 error_report("rdma migration: complete polling error!");
3003 return -1;
3007 qemu_rdma_unregister_waiting(rdma);
3009 return 0;
3013 static int qio_channel_rdma_set_blocking(QIOChannel *ioc,
3014 bool blocking,
3015 Error **errp)
3017 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
3018 /* XXX we should make readv/writev actually honour this :-) */
3019 rioc->blocking = blocking;
3020 return 0;
3024 typedef struct QIOChannelRDMASource QIOChannelRDMASource;
3025 struct QIOChannelRDMASource {
3026 GSource parent;
3027 QIOChannelRDMA *rioc;
3028 GIOCondition condition;
3031 static gboolean
3032 qio_channel_rdma_source_prepare(GSource *source,
3033 gint *timeout)
3035 QIOChannelRDMASource *rsource = (QIOChannelRDMASource *)source;
3036 RDMAContext *rdma;
3037 GIOCondition cond = 0;
3038 *timeout = -1;
3040 RCU_READ_LOCK_GUARD();
3041 if (rsource->condition == G_IO_IN) {
3042 rdma = qatomic_rcu_read(&rsource->rioc->rdmain);
3043 } else {
3044 rdma = qatomic_rcu_read(&rsource->rioc->rdmaout);
3047 if (!rdma) {
3048 error_report("RDMAContext is NULL when prepare Gsource");
3049 return FALSE;
3052 if (rdma->wr_data[0].control_len) {
3053 cond |= G_IO_IN;
3055 cond |= G_IO_OUT;
3057 return cond & rsource->condition;
3060 static gboolean
3061 qio_channel_rdma_source_check(GSource *source)
3063 QIOChannelRDMASource *rsource = (QIOChannelRDMASource *)source;
3064 RDMAContext *rdma;
3065 GIOCondition cond = 0;
3067 RCU_READ_LOCK_GUARD();
3068 if (rsource->condition == G_IO_IN) {
3069 rdma = qatomic_rcu_read(&rsource->rioc->rdmain);
3070 } else {
3071 rdma = qatomic_rcu_read(&rsource->rioc->rdmaout);
3074 if (!rdma) {
3075 error_report("RDMAContext is NULL when check Gsource");
3076 return FALSE;
3079 if (rdma->wr_data[0].control_len) {
3080 cond |= G_IO_IN;
3082 cond |= G_IO_OUT;
3084 return cond & rsource->condition;
3087 static gboolean
3088 qio_channel_rdma_source_dispatch(GSource *source,
3089 GSourceFunc callback,
3090 gpointer user_data)
3092 QIOChannelFunc func = (QIOChannelFunc)callback;
3093 QIOChannelRDMASource *rsource = (QIOChannelRDMASource *)source;
3094 RDMAContext *rdma;
3095 GIOCondition cond = 0;
3097 RCU_READ_LOCK_GUARD();
3098 if (rsource->condition == G_IO_IN) {
3099 rdma = qatomic_rcu_read(&rsource->rioc->rdmain);
3100 } else {
3101 rdma = qatomic_rcu_read(&rsource->rioc->rdmaout);
3104 if (!rdma) {
3105 error_report("RDMAContext is NULL when dispatch Gsource");
3106 return FALSE;
3109 if (rdma->wr_data[0].control_len) {
3110 cond |= G_IO_IN;
3112 cond |= G_IO_OUT;
3114 return (*func)(QIO_CHANNEL(rsource->rioc),
3115 (cond & rsource->condition),
3116 user_data);
3119 static void
3120 qio_channel_rdma_source_finalize(GSource *source)
3122 QIOChannelRDMASource *ssource = (QIOChannelRDMASource *)source;
3124 object_unref(OBJECT(ssource->rioc));
3127 static GSourceFuncs qio_channel_rdma_source_funcs = {
3128 qio_channel_rdma_source_prepare,
3129 qio_channel_rdma_source_check,
3130 qio_channel_rdma_source_dispatch,
3131 qio_channel_rdma_source_finalize
3134 static GSource *qio_channel_rdma_create_watch(QIOChannel *ioc,
3135 GIOCondition condition)
3137 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
3138 QIOChannelRDMASource *ssource;
3139 GSource *source;
3141 source = g_source_new(&qio_channel_rdma_source_funcs,
3142 sizeof(QIOChannelRDMASource));
3143 ssource = (QIOChannelRDMASource *)source;
3145 ssource->rioc = rioc;
3146 object_ref(OBJECT(rioc));
3148 ssource->condition = condition;
3150 return source;
3153 static void qio_channel_rdma_set_aio_fd_handler(QIOChannel *ioc,
3154 AioContext *read_ctx,
3155 IOHandler *io_read,
3156 AioContext *write_ctx,
3157 IOHandler *io_write,
3158 void *opaque)
3160 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
3161 if (io_read) {
3162 aio_set_fd_handler(read_ctx, rioc->rdmain->recv_comp_channel->fd,
3163 io_read, io_write, NULL, NULL, opaque);
3164 aio_set_fd_handler(read_ctx, rioc->rdmain->send_comp_channel->fd,
3165 io_read, io_write, NULL, NULL, opaque);
3166 } else {
3167 aio_set_fd_handler(write_ctx, rioc->rdmaout->recv_comp_channel->fd,
3168 io_read, io_write, NULL, NULL, opaque);
3169 aio_set_fd_handler(write_ctx, rioc->rdmaout->send_comp_channel->fd,
3170 io_read, io_write, NULL, NULL, opaque);
3174 struct rdma_close_rcu {
3175 struct rcu_head rcu;
3176 RDMAContext *rdmain;
3177 RDMAContext *rdmaout;
3180 /* callback from qio_channel_rdma_close via call_rcu */
3181 static void qio_channel_rdma_close_rcu(struct rdma_close_rcu *rcu)
3183 if (rcu->rdmain) {
3184 qemu_rdma_cleanup(rcu->rdmain);
3187 if (rcu->rdmaout) {
3188 qemu_rdma_cleanup(rcu->rdmaout);
3191 g_free(rcu->rdmain);
3192 g_free(rcu->rdmaout);
3193 g_free(rcu);
3196 static int qio_channel_rdma_close(QIOChannel *ioc,
3197 Error **errp)
3199 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
3200 RDMAContext *rdmain, *rdmaout;
3201 struct rdma_close_rcu *rcu = g_new(struct rdma_close_rcu, 1);
3203 trace_qemu_rdma_close();
3205 rdmain = rioc->rdmain;
3206 if (rdmain) {
3207 qatomic_rcu_set(&rioc->rdmain, NULL);
3210 rdmaout = rioc->rdmaout;
3211 if (rdmaout) {
3212 qatomic_rcu_set(&rioc->rdmaout, NULL);
3215 rcu->rdmain = rdmain;
3216 rcu->rdmaout = rdmaout;
3217 call_rcu(rcu, qio_channel_rdma_close_rcu, rcu);
3219 return 0;
3222 static int
3223 qio_channel_rdma_shutdown(QIOChannel *ioc,
3224 QIOChannelShutdown how,
3225 Error **errp)
3227 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
3228 RDMAContext *rdmain, *rdmaout;
3230 RCU_READ_LOCK_GUARD();
3232 rdmain = qatomic_rcu_read(&rioc->rdmain);
3233 rdmaout = qatomic_rcu_read(&rioc->rdmain);
3235 switch (how) {
3236 case QIO_CHANNEL_SHUTDOWN_READ:
3237 if (rdmain) {
3238 rdmain->errored = true;
3240 break;
3241 case QIO_CHANNEL_SHUTDOWN_WRITE:
3242 if (rdmaout) {
3243 rdmaout->errored = true;
3245 break;
3246 case QIO_CHANNEL_SHUTDOWN_BOTH:
3247 default:
3248 if (rdmain) {
3249 rdmain->errored = true;
3251 if (rdmaout) {
3252 rdmaout->errored = true;
3254 break;
3257 return 0;
3261 * Parameters:
3262 * @offset == 0 :
3263 * This means that 'block_offset' is a full virtual address that does not
3264 * belong to a RAMBlock of the virtual machine and instead
3265 * represents a private malloc'd memory area that the caller wishes to
3266 * transfer.
3268 * @offset != 0 :
3269 * Offset is an offset to be added to block_offset and used
3270 * to also lookup the corresponding RAMBlock.
3272 * @size : Number of bytes to transfer
3274 * @pages_sent : User-specificed pointer to indicate how many pages were
3275 * sent. Usually, this will not be more than a few bytes of
3276 * the protocol because most transfers are sent asynchronously.
3278 static int qemu_rdma_save_page(QEMUFile *f, ram_addr_t block_offset,
3279 ram_addr_t offset, size_t size)
3281 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(qemu_file_get_ioc(f));
3282 Error *err = NULL;
3283 RDMAContext *rdma;
3284 int ret;
3286 if (migration_in_postcopy()) {
3287 return RAM_SAVE_CONTROL_NOT_SUPP;
3290 RCU_READ_LOCK_GUARD();
3291 rdma = qatomic_rcu_read(&rioc->rdmaout);
3293 if (!rdma) {
3294 return -1;
3297 if (rdma_errored(rdma)) {
3298 return -1;
3301 qemu_fflush(f);
3304 * Add this page to the current 'chunk'. If the chunk
3305 * is full, or the page doesn't belong to the current chunk,
3306 * an actual RDMA write will occur and a new chunk will be formed.
3308 ret = qemu_rdma_write(rdma, block_offset, offset, size, &err);
3309 if (ret < 0) {
3310 error_report_err(err);
3311 goto err;
3315 * Drain the Completion Queue if possible, but do not block,
3316 * just poll.
3318 * If nothing to poll, the end of the iteration will do this
3319 * again to make sure we don't overflow the request queue.
3321 while (1) {
3322 uint64_t wr_id, wr_id_in;
3323 ret = qemu_rdma_poll(rdma, rdma->recv_cq, &wr_id_in, NULL);
3325 if (ret < 0) {
3326 error_report("rdma migration: polling error");
3327 goto err;
3330 wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
3332 if (wr_id == RDMA_WRID_NONE) {
3333 break;
3337 while (1) {
3338 uint64_t wr_id, wr_id_in;
3339 ret = qemu_rdma_poll(rdma, rdma->send_cq, &wr_id_in, NULL);
3341 if (ret < 0) {
3342 error_report("rdma migration: polling error");
3343 goto err;
3346 wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
3348 if (wr_id == RDMA_WRID_NONE) {
3349 break;
3353 return RAM_SAVE_CONTROL_DELAYED;
3355 err:
3356 rdma->errored = true;
3357 return -1;
3360 static void rdma_accept_incoming_migration(void *opaque);
3362 static void rdma_cm_poll_handler(void *opaque)
3364 RDMAContext *rdma = opaque;
3365 int ret;
3366 struct rdma_cm_event *cm_event;
3367 MigrationIncomingState *mis = migration_incoming_get_current();
3369 ret = rdma_get_cm_event(rdma->channel, &cm_event);
3370 if (ret < 0) {
3371 error_report("get_cm_event failed %d", errno);
3372 return;
3375 if (cm_event->event == RDMA_CM_EVENT_DISCONNECTED ||
3376 cm_event->event == RDMA_CM_EVENT_DEVICE_REMOVAL) {
3377 if (!rdma->errored &&
3378 migration_incoming_get_current()->state !=
3379 MIGRATION_STATUS_COMPLETED) {
3380 error_report("receive cm event, cm event is %d", cm_event->event);
3381 rdma->errored = true;
3382 if (rdma->return_path) {
3383 rdma->return_path->errored = true;
3386 rdma_ack_cm_event(cm_event);
3387 if (mis->loadvm_co) {
3388 qemu_coroutine_enter(mis->loadvm_co);
3390 return;
3392 rdma_ack_cm_event(cm_event);
3395 static int qemu_rdma_accept(RDMAContext *rdma)
3397 Error *err = NULL;
3398 RDMACapabilities cap;
3399 struct rdma_conn_param conn_param = {
3400 .responder_resources = 2,
3401 .private_data = &cap,
3402 .private_data_len = sizeof(cap),
3404 RDMAContext *rdma_return_path = NULL;
3405 struct rdma_cm_event *cm_event;
3406 struct ibv_context *verbs;
3407 int ret;
3408 int idx;
3410 ret = rdma_get_cm_event(rdma->channel, &cm_event);
3411 if (ret < 0) {
3412 goto err_rdma_dest_wait;
3415 if (cm_event->event != RDMA_CM_EVENT_CONNECT_REQUEST) {
3416 rdma_ack_cm_event(cm_event);
3417 goto err_rdma_dest_wait;
3421 * initialize the RDMAContext for return path for postcopy after first
3422 * connection request reached.
3424 if ((migrate_postcopy() || migrate_return_path())
3425 && !rdma->is_return_path) {
3426 rdma_return_path = qemu_rdma_data_init(rdma->host_port, NULL);
3427 if (rdma_return_path == NULL) {
3428 rdma_ack_cm_event(cm_event);
3429 goto err_rdma_dest_wait;
3432 qemu_rdma_return_path_dest_init(rdma_return_path, rdma);
3435 memcpy(&cap, cm_event->param.conn.private_data, sizeof(cap));
3437 network_to_caps(&cap);
3439 if (cap.version < 1 || cap.version > RDMA_CONTROL_VERSION_CURRENT) {
3440 error_report("Unknown source RDMA version: %d, bailing...",
3441 cap.version);
3442 rdma_ack_cm_event(cm_event);
3443 goto err_rdma_dest_wait;
3447 * Respond with only the capabilities this version of QEMU knows about.
3449 cap.flags &= known_capabilities;
3452 * Enable the ones that we do know about.
3453 * Add other checks here as new ones are introduced.
3455 if (cap.flags & RDMA_CAPABILITY_PIN_ALL) {
3456 rdma->pin_all = true;
3459 rdma->cm_id = cm_event->id;
3460 verbs = cm_event->id->verbs;
3462 rdma_ack_cm_event(cm_event);
3464 trace_qemu_rdma_accept_pin_state(rdma->pin_all);
3466 caps_to_network(&cap);
3468 trace_qemu_rdma_accept_pin_verbsc(verbs);
3470 if (!rdma->verbs) {
3471 rdma->verbs = verbs;
3472 } else if (rdma->verbs != verbs) {
3473 error_report("ibv context not matching %p, %p!", rdma->verbs,
3474 verbs);
3475 goto err_rdma_dest_wait;
3478 qemu_rdma_dump_id("dest_init", verbs);
3480 ret = qemu_rdma_alloc_pd_cq(rdma, &err);
3481 if (ret < 0) {
3482 error_report_err(err);
3483 goto err_rdma_dest_wait;
3486 ret = qemu_rdma_alloc_qp(rdma);
3487 if (ret < 0) {
3488 error_report("rdma migration: error allocating qp!");
3489 goto err_rdma_dest_wait;
3492 qemu_rdma_init_ram_blocks(rdma);
3494 for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
3495 ret = qemu_rdma_reg_control(rdma, idx);
3496 if (ret < 0) {
3497 error_report("rdma: error registering %d control", idx);
3498 goto err_rdma_dest_wait;
3502 /* Accept the second connection request for return path */
3503 if ((migrate_postcopy() || migrate_return_path())
3504 && !rdma->is_return_path) {
3505 qemu_set_fd_handler(rdma->channel->fd, rdma_accept_incoming_migration,
3506 NULL,
3507 (void *)(intptr_t)rdma->return_path);
3508 } else {
3509 qemu_set_fd_handler(rdma->channel->fd, rdma_cm_poll_handler,
3510 NULL, rdma);
3513 ret = rdma_accept(rdma->cm_id, &conn_param);
3514 if (ret < 0) {
3515 error_report("rdma_accept failed");
3516 goto err_rdma_dest_wait;
3519 ret = rdma_get_cm_event(rdma->channel, &cm_event);
3520 if (ret < 0) {
3521 error_report("rdma_accept get_cm_event failed");
3522 goto err_rdma_dest_wait;
3525 if (cm_event->event != RDMA_CM_EVENT_ESTABLISHED) {
3526 error_report("rdma_accept not event established");
3527 rdma_ack_cm_event(cm_event);
3528 goto err_rdma_dest_wait;
3531 rdma_ack_cm_event(cm_event);
3532 rdma->connected = true;
3534 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY, &err);
3535 if (ret < 0) {
3536 error_report_err(err);
3537 goto err_rdma_dest_wait;
3540 qemu_rdma_dump_gid("dest_connect", rdma->cm_id);
3542 return 0;
3544 err_rdma_dest_wait:
3545 rdma->errored = true;
3546 qemu_rdma_cleanup(rdma);
3547 g_free(rdma_return_path);
3548 return -1;
3551 static int dest_ram_sort_func(const void *a, const void *b)
3553 unsigned int a_index = ((const RDMALocalBlock *)a)->src_index;
3554 unsigned int b_index = ((const RDMALocalBlock *)b)->src_index;
3556 return (a_index < b_index) ? -1 : (a_index != b_index);
3560 * During each iteration of the migration, we listen for instructions
3561 * by the source VM to perform dynamic page registrations before they
3562 * can perform RDMA operations.
3564 * We respond with the 'rkey'.
3566 * Keep doing this until the source tells us to stop.
3568 static int qemu_rdma_registration_handle(QEMUFile *f)
3570 RDMAControlHeader reg_resp = { .len = sizeof(RDMARegisterResult),
3571 .type = RDMA_CONTROL_REGISTER_RESULT,
3572 .repeat = 0,
3574 RDMAControlHeader unreg_resp = { .len = 0,
3575 .type = RDMA_CONTROL_UNREGISTER_FINISHED,
3576 .repeat = 0,
3578 RDMAControlHeader blocks = { .type = RDMA_CONTROL_RAM_BLOCKS_RESULT,
3579 .repeat = 1 };
3580 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(qemu_file_get_ioc(f));
3581 Error *err = NULL;
3582 RDMAContext *rdma;
3583 RDMALocalBlocks *local;
3584 RDMAControlHeader head;
3585 RDMARegister *reg, *registers;
3586 RDMACompress *comp;
3587 RDMARegisterResult *reg_result;
3588 static RDMARegisterResult results[RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE];
3589 RDMALocalBlock *block;
3590 void *host_addr;
3591 int ret;
3592 int idx = 0;
3593 int count = 0;
3594 int i = 0;
3596 RCU_READ_LOCK_GUARD();
3597 rdma = qatomic_rcu_read(&rioc->rdmain);
3599 if (!rdma) {
3600 return -1;
3603 if (rdma_errored(rdma)) {
3604 return -1;
3607 local = &rdma->local_ram_blocks;
3608 do {
3609 trace_qemu_rdma_registration_handle_wait();
3611 ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_NONE, &err);
3613 if (ret < 0) {
3614 error_report_err(err);
3615 break;
3618 if (head.repeat > RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE) {
3619 error_report("rdma: Too many requests in this message (%d)."
3620 "Bailing.", head.repeat);
3621 break;
3624 switch (head.type) {
3625 case RDMA_CONTROL_COMPRESS:
3626 comp = (RDMACompress *) rdma->wr_data[idx].control_curr;
3627 network_to_compress(comp);
3629 trace_qemu_rdma_registration_handle_compress(comp->length,
3630 comp->block_idx,
3631 comp->offset);
3632 if (comp->block_idx >= rdma->local_ram_blocks.nb_blocks) {
3633 error_report("rdma: 'compress' bad block index %u (vs %d)",
3634 (unsigned int)comp->block_idx,
3635 rdma->local_ram_blocks.nb_blocks);
3636 goto err;
3638 block = &(rdma->local_ram_blocks.block[comp->block_idx]);
3640 host_addr = block->local_host_addr +
3641 (comp->offset - block->offset);
3643 ram_handle_compressed(host_addr, comp->value, comp->length);
3644 break;
3646 case RDMA_CONTROL_REGISTER_FINISHED:
3647 trace_qemu_rdma_registration_handle_finished();
3648 return 0;
3650 case RDMA_CONTROL_RAM_BLOCKS_REQUEST:
3651 trace_qemu_rdma_registration_handle_ram_blocks();
3653 /* Sort our local RAM Block list so it's the same as the source,
3654 * we can do this since we've filled in a src_index in the list
3655 * as we received the RAMBlock list earlier.
3657 qsort(rdma->local_ram_blocks.block,
3658 rdma->local_ram_blocks.nb_blocks,
3659 sizeof(RDMALocalBlock), dest_ram_sort_func);
3660 for (i = 0; i < local->nb_blocks; i++) {
3661 local->block[i].index = i;
3664 if (rdma->pin_all) {
3665 ret = qemu_rdma_reg_whole_ram_blocks(rdma, &err);
3666 if (ret < 0) {
3667 error_report_err(err);
3668 goto err;
3673 * Dest uses this to prepare to transmit the RAMBlock descriptions
3674 * to the source VM after connection setup.
3675 * Both sides use the "remote" structure to communicate and update
3676 * their "local" descriptions with what was sent.
3678 for (i = 0; i < local->nb_blocks; i++) {
3679 rdma->dest_blocks[i].remote_host_addr =
3680 (uintptr_t)(local->block[i].local_host_addr);
3682 if (rdma->pin_all) {
3683 rdma->dest_blocks[i].remote_rkey = local->block[i].mr->rkey;
3686 rdma->dest_blocks[i].offset = local->block[i].offset;
3687 rdma->dest_blocks[i].length = local->block[i].length;
3689 dest_block_to_network(&rdma->dest_blocks[i]);
3690 trace_qemu_rdma_registration_handle_ram_blocks_loop(
3691 local->block[i].block_name,
3692 local->block[i].offset,
3693 local->block[i].length,
3694 local->block[i].local_host_addr,
3695 local->block[i].src_index);
3698 blocks.len = rdma->local_ram_blocks.nb_blocks
3699 * sizeof(RDMADestBlock);
3702 ret = qemu_rdma_post_send_control(rdma,
3703 (uint8_t *) rdma->dest_blocks, &blocks,
3704 &err);
3706 if (ret < 0) {
3707 error_report_err(err);
3708 goto err;
3711 break;
3712 case RDMA_CONTROL_REGISTER_REQUEST:
3713 trace_qemu_rdma_registration_handle_register(head.repeat);
3715 reg_resp.repeat = head.repeat;
3716 registers = (RDMARegister *) rdma->wr_data[idx].control_curr;
3718 for (count = 0; count < head.repeat; count++) {
3719 uint64_t chunk;
3720 uint8_t *chunk_start, *chunk_end;
3722 reg = &registers[count];
3723 network_to_register(reg);
3725 reg_result = &results[count];
3727 trace_qemu_rdma_registration_handle_register_loop(count,
3728 reg->current_index, reg->key.current_addr, reg->chunks);
3730 if (reg->current_index >= rdma->local_ram_blocks.nb_blocks) {
3731 error_report("rdma: 'register' bad block index %u (vs %d)",
3732 (unsigned int)reg->current_index,
3733 rdma->local_ram_blocks.nb_blocks);
3734 goto err;
3736 block = &(rdma->local_ram_blocks.block[reg->current_index]);
3737 if (block->is_ram_block) {
3738 if (block->offset > reg->key.current_addr) {
3739 error_report("rdma: bad register address for block %s"
3740 " offset: %" PRIx64 " current_addr: %" PRIx64,
3741 block->block_name, block->offset,
3742 reg->key.current_addr);
3743 goto err;
3745 host_addr = (block->local_host_addr +
3746 (reg->key.current_addr - block->offset));
3747 chunk = ram_chunk_index(block->local_host_addr,
3748 (uint8_t *) host_addr);
3749 } else {
3750 chunk = reg->key.chunk;
3751 host_addr = block->local_host_addr +
3752 (reg->key.chunk * (1UL << RDMA_REG_CHUNK_SHIFT));
3753 /* Check for particularly bad chunk value */
3754 if (host_addr < (void *)block->local_host_addr) {
3755 error_report("rdma: bad chunk for block %s"
3756 " chunk: %" PRIx64,
3757 block->block_name, reg->key.chunk);
3758 goto err;
3761 chunk_start = ram_chunk_start(block, chunk);
3762 chunk_end = ram_chunk_end(block, chunk + reg->chunks);
3763 /* avoid "-Waddress-of-packed-member" warning */
3764 uint32_t tmp_rkey = 0;
3765 if (qemu_rdma_register_and_get_keys(rdma, block,
3766 (uintptr_t)host_addr, NULL, &tmp_rkey,
3767 chunk, chunk_start, chunk_end)) {
3768 error_report("cannot get rkey");
3769 goto err;
3771 reg_result->rkey = tmp_rkey;
3773 reg_result->host_addr = (uintptr_t)block->local_host_addr;
3775 trace_qemu_rdma_registration_handle_register_rkey(
3776 reg_result->rkey);
3778 result_to_network(reg_result);
3781 ret = qemu_rdma_post_send_control(rdma,
3782 (uint8_t *) results, &reg_resp, &err);
3784 if (ret < 0) {
3785 error_report_err(err);
3786 goto err;
3788 break;
3789 case RDMA_CONTROL_UNREGISTER_REQUEST:
3790 trace_qemu_rdma_registration_handle_unregister(head.repeat);
3791 unreg_resp.repeat = head.repeat;
3792 registers = (RDMARegister *) rdma->wr_data[idx].control_curr;
3794 for (count = 0; count < head.repeat; count++) {
3795 reg = &registers[count];
3796 network_to_register(reg);
3798 trace_qemu_rdma_registration_handle_unregister_loop(count,
3799 reg->current_index, reg->key.chunk);
3801 block = &(rdma->local_ram_blocks.block[reg->current_index]);
3803 ret = ibv_dereg_mr(block->pmr[reg->key.chunk]);
3804 block->pmr[reg->key.chunk] = NULL;
3806 if (ret != 0) {
3807 perror("rdma unregistration chunk failed");
3808 goto err;
3811 rdma->total_registrations--;
3813 trace_qemu_rdma_registration_handle_unregister_success(
3814 reg->key.chunk);
3817 ret = qemu_rdma_post_send_control(rdma, NULL, &unreg_resp, &err);
3819 if (ret < 0) {
3820 error_report_err(err);
3821 goto err;
3823 break;
3824 case RDMA_CONTROL_REGISTER_RESULT:
3825 error_report("Invalid RESULT message at dest.");
3826 goto err;
3827 default:
3828 error_report("Unknown control message %s", control_desc(head.type));
3829 goto err;
3831 } while (1);
3833 err:
3834 rdma->errored = true;
3835 return -1;
3838 /* Destination:
3839 * Called via a ram_control_load_hook during the initial RAM load section which
3840 * lists the RAMBlocks by name. This lets us know the order of the RAMBlocks
3841 * on the source.
3842 * We've already built our local RAMBlock list, but not yet sent the list to
3843 * the source.
3845 static int
3846 rdma_block_notification_handle(QEMUFile *f, const char *name)
3848 RDMAContext *rdma;
3849 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(qemu_file_get_ioc(f));
3850 int curr;
3851 int found = -1;
3853 RCU_READ_LOCK_GUARD();
3854 rdma = qatomic_rcu_read(&rioc->rdmain);
3856 if (!rdma) {
3857 return -1;
3860 /* Find the matching RAMBlock in our local list */
3861 for (curr = 0; curr < rdma->local_ram_blocks.nb_blocks; curr++) {
3862 if (!strcmp(rdma->local_ram_blocks.block[curr].block_name, name)) {
3863 found = curr;
3864 break;
3868 if (found == -1) {
3869 error_report("RAMBlock '%s' not found on destination", name);
3870 return -1;
3873 rdma->local_ram_blocks.block[curr].src_index = rdma->next_src_index;
3874 trace_rdma_block_notification_handle(name, rdma->next_src_index);
3875 rdma->next_src_index++;
3877 return 0;
3880 static int rdma_load_hook(QEMUFile *f, uint64_t flags, void *data)
3882 switch (flags) {
3883 case RAM_CONTROL_BLOCK_REG:
3884 return rdma_block_notification_handle(f, data);
3886 case RAM_CONTROL_HOOK:
3887 return qemu_rdma_registration_handle(f);
3889 default:
3890 /* Shouldn't be called with any other values */
3891 abort();
3895 static int qemu_rdma_registration_start(QEMUFile *f,
3896 uint64_t flags, void *data)
3898 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(qemu_file_get_ioc(f));
3899 RDMAContext *rdma;
3901 if (migration_in_postcopy()) {
3902 return 0;
3905 RCU_READ_LOCK_GUARD();
3906 rdma = qatomic_rcu_read(&rioc->rdmaout);
3907 if (!rdma) {
3908 return -1;
3911 if (rdma_errored(rdma)) {
3912 return -1;
3915 trace_qemu_rdma_registration_start(flags);
3916 qemu_put_be64(f, RAM_SAVE_FLAG_HOOK);
3917 qemu_fflush(f);
3919 return 0;
3923 * Inform dest that dynamic registrations are done for now.
3924 * First, flush writes, if any.
3926 static int qemu_rdma_registration_stop(QEMUFile *f,
3927 uint64_t flags, void *data)
3929 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(qemu_file_get_ioc(f));
3930 Error *err = NULL;
3931 RDMAContext *rdma;
3932 RDMAControlHeader head = { .len = 0, .repeat = 1 };
3933 int ret;
3935 if (migration_in_postcopy()) {
3936 return 0;
3939 RCU_READ_LOCK_GUARD();
3940 rdma = qatomic_rcu_read(&rioc->rdmaout);
3941 if (!rdma) {
3942 return -1;
3945 if (rdma_errored(rdma)) {
3946 return -1;
3949 qemu_fflush(f);
3950 ret = qemu_rdma_drain_cq(rdma);
3952 if (ret < 0) {
3953 goto err;
3956 if (flags == RAM_CONTROL_SETUP) {
3957 RDMAControlHeader resp = {.type = RDMA_CONTROL_RAM_BLOCKS_RESULT };
3958 RDMALocalBlocks *local = &rdma->local_ram_blocks;
3959 int reg_result_idx, i, nb_dest_blocks;
3961 head.type = RDMA_CONTROL_RAM_BLOCKS_REQUEST;
3962 trace_qemu_rdma_registration_stop_ram();
3965 * Make sure that we parallelize the pinning on both sides.
3966 * For very large guests, doing this serially takes a really
3967 * long time, so we have to 'interleave' the pinning locally
3968 * with the control messages by performing the pinning on this
3969 * side before we receive the control response from the other
3970 * side that the pinning has completed.
3972 ret = qemu_rdma_exchange_send(rdma, &head, NULL, &resp,
3973 &reg_result_idx, rdma->pin_all ?
3974 qemu_rdma_reg_whole_ram_blocks : NULL,
3975 &err);
3976 if (ret < 0) {
3977 error_report_err(err);
3978 return -1;
3981 nb_dest_blocks = resp.len / sizeof(RDMADestBlock);
3984 * The protocol uses two different sets of rkeys (mutually exclusive):
3985 * 1. One key to represent the virtual address of the entire ram block.
3986 * (dynamic chunk registration disabled - pin everything with one rkey.)
3987 * 2. One to represent individual chunks within a ram block.
3988 * (dynamic chunk registration enabled - pin individual chunks.)
3990 * Once the capability is successfully negotiated, the destination transmits
3991 * the keys to use (or sends them later) including the virtual addresses
3992 * and then propagates the remote ram block descriptions to his local copy.
3995 if (local->nb_blocks != nb_dest_blocks) {
3996 fprintf(stderr, "ram blocks mismatch (Number of blocks %d vs %d) "
3997 "Your QEMU command line parameters are probably "
3998 "not identical on both the source and destination.",
3999 local->nb_blocks, nb_dest_blocks);
4000 rdma->errored = true;
4001 return -1;
4004 qemu_rdma_move_header(rdma, reg_result_idx, &resp);
4005 memcpy(rdma->dest_blocks,
4006 rdma->wr_data[reg_result_idx].control_curr, resp.len);
4007 for (i = 0; i < nb_dest_blocks; i++) {
4008 network_to_dest_block(&rdma->dest_blocks[i]);
4010 /* We require that the blocks are in the same order */
4011 if (rdma->dest_blocks[i].length != local->block[i].length) {
4012 fprintf(stderr, "Block %s/%d has a different length %" PRIu64
4013 "vs %" PRIu64, local->block[i].block_name, i,
4014 local->block[i].length,
4015 rdma->dest_blocks[i].length);
4016 rdma->errored = true;
4017 return -1;
4019 local->block[i].remote_host_addr =
4020 rdma->dest_blocks[i].remote_host_addr;
4021 local->block[i].remote_rkey = rdma->dest_blocks[i].remote_rkey;
4025 trace_qemu_rdma_registration_stop(flags);
4027 head.type = RDMA_CONTROL_REGISTER_FINISHED;
4028 ret = qemu_rdma_exchange_send(rdma, &head, NULL, NULL, NULL, NULL, &err);
4030 if (ret < 0) {
4031 error_report_err(err);
4032 goto err;
4035 return 0;
4036 err:
4037 rdma->errored = true;
4038 return -1;
4041 static const QEMUFileHooks rdma_read_hooks = {
4042 .hook_ram_load = rdma_load_hook,
4045 static const QEMUFileHooks rdma_write_hooks = {
4046 .before_ram_iterate = qemu_rdma_registration_start,
4047 .after_ram_iterate = qemu_rdma_registration_stop,
4048 .save_page = qemu_rdma_save_page,
4052 static void qio_channel_rdma_finalize(Object *obj)
4054 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(obj);
4055 if (rioc->rdmain) {
4056 qemu_rdma_cleanup(rioc->rdmain);
4057 g_free(rioc->rdmain);
4058 rioc->rdmain = NULL;
4060 if (rioc->rdmaout) {
4061 qemu_rdma_cleanup(rioc->rdmaout);
4062 g_free(rioc->rdmaout);
4063 rioc->rdmaout = NULL;
4067 static void qio_channel_rdma_class_init(ObjectClass *klass,
4068 void *class_data G_GNUC_UNUSED)
4070 QIOChannelClass *ioc_klass = QIO_CHANNEL_CLASS(klass);
4072 ioc_klass->io_writev = qio_channel_rdma_writev;
4073 ioc_klass->io_readv = qio_channel_rdma_readv;
4074 ioc_klass->io_set_blocking = qio_channel_rdma_set_blocking;
4075 ioc_klass->io_close = qio_channel_rdma_close;
4076 ioc_klass->io_create_watch = qio_channel_rdma_create_watch;
4077 ioc_klass->io_set_aio_fd_handler = qio_channel_rdma_set_aio_fd_handler;
4078 ioc_klass->io_shutdown = qio_channel_rdma_shutdown;
4081 static const TypeInfo qio_channel_rdma_info = {
4082 .parent = TYPE_QIO_CHANNEL,
4083 .name = TYPE_QIO_CHANNEL_RDMA,
4084 .instance_size = sizeof(QIOChannelRDMA),
4085 .instance_finalize = qio_channel_rdma_finalize,
4086 .class_init = qio_channel_rdma_class_init,
4089 static void qio_channel_rdma_register_types(void)
4091 type_register_static(&qio_channel_rdma_info);
4094 type_init(qio_channel_rdma_register_types);
4096 static QEMUFile *rdma_new_input(RDMAContext *rdma)
4098 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(object_new(TYPE_QIO_CHANNEL_RDMA));
4100 rioc->file = qemu_file_new_input(QIO_CHANNEL(rioc));
4101 rioc->rdmain = rdma;
4102 rioc->rdmaout = rdma->return_path;
4103 qemu_file_set_hooks(rioc->file, &rdma_read_hooks);
4105 return rioc->file;
4108 static QEMUFile *rdma_new_output(RDMAContext *rdma)
4110 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(object_new(TYPE_QIO_CHANNEL_RDMA));
4112 rioc->file = qemu_file_new_output(QIO_CHANNEL(rioc));
4113 rioc->rdmaout = rdma;
4114 rioc->rdmain = rdma->return_path;
4115 qemu_file_set_hooks(rioc->file, &rdma_write_hooks);
4117 return rioc->file;
4120 static void rdma_accept_incoming_migration(void *opaque)
4122 RDMAContext *rdma = opaque;
4123 int ret;
4124 QEMUFile *f;
4125 Error *local_err = NULL;
4127 trace_qemu_rdma_accept_incoming_migration();
4128 ret = qemu_rdma_accept(rdma);
4130 if (ret < 0) {
4131 fprintf(stderr, "RDMA ERROR: Migration initialization failed\n");
4132 return;
4135 trace_qemu_rdma_accept_incoming_migration_accepted();
4137 if (rdma->is_return_path) {
4138 return;
4141 f = rdma_new_input(rdma);
4142 if (f == NULL) {
4143 fprintf(stderr, "RDMA ERROR: could not open RDMA for input\n");
4144 qemu_rdma_cleanup(rdma);
4145 return;
4148 rdma->migration_started_on_destination = 1;
4149 migration_fd_process_incoming(f, &local_err);
4150 if (local_err) {
4151 error_reportf_err(local_err, "RDMA ERROR:");
4155 void rdma_start_incoming_migration(const char *host_port, Error **errp)
4157 int ret;
4158 RDMAContext *rdma;
4160 trace_rdma_start_incoming_migration();
4162 /* Avoid ram_block_discard_disable(), cannot change during migration. */
4163 if (ram_block_discard_is_required()) {
4164 error_setg(errp, "RDMA: cannot disable RAM discard");
4165 return;
4168 rdma = qemu_rdma_data_init(host_port, errp);
4169 if (rdma == NULL) {
4170 goto err;
4173 ret = qemu_rdma_dest_init(rdma, errp);
4174 if (ret < 0) {
4175 goto err;
4178 trace_rdma_start_incoming_migration_after_dest_init();
4180 ret = rdma_listen(rdma->listen_id, 5);
4182 if (ret < 0) {
4183 error_setg(errp, "RDMA ERROR: listening on socket!");
4184 goto cleanup_rdma;
4187 trace_rdma_start_incoming_migration_after_rdma_listen();
4189 qemu_set_fd_handler(rdma->channel->fd, rdma_accept_incoming_migration,
4190 NULL, (void *)(intptr_t)rdma);
4191 return;
4193 cleanup_rdma:
4194 qemu_rdma_cleanup(rdma);
4195 err:
4196 if (rdma) {
4197 g_free(rdma->host);
4198 g_free(rdma->host_port);
4200 g_free(rdma);
4203 void rdma_start_outgoing_migration(void *opaque,
4204 const char *host_port, Error **errp)
4206 MigrationState *s = opaque;
4207 RDMAContext *rdma_return_path = NULL;
4208 RDMAContext *rdma;
4209 int ret;
4211 /* Avoid ram_block_discard_disable(), cannot change during migration. */
4212 if (ram_block_discard_is_required()) {
4213 error_setg(errp, "RDMA: cannot disable RAM discard");
4214 return;
4217 rdma = qemu_rdma_data_init(host_port, errp);
4218 if (rdma == NULL) {
4219 goto err;
4222 ret = qemu_rdma_source_init(rdma, migrate_rdma_pin_all(), errp);
4224 if (ret < 0) {
4225 goto err;
4228 trace_rdma_start_outgoing_migration_after_rdma_source_init();
4229 ret = qemu_rdma_connect(rdma, false, errp);
4231 if (ret < 0) {
4232 goto err;
4235 /* RDMA postcopy need a separate queue pair for return path */
4236 if (migrate_postcopy() || migrate_return_path()) {
4237 rdma_return_path = qemu_rdma_data_init(host_port, errp);
4239 if (rdma_return_path == NULL) {
4240 goto return_path_err;
4243 ret = qemu_rdma_source_init(rdma_return_path,
4244 migrate_rdma_pin_all(), errp);
4246 if (ret < 0) {
4247 goto return_path_err;
4250 ret = qemu_rdma_connect(rdma_return_path, true, errp);
4252 if (ret < 0) {
4253 goto return_path_err;
4256 rdma->return_path = rdma_return_path;
4257 rdma_return_path->return_path = rdma;
4258 rdma_return_path->is_return_path = true;
4261 trace_rdma_start_outgoing_migration_after_rdma_connect();
4263 s->to_dst_file = rdma_new_output(rdma);
4264 migrate_fd_connect(s, NULL);
4265 return;
4266 return_path_err:
4267 qemu_rdma_cleanup(rdma);
4268 err:
4269 g_free(rdma);
4270 g_free(rdma_return_path);