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