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