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