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