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