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