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