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