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