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