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