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