]> git.proxmox.com Git - mirror_qemu.git/blob - migration/rdma.c
5f6a771e8e369292fa78c9062325607f7b15f97b
[mirror_qemu.git] / migration / rdma.c
1 /*
2 * RDMA protocol and interfaces
3 *
4 * Copyright IBM, Corp. 2010-2013
5 * Copyright Red Hat, Inc. 2015-2016
6 *
7 * Authors:
8 * Michael R. Hines <mrhines@us.ibm.com>
9 * Jiuxing Liu <jl@us.ibm.com>
10 * Daniel P. Berrange <berrange@redhat.com>
11 *
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.
14 *
15 */
16
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>
42
43 #define RDMA_RESOLVE_TIMEOUT_MS 10000
44
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)
48
49 #define RDMA_REG_CHUNK_SHIFT 20 /* 1 MB */
50
51 /*
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.
56 */
57 #define RDMA_SEND_INCREMENT 32768
58
59 /*
60 * Maximum size infiniband SEND message
61 */
62 #define RDMA_CONTROL_MAX_BUFFER (512 * 1024)
63 #define RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE 4096
64
65 #define RDMA_CONTROL_VERSION_CURRENT 1
66 /*
67 * Capabilities for negotiation.
68 */
69 #define RDMA_CAPABILITY_PIN_ALL 0x01
70
71 /*
72 * Add the other flags above to this list of known capabilities
73 * as they are introduced.
74 */
75 static uint32_t known_capabilities = RDMA_CAPABILITY_PIN_ALL;
76
77 /*
78 * A work request ID is 64-bits and we split up these bits
79 * into 3 parts:
80 *
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
84 *
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.
88 */
89 #define RDMA_WRID_TYPE_SHIFT 0UL
90 #define RDMA_WRID_BLOCK_SHIFT 16UL
91 #define RDMA_WRID_CHUNK_SHIFT 30UL
92
93 #define RDMA_WRID_TYPE_MASK \
94 ((1UL << RDMA_WRID_BLOCK_SHIFT) - 1UL)
95
96 #define RDMA_WRID_BLOCK_MASK \
97 (~RDMA_WRID_TYPE_MASK & ((1UL << RDMA_WRID_CHUNK_SHIFT) - 1UL))
98
99 #define RDMA_WRID_CHUNK_MASK (~RDMA_WRID_BLOCK_MASK & ~RDMA_WRID_TYPE_MASK)
100
101 /*
102 * RDMA migration protocol:
103 * 1. RDMA Writes (data messages, i.e. RAM)
104 * 2. IB Send/Recv (control channel messages)
105 */
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,
111 };
112
113 /*
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)
117 *
118 * We could use more WRs, but we have enough for now.
119 */
120 enum {
121 RDMA_WRID_READY = 0,
122 RDMA_WRID_DATA,
123 RDMA_WRID_CONTROL,
124 RDMA_WRID_MAX,
125 };
126
127 /*
128 * SEND/RECV IB Control Messages.
129 */
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 */
143 };
144
145
146 /*
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.
149 */
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;
156
157 /*
158 * Negotiate RDMA capabilities during connection-setup time.
159 */
160 typedef struct {
161 uint32_t version;
162 uint32_t flags;
163 } RDMACapabilities;
164
165 static void caps_to_network(RDMACapabilities *cap)
166 {
167 cap->version = htonl(cap->version);
168 cap->flags = htonl(cap->flags);
169 }
170
171 static void network_to_caps(RDMACapabilities *cap)
172 {
173 cap->version = ntohl(cap->version);
174 cap->flags = ntohl(cap->flags);
175 }
176
177 /*
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.
183 */
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;
201
202 /*
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.
208 */
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;
216
217 static const char *control_desc(unsigned int rdma_control)
218 {
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",
232 };
233
234 if (rdma_control > RDMA_CONTROL_UNREGISTER_FINISHED) {
235 return "??BAD CONTROL VALUE??";
236 }
237
238 return strs[rdma_control];
239 }
240
241 static uint64_t htonll(uint64_t v)
242 {
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;
247 }
248
249 static uint64_t ntohll(uint64_t v)
250 {
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]);
254 }
255
256 static void dest_block_to_network(RDMADestBlock *db)
257 {
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);
262 }
263
264 static void network_to_dest_block(RDMADestBlock *db)
265 {
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);
270 }
271
272 /*
273 * Virtual address of the above structures used for transmitting
274 * the RAMBlock descriptions at connection-time.
275 * This structure is *not* transmitted.
276 */
277 typedef struct RDMALocalBlocks {
278 int nb_blocks;
279 bool init; /* main memory init complete */
280 RDMALocalBlock *block;
281 } RDMALocalBlocks;
282
283 /*
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.
288 */
289 typedef struct RDMAContext {
290 char *host;
291 int port;
292 char *host_port;
293
294 RDMAWorkRequestData wr_data[RDMA_WRID_MAX];
295
296 /*
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.
302 */
303 int control_ready_expected;
304
305 /* number of outstanding writes */
306 int nb_sent;
307
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;
316
317 bool pin_all;
318
319 /*
320 * infiniband-specific variables for opening the device
321 * and maintaining connection state and so forth.
322 *
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.
325 */
326 struct rdma_cm_id *cm_id; /* connection manager ID */
327 struct rdma_cm_id *listen_id;
328 bool connected;
329
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 */
338
339 /*
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.
343 */
344 bool errored;
345 bool error_reported;
346 bool received_error;
347
348 /*
349 * Description of ram blocks used throughout the code.
350 */
351 RDMALocalBlocks local_ram_blocks;
352 RDMADestBlock *dest_blocks;
353
354 /* Index of the next RAMBlock received during block registration */
355 unsigned int next_src_index;
356
357 /*
358 * Migration on *destination* started.
359 * Then use coroutine yield function.
360 * Source runs in a thread, so we don't care.
361 */
362 int migration_started_on_destination;
363
364 int total_registrations;
365 int total_writes;
366
367 int unregister_current, unregister_next;
368 uint64_t unregistrations[RDMA_SIGNALED_SEND_MAX];
369
370 GHashTable *blockmap;
371
372 /* the RDMAContext for return path */
373 struct RDMAContext *return_path;
374 bool is_return_path;
375 } RDMAContext;
376
377 #define TYPE_QIO_CHANNEL_RDMA "qio-channel-rdma"
378 OBJECT_DECLARE_SIMPLE_TYPE(QIOChannelRDMA, QIO_CHANNEL_RDMA)
379
380
381
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 */
388 };
389
390 /*
391 * Main structure for IB Send/Recv control messages.
392 * This gets prepended at the beginning of every Send/Recv.
393 */
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;
400
401 static void control_to_network(RDMAControlHeader *control)
402 {
403 control->type = htonl(control->type);
404 control->len = htonl(control->len);
405 control->repeat = htonl(control->repeat);
406 }
407
408 static void network_to_control(RDMAControlHeader *control)
409 {
410 control->type = ntohl(control->type);
411 control->len = ntohl(control->len);
412 control->repeat = ntohl(control->repeat);
413 }
414
415 /*
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.
420 */
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;
430
431 static bool rdma_errored(RDMAContext *rdma)
432 {
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;
437 }
438 return rdma->errored;
439 }
440
441 static void register_to_network(RDMAContext *rdma, RDMARegister *reg)
442 {
443 RDMALocalBlock *local_block;
444 local_block = &rdma->local_ram_blocks.block[reg->current_index];
445
446 if (local_block->is_ram_block) {
447 /*
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
450 */
451 reg->key.current_addr -= local_block->offset;
452 reg->key.current_addr += rdma->dest_blocks[reg->current_index].offset;
453 }
454 reg->key.current_addr = htonll(reg->key.current_addr);
455 reg->current_index = htonl(reg->current_index);
456 reg->chunks = htonll(reg->chunks);
457 }
458
459 static void network_to_register(RDMARegister *reg)
460 {
461 reg->key.current_addr = ntohll(reg->key.current_addr);
462 reg->current_index = ntohl(reg->current_index);
463 reg->chunks = ntohll(reg->chunks);
464 }
465
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;
472
473 static void compress_to_network(RDMAContext *rdma, RDMACompress *comp)
474 {
475 comp->value = htonl(comp->value);
476 /*
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
479 */
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);
485 }
486
487 static void network_to_compress(RDMACompress *comp)
488 {
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);
493 }
494
495 /*
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.
499 */
500 typedef struct QEMU_PACKED {
501 uint32_t rkey;
502 uint32_t padding;
503 uint64_t host_addr;
504 } RDMARegisterResult;
505
506 static void result_to_network(RDMARegisterResult *result)
507 {
508 result->rkey = htonl(result->rkey);
509 result->host_addr = htonll(result->host_addr);
510 };
511
512 static void network_to_result(RDMARegisterResult *result)
513 {
514 result->rkey = ntohl(result->rkey);
515 result->host_addr = ntohll(result->host_addr);
516 };
517
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);
524
525 static inline uint64_t ram_chunk_index(const uint8_t *start,
526 const uint8_t *host)
527 {
528 return ((uintptr_t) host - (uintptr_t) start) >> RDMA_REG_CHUNK_SHIFT;
529 }
530
531 static inline uint8_t *ram_chunk_start(const RDMALocalBlock *rdma_ram_block,
532 uint64_t i)
533 {
534 return (uint8_t *)(uintptr_t)(rdma_ram_block->local_host_addr +
535 (i << RDMA_REG_CHUNK_SHIFT));
536 }
537
538 static inline uint8_t *ram_chunk_end(const RDMALocalBlock *rdma_ram_block,
539 uint64_t i)
540 {
541 uint8_t *result = ram_chunk_start(rdma_ram_block, i) +
542 (1UL << RDMA_REG_CHUNK_SHIFT);
543
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;
546 }
547
548 return result;
549 }
550
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)
554 {
555 RDMALocalBlocks *local = &rdma->local_ram_blocks;
556 RDMALocalBlock *block;
557 RDMALocalBlock *old = local->block;
558
559 local->block = g_new0(RDMALocalBlock, local->nb_blocks + 1);
560
561 if (local->nb_blocks) {
562 int x;
563
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]);
571 }
572 }
573 memcpy(local->block, old, sizeof(RDMALocalBlock) * local->nb_blocks);
574 g_free(old);
575 }
576
577 block = &local->block[local->nb_blocks];
578
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);
591
592 block->is_ram_block = local->init ? false : true;
593
594 if (rdma->blockmap) {
595 g_hash_table_insert(rdma->blockmap, (void *)(uintptr_t)block_offset, block);
596 }
597
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);
605
606 local->nb_blocks++;
607 }
608
609 /*
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.
613 */
614 static int qemu_rdma_init_one_block(RAMBlock *rb, void *opaque)
615 {
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;
622 }
623
624 /*
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.
628 */
629 static void qemu_rdma_init_ram_blocks(RDMAContext *rdma)
630 {
631 RDMALocalBlocks *local = &rdma->local_ram_blocks;
632 int ret;
633
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;
642 }
643
644 /*
645 * Note: If used outside of cleanup, the caller must ensure that the destination
646 * block structures are also updated
647 */
648 static void rdma_delete_block(RDMAContext *rdma, RDMALocalBlock *block)
649 {
650 RDMALocalBlocks *local = &rdma->local_ram_blocks;
651 RDMALocalBlock *old = local->block;
652 int x;
653
654 if (rdma->blockmap) {
655 g_hash_table_remove(rdma->blockmap, (void *)(uintptr_t)block->offset);
656 }
657 if (block->pmr) {
658 int j;
659
660 for (j = 0; j < block->nb_chunks; j++) {
661 if (!block->pmr[j]) {
662 continue;
663 }
664 ibv_dereg_mr(block->pmr[j]);
665 rdma->total_registrations--;
666 }
667 g_free(block->pmr);
668 block->pmr = NULL;
669 }
670
671 if (block->mr) {
672 ibv_dereg_mr(block->mr);
673 rdma->total_registrations--;
674 block->mr = NULL;
675 }
676
677 g_free(block->transit_bitmap);
678 block->transit_bitmap = NULL;
679
680 g_free(block->unregister_bitmap);
681 block->unregister_bitmap = NULL;
682
683 g_free(block->remote_keys);
684 block->remote_keys = NULL;
685
686 g_free(block->block_name);
687 block->block_name = NULL;
688
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);
693 }
694 }
695
696 if (local->nb_blocks > 1) {
697
698 local->block = g_new0(RDMALocalBlock, local->nb_blocks - 1);
699
700 if (block->index) {
701 memcpy(local->block, old, sizeof(RDMALocalBlock) * block->index);
702 }
703
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--;
710 }
711 }
712 } else {
713 assert(block == local->block);
714 local->block = NULL;
715 }
716
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);
722
723 g_free(old);
724
725 local->nb_blocks--;
726
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]);
732 }
733 }
734 }
735
736 /*
737 * Trace RDMA device open, with device details.
738 */
739 static void qemu_rdma_dump_id(const char *who, struct ibv_context *verbs)
740 {
741 struct ibv_port_attr port;
742
743 if (ibv_query_port(verbs, 1, &port)) {
744 trace_qemu_rdma_dump_id_failed(who);
745 return;
746 }
747
748 trace_qemu_rdma_dump_id(who,
749 verbs->device->name,
750 verbs->device->dev_name,
751 verbs->device->dev_path,
752 verbs->device->ibdev_path,
753 port.link_layer,
754 port.link_layer == IBV_LINK_LAYER_INFINIBAND ? "Infiniband"
755 : port.link_layer == IBV_LINK_LAYER_ETHERNET ? "Ethernet"
756 : "Unknown");
757 }
758
759 /*
760 * Trace RDMA gid addressing information.
761 * Useful for understanding the RDMA device hierarchy in the kernel.
762 */
763 static void qemu_rdma_dump_gid(const char *who, struct rdma_cm_id *id)
764 {
765 char sgid[33];
766 char dgid[33];
767 inet_ntop(AF_INET6, &id->route.addr.addr.ibaddr.sgid, sgid, sizeof sgid);
768 inet_ntop(AF_INET6, &id->route.addr.addr.ibaddr.dgid, dgid, sizeof dgid);
769 trace_qemu_rdma_dump_gid(who, sgid, dgid);
770 }
771
772 /*
773 * As of now, IPv6 over RoCE / iWARP is not supported by linux.
774 * We will try the next addrinfo struct, and fail if there are
775 * no other valid addresses to bind against.
776 *
777 * If user is listening on '[::]', then we will not have a opened a device
778 * yet and have no way of verifying if the device is RoCE or not.
779 *
780 * In this case, the source VM will throw an error for ALL types of
781 * connections (both IPv4 and IPv6) if the destination machine does not have
782 * a regular infiniband network available for use.
783 *
784 * The only way to guarantee that an error is thrown for broken kernels is
785 * for the management software to choose a *specific* interface at bind time
786 * and validate what time of hardware it is.
787 *
788 * Unfortunately, this puts the user in a fix:
789 *
790 * If the source VM connects with an IPv4 address without knowing that the
791 * destination has bound to '[::]' the migration will unconditionally fail
792 * unless the management software is explicitly listening on the IPv4
793 * address while using a RoCE-based device.
794 *
795 * If the source VM connects with an IPv6 address, then we're OK because we can
796 * throw an error on the source (and similarly on the destination).
797 *
798 * But in mixed environments, this will be broken for a while until it is fixed
799 * inside linux.
800 *
801 * We do provide a *tiny* bit of help in this function: We can list all of the
802 * devices in the system and check to see if all the devices are RoCE or
803 * Infiniband.
804 *
805 * If we detect that we have a *pure* RoCE environment, then we can safely
806 * thrown an error even if the management software has specified '[::]' as the
807 * bind address.
808 *
809 * However, if there is are multiple hetergeneous devices, then we cannot make
810 * this assumption and the user just has to be sure they know what they are
811 * doing.
812 *
813 * Patches are being reviewed on linux-rdma.
814 */
815 static int qemu_rdma_broken_ipv6_kernel(struct ibv_context *verbs, Error **errp)
816 {
817 /* This bug only exists in linux, to our knowledge. */
818 #ifdef CONFIG_LINUX
819 struct ibv_port_attr port_attr;
820
821 /*
822 * Verbs are only NULL if management has bound to '[::]'.
823 *
824 * Let's iterate through all the devices and see if there any pure IB
825 * devices (non-ethernet).
826 *
827 * If not, then we can safely proceed with the migration.
828 * Otherwise, there are no guarantees until the bug is fixed in linux.
829 */
830 if (!verbs) {
831 int num_devices, x;
832 struct ibv_device **dev_list = ibv_get_device_list(&num_devices);
833 bool roce_found = false;
834 bool ib_found = false;
835
836 for (x = 0; x < num_devices; x++) {
837 verbs = ibv_open_device(dev_list[x]);
838 /*
839 * ibv_open_device() is not documented to set errno. If
840 * it does, it's somebody else's doc bug. If it doesn't,
841 * the use of errno below is wrong.
842 * TODO Find out whether ibv_open_device() sets errno.
843 */
844 if (!verbs) {
845 if (errno == EPERM) {
846 continue;
847 } else {
848 error_setg_errno(errp, errno,
849 "could not open RDMA device context");
850 return -1;
851 }
852 }
853
854 if (ibv_query_port(verbs, 1, &port_attr)) {
855 ibv_close_device(verbs);
856 error_setg(errp,
857 "RDMA ERROR: Could not query initial IB port");
858 return -1;
859 }
860
861 if (port_attr.link_layer == IBV_LINK_LAYER_INFINIBAND) {
862 ib_found = true;
863 } else if (port_attr.link_layer == IBV_LINK_LAYER_ETHERNET) {
864 roce_found = true;
865 }
866
867 ibv_close_device(verbs);
868
869 }
870
871 if (roce_found) {
872 if (ib_found) {
873 warn_report("migrations may fail:"
874 " IPv6 over RoCE / iWARP in linux"
875 " is broken. But since you appear to have a"
876 " mixed RoCE / IB environment, be sure to only"
877 " migrate over the IB fabric until the kernel "
878 " fixes the bug.");
879 } else {
880 error_setg(errp, "RDMA ERROR: "
881 "You only have RoCE / iWARP devices in your systems"
882 " and your management software has specified '[::]'"
883 ", but IPv6 over RoCE / iWARP is not supported in Linux.");
884 return -1;
885 }
886 }
887
888 return 0;
889 }
890
891 /*
892 * If we have a verbs context, that means that some other than '[::]' was
893 * used by the management software for binding. In which case we can
894 * actually warn the user about a potentially broken kernel.
895 */
896
897 /* IB ports start with 1, not 0 */
898 if (ibv_query_port(verbs, 1, &port_attr)) {
899 error_setg(errp, "RDMA ERROR: Could not query initial IB port");
900 return -1;
901 }
902
903 if (port_attr.link_layer == IBV_LINK_LAYER_ETHERNET) {
904 error_setg(errp, "RDMA ERROR: "
905 "Linux kernel's RoCE / iWARP does not support IPv6 "
906 "(but patches on linux-rdma in progress)");
907 return -1;
908 }
909
910 #endif
911
912 return 0;
913 }
914
915 /*
916 * Figure out which RDMA device corresponds to the requested IP hostname
917 * Also create the initial connection manager identifiers for opening
918 * the connection.
919 */
920 static int qemu_rdma_resolve_host(RDMAContext *rdma, Error **errp)
921 {
922 Error *err = NULL;
923 int ret;
924 struct rdma_addrinfo *res;
925 char port_str[16];
926 struct rdma_cm_event *cm_event;
927 char ip[40] = "unknown";
928 struct rdma_addrinfo *e;
929
930 if (rdma->host == NULL || !strcmp(rdma->host, "")) {
931 error_setg(errp, "RDMA ERROR: RDMA hostname has not been set");
932 return -1;
933 }
934
935 /* create CM channel */
936 rdma->channel = rdma_create_event_channel();
937 if (!rdma->channel) {
938 error_setg(errp, "RDMA ERROR: could not create CM channel");
939 return -1;
940 }
941
942 /* create CM id */
943 ret = rdma_create_id(rdma->channel, &rdma->cm_id, NULL, RDMA_PS_TCP);
944 if (ret < 0) {
945 error_setg(errp, "RDMA ERROR: could not create channel id");
946 goto err_resolve_create_id;
947 }
948
949 snprintf(port_str, 16, "%d", rdma->port);
950 port_str[15] = '\0';
951
952 ret = rdma_getaddrinfo(rdma->host, port_str, NULL, &res);
953 if (ret) {
954 error_setg(errp, "RDMA ERROR: could not rdma_getaddrinfo address %s",
955 rdma->host);
956 goto err_resolve_get_addr;
957 }
958
959 /* Try all addresses, saving the first error in @err */
960 for (e = res; e != NULL; e = e->ai_next) {
961 Error **local_errp = err ? NULL : &err;
962
963 inet_ntop(e->ai_family,
964 &((struct sockaddr_in *) e->ai_dst_addr)->sin_addr, ip, sizeof ip);
965 trace_qemu_rdma_resolve_host_trying(rdma->host, ip);
966
967 ret = rdma_resolve_addr(rdma->cm_id, NULL, e->ai_dst_addr,
968 RDMA_RESOLVE_TIMEOUT_MS);
969 if (ret >= 0) {
970 if (e->ai_family == AF_INET6) {
971 ret = qemu_rdma_broken_ipv6_kernel(rdma->cm_id->verbs,
972 local_errp);
973 if (ret < 0) {
974 continue;
975 }
976 }
977 error_free(err);
978 goto route;
979 }
980 }
981
982 rdma_freeaddrinfo(res);
983 if (err) {
984 error_propagate(errp, err);
985 } else {
986 error_setg(errp, "RDMA ERROR: could not resolve address %s",
987 rdma->host);
988 }
989 goto err_resolve_get_addr;
990
991 route:
992 rdma_freeaddrinfo(res);
993 qemu_rdma_dump_gid("source_resolve_addr", rdma->cm_id);
994
995 ret = rdma_get_cm_event(rdma->channel, &cm_event);
996 if (ret < 0) {
997 error_setg(errp, "RDMA ERROR: could not perform event_addr_resolved");
998 goto err_resolve_get_addr;
999 }
1000
1001 if (cm_event->event != RDMA_CM_EVENT_ADDR_RESOLVED) {
1002 error_setg(errp,
1003 "RDMA ERROR: result not equal to event_addr_resolved %s",
1004 rdma_event_str(cm_event->event));
1005 rdma_ack_cm_event(cm_event);
1006 goto err_resolve_get_addr;
1007 }
1008 rdma_ack_cm_event(cm_event);
1009
1010 /* resolve route */
1011 ret = rdma_resolve_route(rdma->cm_id, RDMA_RESOLVE_TIMEOUT_MS);
1012 if (ret < 0) {
1013 error_setg(errp, "RDMA ERROR: could not resolve rdma route");
1014 goto err_resolve_get_addr;
1015 }
1016
1017 ret = rdma_get_cm_event(rdma->channel, &cm_event);
1018 if (ret < 0) {
1019 error_setg(errp, "RDMA ERROR: could not perform event_route_resolved");
1020 goto err_resolve_get_addr;
1021 }
1022 if (cm_event->event != RDMA_CM_EVENT_ROUTE_RESOLVED) {
1023 error_setg(errp, "RDMA ERROR: "
1024 "result not equal to event_route_resolved: %s",
1025 rdma_event_str(cm_event->event));
1026 rdma_ack_cm_event(cm_event);
1027 goto err_resolve_get_addr;
1028 }
1029 rdma_ack_cm_event(cm_event);
1030 rdma->verbs = rdma->cm_id->verbs;
1031 qemu_rdma_dump_id("source_resolve_host", rdma->cm_id->verbs);
1032 qemu_rdma_dump_gid("source_resolve_host", rdma->cm_id);
1033 return 0;
1034
1035 err_resolve_get_addr:
1036 rdma_destroy_id(rdma->cm_id);
1037 rdma->cm_id = NULL;
1038 err_resolve_create_id:
1039 rdma_destroy_event_channel(rdma->channel);
1040 rdma->channel = NULL;
1041 return -1;
1042 }
1043
1044 /*
1045 * Create protection domain and completion queues
1046 */
1047 static int qemu_rdma_alloc_pd_cq(RDMAContext *rdma, Error **errp)
1048 {
1049 /* allocate pd */
1050 rdma->pd = ibv_alloc_pd(rdma->verbs);
1051 if (!rdma->pd) {
1052 error_setg(errp, "failed to allocate protection domain");
1053 return -1;
1054 }
1055
1056 /* create receive completion channel */
1057 rdma->recv_comp_channel = ibv_create_comp_channel(rdma->verbs);
1058 if (!rdma->recv_comp_channel) {
1059 error_setg(errp, "failed to allocate receive completion channel");
1060 goto err_alloc_pd_cq;
1061 }
1062
1063 /*
1064 * Completion queue can be filled by read work requests.
1065 */
1066 rdma->recv_cq = ibv_create_cq(rdma->verbs, (RDMA_SIGNALED_SEND_MAX * 3),
1067 NULL, rdma->recv_comp_channel, 0);
1068 if (!rdma->recv_cq) {
1069 error_setg(errp, "failed to allocate receive completion queue");
1070 goto err_alloc_pd_cq;
1071 }
1072
1073 /* create send completion channel */
1074 rdma->send_comp_channel = ibv_create_comp_channel(rdma->verbs);
1075 if (!rdma->send_comp_channel) {
1076 error_setg(errp, "failed to allocate send completion channel");
1077 goto err_alloc_pd_cq;
1078 }
1079
1080 rdma->send_cq = ibv_create_cq(rdma->verbs, (RDMA_SIGNALED_SEND_MAX * 3),
1081 NULL, rdma->send_comp_channel, 0);
1082 if (!rdma->send_cq) {
1083 error_setg(errp, "failed to allocate send completion queue");
1084 goto err_alloc_pd_cq;
1085 }
1086
1087 return 0;
1088
1089 err_alloc_pd_cq:
1090 if (rdma->pd) {
1091 ibv_dealloc_pd(rdma->pd);
1092 }
1093 if (rdma->recv_comp_channel) {
1094 ibv_destroy_comp_channel(rdma->recv_comp_channel);
1095 }
1096 if (rdma->send_comp_channel) {
1097 ibv_destroy_comp_channel(rdma->send_comp_channel);
1098 }
1099 if (rdma->recv_cq) {
1100 ibv_destroy_cq(rdma->recv_cq);
1101 rdma->recv_cq = NULL;
1102 }
1103 rdma->pd = NULL;
1104 rdma->recv_comp_channel = NULL;
1105 rdma->send_comp_channel = NULL;
1106 return -1;
1107
1108 }
1109
1110 /*
1111 * Create queue pairs.
1112 */
1113 static int qemu_rdma_alloc_qp(RDMAContext *rdma)
1114 {
1115 struct ibv_qp_init_attr attr = { 0 };
1116 int ret;
1117
1118 attr.cap.max_send_wr = RDMA_SIGNALED_SEND_MAX;
1119 attr.cap.max_recv_wr = 3;
1120 attr.cap.max_send_sge = 1;
1121 attr.cap.max_recv_sge = 1;
1122 attr.send_cq = rdma->send_cq;
1123 attr.recv_cq = rdma->recv_cq;
1124 attr.qp_type = IBV_QPT_RC;
1125
1126 ret = rdma_create_qp(rdma->cm_id, rdma->pd, &attr);
1127 if (ret < 0) {
1128 return -1;
1129 }
1130
1131 rdma->qp = rdma->cm_id->qp;
1132 return 0;
1133 }
1134
1135 /* Check whether On-Demand Paging is supported by RDAM device */
1136 static bool rdma_support_odp(struct ibv_context *dev)
1137 {
1138 struct ibv_device_attr_ex attr = {0};
1139 int ret = ibv_query_device_ex(dev, NULL, &attr);
1140 if (ret) {
1141 return false;
1142 }
1143
1144 if (attr.odp_caps.general_caps & IBV_ODP_SUPPORT) {
1145 return true;
1146 }
1147
1148 return false;
1149 }
1150
1151 /*
1152 * ibv_advise_mr to avoid RNR NAK error as far as possible.
1153 * The responder mr registering with ODP will sent RNR NAK back to
1154 * the requester in the face of the page fault.
1155 */
1156 static void qemu_rdma_advise_prefetch_mr(struct ibv_pd *pd, uint64_t addr,
1157 uint32_t len, uint32_t lkey,
1158 const char *name, bool wr)
1159 {
1160 #ifdef HAVE_IBV_ADVISE_MR
1161 int ret;
1162 int advice = wr ? IBV_ADVISE_MR_ADVICE_PREFETCH_WRITE :
1163 IBV_ADVISE_MR_ADVICE_PREFETCH;
1164 struct ibv_sge sg_list = {.lkey = lkey, .addr = addr, .length = len};
1165
1166 ret = ibv_advise_mr(pd, advice,
1167 IBV_ADVISE_MR_FLAG_FLUSH, &sg_list, 1);
1168 /* ignore the error */
1169 trace_qemu_rdma_advise_mr(name, len, addr, strerror(ret));
1170 #endif
1171 }
1172
1173 static int qemu_rdma_reg_whole_ram_blocks(RDMAContext *rdma, Error **errp)
1174 {
1175 int i;
1176 RDMALocalBlocks *local = &rdma->local_ram_blocks;
1177
1178 for (i = 0; i < local->nb_blocks; i++) {
1179 int access = IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE;
1180
1181 local->block[i].mr =
1182 ibv_reg_mr(rdma->pd,
1183 local->block[i].local_host_addr,
1184 local->block[i].length, access
1185 );
1186 /*
1187 * ibv_reg_mr() is not documented to set errno. If it does,
1188 * it's somebody else's doc bug. If it doesn't, the use of
1189 * errno below is wrong.
1190 * TODO Find out whether ibv_reg_mr() sets errno.
1191 */
1192 if (!local->block[i].mr &&
1193 errno == ENOTSUP && rdma_support_odp(rdma->verbs)) {
1194 access |= IBV_ACCESS_ON_DEMAND;
1195 /* register ODP mr */
1196 local->block[i].mr =
1197 ibv_reg_mr(rdma->pd,
1198 local->block[i].local_host_addr,
1199 local->block[i].length, access);
1200 trace_qemu_rdma_register_odp_mr(local->block[i].block_name);
1201
1202 if (local->block[i].mr) {
1203 qemu_rdma_advise_prefetch_mr(rdma->pd,
1204 (uintptr_t)local->block[i].local_host_addr,
1205 local->block[i].length,
1206 local->block[i].mr->lkey,
1207 local->block[i].block_name,
1208 true);
1209 }
1210 }
1211
1212 if (!local->block[i].mr) {
1213 error_setg_errno(errp, errno,
1214 "Failed to register local dest ram block!");
1215 goto err;
1216 }
1217 rdma->total_registrations++;
1218 }
1219
1220 return 0;
1221
1222 err:
1223 for (i--; i >= 0; i--) {
1224 ibv_dereg_mr(local->block[i].mr);
1225 local->block[i].mr = NULL;
1226 rdma->total_registrations--;
1227 }
1228
1229 return -1;
1230
1231 }
1232
1233 /*
1234 * Find the ram block that corresponds to the page requested to be
1235 * transmitted by QEMU.
1236 *
1237 * Once the block is found, also identify which 'chunk' within that
1238 * block that the page belongs to.
1239 */
1240 static void qemu_rdma_search_ram_block(RDMAContext *rdma,
1241 uintptr_t block_offset,
1242 uint64_t offset,
1243 uint64_t length,
1244 uint64_t *block_index,
1245 uint64_t *chunk_index)
1246 {
1247 uint64_t current_addr = block_offset + offset;
1248 RDMALocalBlock *block = g_hash_table_lookup(rdma->blockmap,
1249 (void *) block_offset);
1250 assert(block);
1251 assert(current_addr >= block->offset);
1252 assert((current_addr + length) <= (block->offset + block->length));
1253
1254 *block_index = block->index;
1255 *chunk_index = ram_chunk_index(block->local_host_addr,
1256 block->local_host_addr + (current_addr - block->offset));
1257 }
1258
1259 /*
1260 * Register a chunk with IB. If the chunk was already registered
1261 * previously, then skip.
1262 *
1263 * Also return the keys associated with the registration needed
1264 * to perform the actual RDMA operation.
1265 */
1266 static int qemu_rdma_register_and_get_keys(RDMAContext *rdma,
1267 RDMALocalBlock *block, uintptr_t host_addr,
1268 uint32_t *lkey, uint32_t *rkey, int chunk,
1269 uint8_t *chunk_start, uint8_t *chunk_end)
1270 {
1271 if (block->mr) {
1272 if (lkey) {
1273 *lkey = block->mr->lkey;
1274 }
1275 if (rkey) {
1276 *rkey = block->mr->rkey;
1277 }
1278 return 0;
1279 }
1280
1281 /* allocate memory to store chunk MRs */
1282 if (!block->pmr) {
1283 block->pmr = g_new0(struct ibv_mr *, block->nb_chunks);
1284 }
1285
1286 /*
1287 * If 'rkey', then we're the destination, so grant access to the source.
1288 *
1289 * If 'lkey', then we're the source VM, so grant access only to ourselves.
1290 */
1291 if (!block->pmr[chunk]) {
1292 uint64_t len = chunk_end - chunk_start;
1293 int access = rkey ? IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE :
1294 0;
1295
1296 trace_qemu_rdma_register_and_get_keys(len, chunk_start);
1297
1298 block->pmr[chunk] = ibv_reg_mr(rdma->pd, chunk_start, len, access);
1299 /*
1300 * ibv_reg_mr() is not documented to set errno. If it does,
1301 * it's somebody else's doc bug. If it doesn't, the use of
1302 * errno below is wrong.
1303 * TODO Find out whether ibv_reg_mr() sets errno.
1304 */
1305 if (!block->pmr[chunk] &&
1306 errno == ENOTSUP && rdma_support_odp(rdma->verbs)) {
1307 access |= IBV_ACCESS_ON_DEMAND;
1308 /* register ODP mr */
1309 block->pmr[chunk] = ibv_reg_mr(rdma->pd, chunk_start, len, access);
1310 trace_qemu_rdma_register_odp_mr(block->block_name);
1311
1312 if (block->pmr[chunk]) {
1313 qemu_rdma_advise_prefetch_mr(rdma->pd, (uintptr_t)chunk_start,
1314 len, block->pmr[chunk]->lkey,
1315 block->block_name, rkey);
1316
1317 }
1318 }
1319 }
1320 if (!block->pmr[chunk]) {
1321 return -1;
1322 }
1323 rdma->total_registrations++;
1324
1325 if (lkey) {
1326 *lkey = block->pmr[chunk]->lkey;
1327 }
1328 if (rkey) {
1329 *rkey = block->pmr[chunk]->rkey;
1330 }
1331 return 0;
1332 }
1333
1334 /*
1335 * Register (at connection time) the memory used for control
1336 * channel messages.
1337 */
1338 static int qemu_rdma_reg_control(RDMAContext *rdma, int idx)
1339 {
1340 rdma->wr_data[idx].control_mr = ibv_reg_mr(rdma->pd,
1341 rdma->wr_data[idx].control, RDMA_CONTROL_MAX_BUFFER,
1342 IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE);
1343 if (rdma->wr_data[idx].control_mr) {
1344 rdma->total_registrations++;
1345 return 0;
1346 }
1347 return -1;
1348 }
1349
1350 /*
1351 * Perform a non-optimized memory unregistration after every transfer
1352 * for demonstration purposes, only if pin-all is not requested.
1353 *
1354 * Potential optimizations:
1355 * 1. Start a new thread to run this function continuously
1356 - for bit clearing
1357 - and for receipt of unregister messages
1358 * 2. Use an LRU.
1359 * 3. Use workload hints.
1360 */
1361 static int qemu_rdma_unregister_waiting(RDMAContext *rdma)
1362 {
1363 Error *err = NULL;
1364
1365 while (rdma->unregistrations[rdma->unregister_current]) {
1366 int ret;
1367 uint64_t wr_id = rdma->unregistrations[rdma->unregister_current];
1368 uint64_t chunk =
1369 (wr_id & RDMA_WRID_CHUNK_MASK) >> RDMA_WRID_CHUNK_SHIFT;
1370 uint64_t index =
1371 (wr_id & RDMA_WRID_BLOCK_MASK) >> RDMA_WRID_BLOCK_SHIFT;
1372 RDMALocalBlock *block =
1373 &(rdma->local_ram_blocks.block[index]);
1374 RDMARegister reg = { .current_index = index };
1375 RDMAControlHeader resp = { .type = RDMA_CONTROL_UNREGISTER_FINISHED,
1376 };
1377 RDMAControlHeader head = { .len = sizeof(RDMARegister),
1378 .type = RDMA_CONTROL_UNREGISTER_REQUEST,
1379 .repeat = 1,
1380 };
1381
1382 trace_qemu_rdma_unregister_waiting_proc(chunk,
1383 rdma->unregister_current);
1384
1385 rdma->unregistrations[rdma->unregister_current] = 0;
1386 rdma->unregister_current++;
1387
1388 if (rdma->unregister_current == RDMA_SIGNALED_SEND_MAX) {
1389 rdma->unregister_current = 0;
1390 }
1391
1392
1393 /*
1394 * Unregistration is speculative (because migration is single-threaded
1395 * and we cannot break the protocol's inifinband message ordering).
1396 * Thus, if the memory is currently being used for transmission,
1397 * then abort the attempt to unregister and try again
1398 * later the next time a completion is received for this memory.
1399 */
1400 clear_bit(chunk, block->unregister_bitmap);
1401
1402 if (test_bit(chunk, block->transit_bitmap)) {
1403 trace_qemu_rdma_unregister_waiting_inflight(chunk);
1404 continue;
1405 }
1406
1407 trace_qemu_rdma_unregister_waiting_send(chunk);
1408
1409 ret = ibv_dereg_mr(block->pmr[chunk]);
1410 block->pmr[chunk] = NULL;
1411 block->remote_keys[chunk] = 0;
1412
1413 if (ret != 0) {
1414 error_report("unregistration chunk failed: %s",
1415 strerror(ret));
1416 return -1;
1417 }
1418 rdma->total_registrations--;
1419
1420 reg.key.chunk = chunk;
1421 register_to_network(rdma, &reg);
1422 ret = qemu_rdma_exchange_send(rdma, &head, (uint8_t *) &reg,
1423 &resp, NULL, NULL, &err);
1424 if (ret < 0) {
1425 error_report_err(err);
1426 return -1;
1427 }
1428
1429 trace_qemu_rdma_unregister_waiting_complete(chunk);
1430 }
1431
1432 return 0;
1433 }
1434
1435 static uint64_t qemu_rdma_make_wrid(uint64_t wr_id, uint64_t index,
1436 uint64_t chunk)
1437 {
1438 uint64_t result = wr_id & RDMA_WRID_TYPE_MASK;
1439
1440 result |= (index << RDMA_WRID_BLOCK_SHIFT);
1441 result |= (chunk << RDMA_WRID_CHUNK_SHIFT);
1442
1443 return result;
1444 }
1445
1446 /*
1447 * Consult the connection manager to see a work request
1448 * (of any kind) has completed.
1449 * Return the work request ID that completed.
1450 */
1451 static int qemu_rdma_poll(RDMAContext *rdma, struct ibv_cq *cq,
1452 uint64_t *wr_id_out, uint32_t *byte_len)
1453 {
1454 int ret;
1455 struct ibv_wc wc;
1456 uint64_t wr_id;
1457
1458 ret = ibv_poll_cq(cq, 1, &wc);
1459
1460 if (!ret) {
1461 *wr_id_out = RDMA_WRID_NONE;
1462 return 0;
1463 }
1464
1465 if (ret < 0) {
1466 return -1;
1467 }
1468
1469 wr_id = wc.wr_id & RDMA_WRID_TYPE_MASK;
1470
1471 if (wc.status != IBV_WC_SUCCESS) {
1472 return -1;
1473 }
1474
1475 if (rdma->control_ready_expected &&
1476 (wr_id >= RDMA_WRID_RECV_CONTROL)) {
1477 trace_qemu_rdma_poll_recv(wr_id - RDMA_WRID_RECV_CONTROL, wr_id,
1478 rdma->nb_sent);
1479 rdma->control_ready_expected = 0;
1480 }
1481
1482 if (wr_id == RDMA_WRID_RDMA_WRITE) {
1483 uint64_t chunk =
1484 (wc.wr_id & RDMA_WRID_CHUNK_MASK) >> RDMA_WRID_CHUNK_SHIFT;
1485 uint64_t index =
1486 (wc.wr_id & RDMA_WRID_BLOCK_MASK) >> RDMA_WRID_BLOCK_SHIFT;
1487 RDMALocalBlock *block = &(rdma->local_ram_blocks.block[index]);
1488
1489 trace_qemu_rdma_poll_write(wr_id, rdma->nb_sent,
1490 index, chunk, block->local_host_addr,
1491 (void *)(uintptr_t)block->remote_host_addr);
1492
1493 clear_bit(chunk, block->transit_bitmap);
1494
1495 if (rdma->nb_sent > 0) {
1496 rdma->nb_sent--;
1497 }
1498 } else {
1499 trace_qemu_rdma_poll_other(wr_id, rdma->nb_sent);
1500 }
1501
1502 *wr_id_out = wc.wr_id;
1503 if (byte_len) {
1504 *byte_len = wc.byte_len;
1505 }
1506
1507 return 0;
1508 }
1509
1510 /* Wait for activity on the completion channel.
1511 * Returns 0 on success, none-0 on error.
1512 */
1513 static int qemu_rdma_wait_comp_channel(RDMAContext *rdma,
1514 struct ibv_comp_channel *comp_channel)
1515 {
1516 struct rdma_cm_event *cm_event;
1517 int ret;
1518
1519 /*
1520 * Coroutine doesn't start until migration_fd_process_incoming()
1521 * so don't yield unless we know we're running inside of a coroutine.
1522 */
1523 if (rdma->migration_started_on_destination &&
1524 migration_incoming_get_current()->state == MIGRATION_STATUS_ACTIVE) {
1525 yield_until_fd_readable(comp_channel->fd);
1526 } else {
1527 /* This is the source side, we're in a separate thread
1528 * or destination prior to migration_fd_process_incoming()
1529 * after postcopy, the destination also in a separate thread.
1530 * we can't yield; so we have to poll the fd.
1531 * But we need to be able to handle 'cancel' or an error
1532 * without hanging forever.
1533 */
1534 while (!rdma->errored && !rdma->received_error) {
1535 GPollFD pfds[2];
1536 pfds[0].fd = comp_channel->fd;
1537 pfds[0].events = G_IO_IN | G_IO_HUP | G_IO_ERR;
1538 pfds[0].revents = 0;
1539
1540 pfds[1].fd = rdma->channel->fd;
1541 pfds[1].events = G_IO_IN | G_IO_HUP | G_IO_ERR;
1542 pfds[1].revents = 0;
1543
1544 /* 0.1s timeout, should be fine for a 'cancel' */
1545 switch (qemu_poll_ns(pfds, 2, 100 * 1000 * 1000)) {
1546 case 2:
1547 case 1: /* fd active */
1548 if (pfds[0].revents) {
1549 return 0;
1550 }
1551
1552 if (pfds[1].revents) {
1553 ret = rdma_get_cm_event(rdma->channel, &cm_event);
1554 if (ret < 0) {
1555 return -1;
1556 }
1557
1558 if (cm_event->event == RDMA_CM_EVENT_DISCONNECTED ||
1559 cm_event->event == RDMA_CM_EVENT_DEVICE_REMOVAL) {
1560 rdma_ack_cm_event(cm_event);
1561 return -1;
1562 }
1563 rdma_ack_cm_event(cm_event);
1564 }
1565 break;
1566
1567 case 0: /* Timeout, go around again */
1568 break;
1569
1570 default: /* Error of some type -
1571 * I don't trust errno from qemu_poll_ns
1572 */
1573 return -1;
1574 }
1575
1576 if (migrate_get_current()->state == MIGRATION_STATUS_CANCELLING) {
1577 /* Bail out and let the cancellation happen */
1578 return -1;
1579 }
1580 }
1581 }
1582
1583 if (rdma->received_error) {
1584 return -1;
1585 }
1586 return -rdma->errored;
1587 }
1588
1589 static struct ibv_comp_channel *to_channel(RDMAContext *rdma, uint64_t wrid)
1590 {
1591 return wrid < RDMA_WRID_RECV_CONTROL ? rdma->send_comp_channel :
1592 rdma->recv_comp_channel;
1593 }
1594
1595 static struct ibv_cq *to_cq(RDMAContext *rdma, uint64_t wrid)
1596 {
1597 return wrid < RDMA_WRID_RECV_CONTROL ? rdma->send_cq : rdma->recv_cq;
1598 }
1599
1600 /*
1601 * Block until the next work request has completed.
1602 *
1603 * First poll to see if a work request has already completed,
1604 * otherwise block.
1605 *
1606 * If we encounter completed work requests for IDs other than
1607 * the one we're interested in, then that's generally an error.
1608 *
1609 * The only exception is actual RDMA Write completions. These
1610 * completions only need to be recorded, but do not actually
1611 * need further processing.
1612 */
1613 static int qemu_rdma_block_for_wrid(RDMAContext *rdma,
1614 uint64_t wrid_requested,
1615 uint32_t *byte_len)
1616 {
1617 int num_cq_events = 0, ret;
1618 struct ibv_cq *cq;
1619 void *cq_ctx;
1620 uint64_t wr_id = RDMA_WRID_NONE, wr_id_in;
1621 struct ibv_comp_channel *ch = to_channel(rdma, wrid_requested);
1622 struct ibv_cq *poll_cq = to_cq(rdma, wrid_requested);
1623
1624 if (ibv_req_notify_cq(poll_cq, 0)) {
1625 return -1;
1626 }
1627 /* poll cq first */
1628 while (wr_id != wrid_requested) {
1629 ret = qemu_rdma_poll(rdma, poll_cq, &wr_id_in, byte_len);
1630 if (ret < 0) {
1631 return -1;
1632 }
1633
1634 wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
1635
1636 if (wr_id == RDMA_WRID_NONE) {
1637 break;
1638 }
1639 if (wr_id != wrid_requested) {
1640 trace_qemu_rdma_block_for_wrid_miss(wrid_requested, wr_id);
1641 }
1642 }
1643
1644 if (wr_id == wrid_requested) {
1645 return 0;
1646 }
1647
1648 while (1) {
1649 ret = qemu_rdma_wait_comp_channel(rdma, ch);
1650 if (ret < 0) {
1651 goto err_block_for_wrid;
1652 }
1653
1654 ret = ibv_get_cq_event(ch, &cq, &cq_ctx);
1655 if (ret < 0) {
1656 goto err_block_for_wrid;
1657 }
1658
1659 num_cq_events++;
1660
1661 if (ibv_req_notify_cq(cq, 0)) {
1662 goto err_block_for_wrid;
1663 }
1664
1665 while (wr_id != wrid_requested) {
1666 ret = qemu_rdma_poll(rdma, poll_cq, &wr_id_in, byte_len);
1667 if (ret < 0) {
1668 goto err_block_for_wrid;
1669 }
1670
1671 wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
1672
1673 if (wr_id == RDMA_WRID_NONE) {
1674 break;
1675 }
1676 if (wr_id != wrid_requested) {
1677 trace_qemu_rdma_block_for_wrid_miss(wrid_requested, wr_id);
1678 }
1679 }
1680
1681 if (wr_id == wrid_requested) {
1682 goto success_block_for_wrid;
1683 }
1684 }
1685
1686 success_block_for_wrid:
1687 if (num_cq_events) {
1688 ibv_ack_cq_events(cq, num_cq_events);
1689 }
1690 return 0;
1691
1692 err_block_for_wrid:
1693 if (num_cq_events) {
1694 ibv_ack_cq_events(cq, num_cq_events);
1695 }
1696
1697 rdma->errored = true;
1698 return -1;
1699 }
1700
1701 /*
1702 * Post a SEND message work request for the control channel
1703 * containing some data and block until the post completes.
1704 */
1705 static int qemu_rdma_post_send_control(RDMAContext *rdma, uint8_t *buf,
1706 RDMAControlHeader *head,
1707 Error **errp)
1708 {
1709 int ret;
1710 RDMAWorkRequestData *wr = &rdma->wr_data[RDMA_WRID_CONTROL];
1711 struct ibv_send_wr *bad_wr;
1712 struct ibv_sge sge = {
1713 .addr = (uintptr_t)(wr->control),
1714 .length = head->len + sizeof(RDMAControlHeader),
1715 .lkey = wr->control_mr->lkey,
1716 };
1717 struct ibv_send_wr send_wr = {
1718 .wr_id = RDMA_WRID_SEND_CONTROL,
1719 .opcode = IBV_WR_SEND,
1720 .send_flags = IBV_SEND_SIGNALED,
1721 .sg_list = &sge,
1722 .num_sge = 1,
1723 };
1724
1725 trace_qemu_rdma_post_send_control(control_desc(head->type));
1726
1727 /*
1728 * We don't actually need to do a memcpy() in here if we used
1729 * the "sge" properly, but since we're only sending control messages
1730 * (not RAM in a performance-critical path), then its OK for now.
1731 *
1732 * The copy makes the RDMAControlHeader simpler to manipulate
1733 * for the time being.
1734 */
1735 assert(head->len <= RDMA_CONTROL_MAX_BUFFER - sizeof(*head));
1736 memcpy(wr->control, head, sizeof(RDMAControlHeader));
1737 control_to_network((void *) wr->control);
1738
1739 if (buf) {
1740 memcpy(wr->control + sizeof(RDMAControlHeader), buf, head->len);
1741 }
1742
1743
1744 ret = ibv_post_send(rdma->qp, &send_wr, &bad_wr);
1745
1746 if (ret > 0) {
1747 error_setg(errp, "Failed to use post IB SEND for control");
1748 return -1;
1749 }
1750
1751 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_SEND_CONTROL, NULL);
1752 if (ret < 0) {
1753 error_setg(errp, "rdma migration: send polling control error");
1754 return -1;
1755 }
1756
1757 return 0;
1758 }
1759
1760 /*
1761 * Post a RECV work request in anticipation of some future receipt
1762 * of data on the control channel.
1763 */
1764 static int qemu_rdma_post_recv_control(RDMAContext *rdma, int idx,
1765 Error **errp)
1766 {
1767 struct ibv_recv_wr *bad_wr;
1768 struct ibv_sge sge = {
1769 .addr = (uintptr_t)(rdma->wr_data[idx].control),
1770 .length = RDMA_CONTROL_MAX_BUFFER,
1771 .lkey = rdma->wr_data[idx].control_mr->lkey,
1772 };
1773
1774 struct ibv_recv_wr recv_wr = {
1775 .wr_id = RDMA_WRID_RECV_CONTROL + idx,
1776 .sg_list = &sge,
1777 .num_sge = 1,
1778 };
1779
1780
1781 if (ibv_post_recv(rdma->qp, &recv_wr, &bad_wr)) {
1782 error_setg(errp, "error posting control recv");
1783 return -1;
1784 }
1785
1786 return 0;
1787 }
1788
1789 /*
1790 * Block and wait for a RECV control channel message to arrive.
1791 */
1792 static int qemu_rdma_exchange_get_response(RDMAContext *rdma,
1793 RDMAControlHeader *head, uint32_t expecting, int idx,
1794 Error **errp)
1795 {
1796 uint32_t byte_len;
1797 int ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RECV_CONTROL + idx,
1798 &byte_len);
1799
1800 if (ret < 0) {
1801 error_setg(errp, "rdma migration: recv polling control error!");
1802 return -1;
1803 }
1804
1805 network_to_control((void *) rdma->wr_data[idx].control);
1806 memcpy(head, rdma->wr_data[idx].control, sizeof(RDMAControlHeader));
1807
1808 trace_qemu_rdma_exchange_get_response_start(control_desc(expecting));
1809
1810 if (expecting == RDMA_CONTROL_NONE) {
1811 trace_qemu_rdma_exchange_get_response_none(control_desc(head->type),
1812 head->type);
1813 } else if (head->type != expecting || head->type == RDMA_CONTROL_ERROR) {
1814 error_setg(errp, "Was expecting a %s (%d) control message"
1815 ", but got: %s (%d), length: %d",
1816 control_desc(expecting), expecting,
1817 control_desc(head->type), head->type, head->len);
1818 if (head->type == RDMA_CONTROL_ERROR) {
1819 rdma->received_error = true;
1820 }
1821 return -1;
1822 }
1823 if (head->len > RDMA_CONTROL_MAX_BUFFER - sizeof(*head)) {
1824 error_setg(errp, "too long length: %d", head->len);
1825 return -1;
1826 }
1827 if (sizeof(*head) + head->len != byte_len) {
1828 error_setg(errp, "Malformed length: %d byte_len %d",
1829 head->len, byte_len);
1830 return -1;
1831 }
1832
1833 return 0;
1834 }
1835
1836 /*
1837 * When a RECV work request has completed, the work request's
1838 * buffer is pointed at the header.
1839 *
1840 * This will advance the pointer to the data portion
1841 * of the control message of the work request's buffer that
1842 * was populated after the work request finished.
1843 */
1844 static void qemu_rdma_move_header(RDMAContext *rdma, int idx,
1845 RDMAControlHeader *head)
1846 {
1847 rdma->wr_data[idx].control_len = head->len;
1848 rdma->wr_data[idx].control_curr =
1849 rdma->wr_data[idx].control + sizeof(RDMAControlHeader);
1850 }
1851
1852 /*
1853 * This is an 'atomic' high-level operation to deliver a single, unified
1854 * control-channel message.
1855 *
1856 * Additionally, if the user is expecting some kind of reply to this message,
1857 * they can request a 'resp' response message be filled in by posting an
1858 * additional work request on behalf of the user and waiting for an additional
1859 * completion.
1860 *
1861 * The extra (optional) response is used during registration to us from having
1862 * to perform an *additional* exchange of message just to provide a response by
1863 * instead piggy-backing on the acknowledgement.
1864 */
1865 static int qemu_rdma_exchange_send(RDMAContext *rdma, RDMAControlHeader *head,
1866 uint8_t *data, RDMAControlHeader *resp,
1867 int *resp_idx,
1868 int (*callback)(RDMAContext *rdma,
1869 Error **errp),
1870 Error **errp)
1871 {
1872 int ret;
1873
1874 /*
1875 * Wait until the dest is ready before attempting to deliver the message
1876 * by waiting for a READY message.
1877 */
1878 if (rdma->control_ready_expected) {
1879 RDMAControlHeader resp_ignored;
1880
1881 ret = qemu_rdma_exchange_get_response(rdma, &resp_ignored,
1882 RDMA_CONTROL_READY,
1883 RDMA_WRID_READY, errp);
1884 if (ret < 0) {
1885 return -1;
1886 }
1887 }
1888
1889 /*
1890 * If the user is expecting a response, post a WR in anticipation of it.
1891 */
1892 if (resp) {
1893 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_DATA, errp);
1894 if (ret < 0) {
1895 return -1;
1896 }
1897 }
1898
1899 /*
1900 * Post a WR to replace the one we just consumed for the READY message.
1901 */
1902 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY, errp);
1903 if (ret < 0) {
1904 return -1;
1905 }
1906
1907 /*
1908 * Deliver the control message that was requested.
1909 */
1910 ret = qemu_rdma_post_send_control(rdma, data, head, errp);
1911
1912 if (ret < 0) {
1913 return -1;
1914 }
1915
1916 /*
1917 * If we're expecting a response, block and wait for it.
1918 */
1919 if (resp) {
1920 if (callback) {
1921 trace_qemu_rdma_exchange_send_issue_callback();
1922 ret = callback(rdma, errp);
1923 if (ret < 0) {
1924 return -1;
1925 }
1926 }
1927
1928 trace_qemu_rdma_exchange_send_waiting(control_desc(resp->type));
1929 ret = qemu_rdma_exchange_get_response(rdma, resp,
1930 resp->type, RDMA_WRID_DATA,
1931 errp);
1932
1933 if (ret < 0) {
1934 return -1;
1935 }
1936
1937 qemu_rdma_move_header(rdma, RDMA_WRID_DATA, resp);
1938 if (resp_idx) {
1939 *resp_idx = RDMA_WRID_DATA;
1940 }
1941 trace_qemu_rdma_exchange_send_received(control_desc(resp->type));
1942 }
1943
1944 rdma->control_ready_expected = 1;
1945
1946 return 0;
1947 }
1948
1949 /*
1950 * This is an 'atomic' high-level operation to receive a single, unified
1951 * control-channel message.
1952 */
1953 static int qemu_rdma_exchange_recv(RDMAContext *rdma, RDMAControlHeader *head,
1954 uint32_t expecting, Error **errp)
1955 {
1956 RDMAControlHeader ready = {
1957 .len = 0,
1958 .type = RDMA_CONTROL_READY,
1959 .repeat = 1,
1960 };
1961 int ret;
1962
1963 /*
1964 * Inform the source that we're ready to receive a message.
1965 */
1966 ret = qemu_rdma_post_send_control(rdma, NULL, &ready, errp);
1967
1968 if (ret < 0) {
1969 return -1;
1970 }
1971
1972 /*
1973 * Block and wait for the message.
1974 */
1975 ret = qemu_rdma_exchange_get_response(rdma, head,
1976 expecting, RDMA_WRID_READY, errp);
1977
1978 if (ret < 0) {
1979 return -1;
1980 }
1981
1982 qemu_rdma_move_header(rdma, RDMA_WRID_READY, head);
1983
1984 /*
1985 * Post a new RECV work request to replace the one we just consumed.
1986 */
1987 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY, errp);
1988 if (ret < 0) {
1989 return -1;
1990 }
1991
1992 return 0;
1993 }
1994
1995 /*
1996 * Write an actual chunk of memory using RDMA.
1997 *
1998 * If we're using dynamic registration on the dest-side, we have to
1999 * send a registration command first.
2000 */
2001 static int qemu_rdma_write_one(RDMAContext *rdma,
2002 int current_index, uint64_t current_addr,
2003 uint64_t length, Error **errp)
2004 {
2005 struct ibv_sge sge;
2006 struct ibv_send_wr send_wr = { 0 };
2007 struct ibv_send_wr *bad_wr;
2008 int reg_result_idx, ret, count = 0;
2009 uint64_t chunk, chunks;
2010 uint8_t *chunk_start, *chunk_end;
2011 RDMALocalBlock *block = &(rdma->local_ram_blocks.block[current_index]);
2012 RDMARegister reg;
2013 RDMARegisterResult *reg_result;
2014 RDMAControlHeader resp = { .type = RDMA_CONTROL_REGISTER_RESULT };
2015 RDMAControlHeader head = { .len = sizeof(RDMARegister),
2016 .type = RDMA_CONTROL_REGISTER_REQUEST,
2017 .repeat = 1,
2018 };
2019
2020 retry:
2021 sge.addr = (uintptr_t)(block->local_host_addr +
2022 (current_addr - block->offset));
2023 sge.length = length;
2024
2025 chunk = ram_chunk_index(block->local_host_addr,
2026 (uint8_t *)(uintptr_t)sge.addr);
2027 chunk_start = ram_chunk_start(block, chunk);
2028
2029 if (block->is_ram_block) {
2030 chunks = length / (1UL << RDMA_REG_CHUNK_SHIFT);
2031
2032 if (chunks && ((length % (1UL << RDMA_REG_CHUNK_SHIFT)) == 0)) {
2033 chunks--;
2034 }
2035 } else {
2036 chunks = block->length / (1UL << RDMA_REG_CHUNK_SHIFT);
2037
2038 if (chunks && ((block->length % (1UL << RDMA_REG_CHUNK_SHIFT)) == 0)) {
2039 chunks--;
2040 }
2041 }
2042
2043 trace_qemu_rdma_write_one_top(chunks + 1,
2044 (chunks + 1) *
2045 (1UL << RDMA_REG_CHUNK_SHIFT) / 1024 / 1024);
2046
2047 chunk_end = ram_chunk_end(block, chunk + chunks);
2048
2049
2050 while (test_bit(chunk, block->transit_bitmap)) {
2051 (void)count;
2052 trace_qemu_rdma_write_one_block(count++, current_index, chunk,
2053 sge.addr, length, rdma->nb_sent, block->nb_chunks);
2054
2055 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL);
2056
2057 if (ret < 0) {
2058 error_setg(errp, "Failed to Wait for previous write to complete "
2059 "block %d chunk %" PRIu64
2060 " current %" PRIu64 " len %" PRIu64 " %d",
2061 current_index, chunk, sge.addr, length, rdma->nb_sent);
2062 return -1;
2063 }
2064 }
2065
2066 if (!rdma->pin_all || !block->is_ram_block) {
2067 if (!block->remote_keys[chunk]) {
2068 /*
2069 * This chunk has not yet been registered, so first check to see
2070 * if the entire chunk is zero. If so, tell the other size to
2071 * memset() + madvise() the entire chunk without RDMA.
2072 */
2073
2074 if (buffer_is_zero((void *)(uintptr_t)sge.addr, length)) {
2075 RDMACompress comp = {
2076 .offset = current_addr,
2077 .value = 0,
2078 .block_idx = current_index,
2079 .length = length,
2080 };
2081
2082 head.len = sizeof(comp);
2083 head.type = RDMA_CONTROL_COMPRESS;
2084
2085 trace_qemu_rdma_write_one_zero(chunk, sge.length,
2086 current_index, current_addr);
2087
2088 compress_to_network(rdma, &comp);
2089 ret = qemu_rdma_exchange_send(rdma, &head,
2090 (uint8_t *) &comp, NULL, NULL, NULL, errp);
2091
2092 if (ret < 0) {
2093 return -1;
2094 }
2095
2096 /*
2097 * TODO: Here we are sending something, but we are not
2098 * accounting for anything transferred. The following is wrong:
2099 *
2100 * stat64_add(&mig_stats.rdma_bytes, sge.length);
2101 *
2102 * because we are using some kind of compression. I
2103 * would think that head.len would be the more similar
2104 * thing to a correct value.
2105 */
2106 stat64_add(&mig_stats.zero_pages,
2107 sge.length / qemu_target_page_size());
2108 return 1;
2109 }
2110
2111 /*
2112 * Otherwise, tell other side to register.
2113 */
2114 reg.current_index = current_index;
2115 if (block->is_ram_block) {
2116 reg.key.current_addr = current_addr;
2117 } else {
2118 reg.key.chunk = chunk;
2119 }
2120 reg.chunks = chunks;
2121
2122 trace_qemu_rdma_write_one_sendreg(chunk, sge.length, current_index,
2123 current_addr);
2124
2125 register_to_network(rdma, &reg);
2126 ret = qemu_rdma_exchange_send(rdma, &head, (uint8_t *) &reg,
2127 &resp, &reg_result_idx, NULL, errp);
2128 if (ret < 0) {
2129 return -1;
2130 }
2131
2132 /* try to overlap this single registration with the one we sent. */
2133 if (qemu_rdma_register_and_get_keys(rdma, block, sge.addr,
2134 &sge.lkey, NULL, chunk,
2135 chunk_start, chunk_end)) {
2136 error_setg(errp, "cannot get lkey");
2137 return -1;
2138 }
2139
2140 reg_result = (RDMARegisterResult *)
2141 rdma->wr_data[reg_result_idx].control_curr;
2142
2143 network_to_result(reg_result);
2144
2145 trace_qemu_rdma_write_one_recvregres(block->remote_keys[chunk],
2146 reg_result->rkey, chunk);
2147
2148 block->remote_keys[chunk] = reg_result->rkey;
2149 block->remote_host_addr = reg_result->host_addr;
2150 } else {
2151 /* already registered before */
2152 if (qemu_rdma_register_and_get_keys(rdma, block, sge.addr,
2153 &sge.lkey, NULL, chunk,
2154 chunk_start, chunk_end)) {
2155 error_setg(errp, "cannot get lkey!");
2156 return -1;
2157 }
2158 }
2159
2160 send_wr.wr.rdma.rkey = block->remote_keys[chunk];
2161 } else {
2162 send_wr.wr.rdma.rkey = block->remote_rkey;
2163
2164 if (qemu_rdma_register_and_get_keys(rdma, block, sge.addr,
2165 &sge.lkey, NULL, chunk,
2166 chunk_start, chunk_end)) {
2167 error_setg(errp, "cannot get lkey!");
2168 return -1;
2169 }
2170 }
2171
2172 /*
2173 * Encode the ram block index and chunk within this wrid.
2174 * We will use this information at the time of completion
2175 * to figure out which bitmap to check against and then which
2176 * chunk in the bitmap to look for.
2177 */
2178 send_wr.wr_id = qemu_rdma_make_wrid(RDMA_WRID_RDMA_WRITE,
2179 current_index, chunk);
2180
2181 send_wr.opcode = IBV_WR_RDMA_WRITE;
2182 send_wr.send_flags = IBV_SEND_SIGNALED;
2183 send_wr.sg_list = &sge;
2184 send_wr.num_sge = 1;
2185 send_wr.wr.rdma.remote_addr = block->remote_host_addr +
2186 (current_addr - block->offset);
2187
2188 trace_qemu_rdma_write_one_post(chunk, sge.addr, send_wr.wr.rdma.remote_addr,
2189 sge.length);
2190
2191 /*
2192 * ibv_post_send() does not return negative error numbers,
2193 * per the specification they are positive - no idea why.
2194 */
2195 ret = ibv_post_send(rdma->qp, &send_wr, &bad_wr);
2196
2197 if (ret == ENOMEM) {
2198 trace_qemu_rdma_write_one_queue_full();
2199 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL);
2200 if (ret < 0) {
2201 error_setg(errp, "rdma migration: failed to make "
2202 "room in full send queue!");
2203 return -1;
2204 }
2205
2206 goto retry;
2207
2208 } else if (ret > 0) {
2209 error_setg_errno(errp, ret,
2210 "rdma migration: post rdma write failed");
2211 return -1;
2212 }
2213
2214 set_bit(chunk, block->transit_bitmap);
2215 stat64_add(&mig_stats.normal_pages, sge.length / qemu_target_page_size());
2216 /*
2217 * We are adding to transferred the amount of data written, but no
2218 * overhead at all. I will asume that RDMA is magicaly and don't
2219 * need to transfer (at least) the addresses where it wants to
2220 * write the pages. Here it looks like it should be something
2221 * like:
2222 * sizeof(send_wr) + sge.length
2223 * but this being RDMA, who knows.
2224 */
2225 stat64_add(&mig_stats.rdma_bytes, sge.length);
2226 ram_transferred_add(sge.length);
2227 rdma->total_writes++;
2228
2229 return 0;
2230 }
2231
2232 /*
2233 * Push out any unwritten RDMA operations.
2234 *
2235 * We support sending out multiple chunks at the same time.
2236 * Not all of them need to get signaled in the completion queue.
2237 */
2238 static int qemu_rdma_write_flush(RDMAContext *rdma, Error **errp)
2239 {
2240 int ret;
2241
2242 if (!rdma->current_length) {
2243 return 0;
2244 }
2245
2246 ret = qemu_rdma_write_one(rdma, rdma->current_index, rdma->current_addr,
2247 rdma->current_length, errp);
2248
2249 if (ret < 0) {
2250 return -1;
2251 }
2252
2253 if (ret == 0) {
2254 rdma->nb_sent++;
2255 trace_qemu_rdma_write_flush(rdma->nb_sent);
2256 }
2257
2258 rdma->current_length = 0;
2259 rdma->current_addr = 0;
2260
2261 return 0;
2262 }
2263
2264 static inline bool qemu_rdma_buffer_mergeable(RDMAContext *rdma,
2265 uint64_t offset, uint64_t len)
2266 {
2267 RDMALocalBlock *block;
2268 uint8_t *host_addr;
2269 uint8_t *chunk_end;
2270
2271 if (rdma->current_index < 0) {
2272 return false;
2273 }
2274
2275 if (rdma->current_chunk < 0) {
2276 return false;
2277 }
2278
2279 block = &(rdma->local_ram_blocks.block[rdma->current_index]);
2280 host_addr = block->local_host_addr + (offset - block->offset);
2281 chunk_end = ram_chunk_end(block, rdma->current_chunk);
2282
2283 if (rdma->current_length == 0) {
2284 return false;
2285 }
2286
2287 /*
2288 * Only merge into chunk sequentially.
2289 */
2290 if (offset != (rdma->current_addr + rdma->current_length)) {
2291 return false;
2292 }
2293
2294 if (offset < block->offset) {
2295 return false;
2296 }
2297
2298 if ((offset + len) > (block->offset + block->length)) {
2299 return false;
2300 }
2301
2302 if ((host_addr + len) > chunk_end) {
2303 return false;
2304 }
2305
2306 return true;
2307 }
2308
2309 /*
2310 * We're not actually writing here, but doing three things:
2311 *
2312 * 1. Identify the chunk the buffer belongs to.
2313 * 2. If the chunk is full or the buffer doesn't belong to the current
2314 * chunk, then start a new chunk and flush() the old chunk.
2315 * 3. To keep the hardware busy, we also group chunks into batches
2316 * and only require that a batch gets acknowledged in the completion
2317 * queue instead of each individual chunk.
2318 */
2319 static int qemu_rdma_write(RDMAContext *rdma,
2320 uint64_t block_offset, uint64_t offset,
2321 uint64_t len, Error **errp)
2322 {
2323 uint64_t current_addr = block_offset + offset;
2324 uint64_t index = rdma->current_index;
2325 uint64_t chunk = rdma->current_chunk;
2326 int ret;
2327
2328 /* If we cannot merge it, we flush the current buffer first. */
2329 if (!qemu_rdma_buffer_mergeable(rdma, current_addr, len)) {
2330 ret = qemu_rdma_write_flush(rdma, errp);
2331 if (ret < 0) {
2332 return -1;
2333 }
2334 rdma->current_length = 0;
2335 rdma->current_addr = current_addr;
2336
2337 qemu_rdma_search_ram_block(rdma, block_offset,
2338 offset, len, &index, &chunk);
2339 rdma->current_index = index;
2340 rdma->current_chunk = chunk;
2341 }
2342
2343 /* merge it */
2344 rdma->current_length += len;
2345
2346 /* flush it if buffer is too large */
2347 if (rdma->current_length >= RDMA_MERGE_MAX) {
2348 return qemu_rdma_write_flush(rdma, errp);
2349 }
2350
2351 return 0;
2352 }
2353
2354 static void qemu_rdma_cleanup(RDMAContext *rdma)
2355 {
2356 Error *err = NULL;
2357
2358 if (rdma->cm_id && rdma->connected) {
2359 if ((rdma->errored ||
2360 migrate_get_current()->state == MIGRATION_STATUS_CANCELLING) &&
2361 !rdma->received_error) {
2362 RDMAControlHeader head = { .len = 0,
2363 .type = RDMA_CONTROL_ERROR,
2364 .repeat = 1,
2365 };
2366 warn_report("Early error. Sending error.");
2367 if (qemu_rdma_post_send_control(rdma, NULL, &head, &err) < 0) {
2368 warn_report_err(err);
2369 }
2370 }
2371
2372 rdma_disconnect(rdma->cm_id);
2373 trace_qemu_rdma_cleanup_disconnect();
2374 rdma->connected = false;
2375 }
2376
2377 if (rdma->channel) {
2378 qemu_set_fd_handler(rdma->channel->fd, NULL, NULL, NULL);
2379 }
2380 g_free(rdma->dest_blocks);
2381 rdma->dest_blocks = NULL;
2382
2383 for (int i = 0; i < RDMA_WRID_MAX; i++) {
2384 if (rdma->wr_data[i].control_mr) {
2385 rdma->total_registrations--;
2386 ibv_dereg_mr(rdma->wr_data[i].control_mr);
2387 }
2388 rdma->wr_data[i].control_mr = NULL;
2389 }
2390
2391 if (rdma->local_ram_blocks.block) {
2392 while (rdma->local_ram_blocks.nb_blocks) {
2393 rdma_delete_block(rdma, &rdma->local_ram_blocks.block[0]);
2394 }
2395 }
2396
2397 if (rdma->qp) {
2398 rdma_destroy_qp(rdma->cm_id);
2399 rdma->qp = NULL;
2400 }
2401 if (rdma->recv_cq) {
2402 ibv_destroy_cq(rdma->recv_cq);
2403 rdma->recv_cq = NULL;
2404 }
2405 if (rdma->send_cq) {
2406 ibv_destroy_cq(rdma->send_cq);
2407 rdma->send_cq = NULL;
2408 }
2409 if (rdma->recv_comp_channel) {
2410 ibv_destroy_comp_channel(rdma->recv_comp_channel);
2411 rdma->recv_comp_channel = NULL;
2412 }
2413 if (rdma->send_comp_channel) {
2414 ibv_destroy_comp_channel(rdma->send_comp_channel);
2415 rdma->send_comp_channel = NULL;
2416 }
2417 if (rdma->pd) {
2418 ibv_dealloc_pd(rdma->pd);
2419 rdma->pd = NULL;
2420 }
2421 if (rdma->cm_id) {
2422 rdma_destroy_id(rdma->cm_id);
2423 rdma->cm_id = NULL;
2424 }
2425
2426 /* the destination side, listen_id and channel is shared */
2427 if (rdma->listen_id) {
2428 if (!rdma->is_return_path) {
2429 rdma_destroy_id(rdma->listen_id);
2430 }
2431 rdma->listen_id = NULL;
2432
2433 if (rdma->channel) {
2434 if (!rdma->is_return_path) {
2435 rdma_destroy_event_channel(rdma->channel);
2436 }
2437 rdma->channel = NULL;
2438 }
2439 }
2440
2441 if (rdma->channel) {
2442 rdma_destroy_event_channel(rdma->channel);
2443 rdma->channel = NULL;
2444 }
2445 g_free(rdma->host);
2446 g_free(rdma->host_port);
2447 rdma->host = NULL;
2448 rdma->host_port = NULL;
2449 }
2450
2451
2452 static int qemu_rdma_source_init(RDMAContext *rdma, bool pin_all, Error **errp)
2453 {
2454 int ret;
2455
2456 /*
2457 * Will be validated against destination's actual capabilities
2458 * after the connect() completes.
2459 */
2460 rdma->pin_all = pin_all;
2461
2462 ret = qemu_rdma_resolve_host(rdma, errp);
2463 if (ret < 0) {
2464 goto err_rdma_source_init;
2465 }
2466
2467 ret = qemu_rdma_alloc_pd_cq(rdma, errp);
2468 if (ret < 0) {
2469 goto err_rdma_source_init;
2470 }
2471
2472 ret = qemu_rdma_alloc_qp(rdma);
2473 if (ret < 0) {
2474 error_setg(errp, "RDMA ERROR: rdma migration: error allocating qp!");
2475 goto err_rdma_source_init;
2476 }
2477
2478 qemu_rdma_init_ram_blocks(rdma);
2479
2480 /* Build the hash that maps from offset to RAMBlock */
2481 rdma->blockmap = g_hash_table_new(g_direct_hash, g_direct_equal);
2482 for (int i = 0; i < rdma->local_ram_blocks.nb_blocks; i++) {
2483 g_hash_table_insert(rdma->blockmap,
2484 (void *)(uintptr_t)rdma->local_ram_blocks.block[i].offset,
2485 &rdma->local_ram_blocks.block[i]);
2486 }
2487
2488 for (int i = 0; i < RDMA_WRID_MAX; i++) {
2489 ret = qemu_rdma_reg_control(rdma, i);
2490 if (ret < 0) {
2491 error_setg(errp, "RDMA ERROR: rdma migration: error "
2492 "registering %d control!", i);
2493 goto err_rdma_source_init;
2494 }
2495 }
2496
2497 return 0;
2498
2499 err_rdma_source_init:
2500 qemu_rdma_cleanup(rdma);
2501 return -1;
2502 }
2503
2504 static int qemu_get_cm_event_timeout(RDMAContext *rdma,
2505 struct rdma_cm_event **cm_event,
2506 long msec, Error **errp)
2507 {
2508 int ret;
2509 struct pollfd poll_fd = {
2510 .fd = rdma->channel->fd,
2511 .events = POLLIN,
2512 .revents = 0
2513 };
2514
2515 do {
2516 ret = poll(&poll_fd, 1, msec);
2517 } while (ret < 0 && errno == EINTR);
2518
2519 if (ret == 0) {
2520 error_setg(errp, "RDMA ERROR: poll cm event timeout");
2521 return -1;
2522 } else if (ret < 0) {
2523 error_setg(errp, "RDMA ERROR: failed to poll cm event, errno=%i",
2524 errno);
2525 return -1;
2526 } else if (poll_fd.revents & POLLIN) {
2527 if (rdma_get_cm_event(rdma->channel, cm_event) < 0) {
2528 error_setg(errp, "RDMA ERROR: failed to get cm event");
2529 return -1;
2530 }
2531 return 0;
2532 } else {
2533 error_setg(errp, "RDMA ERROR: no POLLIN event, revent=%x",
2534 poll_fd.revents);
2535 return -1;
2536 }
2537 }
2538
2539 static int qemu_rdma_connect(RDMAContext *rdma, bool return_path,
2540 Error **errp)
2541 {
2542 RDMACapabilities cap = {
2543 .version = RDMA_CONTROL_VERSION_CURRENT,
2544 .flags = 0,
2545 };
2546 struct rdma_conn_param conn_param = { .initiator_depth = 2,
2547 .retry_count = 5,
2548 .private_data = &cap,
2549 .private_data_len = sizeof(cap),
2550 };
2551 struct rdma_cm_event *cm_event;
2552 int ret;
2553
2554 /*
2555 * Only negotiate the capability with destination if the user
2556 * on the source first requested the capability.
2557 */
2558 if (rdma->pin_all) {
2559 trace_qemu_rdma_connect_pin_all_requested();
2560 cap.flags |= RDMA_CAPABILITY_PIN_ALL;
2561 }
2562
2563 caps_to_network(&cap);
2564
2565 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY, errp);
2566 if (ret < 0) {
2567 goto err_rdma_source_connect;
2568 }
2569
2570 ret = rdma_connect(rdma->cm_id, &conn_param);
2571 if (ret < 0) {
2572 error_setg_errno(errp, errno,
2573 "RDMA ERROR: connecting to destination!");
2574 goto err_rdma_source_connect;
2575 }
2576
2577 if (return_path) {
2578 ret = qemu_get_cm_event_timeout(rdma, &cm_event, 5000, errp);
2579 } else {
2580 ret = rdma_get_cm_event(rdma->channel, &cm_event);
2581 if (ret < 0) {
2582 error_setg_errno(errp, errno,
2583 "RDMA ERROR: failed to get cm event");
2584 }
2585 }
2586 if (ret < 0) {
2587 goto err_rdma_source_connect;
2588 }
2589
2590 if (cm_event->event != RDMA_CM_EVENT_ESTABLISHED) {
2591 error_setg(errp, "RDMA ERROR: connecting to destination!");
2592 rdma_ack_cm_event(cm_event);
2593 goto err_rdma_source_connect;
2594 }
2595 rdma->connected = true;
2596
2597 memcpy(&cap, cm_event->param.conn.private_data, sizeof(cap));
2598 network_to_caps(&cap);
2599
2600 /*
2601 * Verify that the *requested* capabilities are supported by the destination
2602 * and disable them otherwise.
2603 */
2604 if (rdma->pin_all && !(cap.flags & RDMA_CAPABILITY_PIN_ALL)) {
2605 warn_report("RDMA: Server cannot support pinning all memory. "
2606 "Will register memory dynamically.");
2607 rdma->pin_all = false;
2608 }
2609
2610 trace_qemu_rdma_connect_pin_all_outcome(rdma->pin_all);
2611
2612 rdma_ack_cm_event(cm_event);
2613
2614 rdma->control_ready_expected = 1;
2615 rdma->nb_sent = 0;
2616 return 0;
2617
2618 err_rdma_source_connect:
2619 qemu_rdma_cleanup(rdma);
2620 return -1;
2621 }
2622
2623 static int qemu_rdma_dest_init(RDMAContext *rdma, Error **errp)
2624 {
2625 Error *err = NULL;
2626 int ret;
2627 struct rdma_cm_id *listen_id;
2628 char ip[40] = "unknown";
2629 struct rdma_addrinfo *res, *e;
2630 char port_str[16];
2631 int reuse = 1;
2632
2633 for (int i = 0; i < RDMA_WRID_MAX; i++) {
2634 rdma->wr_data[i].control_len = 0;
2635 rdma->wr_data[i].control_curr = NULL;
2636 }
2637
2638 if (!rdma->host || !rdma->host[0]) {
2639 error_setg(errp, "RDMA ERROR: RDMA host is not set!");
2640 rdma->errored = true;
2641 return -1;
2642 }
2643 /* create CM channel */
2644 rdma->channel = rdma_create_event_channel();
2645 if (!rdma->channel) {
2646 error_setg(errp, "RDMA ERROR: could not create rdma event channel");
2647 rdma->errored = true;
2648 return -1;
2649 }
2650
2651 /* create CM id */
2652 ret = rdma_create_id(rdma->channel, &listen_id, NULL, RDMA_PS_TCP);
2653 if (ret < 0) {
2654 error_setg(errp, "RDMA ERROR: could not create cm_id!");
2655 goto err_dest_init_create_listen_id;
2656 }
2657
2658 snprintf(port_str, 16, "%d", rdma->port);
2659 port_str[15] = '\0';
2660
2661 ret = rdma_getaddrinfo(rdma->host, port_str, NULL, &res);
2662 if (ret) {
2663 error_setg(errp, "RDMA ERROR: could not rdma_getaddrinfo address %s",
2664 rdma->host);
2665 goto err_dest_init_bind_addr;
2666 }
2667
2668 ret = rdma_set_option(listen_id, RDMA_OPTION_ID, RDMA_OPTION_ID_REUSEADDR,
2669 &reuse, sizeof reuse);
2670 if (ret < 0) {
2671 error_setg(errp, "RDMA ERROR: Error: could not set REUSEADDR option");
2672 goto err_dest_init_bind_addr;
2673 }
2674
2675 /* Try all addresses, saving the first error in @err */
2676 for (e = res; e != NULL; e = e->ai_next) {
2677 Error **local_errp = err ? NULL : &err;
2678
2679 inet_ntop(e->ai_family,
2680 &((struct sockaddr_in *) e->ai_dst_addr)->sin_addr, ip, sizeof ip);
2681 trace_qemu_rdma_dest_init_trying(rdma->host, ip);
2682 ret = rdma_bind_addr(listen_id, e->ai_dst_addr);
2683 if (ret < 0) {
2684 continue;
2685 }
2686 if (e->ai_family == AF_INET6) {
2687 ret = qemu_rdma_broken_ipv6_kernel(listen_id->verbs,
2688 local_errp);
2689 if (ret < 0) {
2690 continue;
2691 }
2692 }
2693 error_free(err);
2694 break;
2695 }
2696
2697 rdma_freeaddrinfo(res);
2698 if (!e) {
2699 if (err) {
2700 error_propagate(errp, err);
2701 } else {
2702 error_setg(errp, "RDMA ERROR: Error: could not rdma_bind_addr!");
2703 }
2704 goto err_dest_init_bind_addr;
2705 }
2706
2707 rdma->listen_id = listen_id;
2708 qemu_rdma_dump_gid("dest_init", listen_id);
2709 return 0;
2710
2711 err_dest_init_bind_addr:
2712 rdma_destroy_id(listen_id);
2713 err_dest_init_create_listen_id:
2714 rdma_destroy_event_channel(rdma->channel);
2715 rdma->channel = NULL;
2716 rdma->errored = true;
2717 return -1;
2718
2719 }
2720
2721 static void qemu_rdma_return_path_dest_init(RDMAContext *rdma_return_path,
2722 RDMAContext *rdma)
2723 {
2724 for (int i = 0; i < RDMA_WRID_MAX; i++) {
2725 rdma_return_path->wr_data[i].control_len = 0;
2726 rdma_return_path->wr_data[i].control_curr = NULL;
2727 }
2728
2729 /*the CM channel and CM id is shared*/
2730 rdma_return_path->channel = rdma->channel;
2731 rdma_return_path->listen_id = rdma->listen_id;
2732
2733 rdma->return_path = rdma_return_path;
2734 rdma_return_path->return_path = rdma;
2735 rdma_return_path->is_return_path = true;
2736 }
2737
2738 static RDMAContext *qemu_rdma_data_init(const char *host_port, Error **errp)
2739 {
2740 RDMAContext *rdma = NULL;
2741 InetSocketAddress *addr;
2742
2743 rdma = g_new0(RDMAContext, 1);
2744 rdma->current_index = -1;
2745 rdma->current_chunk = -1;
2746
2747 addr = g_new(InetSocketAddress, 1);
2748 if (!inet_parse(addr, host_port, NULL)) {
2749 rdma->port = atoi(addr->port);
2750 rdma->host = g_strdup(addr->host);
2751 rdma->host_port = g_strdup(host_port);
2752 } else {
2753 error_setg(errp, "RDMA ERROR: bad RDMA migration address '%s'",
2754 host_port);
2755 g_free(rdma);
2756 rdma = NULL;
2757 }
2758
2759 qapi_free_InetSocketAddress(addr);
2760 return rdma;
2761 }
2762
2763 /*
2764 * QEMUFile interface to the control channel.
2765 * SEND messages for control only.
2766 * VM's ram is handled with regular RDMA messages.
2767 */
2768 static ssize_t qio_channel_rdma_writev(QIOChannel *ioc,
2769 const struct iovec *iov,
2770 size_t niov,
2771 int *fds,
2772 size_t nfds,
2773 int flags,
2774 Error **errp)
2775 {
2776 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
2777 RDMAContext *rdma;
2778 int ret;
2779 ssize_t done = 0;
2780 size_t i, len;
2781
2782 RCU_READ_LOCK_GUARD();
2783 rdma = qatomic_rcu_read(&rioc->rdmaout);
2784
2785 if (!rdma) {
2786 error_setg(errp, "RDMA control channel output is not set");
2787 return -1;
2788 }
2789
2790 if (rdma->errored) {
2791 error_setg(errp,
2792 "RDMA is in an error state waiting migration to abort!");
2793 return -1;
2794 }
2795
2796 /*
2797 * Push out any writes that
2798 * we're queued up for VM's ram.
2799 */
2800 ret = qemu_rdma_write_flush(rdma, errp);
2801 if (ret < 0) {
2802 rdma->errored = true;
2803 return -1;
2804 }
2805
2806 for (i = 0; i < niov; i++) {
2807 size_t remaining = iov[i].iov_len;
2808 uint8_t * data = (void *)iov[i].iov_base;
2809 while (remaining) {
2810 RDMAControlHeader head = {};
2811
2812 len = MIN(remaining, RDMA_SEND_INCREMENT);
2813 remaining -= len;
2814
2815 head.len = len;
2816 head.type = RDMA_CONTROL_QEMU_FILE;
2817
2818 ret = qemu_rdma_exchange_send(rdma, &head,
2819 data, NULL, NULL, NULL, errp);
2820
2821 if (ret < 0) {
2822 rdma->errored = true;
2823 return -1;
2824 }
2825
2826 data += len;
2827 done += len;
2828 }
2829 }
2830
2831 return done;
2832 }
2833
2834 static size_t qemu_rdma_fill(RDMAContext *rdma, uint8_t *buf,
2835 size_t size, int idx)
2836 {
2837 size_t len = 0;
2838
2839 if (rdma->wr_data[idx].control_len) {
2840 trace_qemu_rdma_fill(rdma->wr_data[idx].control_len, size);
2841
2842 len = MIN(size, rdma->wr_data[idx].control_len);
2843 memcpy(buf, rdma->wr_data[idx].control_curr, len);
2844 rdma->wr_data[idx].control_curr += len;
2845 rdma->wr_data[idx].control_len -= len;
2846 }
2847
2848 return len;
2849 }
2850
2851 /*
2852 * QEMUFile interface to the control channel.
2853 * RDMA links don't use bytestreams, so we have to
2854 * return bytes to QEMUFile opportunistically.
2855 */
2856 static ssize_t qio_channel_rdma_readv(QIOChannel *ioc,
2857 const struct iovec *iov,
2858 size_t niov,
2859 int **fds,
2860 size_t *nfds,
2861 int flags,
2862 Error **errp)
2863 {
2864 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
2865 RDMAContext *rdma;
2866 RDMAControlHeader head;
2867 int ret;
2868 ssize_t done = 0;
2869 size_t i, len;
2870
2871 RCU_READ_LOCK_GUARD();
2872 rdma = qatomic_rcu_read(&rioc->rdmain);
2873
2874 if (!rdma) {
2875 error_setg(errp, "RDMA control channel input is not set");
2876 return -1;
2877 }
2878
2879 if (rdma->errored) {
2880 error_setg(errp,
2881 "RDMA is in an error state waiting migration to abort!");
2882 return -1;
2883 }
2884
2885 for (i = 0; i < niov; i++) {
2886 size_t want = iov[i].iov_len;
2887 uint8_t *data = (void *)iov[i].iov_base;
2888
2889 /*
2890 * First, we hold on to the last SEND message we
2891 * were given and dish out the bytes until we run
2892 * out of bytes.
2893 */
2894 len = qemu_rdma_fill(rdma, data, want, 0);
2895 done += len;
2896 want -= len;
2897 /* Got what we needed, so go to next iovec */
2898 if (want == 0) {
2899 continue;
2900 }
2901
2902 /* If we got any data so far, then don't wait
2903 * for more, just return what we have */
2904 if (done > 0) {
2905 break;
2906 }
2907
2908
2909 /* We've got nothing at all, so lets wait for
2910 * more to arrive
2911 */
2912 ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_QEMU_FILE,
2913 errp);
2914
2915 if (ret < 0) {
2916 rdma->errored = true;
2917 return -1;
2918 }
2919
2920 /*
2921 * SEND was received with new bytes, now try again.
2922 */
2923 len = qemu_rdma_fill(rdma, data, want, 0);
2924 done += len;
2925 want -= len;
2926
2927 /* Still didn't get enough, so lets just return */
2928 if (want) {
2929 if (done == 0) {
2930 return QIO_CHANNEL_ERR_BLOCK;
2931 } else {
2932 break;
2933 }
2934 }
2935 }
2936 return done;
2937 }
2938
2939 /*
2940 * Block until all the outstanding chunks have been delivered by the hardware.
2941 */
2942 static int qemu_rdma_drain_cq(RDMAContext *rdma)
2943 {
2944 Error *err = NULL;
2945 int ret;
2946
2947 if (qemu_rdma_write_flush(rdma, &err) < 0) {
2948 error_report_err(err);
2949 return -1;
2950 }
2951
2952 while (rdma->nb_sent) {
2953 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL);
2954 if (ret < 0) {
2955 error_report("rdma migration: complete polling error!");
2956 return -1;
2957 }
2958 }
2959
2960 qemu_rdma_unregister_waiting(rdma);
2961
2962 return 0;
2963 }
2964
2965
2966 static int qio_channel_rdma_set_blocking(QIOChannel *ioc,
2967 bool blocking,
2968 Error **errp)
2969 {
2970 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
2971 /* XXX we should make readv/writev actually honour this :-) */
2972 rioc->blocking = blocking;
2973 return 0;
2974 }
2975
2976
2977 typedef struct QIOChannelRDMASource QIOChannelRDMASource;
2978 struct QIOChannelRDMASource {
2979 GSource parent;
2980 QIOChannelRDMA *rioc;
2981 GIOCondition condition;
2982 };
2983
2984 static gboolean
2985 qio_channel_rdma_source_prepare(GSource *source,
2986 gint *timeout)
2987 {
2988 QIOChannelRDMASource *rsource = (QIOChannelRDMASource *)source;
2989 RDMAContext *rdma;
2990 GIOCondition cond = 0;
2991 *timeout = -1;
2992
2993 RCU_READ_LOCK_GUARD();
2994 if (rsource->condition == G_IO_IN) {
2995 rdma = qatomic_rcu_read(&rsource->rioc->rdmain);
2996 } else {
2997 rdma = qatomic_rcu_read(&rsource->rioc->rdmaout);
2998 }
2999
3000 if (!rdma) {
3001 error_report("RDMAContext is NULL when prepare Gsource");
3002 return FALSE;
3003 }
3004
3005 if (rdma->wr_data[0].control_len) {
3006 cond |= G_IO_IN;
3007 }
3008 cond |= G_IO_OUT;
3009
3010 return cond & rsource->condition;
3011 }
3012
3013 static gboolean
3014 qio_channel_rdma_source_check(GSource *source)
3015 {
3016 QIOChannelRDMASource *rsource = (QIOChannelRDMASource *)source;
3017 RDMAContext *rdma;
3018 GIOCondition cond = 0;
3019
3020 RCU_READ_LOCK_GUARD();
3021 if (rsource->condition == G_IO_IN) {
3022 rdma = qatomic_rcu_read(&rsource->rioc->rdmain);
3023 } else {
3024 rdma = qatomic_rcu_read(&rsource->rioc->rdmaout);
3025 }
3026
3027 if (!rdma) {
3028 error_report("RDMAContext is NULL when check Gsource");
3029 return FALSE;
3030 }
3031
3032 if (rdma->wr_data[0].control_len) {
3033 cond |= G_IO_IN;
3034 }
3035 cond |= G_IO_OUT;
3036
3037 return cond & rsource->condition;
3038 }
3039
3040 static gboolean
3041 qio_channel_rdma_source_dispatch(GSource *source,
3042 GSourceFunc callback,
3043 gpointer user_data)
3044 {
3045 QIOChannelFunc func = (QIOChannelFunc)callback;
3046 QIOChannelRDMASource *rsource = (QIOChannelRDMASource *)source;
3047 RDMAContext *rdma;
3048 GIOCondition cond = 0;
3049
3050 RCU_READ_LOCK_GUARD();
3051 if (rsource->condition == G_IO_IN) {
3052 rdma = qatomic_rcu_read(&rsource->rioc->rdmain);
3053 } else {
3054 rdma = qatomic_rcu_read(&rsource->rioc->rdmaout);
3055 }
3056
3057 if (!rdma) {
3058 error_report("RDMAContext is NULL when dispatch Gsource");
3059 return FALSE;
3060 }
3061
3062 if (rdma->wr_data[0].control_len) {
3063 cond |= G_IO_IN;
3064 }
3065 cond |= G_IO_OUT;
3066
3067 return (*func)(QIO_CHANNEL(rsource->rioc),
3068 (cond & rsource->condition),
3069 user_data);
3070 }
3071
3072 static void
3073 qio_channel_rdma_source_finalize(GSource *source)
3074 {
3075 QIOChannelRDMASource *ssource = (QIOChannelRDMASource *)source;
3076
3077 object_unref(OBJECT(ssource->rioc));
3078 }
3079
3080 static GSourceFuncs qio_channel_rdma_source_funcs = {
3081 qio_channel_rdma_source_prepare,
3082 qio_channel_rdma_source_check,
3083 qio_channel_rdma_source_dispatch,
3084 qio_channel_rdma_source_finalize
3085 };
3086
3087 static GSource *qio_channel_rdma_create_watch(QIOChannel *ioc,
3088 GIOCondition condition)
3089 {
3090 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
3091 QIOChannelRDMASource *ssource;
3092 GSource *source;
3093
3094 source = g_source_new(&qio_channel_rdma_source_funcs,
3095 sizeof(QIOChannelRDMASource));
3096 ssource = (QIOChannelRDMASource *)source;
3097
3098 ssource->rioc = rioc;
3099 object_ref(OBJECT(rioc));
3100
3101 ssource->condition = condition;
3102
3103 return source;
3104 }
3105
3106 static void qio_channel_rdma_set_aio_fd_handler(QIOChannel *ioc,
3107 AioContext *read_ctx,
3108 IOHandler *io_read,
3109 AioContext *write_ctx,
3110 IOHandler *io_write,
3111 void *opaque)
3112 {
3113 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
3114 if (io_read) {
3115 aio_set_fd_handler(read_ctx, rioc->rdmain->recv_comp_channel->fd,
3116 io_read, io_write, NULL, NULL, opaque);
3117 aio_set_fd_handler(read_ctx, rioc->rdmain->send_comp_channel->fd,
3118 io_read, io_write, NULL, NULL, opaque);
3119 } else {
3120 aio_set_fd_handler(write_ctx, rioc->rdmaout->recv_comp_channel->fd,
3121 io_read, io_write, NULL, NULL, opaque);
3122 aio_set_fd_handler(write_ctx, rioc->rdmaout->send_comp_channel->fd,
3123 io_read, io_write, NULL, NULL, opaque);
3124 }
3125 }
3126
3127 struct rdma_close_rcu {
3128 struct rcu_head rcu;
3129 RDMAContext *rdmain;
3130 RDMAContext *rdmaout;
3131 };
3132
3133 /* callback from qio_channel_rdma_close via call_rcu */
3134 static void qio_channel_rdma_close_rcu(struct rdma_close_rcu *rcu)
3135 {
3136 if (rcu->rdmain) {
3137 qemu_rdma_cleanup(rcu->rdmain);
3138 }
3139
3140 if (rcu->rdmaout) {
3141 qemu_rdma_cleanup(rcu->rdmaout);
3142 }
3143
3144 g_free(rcu->rdmain);
3145 g_free(rcu->rdmaout);
3146 g_free(rcu);
3147 }
3148
3149 static int qio_channel_rdma_close(QIOChannel *ioc,
3150 Error **errp)
3151 {
3152 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
3153 RDMAContext *rdmain, *rdmaout;
3154 struct rdma_close_rcu *rcu = g_new(struct rdma_close_rcu, 1);
3155
3156 trace_qemu_rdma_close();
3157
3158 rdmain = rioc->rdmain;
3159 if (rdmain) {
3160 qatomic_rcu_set(&rioc->rdmain, NULL);
3161 }
3162
3163 rdmaout = rioc->rdmaout;
3164 if (rdmaout) {
3165 qatomic_rcu_set(&rioc->rdmaout, NULL);
3166 }
3167
3168 rcu->rdmain = rdmain;
3169 rcu->rdmaout = rdmaout;
3170 call_rcu(rcu, qio_channel_rdma_close_rcu, rcu);
3171
3172 return 0;
3173 }
3174
3175 static int
3176 qio_channel_rdma_shutdown(QIOChannel *ioc,
3177 QIOChannelShutdown how,
3178 Error **errp)
3179 {
3180 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
3181 RDMAContext *rdmain, *rdmaout;
3182
3183 RCU_READ_LOCK_GUARD();
3184
3185 rdmain = qatomic_rcu_read(&rioc->rdmain);
3186 rdmaout = qatomic_rcu_read(&rioc->rdmain);
3187
3188 switch (how) {
3189 case QIO_CHANNEL_SHUTDOWN_READ:
3190 if (rdmain) {
3191 rdmain->errored = true;
3192 }
3193 break;
3194 case QIO_CHANNEL_SHUTDOWN_WRITE:
3195 if (rdmaout) {
3196 rdmaout->errored = true;
3197 }
3198 break;
3199 case QIO_CHANNEL_SHUTDOWN_BOTH:
3200 default:
3201 if (rdmain) {
3202 rdmain->errored = true;
3203 }
3204 if (rdmaout) {
3205 rdmaout->errored = true;
3206 }
3207 break;
3208 }
3209
3210 return 0;
3211 }
3212
3213 /*
3214 * Parameters:
3215 * @offset == 0 :
3216 * This means that 'block_offset' is a full virtual address that does not
3217 * belong to a RAMBlock of the virtual machine and instead
3218 * represents a private malloc'd memory area that the caller wishes to
3219 * transfer.
3220 *
3221 * @offset != 0 :
3222 * Offset is an offset to be added to block_offset and used
3223 * to also lookup the corresponding RAMBlock.
3224 *
3225 * @size : Number of bytes to transfer
3226 *
3227 * @pages_sent : User-specificed pointer to indicate how many pages were
3228 * sent. Usually, this will not be more than a few bytes of
3229 * the protocol because most transfers are sent asynchronously.
3230 */
3231 static int qemu_rdma_save_page(QEMUFile *f, ram_addr_t block_offset,
3232 ram_addr_t offset, size_t size)
3233 {
3234 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(qemu_file_get_ioc(f));
3235 Error *err = NULL;
3236 RDMAContext *rdma;
3237 int ret;
3238
3239 RCU_READ_LOCK_GUARD();
3240 rdma = qatomic_rcu_read(&rioc->rdmaout);
3241
3242 if (!rdma) {
3243 return -1;
3244 }
3245
3246 if (rdma_errored(rdma)) {
3247 return -1;
3248 }
3249
3250 qemu_fflush(f);
3251
3252 /*
3253 * Add this page to the current 'chunk'. If the chunk
3254 * is full, or the page doesn't belong to the current chunk,
3255 * an actual RDMA write will occur and a new chunk will be formed.
3256 */
3257 ret = qemu_rdma_write(rdma, block_offset, offset, size, &err);
3258 if (ret < 0) {
3259 error_report_err(err);
3260 goto err;
3261 }
3262
3263 /*
3264 * Drain the Completion Queue if possible, but do not block,
3265 * just poll.
3266 *
3267 * If nothing to poll, the end of the iteration will do this
3268 * again to make sure we don't overflow the request queue.
3269 */
3270 while (1) {
3271 uint64_t wr_id, wr_id_in;
3272 ret = qemu_rdma_poll(rdma, rdma->recv_cq, &wr_id_in, NULL);
3273
3274 if (ret < 0) {
3275 error_report("rdma migration: polling error");
3276 goto err;
3277 }
3278
3279 wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
3280
3281 if (wr_id == RDMA_WRID_NONE) {
3282 break;
3283 }
3284 }
3285
3286 while (1) {
3287 uint64_t wr_id, wr_id_in;
3288 ret = qemu_rdma_poll(rdma, rdma->send_cq, &wr_id_in, NULL);
3289
3290 if (ret < 0) {
3291 error_report("rdma migration: polling error");
3292 goto err;
3293 }
3294
3295 wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
3296
3297 if (wr_id == RDMA_WRID_NONE) {
3298 break;
3299 }
3300 }
3301
3302 return RAM_SAVE_CONTROL_DELAYED;
3303
3304 err:
3305 rdma->errored = true;
3306 return -1;
3307 }
3308
3309 int rdma_control_save_page(QEMUFile *f, ram_addr_t block_offset,
3310 ram_addr_t offset, size_t size)
3311 {
3312 if (!migrate_rdma() || migration_in_postcopy()) {
3313 return RAM_SAVE_CONTROL_NOT_SUPP;
3314 }
3315
3316 int ret = qemu_rdma_save_page(f, block_offset, offset, size);
3317
3318 if (ret != RAM_SAVE_CONTROL_DELAYED &&
3319 ret != RAM_SAVE_CONTROL_NOT_SUPP) {
3320 if (ret < 0) {
3321 qemu_file_set_error(f, ret);
3322 }
3323 }
3324 return ret;
3325 }
3326
3327 static void rdma_accept_incoming_migration(void *opaque);
3328
3329 static void rdma_cm_poll_handler(void *opaque)
3330 {
3331 RDMAContext *rdma = opaque;
3332 int ret;
3333 struct rdma_cm_event *cm_event;
3334 MigrationIncomingState *mis = migration_incoming_get_current();
3335
3336 ret = rdma_get_cm_event(rdma->channel, &cm_event);
3337 if (ret < 0) {
3338 error_report("get_cm_event failed %d", errno);
3339 return;
3340 }
3341
3342 if (cm_event->event == RDMA_CM_EVENT_DISCONNECTED ||
3343 cm_event->event == RDMA_CM_EVENT_DEVICE_REMOVAL) {
3344 if (!rdma->errored &&
3345 migration_incoming_get_current()->state !=
3346 MIGRATION_STATUS_COMPLETED) {
3347 error_report("receive cm event, cm event is %d", cm_event->event);
3348 rdma->errored = true;
3349 if (rdma->return_path) {
3350 rdma->return_path->errored = true;
3351 }
3352 }
3353 rdma_ack_cm_event(cm_event);
3354 if (mis->loadvm_co) {
3355 qemu_coroutine_enter(mis->loadvm_co);
3356 }
3357 return;
3358 }
3359 rdma_ack_cm_event(cm_event);
3360 }
3361
3362 static int qemu_rdma_accept(RDMAContext *rdma)
3363 {
3364 Error *err = NULL;
3365 RDMACapabilities cap;
3366 struct rdma_conn_param conn_param = {
3367 .responder_resources = 2,
3368 .private_data = &cap,
3369 .private_data_len = sizeof(cap),
3370 };
3371 RDMAContext *rdma_return_path = NULL;
3372 struct rdma_cm_event *cm_event;
3373 struct ibv_context *verbs;
3374 int ret;
3375
3376 ret = rdma_get_cm_event(rdma->channel, &cm_event);
3377 if (ret < 0) {
3378 goto err_rdma_dest_wait;
3379 }
3380
3381 if (cm_event->event != RDMA_CM_EVENT_CONNECT_REQUEST) {
3382 rdma_ack_cm_event(cm_event);
3383 goto err_rdma_dest_wait;
3384 }
3385
3386 /*
3387 * initialize the RDMAContext for return path for postcopy after first
3388 * connection request reached.
3389 */
3390 if ((migrate_postcopy() || migrate_return_path())
3391 && !rdma->is_return_path) {
3392 rdma_return_path = qemu_rdma_data_init(rdma->host_port, NULL);
3393 if (rdma_return_path == NULL) {
3394 rdma_ack_cm_event(cm_event);
3395 goto err_rdma_dest_wait;
3396 }
3397
3398 qemu_rdma_return_path_dest_init(rdma_return_path, rdma);
3399 }
3400
3401 memcpy(&cap, cm_event->param.conn.private_data, sizeof(cap));
3402
3403 network_to_caps(&cap);
3404
3405 if (cap.version < 1 || cap.version > RDMA_CONTROL_VERSION_CURRENT) {
3406 error_report("Unknown source RDMA version: %d, bailing...",
3407 cap.version);
3408 rdma_ack_cm_event(cm_event);
3409 goto err_rdma_dest_wait;
3410 }
3411
3412 /*
3413 * Respond with only the capabilities this version of QEMU knows about.
3414 */
3415 cap.flags &= known_capabilities;
3416
3417 /*
3418 * Enable the ones that we do know about.
3419 * Add other checks here as new ones are introduced.
3420 */
3421 if (cap.flags & RDMA_CAPABILITY_PIN_ALL) {
3422 rdma->pin_all = true;
3423 }
3424
3425 rdma->cm_id = cm_event->id;
3426 verbs = cm_event->id->verbs;
3427
3428 rdma_ack_cm_event(cm_event);
3429
3430 trace_qemu_rdma_accept_pin_state(rdma->pin_all);
3431
3432 caps_to_network(&cap);
3433
3434 trace_qemu_rdma_accept_pin_verbsc(verbs);
3435
3436 if (!rdma->verbs) {
3437 rdma->verbs = verbs;
3438 } else if (rdma->verbs != verbs) {
3439 error_report("ibv context not matching %p, %p!", rdma->verbs,
3440 verbs);
3441 goto err_rdma_dest_wait;
3442 }
3443
3444 qemu_rdma_dump_id("dest_init", verbs);
3445
3446 ret = qemu_rdma_alloc_pd_cq(rdma, &err);
3447 if (ret < 0) {
3448 error_report_err(err);
3449 goto err_rdma_dest_wait;
3450 }
3451
3452 ret = qemu_rdma_alloc_qp(rdma);
3453 if (ret < 0) {
3454 error_report("rdma migration: error allocating qp!");
3455 goto err_rdma_dest_wait;
3456 }
3457
3458 qemu_rdma_init_ram_blocks(rdma);
3459
3460 for (int i = 0; i < RDMA_WRID_MAX; i++) {
3461 ret = qemu_rdma_reg_control(rdma, i);
3462 if (ret < 0) {
3463 error_report("rdma: error registering %d control", i);
3464 goto err_rdma_dest_wait;
3465 }
3466 }
3467
3468 /* Accept the second connection request for return path */
3469 if ((migrate_postcopy() || migrate_return_path())
3470 && !rdma->is_return_path) {
3471 qemu_set_fd_handler(rdma->channel->fd, rdma_accept_incoming_migration,
3472 NULL,
3473 (void *)(intptr_t)rdma->return_path);
3474 } else {
3475 qemu_set_fd_handler(rdma->channel->fd, rdma_cm_poll_handler,
3476 NULL, rdma);
3477 }
3478
3479 ret = rdma_accept(rdma->cm_id, &conn_param);
3480 if (ret < 0) {
3481 error_report("rdma_accept failed");
3482 goto err_rdma_dest_wait;
3483 }
3484
3485 ret = rdma_get_cm_event(rdma->channel, &cm_event);
3486 if (ret < 0) {
3487 error_report("rdma_accept get_cm_event failed");
3488 goto err_rdma_dest_wait;
3489 }
3490
3491 if (cm_event->event != RDMA_CM_EVENT_ESTABLISHED) {
3492 error_report("rdma_accept not event established");
3493 rdma_ack_cm_event(cm_event);
3494 goto err_rdma_dest_wait;
3495 }
3496
3497 rdma_ack_cm_event(cm_event);
3498 rdma->connected = true;
3499
3500 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY, &err);
3501 if (ret < 0) {
3502 error_report_err(err);
3503 goto err_rdma_dest_wait;
3504 }
3505
3506 qemu_rdma_dump_gid("dest_connect", rdma->cm_id);
3507
3508 return 0;
3509
3510 err_rdma_dest_wait:
3511 rdma->errored = true;
3512 qemu_rdma_cleanup(rdma);
3513 g_free(rdma_return_path);
3514 return -1;
3515 }
3516
3517 static int dest_ram_sort_func(const void *a, const void *b)
3518 {
3519 unsigned int a_index = ((const RDMALocalBlock *)a)->src_index;
3520 unsigned int b_index = ((const RDMALocalBlock *)b)->src_index;
3521
3522 return (a_index < b_index) ? -1 : (a_index != b_index);
3523 }
3524
3525 /*
3526 * During each iteration of the migration, we listen for instructions
3527 * by the source VM to perform dynamic page registrations before they
3528 * can perform RDMA operations.
3529 *
3530 * We respond with the 'rkey'.
3531 *
3532 * Keep doing this until the source tells us to stop.
3533 */
3534 int rdma_registration_handle(QEMUFile *f)
3535 {
3536 RDMAControlHeader reg_resp = { .len = sizeof(RDMARegisterResult),
3537 .type = RDMA_CONTROL_REGISTER_RESULT,
3538 .repeat = 0,
3539 };
3540 RDMAControlHeader unreg_resp = { .len = 0,
3541 .type = RDMA_CONTROL_UNREGISTER_FINISHED,
3542 .repeat = 0,
3543 };
3544 RDMAControlHeader blocks = { .type = RDMA_CONTROL_RAM_BLOCKS_RESULT,
3545 .repeat = 1 };
3546 QIOChannelRDMA *rioc;
3547 Error *err = NULL;
3548 RDMAContext *rdma;
3549 RDMALocalBlocks *local;
3550 RDMAControlHeader head;
3551 RDMARegister *reg, *registers;
3552 RDMACompress *comp;
3553 RDMARegisterResult *reg_result;
3554 static RDMARegisterResult results[RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE];
3555 RDMALocalBlock *block;
3556 void *host_addr;
3557 int ret;
3558 int idx = 0;
3559 int count = 0;
3560 int i = 0;
3561
3562 if (!migrate_rdma()) {
3563 return 0;
3564 }
3565
3566 RCU_READ_LOCK_GUARD();
3567 rioc = QIO_CHANNEL_RDMA(qemu_file_get_ioc(f));
3568 rdma = qatomic_rcu_read(&rioc->rdmain);
3569
3570 if (!rdma) {
3571 return -1;
3572 }
3573
3574 if (rdma_errored(rdma)) {
3575 return -1;
3576 }
3577
3578 local = &rdma->local_ram_blocks;
3579 do {
3580 trace_rdma_registration_handle_wait();
3581
3582 ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_NONE, &err);
3583
3584 if (ret < 0) {
3585 error_report_err(err);
3586 break;
3587 }
3588
3589 if (head.repeat > RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE) {
3590 error_report("rdma: Too many requests in this message (%d)."
3591 "Bailing.", head.repeat);
3592 break;
3593 }
3594
3595 switch (head.type) {
3596 case RDMA_CONTROL_COMPRESS:
3597 comp = (RDMACompress *) rdma->wr_data[idx].control_curr;
3598 network_to_compress(comp);
3599
3600 trace_rdma_registration_handle_compress(comp->length,
3601 comp->block_idx,
3602 comp->offset);
3603 if (comp->block_idx >= rdma->local_ram_blocks.nb_blocks) {
3604 error_report("rdma: 'compress' bad block index %u (vs %d)",
3605 (unsigned int)comp->block_idx,
3606 rdma->local_ram_blocks.nb_blocks);
3607 goto err;
3608 }
3609 block = &(rdma->local_ram_blocks.block[comp->block_idx]);
3610
3611 host_addr = block->local_host_addr +
3612 (comp->offset - block->offset);
3613
3614 ram_handle_compressed(host_addr, comp->value, comp->length);
3615 break;
3616
3617 case RDMA_CONTROL_REGISTER_FINISHED:
3618 trace_rdma_registration_handle_finished();
3619 return 0;
3620
3621 case RDMA_CONTROL_RAM_BLOCKS_REQUEST:
3622 trace_rdma_registration_handle_ram_blocks();
3623
3624 /* Sort our local RAM Block list so it's the same as the source,
3625 * we can do this since we've filled in a src_index in the list
3626 * as we received the RAMBlock list earlier.
3627 */
3628 qsort(rdma->local_ram_blocks.block,
3629 rdma->local_ram_blocks.nb_blocks,
3630 sizeof(RDMALocalBlock), dest_ram_sort_func);
3631 for (i = 0; i < local->nb_blocks; i++) {
3632 local->block[i].index = i;
3633 }
3634
3635 if (rdma->pin_all) {
3636 ret = qemu_rdma_reg_whole_ram_blocks(rdma, &err);
3637 if (ret < 0) {
3638 error_report_err(err);
3639 goto err;
3640 }
3641 }
3642
3643 /*
3644 * Dest uses this to prepare to transmit the RAMBlock descriptions
3645 * to the source VM after connection setup.
3646 * Both sides use the "remote" structure to communicate and update
3647 * their "local" descriptions with what was sent.
3648 */
3649 for (i = 0; i < local->nb_blocks; i++) {
3650 rdma->dest_blocks[i].remote_host_addr =
3651 (uintptr_t)(local->block[i].local_host_addr);
3652
3653 if (rdma->pin_all) {
3654 rdma->dest_blocks[i].remote_rkey = local->block[i].mr->rkey;
3655 }
3656
3657 rdma->dest_blocks[i].offset = local->block[i].offset;
3658 rdma->dest_blocks[i].length = local->block[i].length;
3659
3660 dest_block_to_network(&rdma->dest_blocks[i]);
3661 trace_rdma_registration_handle_ram_blocks_loop(
3662 local->block[i].block_name,
3663 local->block[i].offset,
3664 local->block[i].length,
3665 local->block[i].local_host_addr,
3666 local->block[i].src_index);
3667 }
3668
3669 blocks.len = rdma->local_ram_blocks.nb_blocks
3670 * sizeof(RDMADestBlock);
3671
3672
3673 ret = qemu_rdma_post_send_control(rdma,
3674 (uint8_t *) rdma->dest_blocks, &blocks,
3675 &err);
3676
3677 if (ret < 0) {
3678 error_report_err(err);
3679 goto err;
3680 }
3681
3682 break;
3683 case RDMA_CONTROL_REGISTER_REQUEST:
3684 trace_rdma_registration_handle_register(head.repeat);
3685
3686 reg_resp.repeat = head.repeat;
3687 registers = (RDMARegister *) rdma->wr_data[idx].control_curr;
3688
3689 for (count = 0; count < head.repeat; count++) {
3690 uint64_t chunk;
3691 uint8_t *chunk_start, *chunk_end;
3692
3693 reg = &registers[count];
3694 network_to_register(reg);
3695
3696 reg_result = &results[count];
3697
3698 trace_rdma_registration_handle_register_loop(count,
3699 reg->current_index, reg->key.current_addr, reg->chunks);
3700
3701 if (reg->current_index >= rdma->local_ram_blocks.nb_blocks) {
3702 error_report("rdma: 'register' bad block index %u (vs %d)",
3703 (unsigned int)reg->current_index,
3704 rdma->local_ram_blocks.nb_blocks);
3705 goto err;
3706 }
3707 block = &(rdma->local_ram_blocks.block[reg->current_index]);
3708 if (block->is_ram_block) {
3709 if (block->offset > reg->key.current_addr) {
3710 error_report("rdma: bad register address for block %s"
3711 " offset: %" PRIx64 " current_addr: %" PRIx64,
3712 block->block_name, block->offset,
3713 reg->key.current_addr);
3714 goto err;
3715 }
3716 host_addr = (block->local_host_addr +
3717 (reg->key.current_addr - block->offset));
3718 chunk = ram_chunk_index(block->local_host_addr,
3719 (uint8_t *) host_addr);
3720 } else {
3721 chunk = reg->key.chunk;
3722 host_addr = block->local_host_addr +
3723 (reg->key.chunk * (1UL << RDMA_REG_CHUNK_SHIFT));
3724 /* Check for particularly bad chunk value */
3725 if (host_addr < (void *)block->local_host_addr) {
3726 error_report("rdma: bad chunk for block %s"
3727 " chunk: %" PRIx64,
3728 block->block_name, reg->key.chunk);
3729 goto err;
3730 }
3731 }
3732 chunk_start = ram_chunk_start(block, chunk);
3733 chunk_end = ram_chunk_end(block, chunk + reg->chunks);
3734 /* avoid "-Waddress-of-packed-member" warning */
3735 uint32_t tmp_rkey = 0;
3736 if (qemu_rdma_register_and_get_keys(rdma, block,
3737 (uintptr_t)host_addr, NULL, &tmp_rkey,
3738 chunk, chunk_start, chunk_end)) {
3739 error_report("cannot get rkey");
3740 goto err;
3741 }
3742 reg_result->rkey = tmp_rkey;
3743
3744 reg_result->host_addr = (uintptr_t)block->local_host_addr;
3745
3746 trace_rdma_registration_handle_register_rkey(reg_result->rkey);
3747
3748 result_to_network(reg_result);
3749 }
3750
3751 ret = qemu_rdma_post_send_control(rdma,
3752 (uint8_t *) results, &reg_resp, &err);
3753
3754 if (ret < 0) {
3755 error_report_err(err);
3756 goto err;
3757 }
3758 break;
3759 case RDMA_CONTROL_UNREGISTER_REQUEST:
3760 trace_rdma_registration_handle_unregister(head.repeat);
3761 unreg_resp.repeat = head.repeat;
3762 registers = (RDMARegister *) rdma->wr_data[idx].control_curr;
3763
3764 for (count = 0; count < head.repeat; count++) {
3765 reg = &registers[count];
3766 network_to_register(reg);
3767
3768 trace_rdma_registration_handle_unregister_loop(count,
3769 reg->current_index, reg->key.chunk);
3770
3771 block = &(rdma->local_ram_blocks.block[reg->current_index]);
3772
3773 ret = ibv_dereg_mr(block->pmr[reg->key.chunk]);
3774 block->pmr[reg->key.chunk] = NULL;
3775
3776 if (ret != 0) {
3777 error_report("rdma unregistration chunk failed: %s",
3778 strerror(errno));
3779 goto err;
3780 }
3781
3782 rdma->total_registrations--;
3783
3784 trace_rdma_registration_handle_unregister_success(reg->key.chunk);
3785 }
3786
3787 ret = qemu_rdma_post_send_control(rdma, NULL, &unreg_resp, &err);
3788
3789 if (ret < 0) {
3790 error_report_err(err);
3791 goto err;
3792 }
3793 break;
3794 case RDMA_CONTROL_REGISTER_RESULT:
3795 error_report("Invalid RESULT message at dest.");
3796 goto err;
3797 default:
3798 error_report("Unknown control message %s", control_desc(head.type));
3799 goto err;
3800 }
3801 } while (1);
3802
3803 err:
3804 rdma->errored = true;
3805 return -1;
3806 }
3807
3808 /* Destination:
3809 * Called during the initial RAM load section which lists the
3810 * RAMBlocks by name. This lets us know the order of the RAMBlocks on
3811 * the source. We've already built our local RAMBlock list, but not
3812 * yet sent the list to the source.
3813 */
3814 int rdma_block_notification_handle(QEMUFile *f, const char *name)
3815 {
3816 int curr;
3817 int found = -1;
3818
3819 if (!migrate_rdma()) {
3820 return 0;
3821 }
3822
3823 RCU_READ_LOCK_GUARD();
3824 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(qemu_file_get_ioc(f));
3825 RDMAContext *rdma = qatomic_rcu_read(&rioc->rdmain);
3826
3827 if (!rdma) {
3828 return -1;
3829 }
3830
3831 /* Find the matching RAMBlock in our local list */
3832 for (curr = 0; curr < rdma->local_ram_blocks.nb_blocks; curr++) {
3833 if (!strcmp(rdma->local_ram_blocks.block[curr].block_name, name)) {
3834 found = curr;
3835 break;
3836 }
3837 }
3838
3839 if (found == -1) {
3840 error_report("RAMBlock '%s' not found on destination", name);
3841 return -1;
3842 }
3843
3844 rdma->local_ram_blocks.block[curr].src_index = rdma->next_src_index;
3845 trace_rdma_block_notification_handle(name, rdma->next_src_index);
3846 rdma->next_src_index++;
3847
3848 return 0;
3849 }
3850
3851 int rdma_registration_start(QEMUFile *f, uint64_t flags)
3852 {
3853 if (!migrate_rdma() || migration_in_postcopy()) {
3854 return 0;
3855 }
3856
3857 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(qemu_file_get_ioc(f));
3858 RCU_READ_LOCK_GUARD();
3859 RDMAContext *rdma = qatomic_rcu_read(&rioc->rdmaout);
3860 if (!rdma) {
3861 return -1;
3862 }
3863
3864 if (rdma_errored(rdma)) {
3865 return -1;
3866 }
3867
3868 trace_rdma_registration_start(flags);
3869 qemu_put_be64(f, RAM_SAVE_FLAG_HOOK);
3870 qemu_fflush(f);
3871
3872 return 0;
3873 }
3874
3875 /*
3876 * Inform dest that dynamic registrations are done for now.
3877 * First, flush writes, if any.
3878 */
3879 int rdma_registration_stop(QEMUFile *f, uint64_t flags)
3880 {
3881 QIOChannelRDMA *rioc;
3882 Error *err = NULL;
3883 RDMAContext *rdma;
3884 RDMAControlHeader head = { .len = 0, .repeat = 1 };
3885 int ret;
3886
3887 if (!migrate_rdma() || migration_in_postcopy()) {
3888 return 0;
3889 }
3890
3891 RCU_READ_LOCK_GUARD();
3892 rioc = QIO_CHANNEL_RDMA(qemu_file_get_ioc(f));
3893 rdma = qatomic_rcu_read(&rioc->rdmaout);
3894 if (!rdma) {
3895 return -1;
3896 }
3897
3898 if (rdma_errored(rdma)) {
3899 return -1;
3900 }
3901
3902 qemu_fflush(f);
3903 ret = qemu_rdma_drain_cq(rdma);
3904
3905 if (ret < 0) {
3906 goto err;
3907 }
3908
3909 if (flags == RAM_CONTROL_SETUP) {
3910 RDMAControlHeader resp = {.type = RDMA_CONTROL_RAM_BLOCKS_RESULT };
3911 RDMALocalBlocks *local = &rdma->local_ram_blocks;
3912 int reg_result_idx, i, nb_dest_blocks;
3913
3914 head.type = RDMA_CONTROL_RAM_BLOCKS_REQUEST;
3915 trace_rdma_registration_stop_ram();
3916
3917 /*
3918 * Make sure that we parallelize the pinning on both sides.
3919 * For very large guests, doing this serially takes a really
3920 * long time, so we have to 'interleave' the pinning locally
3921 * with the control messages by performing the pinning on this
3922 * side before we receive the control response from the other
3923 * side that the pinning has completed.
3924 */
3925 ret = qemu_rdma_exchange_send(rdma, &head, NULL, &resp,
3926 &reg_result_idx, rdma->pin_all ?
3927 qemu_rdma_reg_whole_ram_blocks : NULL,
3928 &err);
3929 if (ret < 0) {
3930 error_report_err(err);
3931 return -1;
3932 }
3933
3934 nb_dest_blocks = resp.len / sizeof(RDMADestBlock);
3935
3936 /*
3937 * The protocol uses two different sets of rkeys (mutually exclusive):
3938 * 1. One key to represent the virtual address of the entire ram block.
3939 * (dynamic chunk registration disabled - pin everything with one rkey.)
3940 * 2. One to represent individual chunks within a ram block.
3941 * (dynamic chunk registration enabled - pin individual chunks.)
3942 *
3943 * Once the capability is successfully negotiated, the destination transmits
3944 * the keys to use (or sends them later) including the virtual addresses
3945 * and then propagates the remote ram block descriptions to his local copy.
3946 */
3947
3948 if (local->nb_blocks != nb_dest_blocks) {
3949 error_report("ram blocks mismatch (Number of blocks %d vs %d)",
3950 local->nb_blocks, nb_dest_blocks);
3951 error_printf("Your QEMU command line parameters are probably "
3952 "not identical on both the source and destination.");
3953 rdma->errored = true;
3954 return -1;
3955 }
3956
3957 qemu_rdma_move_header(rdma, reg_result_idx, &resp);
3958 memcpy(rdma->dest_blocks,
3959 rdma->wr_data[reg_result_idx].control_curr, resp.len);
3960 for (i = 0; i < nb_dest_blocks; i++) {
3961 network_to_dest_block(&rdma->dest_blocks[i]);
3962
3963 /* We require that the blocks are in the same order */
3964 if (rdma->dest_blocks[i].length != local->block[i].length) {
3965 error_report("Block %s/%d has a different length %" PRIu64
3966 "vs %" PRIu64,
3967 local->block[i].block_name, i,
3968 local->block[i].length,
3969 rdma->dest_blocks[i].length);
3970 rdma->errored = true;
3971 return -1;
3972 }
3973 local->block[i].remote_host_addr =
3974 rdma->dest_blocks[i].remote_host_addr;
3975 local->block[i].remote_rkey = rdma->dest_blocks[i].remote_rkey;
3976 }
3977 }
3978
3979 trace_rdma_registration_stop(flags);
3980
3981 head.type = RDMA_CONTROL_REGISTER_FINISHED;
3982 ret = qemu_rdma_exchange_send(rdma, &head, NULL, NULL, NULL, NULL, &err);
3983
3984 if (ret < 0) {
3985 error_report_err(err);
3986 goto err;
3987 }
3988
3989 return 0;
3990 err:
3991 rdma->errored = true;
3992 return -1;
3993 }
3994
3995 static void qio_channel_rdma_finalize(Object *obj)
3996 {
3997 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(obj);
3998 if (rioc->rdmain) {
3999 qemu_rdma_cleanup(rioc->rdmain);
4000 g_free(rioc->rdmain);
4001 rioc->rdmain = NULL;
4002 }
4003 if (rioc->rdmaout) {
4004 qemu_rdma_cleanup(rioc->rdmaout);
4005 g_free(rioc->rdmaout);
4006 rioc->rdmaout = NULL;
4007 }
4008 }
4009
4010 static void qio_channel_rdma_class_init(ObjectClass *klass,
4011 void *class_data G_GNUC_UNUSED)
4012 {
4013 QIOChannelClass *ioc_klass = QIO_CHANNEL_CLASS(klass);
4014
4015 ioc_klass->io_writev = qio_channel_rdma_writev;
4016 ioc_klass->io_readv = qio_channel_rdma_readv;
4017 ioc_klass->io_set_blocking = qio_channel_rdma_set_blocking;
4018 ioc_klass->io_close = qio_channel_rdma_close;
4019 ioc_klass->io_create_watch = qio_channel_rdma_create_watch;
4020 ioc_klass->io_set_aio_fd_handler = qio_channel_rdma_set_aio_fd_handler;
4021 ioc_klass->io_shutdown = qio_channel_rdma_shutdown;
4022 }
4023
4024 static const TypeInfo qio_channel_rdma_info = {
4025 .parent = TYPE_QIO_CHANNEL,
4026 .name = TYPE_QIO_CHANNEL_RDMA,
4027 .instance_size = sizeof(QIOChannelRDMA),
4028 .instance_finalize = qio_channel_rdma_finalize,
4029 .class_init = qio_channel_rdma_class_init,
4030 };
4031
4032 static void qio_channel_rdma_register_types(void)
4033 {
4034 type_register_static(&qio_channel_rdma_info);
4035 }
4036
4037 type_init(qio_channel_rdma_register_types);
4038
4039 static QEMUFile *rdma_new_input(RDMAContext *rdma)
4040 {
4041 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(object_new(TYPE_QIO_CHANNEL_RDMA));
4042
4043 rioc->file = qemu_file_new_input(QIO_CHANNEL(rioc));
4044 rioc->rdmain = rdma;
4045 rioc->rdmaout = rdma->return_path;
4046
4047 return rioc->file;
4048 }
4049
4050 static QEMUFile *rdma_new_output(RDMAContext *rdma)
4051 {
4052 QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(object_new(TYPE_QIO_CHANNEL_RDMA));
4053
4054 rioc->file = qemu_file_new_output(QIO_CHANNEL(rioc));
4055 rioc->rdmaout = rdma;
4056 rioc->rdmain = rdma->return_path;
4057
4058 return rioc->file;
4059 }
4060
4061 static void rdma_accept_incoming_migration(void *opaque)
4062 {
4063 RDMAContext *rdma = opaque;
4064 int ret;
4065 QEMUFile *f;
4066 Error *local_err = NULL;
4067
4068 trace_qemu_rdma_accept_incoming_migration();
4069 ret = qemu_rdma_accept(rdma);
4070
4071 if (ret < 0) {
4072 error_report("RDMA ERROR: Migration initialization failed");
4073 return;
4074 }
4075
4076 trace_qemu_rdma_accept_incoming_migration_accepted();
4077
4078 if (rdma->is_return_path) {
4079 return;
4080 }
4081
4082 f = rdma_new_input(rdma);
4083 if (f == NULL) {
4084 error_report("RDMA ERROR: could not open RDMA for input");
4085 qemu_rdma_cleanup(rdma);
4086 return;
4087 }
4088
4089 rdma->migration_started_on_destination = 1;
4090 migration_fd_process_incoming(f, &local_err);
4091 if (local_err) {
4092 error_reportf_err(local_err, "RDMA ERROR:");
4093 }
4094 }
4095
4096 void rdma_start_incoming_migration(const char *host_port, Error **errp)
4097 {
4098 MigrationState *s = migrate_get_current();
4099 int ret;
4100 RDMAContext *rdma;
4101
4102 trace_rdma_start_incoming_migration();
4103
4104 /* Avoid ram_block_discard_disable(), cannot change during migration. */
4105 if (ram_block_discard_is_required()) {
4106 error_setg(errp, "RDMA: cannot disable RAM discard");
4107 return;
4108 }
4109
4110 rdma = qemu_rdma_data_init(host_port, errp);
4111 if (rdma == NULL) {
4112 goto err;
4113 }
4114
4115 ret = qemu_rdma_dest_init(rdma, errp);
4116 if (ret < 0) {
4117 goto err;
4118 }
4119
4120 trace_rdma_start_incoming_migration_after_dest_init();
4121
4122 ret = rdma_listen(rdma->listen_id, 5);
4123
4124 if (ret < 0) {
4125 error_setg(errp, "RDMA ERROR: listening on socket!");
4126 goto cleanup_rdma;
4127 }
4128
4129 trace_rdma_start_incoming_migration_after_rdma_listen();
4130 s->rdma_migration = true;
4131 qemu_set_fd_handler(rdma->channel->fd, rdma_accept_incoming_migration,
4132 NULL, (void *)(intptr_t)rdma);
4133 return;
4134
4135 cleanup_rdma:
4136 qemu_rdma_cleanup(rdma);
4137 err:
4138 if (rdma) {
4139 g_free(rdma->host);
4140 g_free(rdma->host_port);
4141 }
4142 g_free(rdma);
4143 }
4144
4145 void rdma_start_outgoing_migration(void *opaque,
4146 const char *host_port, Error **errp)
4147 {
4148 MigrationState *s = opaque;
4149 RDMAContext *rdma_return_path = NULL;
4150 RDMAContext *rdma;
4151 int ret;
4152
4153 /* Avoid ram_block_discard_disable(), cannot change during migration. */
4154 if (ram_block_discard_is_required()) {
4155 error_setg(errp, "RDMA: cannot disable RAM discard");
4156 return;
4157 }
4158
4159 rdma = qemu_rdma_data_init(host_port, errp);
4160 if (rdma == NULL) {
4161 goto err;
4162 }
4163
4164 ret = qemu_rdma_source_init(rdma, migrate_rdma_pin_all(), errp);
4165
4166 if (ret < 0) {
4167 goto err;
4168 }
4169
4170 trace_rdma_start_outgoing_migration_after_rdma_source_init();
4171 ret = qemu_rdma_connect(rdma, false, errp);
4172
4173 if (ret < 0) {
4174 goto err;
4175 }
4176
4177 /* RDMA postcopy need a separate queue pair for return path */
4178 if (migrate_postcopy() || migrate_return_path()) {
4179 rdma_return_path = qemu_rdma_data_init(host_port, errp);
4180
4181 if (rdma_return_path == NULL) {
4182 goto return_path_err;
4183 }
4184
4185 ret = qemu_rdma_source_init(rdma_return_path,
4186 migrate_rdma_pin_all(), errp);
4187
4188 if (ret < 0) {
4189 goto return_path_err;
4190 }
4191
4192 ret = qemu_rdma_connect(rdma_return_path, true, errp);
4193
4194 if (ret < 0) {
4195 goto return_path_err;
4196 }
4197
4198 rdma->return_path = rdma_return_path;
4199 rdma_return_path->return_path = rdma;
4200 rdma_return_path->is_return_path = true;
4201 }
4202
4203 trace_rdma_start_outgoing_migration_after_rdma_connect();
4204
4205 s->to_dst_file = rdma_new_output(rdma);
4206 s->rdma_migration = true;
4207 migrate_fd_connect(s, NULL);
4208 return;
4209 return_path_err:
4210 qemu_rdma_cleanup(rdma);
4211 err:
4212 g_free(rdma);
4213 g_free(rdma_return_path);
4214 }