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