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