2 * RDMA protocol and interfaces
4 * Copyright IBM, Corp. 2010-2013
5 * Copyright Red Hat, Inc. 2015-2016
8 * Michael R. Hines <mrhines@us.ibm.com>
9 * Jiuxing Liu <jl@us.ibm.com>
10 * Daniel P. Berrange <berrange@redhat.com>
12 * This work is licensed under the terms of the GNU GPL, version 2 or
13 * later. See the COPYING file in the top-level directory.
16 #include "qemu/osdep.h"
17 #include "qapi/error.h"
18 #include "qemu-common.h"
19 #include "qemu/cutils.h"
21 #include "migration.h"
22 #include "qemu-file.h"
24 #include "qemu-file-channel.h"
25 #include "qemu/error-report.h"
26 #include "qemu/main-loop.h"
27 #include "qemu/sockets.h"
28 #include "qemu/bitmap.h"
29 #include "qemu/coroutine.h"
30 #include <sys/socket.h>
32 #include <arpa/inet.h>
33 #include <rdma/rdma_cma.h>
37 * Print and error on both the Monitor and the Log file.
39 #define ERROR(errp, fmt, ...) \
41 fprintf(stderr, "RDMA ERROR: " fmt "\n", ## __VA_ARGS__); \
42 if (errp && (*(errp) == NULL)) { \
43 error_setg(errp, "RDMA ERROR: " fmt, ## __VA_ARGS__); \
47 #define RDMA_RESOLVE_TIMEOUT_MS 10000
49 /* Do not merge data if larger than this. */
50 #define RDMA_MERGE_MAX (2 * 1024 * 1024)
51 #define RDMA_SIGNALED_SEND_MAX (RDMA_MERGE_MAX / 4096)
53 #define RDMA_REG_CHUNK_SHIFT 20 /* 1 MB */
56 * This is only for non-live state being migrated.
57 * Instead of RDMA_WRITE messages, we use RDMA_SEND
58 * messages for that state, which requires a different
59 * delivery design than main memory.
61 #define RDMA_SEND_INCREMENT 32768
64 * Maximum size infiniband SEND message
66 #define RDMA_CONTROL_MAX_BUFFER (512 * 1024)
67 #define RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE 4096
69 #define RDMA_CONTROL_VERSION_CURRENT 1
71 * Capabilities for negotiation.
73 #define RDMA_CAPABILITY_PIN_ALL 0x01
76 * Add the other flags above to this list of known capabilities
77 * as they are introduced.
79 static uint32_t known_capabilities
= RDMA_CAPABILITY_PIN_ALL
;
81 #define CHECK_ERROR_STATE() \
83 if (rdma->error_state) { \
84 if (!rdma->error_reported) { \
85 error_report("RDMA is in an error state waiting migration" \
87 rdma->error_reported = 1; \
89 return rdma->error_state; \
94 * A work request ID is 64-bits and we split up these bits
97 * bits 0-15 : type of control message, 2^16
98 * bits 16-29: ram block index, 2^14
99 * bits 30-63: ram block chunk number, 2^34
101 * The last two bit ranges are only used for RDMA writes,
102 * in order to track their completion and potentially
103 * also track unregistration status of the message.
105 #define RDMA_WRID_TYPE_SHIFT 0UL
106 #define RDMA_WRID_BLOCK_SHIFT 16UL
107 #define RDMA_WRID_CHUNK_SHIFT 30UL
109 #define RDMA_WRID_TYPE_MASK \
110 ((1UL << RDMA_WRID_BLOCK_SHIFT) - 1UL)
112 #define RDMA_WRID_BLOCK_MASK \
113 (~RDMA_WRID_TYPE_MASK & ((1UL << RDMA_WRID_CHUNK_SHIFT) - 1UL))
115 #define RDMA_WRID_CHUNK_MASK (~RDMA_WRID_BLOCK_MASK & ~RDMA_WRID_TYPE_MASK)
118 * RDMA migration protocol:
119 * 1. RDMA Writes (data messages, i.e. RAM)
120 * 2. IB Send/Recv (control channel messages)
124 RDMA_WRID_RDMA_WRITE
= 1,
125 RDMA_WRID_SEND_CONTROL
= 2000,
126 RDMA_WRID_RECV_CONTROL
= 4000,
129 static const char *wrid_desc
[] = {
130 [RDMA_WRID_NONE
] = "NONE",
131 [RDMA_WRID_RDMA_WRITE
] = "WRITE RDMA",
132 [RDMA_WRID_SEND_CONTROL
] = "CONTROL SEND",
133 [RDMA_WRID_RECV_CONTROL
] = "CONTROL RECV",
137 * Work request IDs for IB SEND messages only (not RDMA writes).
138 * This is used by the migration protocol to transmit
139 * control messages (such as device state and registration commands)
141 * We could use more WRs, but we have enough for now.
151 * SEND/RECV IB Control Messages.
154 RDMA_CONTROL_NONE
= 0,
156 RDMA_CONTROL_READY
, /* ready to receive */
157 RDMA_CONTROL_QEMU_FILE
, /* QEMUFile-transmitted bytes */
158 RDMA_CONTROL_RAM_BLOCKS_REQUEST
, /* RAMBlock synchronization */
159 RDMA_CONTROL_RAM_BLOCKS_RESULT
, /* RAMBlock synchronization */
160 RDMA_CONTROL_COMPRESS
, /* page contains repeat values */
161 RDMA_CONTROL_REGISTER_REQUEST
, /* dynamic page registration */
162 RDMA_CONTROL_REGISTER_RESULT
, /* key to use after registration */
163 RDMA_CONTROL_REGISTER_FINISHED
, /* current iteration finished */
164 RDMA_CONTROL_UNREGISTER_REQUEST
, /* dynamic UN-registration */
165 RDMA_CONTROL_UNREGISTER_FINISHED
, /* unpinning finished */
170 * Memory and MR structures used to represent an IB Send/Recv work request.
171 * This is *not* used for RDMA writes, only IB Send/Recv.
174 uint8_t control
[RDMA_CONTROL_MAX_BUFFER
]; /* actual buffer to register */
175 struct ibv_mr
*control_mr
; /* registration metadata */
176 size_t control_len
; /* length of the message */
177 uint8_t *control_curr
; /* start of unconsumed bytes */
178 } RDMAWorkRequestData
;
181 * Negotiate RDMA capabilities during connection-setup time.
188 static void caps_to_network(RDMACapabilities
*cap
)
190 cap
->version
= htonl(cap
->version
);
191 cap
->flags
= htonl(cap
->flags
);
194 static void network_to_caps(RDMACapabilities
*cap
)
196 cap
->version
= ntohl(cap
->version
);
197 cap
->flags
= ntohl(cap
->flags
);
201 * Representation of a RAMBlock from an RDMA perspective.
202 * This is not transmitted, only local.
203 * This and subsequent structures cannot be linked lists
204 * because we're using a single IB message to transmit
205 * the information. It's small anyway, so a list is overkill.
207 typedef struct RDMALocalBlock
{
209 uint8_t *local_host_addr
; /* local virtual address */
210 uint64_t remote_host_addr
; /* remote virtual address */
213 struct ibv_mr
**pmr
; /* MRs for chunk-level registration */
214 struct ibv_mr
*mr
; /* MR for non-chunk-level registration */
215 uint32_t *remote_keys
; /* rkeys for chunk-level registration */
216 uint32_t remote_rkey
; /* rkeys for non-chunk-level registration */
217 int index
; /* which block are we */
218 unsigned int src_index
; /* (Only used on dest) */
221 unsigned long *transit_bitmap
;
222 unsigned long *unregister_bitmap
;
226 * Also represents a RAMblock, but only on the dest.
227 * This gets transmitted by the dest during connection-time
228 * to the source VM and then is used to populate the
229 * corresponding RDMALocalBlock with
230 * the information needed to perform the actual RDMA.
232 typedef struct QEMU_PACKED RDMADestBlock
{
233 uint64_t remote_host_addr
;
236 uint32_t remote_rkey
;
240 static const char *control_desc(unsigned int rdma_control
)
242 static const char *strs
[] = {
243 [RDMA_CONTROL_NONE
] = "NONE",
244 [RDMA_CONTROL_ERROR
] = "ERROR",
245 [RDMA_CONTROL_READY
] = "READY",
246 [RDMA_CONTROL_QEMU_FILE
] = "QEMU FILE",
247 [RDMA_CONTROL_RAM_BLOCKS_REQUEST
] = "RAM BLOCKS REQUEST",
248 [RDMA_CONTROL_RAM_BLOCKS_RESULT
] = "RAM BLOCKS RESULT",
249 [RDMA_CONTROL_COMPRESS
] = "COMPRESS",
250 [RDMA_CONTROL_REGISTER_REQUEST
] = "REGISTER REQUEST",
251 [RDMA_CONTROL_REGISTER_RESULT
] = "REGISTER RESULT",
252 [RDMA_CONTROL_REGISTER_FINISHED
] = "REGISTER FINISHED",
253 [RDMA_CONTROL_UNREGISTER_REQUEST
] = "UNREGISTER REQUEST",
254 [RDMA_CONTROL_UNREGISTER_FINISHED
] = "UNREGISTER FINISHED",
257 if (rdma_control
> RDMA_CONTROL_UNREGISTER_FINISHED
) {
258 return "??BAD CONTROL VALUE??";
261 return strs
[rdma_control
];
264 static uint64_t htonll(uint64_t v
)
266 union { uint32_t lv
[2]; uint64_t llv
; } u
;
267 u
.lv
[0] = htonl(v
>> 32);
268 u
.lv
[1] = htonl(v
& 0xFFFFFFFFULL
);
272 static uint64_t ntohll(uint64_t v
) {
273 union { uint32_t lv
[2]; uint64_t llv
; } u
;
275 return ((uint64_t)ntohl(u
.lv
[0]) << 32) | (uint64_t) ntohl(u
.lv
[1]);
278 static void dest_block_to_network(RDMADestBlock
*db
)
280 db
->remote_host_addr
= htonll(db
->remote_host_addr
);
281 db
->offset
= htonll(db
->offset
);
282 db
->length
= htonll(db
->length
);
283 db
->remote_rkey
= htonl(db
->remote_rkey
);
286 static void network_to_dest_block(RDMADestBlock
*db
)
288 db
->remote_host_addr
= ntohll(db
->remote_host_addr
);
289 db
->offset
= ntohll(db
->offset
);
290 db
->length
= ntohll(db
->length
);
291 db
->remote_rkey
= ntohl(db
->remote_rkey
);
295 * Virtual address of the above structures used for transmitting
296 * the RAMBlock descriptions at connection-time.
297 * This structure is *not* transmitted.
299 typedef struct RDMALocalBlocks
{
301 bool init
; /* main memory init complete */
302 RDMALocalBlock
*block
;
306 * Main data structure for RDMA state.
307 * While there is only one copy of this structure being allocated right now,
308 * this is the place where one would start if you wanted to consider
309 * having more than one RDMA connection open at the same time.
311 typedef struct RDMAContext
{
315 RDMAWorkRequestData wr_data
[RDMA_WRID_MAX
];
318 * This is used by *_exchange_send() to figure out whether or not
319 * the initial "READY" message has already been received or not.
320 * This is because other functions may potentially poll() and detect
321 * the READY message before send() does, in which case we need to
322 * know if it completed.
324 int control_ready_expected
;
326 /* number of outstanding writes */
329 /* store info about current buffer so that we can
330 merge it with future sends */
331 uint64_t current_addr
;
332 uint64_t current_length
;
333 /* index of ram block the current buffer belongs to */
335 /* index of the chunk in the current ram block */
341 * infiniband-specific variables for opening the device
342 * and maintaining connection state and so forth.
344 * cm_id also has ibv_context, rdma_event_channel, and ibv_qp in
345 * cm_id->verbs, cm_id->channel, and cm_id->qp.
347 struct rdma_cm_id
*cm_id
; /* connection manager ID */
348 struct rdma_cm_id
*listen_id
;
351 struct ibv_context
*verbs
;
352 struct rdma_event_channel
*channel
;
353 struct ibv_qp
*qp
; /* queue pair */
354 struct ibv_comp_channel
*comp_channel
; /* completion channel */
355 struct ibv_pd
*pd
; /* protection domain */
356 struct ibv_cq
*cq
; /* completion queue */
359 * If a previous write failed (perhaps because of a failed
360 * memory registration, then do not attempt any future work
361 * and remember the error state.
368 * Description of ram blocks used throughout the code.
370 RDMALocalBlocks local_ram_blocks
;
371 RDMADestBlock
*dest_blocks
;
373 /* Index of the next RAMBlock received during block registration */
374 unsigned int next_src_index
;
377 * Migration on *destination* started.
378 * Then use coroutine yield function.
379 * Source runs in a thread, so we don't care.
381 int migration_started_on_destination
;
383 int total_registrations
;
386 int unregister_current
, unregister_next
;
387 uint64_t unregistrations
[RDMA_SIGNALED_SEND_MAX
];
389 GHashTable
*blockmap
;
392 #define TYPE_QIO_CHANNEL_RDMA "qio-channel-rdma"
393 #define QIO_CHANNEL_RDMA(obj) \
394 OBJECT_CHECK(QIOChannelRDMA, (obj), TYPE_QIO_CHANNEL_RDMA)
396 typedef struct QIOChannelRDMA QIOChannelRDMA
;
399 struct QIOChannelRDMA
{
404 bool blocking
; /* XXX we don't actually honour this yet */
408 * Main structure for IB Send/Recv control messages.
409 * This gets prepended at the beginning of every Send/Recv.
411 typedef struct QEMU_PACKED
{
412 uint32_t len
; /* Total length of data portion */
413 uint32_t type
; /* which control command to perform */
414 uint32_t repeat
; /* number of commands in data portion of same type */
418 static void control_to_network(RDMAControlHeader
*control
)
420 control
->type
= htonl(control
->type
);
421 control
->len
= htonl(control
->len
);
422 control
->repeat
= htonl(control
->repeat
);
425 static void network_to_control(RDMAControlHeader
*control
)
427 control
->type
= ntohl(control
->type
);
428 control
->len
= ntohl(control
->len
);
429 control
->repeat
= ntohl(control
->repeat
);
433 * Register a single Chunk.
434 * Information sent by the source VM to inform the dest
435 * to register an single chunk of memory before we can perform
436 * the actual RDMA operation.
438 typedef struct QEMU_PACKED
{
440 uint64_t current_addr
; /* offset into the ram_addr_t space */
441 uint64_t chunk
; /* chunk to lookup if unregistering */
443 uint32_t current_index
; /* which ramblock the chunk belongs to */
445 uint64_t chunks
; /* how many sequential chunks to register */
448 static void register_to_network(RDMAContext
*rdma
, RDMARegister
*reg
)
450 RDMALocalBlock
*local_block
;
451 local_block
= &rdma
->local_ram_blocks
.block
[reg
->current_index
];
453 if (local_block
->is_ram_block
) {
455 * current_addr as passed in is an address in the local ram_addr_t
456 * space, we need to translate this for the destination
458 reg
->key
.current_addr
-= local_block
->offset
;
459 reg
->key
.current_addr
+= rdma
->dest_blocks
[reg
->current_index
].offset
;
461 reg
->key
.current_addr
= htonll(reg
->key
.current_addr
);
462 reg
->current_index
= htonl(reg
->current_index
);
463 reg
->chunks
= htonll(reg
->chunks
);
466 static void network_to_register(RDMARegister
*reg
)
468 reg
->key
.current_addr
= ntohll(reg
->key
.current_addr
);
469 reg
->current_index
= ntohl(reg
->current_index
);
470 reg
->chunks
= ntohll(reg
->chunks
);
473 typedef struct QEMU_PACKED
{
474 uint32_t value
; /* if zero, we will madvise() */
475 uint32_t block_idx
; /* which ram block index */
476 uint64_t offset
; /* Address in remote ram_addr_t space */
477 uint64_t length
; /* length of the chunk */
480 static void compress_to_network(RDMAContext
*rdma
, RDMACompress
*comp
)
482 comp
->value
= htonl(comp
->value
);
484 * comp->offset as passed in is an address in the local ram_addr_t
485 * space, we need to translate this for the destination
487 comp
->offset
-= rdma
->local_ram_blocks
.block
[comp
->block_idx
].offset
;
488 comp
->offset
+= rdma
->dest_blocks
[comp
->block_idx
].offset
;
489 comp
->block_idx
= htonl(comp
->block_idx
);
490 comp
->offset
= htonll(comp
->offset
);
491 comp
->length
= htonll(comp
->length
);
494 static void network_to_compress(RDMACompress
*comp
)
496 comp
->value
= ntohl(comp
->value
);
497 comp
->block_idx
= ntohl(comp
->block_idx
);
498 comp
->offset
= ntohll(comp
->offset
);
499 comp
->length
= ntohll(comp
->length
);
503 * The result of the dest's memory registration produces an "rkey"
504 * which the source VM must reference in order to perform
505 * the RDMA operation.
507 typedef struct QEMU_PACKED
{
511 } RDMARegisterResult
;
513 static void result_to_network(RDMARegisterResult
*result
)
515 result
->rkey
= htonl(result
->rkey
);
516 result
->host_addr
= htonll(result
->host_addr
);
519 static void network_to_result(RDMARegisterResult
*result
)
521 result
->rkey
= ntohl(result
->rkey
);
522 result
->host_addr
= ntohll(result
->host_addr
);
525 const char *print_wrid(int wrid
);
526 static int qemu_rdma_exchange_send(RDMAContext
*rdma
, RDMAControlHeader
*head
,
527 uint8_t *data
, RDMAControlHeader
*resp
,
529 int (*callback
)(RDMAContext
*rdma
));
531 static inline uint64_t ram_chunk_index(const uint8_t *start
,
534 return ((uintptr_t) host
- (uintptr_t) start
) >> RDMA_REG_CHUNK_SHIFT
;
537 static inline uint8_t *ram_chunk_start(const RDMALocalBlock
*rdma_ram_block
,
540 return (uint8_t *)(uintptr_t)(rdma_ram_block
->local_host_addr
+
541 (i
<< RDMA_REG_CHUNK_SHIFT
));
544 static inline uint8_t *ram_chunk_end(const RDMALocalBlock
*rdma_ram_block
,
547 uint8_t *result
= ram_chunk_start(rdma_ram_block
, i
) +
548 (1UL << RDMA_REG_CHUNK_SHIFT
);
550 if (result
> (rdma_ram_block
->local_host_addr
+ rdma_ram_block
->length
)) {
551 result
= rdma_ram_block
->local_host_addr
+ rdma_ram_block
->length
;
557 static int rdma_add_block(RDMAContext
*rdma
, const char *block_name
,
559 ram_addr_t block_offset
, uint64_t length
)
561 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
562 RDMALocalBlock
*block
;
563 RDMALocalBlock
*old
= local
->block
;
565 local
->block
= g_new0(RDMALocalBlock
, local
->nb_blocks
+ 1);
567 if (local
->nb_blocks
) {
570 if (rdma
->blockmap
) {
571 for (x
= 0; x
< local
->nb_blocks
; x
++) {
572 g_hash_table_remove(rdma
->blockmap
,
573 (void *)(uintptr_t)old
[x
].offset
);
574 g_hash_table_insert(rdma
->blockmap
,
575 (void *)(uintptr_t)old
[x
].offset
,
579 memcpy(local
->block
, old
, sizeof(RDMALocalBlock
) * local
->nb_blocks
);
583 block
= &local
->block
[local
->nb_blocks
];
585 block
->block_name
= g_strdup(block_name
);
586 block
->local_host_addr
= host_addr
;
587 block
->offset
= block_offset
;
588 block
->length
= length
;
589 block
->index
= local
->nb_blocks
;
590 block
->src_index
= ~0U; /* Filled in by the receipt of the block list */
591 block
->nb_chunks
= ram_chunk_index(host_addr
, host_addr
+ length
) + 1UL;
592 block
->transit_bitmap
= bitmap_new(block
->nb_chunks
);
593 bitmap_clear(block
->transit_bitmap
, 0, block
->nb_chunks
);
594 block
->unregister_bitmap
= bitmap_new(block
->nb_chunks
);
595 bitmap_clear(block
->unregister_bitmap
, 0, block
->nb_chunks
);
596 block
->remote_keys
= g_new0(uint32_t, block
->nb_chunks
);
598 block
->is_ram_block
= local
->init
? false : true;
600 if (rdma
->blockmap
) {
601 g_hash_table_insert(rdma
->blockmap
, (void *)(uintptr_t)block_offset
, block
);
604 trace_rdma_add_block(block_name
, local
->nb_blocks
,
605 (uintptr_t) block
->local_host_addr
,
606 block
->offset
, block
->length
,
607 (uintptr_t) (block
->local_host_addr
+ block
->length
),
608 BITS_TO_LONGS(block
->nb_chunks
) *
609 sizeof(unsigned long) * 8,
618 * Memory regions need to be registered with the device and queue pairs setup
619 * in advanced before the migration starts. This tells us where the RAM blocks
620 * are so that we can register them individually.
622 static int qemu_rdma_init_one_block(const char *block_name
, void *host_addr
,
623 ram_addr_t block_offset
, ram_addr_t length
, void *opaque
)
625 return rdma_add_block(opaque
, block_name
, host_addr
, block_offset
, length
);
629 * Identify the RAMBlocks and their quantity. They will be references to
630 * identify chunk boundaries inside each RAMBlock and also be referenced
631 * during dynamic page registration.
633 static int qemu_rdma_init_ram_blocks(RDMAContext
*rdma
)
635 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
637 assert(rdma
->blockmap
== NULL
);
638 memset(local
, 0, sizeof *local
);
639 qemu_ram_foreach_block(qemu_rdma_init_one_block
, rdma
);
640 trace_qemu_rdma_init_ram_blocks(local
->nb_blocks
);
641 rdma
->dest_blocks
= g_new0(RDMADestBlock
,
642 rdma
->local_ram_blocks
.nb_blocks
);
648 * Note: If used outside of cleanup, the caller must ensure that the destination
649 * block structures are also updated
651 static int rdma_delete_block(RDMAContext
*rdma
, RDMALocalBlock
*block
)
653 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
654 RDMALocalBlock
*old
= local
->block
;
657 if (rdma
->blockmap
) {
658 g_hash_table_remove(rdma
->blockmap
, (void *)(uintptr_t)block
->offset
);
663 for (j
= 0; j
< block
->nb_chunks
; j
++) {
664 if (!block
->pmr
[j
]) {
667 ibv_dereg_mr(block
->pmr
[j
]);
668 rdma
->total_registrations
--;
675 ibv_dereg_mr(block
->mr
);
676 rdma
->total_registrations
--;
680 g_free(block
->transit_bitmap
);
681 block
->transit_bitmap
= NULL
;
683 g_free(block
->unregister_bitmap
);
684 block
->unregister_bitmap
= NULL
;
686 g_free(block
->remote_keys
);
687 block
->remote_keys
= NULL
;
689 g_free(block
->block_name
);
690 block
->block_name
= NULL
;
692 if (rdma
->blockmap
) {
693 for (x
= 0; x
< local
->nb_blocks
; x
++) {
694 g_hash_table_remove(rdma
->blockmap
,
695 (void *)(uintptr_t)old
[x
].offset
);
699 if (local
->nb_blocks
> 1) {
701 local
->block
= g_new0(RDMALocalBlock
, local
->nb_blocks
- 1);
704 memcpy(local
->block
, old
, sizeof(RDMALocalBlock
) * block
->index
);
707 if (block
->index
< (local
->nb_blocks
- 1)) {
708 memcpy(local
->block
+ block
->index
, old
+ (block
->index
+ 1),
709 sizeof(RDMALocalBlock
) *
710 (local
->nb_blocks
- (block
->index
+ 1)));
711 for (x
= block
->index
; x
< local
->nb_blocks
- 1; x
++) {
712 local
->block
[x
].index
--;
716 assert(block
== local
->block
);
720 trace_rdma_delete_block(block
, (uintptr_t)block
->local_host_addr
,
721 block
->offset
, block
->length
,
722 (uintptr_t)(block
->local_host_addr
+ block
->length
),
723 BITS_TO_LONGS(block
->nb_chunks
) *
724 sizeof(unsigned long) * 8, block
->nb_chunks
);
730 if (local
->nb_blocks
&& rdma
->blockmap
) {
731 for (x
= 0; x
< local
->nb_blocks
; x
++) {
732 g_hash_table_insert(rdma
->blockmap
,
733 (void *)(uintptr_t)local
->block
[x
].offset
,
742 * Put in the log file which RDMA device was opened and the details
743 * associated with that device.
745 static void qemu_rdma_dump_id(const char *who
, struct ibv_context
*verbs
)
747 struct ibv_port_attr port
;
749 if (ibv_query_port(verbs
, 1, &port
)) {
750 error_report("Failed to query port information");
754 printf("%s RDMA Device opened: kernel name %s "
755 "uverbs device name %s, "
756 "infiniband_verbs class device path %s, "
757 "infiniband class device path %s, "
758 "transport: (%d) %s\n",
761 verbs
->device
->dev_name
,
762 verbs
->device
->dev_path
,
763 verbs
->device
->ibdev_path
,
765 (port
.link_layer
== IBV_LINK_LAYER_INFINIBAND
) ? "Infiniband" :
766 ((port
.link_layer
== IBV_LINK_LAYER_ETHERNET
)
767 ? "Ethernet" : "Unknown"));
771 * Put in the log file the RDMA gid addressing information,
772 * useful for folks who have trouble understanding the
773 * RDMA device hierarchy in the kernel.
775 static void qemu_rdma_dump_gid(const char *who
, struct rdma_cm_id
*id
)
779 inet_ntop(AF_INET6
, &id
->route
.addr
.addr
.ibaddr
.sgid
, sgid
, sizeof sgid
);
780 inet_ntop(AF_INET6
, &id
->route
.addr
.addr
.ibaddr
.dgid
, dgid
, sizeof dgid
);
781 trace_qemu_rdma_dump_gid(who
, sgid
, dgid
);
785 * As of now, IPv6 over RoCE / iWARP is not supported by linux.
786 * We will try the next addrinfo struct, and fail if there are
787 * no other valid addresses to bind against.
789 * If user is listening on '[::]', then we will not have a opened a device
790 * yet and have no way of verifying if the device is RoCE or not.
792 * In this case, the source VM will throw an error for ALL types of
793 * connections (both IPv4 and IPv6) if the destination machine does not have
794 * a regular infiniband network available for use.
796 * The only way to guarantee that an error is thrown for broken kernels is
797 * for the management software to choose a *specific* interface at bind time
798 * and validate what time of hardware it is.
800 * Unfortunately, this puts the user in a fix:
802 * If the source VM connects with an IPv4 address without knowing that the
803 * destination has bound to '[::]' the migration will unconditionally fail
804 * unless the management software is explicitly listening on the IPv4
805 * address while using a RoCE-based device.
807 * If the source VM connects with an IPv6 address, then we're OK because we can
808 * throw an error on the source (and similarly on the destination).
810 * But in mixed environments, this will be broken for a while until it is fixed
813 * We do provide a *tiny* bit of help in this function: We can list all of the
814 * devices in the system and check to see if all the devices are RoCE or
817 * If we detect that we have a *pure* RoCE environment, then we can safely
818 * thrown an error even if the management software has specified '[::]' as the
821 * However, if there is are multiple hetergeneous devices, then we cannot make
822 * this assumption and the user just has to be sure they know what they are
825 * Patches are being reviewed on linux-rdma.
827 static int qemu_rdma_broken_ipv6_kernel(struct ibv_context
*verbs
, Error
**errp
)
829 struct ibv_port_attr port_attr
;
831 /* This bug only exists in linux, to our knowledge. */
835 * Verbs are only NULL if management has bound to '[::]'.
837 * Let's iterate through all the devices and see if there any pure IB
838 * devices (non-ethernet).
840 * If not, then we can safely proceed with the migration.
841 * Otherwise, there are no guarantees until the bug is fixed in linux.
845 struct ibv_device
** dev_list
= ibv_get_device_list(&num_devices
);
846 bool roce_found
= false;
847 bool ib_found
= false;
849 for (x
= 0; x
< num_devices
; x
++) {
850 verbs
= ibv_open_device(dev_list
[x
]);
852 if (errno
== EPERM
) {
859 if (ibv_query_port(verbs
, 1, &port_attr
)) {
860 ibv_close_device(verbs
);
861 ERROR(errp
, "Could not query initial IB port");
865 if (port_attr
.link_layer
== IBV_LINK_LAYER_INFINIBAND
) {
867 } else if (port_attr
.link_layer
== IBV_LINK_LAYER_ETHERNET
) {
871 ibv_close_device(verbs
);
877 fprintf(stderr
, "WARN: migrations may fail:"
878 " IPv6 over RoCE / iWARP in linux"
879 " is broken. But since you appear to have a"
880 " mixed RoCE / IB environment, be sure to only"
881 " migrate over the IB fabric until the kernel "
882 " fixes the bug.\n");
884 ERROR(errp
, "You only have RoCE / iWARP devices in your systems"
885 " and your management software has specified '[::]'"
886 ", but IPv6 over RoCE / iWARP is not supported in Linux.");
895 * If we have a verbs context, that means that some other than '[::]' was
896 * used by the management software for binding. In which case we can
897 * actually warn the user about a potentially broken kernel.
900 /* IB ports start with 1, not 0 */
901 if (ibv_query_port(verbs
, 1, &port_attr
)) {
902 ERROR(errp
, "Could not query initial IB port");
906 if (port_attr
.link_layer
== IBV_LINK_LAYER_ETHERNET
) {
907 ERROR(errp
, "Linux kernel's RoCE / iWARP does not support IPv6 "
908 "(but patches on linux-rdma in progress)");
918 * Figure out which RDMA device corresponds to the requested IP hostname
919 * Also create the initial connection manager identifiers for opening
922 static int qemu_rdma_resolve_host(RDMAContext
*rdma
, Error
**errp
)
925 struct rdma_addrinfo
*res
;
927 struct rdma_cm_event
*cm_event
;
928 char ip
[40] = "unknown";
929 struct rdma_addrinfo
*e
;
931 if (rdma
->host
== NULL
|| !strcmp(rdma
->host
, "")) {
932 ERROR(errp
, "RDMA hostname has not been set");
936 /* create CM channel */
937 rdma
->channel
= rdma_create_event_channel();
938 if (!rdma
->channel
) {
939 ERROR(errp
, "could not create CM channel");
944 ret
= rdma_create_id(rdma
->channel
, &rdma
->cm_id
, NULL
, RDMA_PS_TCP
);
946 ERROR(errp
, "could not create channel id");
947 goto err_resolve_create_id
;
950 snprintf(port_str
, 16, "%d", rdma
->port
);
953 ret
= rdma_getaddrinfo(rdma
->host
, port_str
, NULL
, &res
);
955 ERROR(errp
, "could not rdma_getaddrinfo address %s", rdma
->host
);
956 goto err_resolve_get_addr
;
959 for (e
= res
; e
!= NULL
; e
= e
->ai_next
) {
960 inet_ntop(e
->ai_family
,
961 &((struct sockaddr_in
*) e
->ai_dst_addr
)->sin_addr
, ip
, sizeof ip
);
962 trace_qemu_rdma_resolve_host_trying(rdma
->host
, ip
);
964 ret
= rdma_resolve_addr(rdma
->cm_id
, NULL
, e
->ai_dst_addr
,
965 RDMA_RESOLVE_TIMEOUT_MS
);
967 if (e
->ai_family
== AF_INET6
) {
968 ret
= qemu_rdma_broken_ipv6_kernel(rdma
->cm_id
->verbs
, errp
);
977 ERROR(errp
, "could not resolve address %s", rdma
->host
);
978 goto err_resolve_get_addr
;
981 qemu_rdma_dump_gid("source_resolve_addr", rdma
->cm_id
);
983 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
985 ERROR(errp
, "could not perform event_addr_resolved");
986 goto err_resolve_get_addr
;
989 if (cm_event
->event
!= RDMA_CM_EVENT_ADDR_RESOLVED
) {
990 ERROR(errp
, "result not equal to event_addr_resolved %s",
991 rdma_event_str(cm_event
->event
));
992 perror("rdma_resolve_addr");
993 rdma_ack_cm_event(cm_event
);
995 goto err_resolve_get_addr
;
997 rdma_ack_cm_event(cm_event
);
1000 ret
= rdma_resolve_route(rdma
->cm_id
, RDMA_RESOLVE_TIMEOUT_MS
);
1002 ERROR(errp
, "could not resolve rdma route");
1003 goto err_resolve_get_addr
;
1006 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
1008 ERROR(errp
, "could not perform event_route_resolved");
1009 goto err_resolve_get_addr
;
1011 if (cm_event
->event
!= RDMA_CM_EVENT_ROUTE_RESOLVED
) {
1012 ERROR(errp
, "result not equal to event_route_resolved: %s",
1013 rdma_event_str(cm_event
->event
));
1014 rdma_ack_cm_event(cm_event
);
1016 goto err_resolve_get_addr
;
1018 rdma_ack_cm_event(cm_event
);
1019 rdma
->verbs
= rdma
->cm_id
->verbs
;
1020 qemu_rdma_dump_id("source_resolve_host", rdma
->cm_id
->verbs
);
1021 qemu_rdma_dump_gid("source_resolve_host", rdma
->cm_id
);
1024 err_resolve_get_addr
:
1025 rdma_destroy_id(rdma
->cm_id
);
1027 err_resolve_create_id
:
1028 rdma_destroy_event_channel(rdma
->channel
);
1029 rdma
->channel
= NULL
;
1034 * Create protection domain and completion queues
1036 static int qemu_rdma_alloc_pd_cq(RDMAContext
*rdma
)
1039 rdma
->pd
= ibv_alloc_pd(rdma
->verbs
);
1041 error_report("failed to allocate protection domain");
1045 /* create completion channel */
1046 rdma
->comp_channel
= ibv_create_comp_channel(rdma
->verbs
);
1047 if (!rdma
->comp_channel
) {
1048 error_report("failed to allocate completion channel");
1049 goto err_alloc_pd_cq
;
1053 * Completion queue can be filled by both read and write work requests,
1054 * so must reflect the sum of both possible queue sizes.
1056 rdma
->cq
= ibv_create_cq(rdma
->verbs
, (RDMA_SIGNALED_SEND_MAX
* 3),
1057 NULL
, rdma
->comp_channel
, 0);
1059 error_report("failed to allocate completion queue");
1060 goto err_alloc_pd_cq
;
1067 ibv_dealloc_pd(rdma
->pd
);
1069 if (rdma
->comp_channel
) {
1070 ibv_destroy_comp_channel(rdma
->comp_channel
);
1073 rdma
->comp_channel
= NULL
;
1079 * Create queue pairs.
1081 static int qemu_rdma_alloc_qp(RDMAContext
*rdma
)
1083 struct ibv_qp_init_attr attr
= { 0 };
1086 attr
.cap
.max_send_wr
= RDMA_SIGNALED_SEND_MAX
;
1087 attr
.cap
.max_recv_wr
= 3;
1088 attr
.cap
.max_send_sge
= 1;
1089 attr
.cap
.max_recv_sge
= 1;
1090 attr
.send_cq
= rdma
->cq
;
1091 attr
.recv_cq
= rdma
->cq
;
1092 attr
.qp_type
= IBV_QPT_RC
;
1094 ret
= rdma_create_qp(rdma
->cm_id
, rdma
->pd
, &attr
);
1099 rdma
->qp
= rdma
->cm_id
->qp
;
1103 static int qemu_rdma_reg_whole_ram_blocks(RDMAContext
*rdma
)
1106 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
1108 for (i
= 0; i
< local
->nb_blocks
; i
++) {
1109 local
->block
[i
].mr
=
1110 ibv_reg_mr(rdma
->pd
,
1111 local
->block
[i
].local_host_addr
,
1112 local
->block
[i
].length
,
1113 IBV_ACCESS_LOCAL_WRITE
|
1114 IBV_ACCESS_REMOTE_WRITE
1116 if (!local
->block
[i
].mr
) {
1117 perror("Failed to register local dest ram block!\n");
1120 rdma
->total_registrations
++;
1123 if (i
>= local
->nb_blocks
) {
1127 for (i
--; i
>= 0; i
--) {
1128 ibv_dereg_mr(local
->block
[i
].mr
);
1129 rdma
->total_registrations
--;
1137 * Find the ram block that corresponds to the page requested to be
1138 * transmitted by QEMU.
1140 * Once the block is found, also identify which 'chunk' within that
1141 * block that the page belongs to.
1143 * This search cannot fail or the migration will fail.
1145 static int qemu_rdma_search_ram_block(RDMAContext
*rdma
,
1146 uintptr_t block_offset
,
1149 uint64_t *block_index
,
1150 uint64_t *chunk_index
)
1152 uint64_t current_addr
= block_offset
+ offset
;
1153 RDMALocalBlock
*block
= g_hash_table_lookup(rdma
->blockmap
,
1154 (void *) block_offset
);
1156 assert(current_addr
>= block
->offset
);
1157 assert((current_addr
+ length
) <= (block
->offset
+ block
->length
));
1159 *block_index
= block
->index
;
1160 *chunk_index
= ram_chunk_index(block
->local_host_addr
,
1161 block
->local_host_addr
+ (current_addr
- block
->offset
));
1167 * Register a chunk with IB. If the chunk was already registered
1168 * previously, then skip.
1170 * Also return the keys associated with the registration needed
1171 * to perform the actual RDMA operation.
1173 static int qemu_rdma_register_and_get_keys(RDMAContext
*rdma
,
1174 RDMALocalBlock
*block
, uintptr_t host_addr
,
1175 uint32_t *lkey
, uint32_t *rkey
, int chunk
,
1176 uint8_t *chunk_start
, uint8_t *chunk_end
)
1180 *lkey
= block
->mr
->lkey
;
1183 *rkey
= block
->mr
->rkey
;
1188 /* allocate memory to store chunk MRs */
1190 block
->pmr
= g_new0(struct ibv_mr
*, block
->nb_chunks
);
1194 * If 'rkey', then we're the destination, so grant access to the source.
1196 * If 'lkey', then we're the source VM, so grant access only to ourselves.
1198 if (!block
->pmr
[chunk
]) {
1199 uint64_t len
= chunk_end
- chunk_start
;
1201 trace_qemu_rdma_register_and_get_keys(len
, chunk_start
);
1203 block
->pmr
[chunk
] = ibv_reg_mr(rdma
->pd
,
1205 (rkey
? (IBV_ACCESS_LOCAL_WRITE
|
1206 IBV_ACCESS_REMOTE_WRITE
) : 0));
1208 if (!block
->pmr
[chunk
]) {
1209 perror("Failed to register chunk!");
1210 fprintf(stderr
, "Chunk details: block: %d chunk index %d"
1211 " start %" PRIuPTR
" end %" PRIuPTR
1213 " local %" PRIuPTR
" registrations: %d\n",
1214 block
->index
, chunk
, (uintptr_t)chunk_start
,
1215 (uintptr_t)chunk_end
, host_addr
,
1216 (uintptr_t)block
->local_host_addr
,
1217 rdma
->total_registrations
);
1220 rdma
->total_registrations
++;
1224 *lkey
= block
->pmr
[chunk
]->lkey
;
1227 *rkey
= block
->pmr
[chunk
]->rkey
;
1233 * Register (at connection time) the memory used for control
1236 static int qemu_rdma_reg_control(RDMAContext
*rdma
, int idx
)
1238 rdma
->wr_data
[idx
].control_mr
= ibv_reg_mr(rdma
->pd
,
1239 rdma
->wr_data
[idx
].control
, RDMA_CONTROL_MAX_BUFFER
,
1240 IBV_ACCESS_LOCAL_WRITE
| IBV_ACCESS_REMOTE_WRITE
);
1241 if (rdma
->wr_data
[idx
].control_mr
) {
1242 rdma
->total_registrations
++;
1245 error_report("qemu_rdma_reg_control failed");
1249 const char *print_wrid(int wrid
)
1251 if (wrid
>= RDMA_WRID_RECV_CONTROL
) {
1252 return wrid_desc
[RDMA_WRID_RECV_CONTROL
];
1254 return wrid_desc
[wrid
];
1258 * RDMA requires memory registration (mlock/pinning), but this is not good for
1261 * In preparation for the future where LRU information or workload-specific
1262 * writable writable working set memory access behavior is available to QEMU
1263 * it would be nice to have in place the ability to UN-register/UN-pin
1264 * particular memory regions from the RDMA hardware when it is determine that
1265 * those regions of memory will likely not be accessed again in the near future.
1267 * While we do not yet have such information right now, the following
1268 * compile-time option allows us to perform a non-optimized version of this
1271 * By uncommenting this option, you will cause *all* RDMA transfers to be
1272 * unregistered immediately after the transfer completes on both sides of the
1273 * connection. This has no effect in 'rdma-pin-all' mode, only regular mode.
1275 * This will have a terrible impact on migration performance, so until future
1276 * workload information or LRU information is available, do not attempt to use
1277 * this feature except for basic testing.
1279 //#define RDMA_UNREGISTRATION_EXAMPLE
1282 * Perform a non-optimized memory unregistration after every transfer
1283 * for demonstration purposes, only if pin-all is not requested.
1285 * Potential optimizations:
1286 * 1. Start a new thread to run this function continuously
1288 - and for receipt of unregister messages
1290 * 3. Use workload hints.
1292 static int qemu_rdma_unregister_waiting(RDMAContext
*rdma
)
1294 while (rdma
->unregistrations
[rdma
->unregister_current
]) {
1296 uint64_t wr_id
= rdma
->unregistrations
[rdma
->unregister_current
];
1298 (wr_id
& RDMA_WRID_CHUNK_MASK
) >> RDMA_WRID_CHUNK_SHIFT
;
1300 (wr_id
& RDMA_WRID_BLOCK_MASK
) >> RDMA_WRID_BLOCK_SHIFT
;
1301 RDMALocalBlock
*block
=
1302 &(rdma
->local_ram_blocks
.block
[index
]);
1303 RDMARegister reg
= { .current_index
= index
};
1304 RDMAControlHeader resp
= { .type
= RDMA_CONTROL_UNREGISTER_FINISHED
,
1306 RDMAControlHeader head
= { .len
= sizeof(RDMARegister
),
1307 .type
= RDMA_CONTROL_UNREGISTER_REQUEST
,
1311 trace_qemu_rdma_unregister_waiting_proc(chunk
,
1312 rdma
->unregister_current
);
1314 rdma
->unregistrations
[rdma
->unregister_current
] = 0;
1315 rdma
->unregister_current
++;
1317 if (rdma
->unregister_current
== RDMA_SIGNALED_SEND_MAX
) {
1318 rdma
->unregister_current
= 0;
1323 * Unregistration is speculative (because migration is single-threaded
1324 * and we cannot break the protocol's inifinband message ordering).
1325 * Thus, if the memory is currently being used for transmission,
1326 * then abort the attempt to unregister and try again
1327 * later the next time a completion is received for this memory.
1329 clear_bit(chunk
, block
->unregister_bitmap
);
1331 if (test_bit(chunk
, block
->transit_bitmap
)) {
1332 trace_qemu_rdma_unregister_waiting_inflight(chunk
);
1336 trace_qemu_rdma_unregister_waiting_send(chunk
);
1338 ret
= ibv_dereg_mr(block
->pmr
[chunk
]);
1339 block
->pmr
[chunk
] = NULL
;
1340 block
->remote_keys
[chunk
] = 0;
1343 perror("unregistration chunk failed");
1346 rdma
->total_registrations
--;
1348 reg
.key
.chunk
= chunk
;
1349 register_to_network(rdma
, ®
);
1350 ret
= qemu_rdma_exchange_send(rdma
, &head
, (uint8_t *) ®
,
1356 trace_qemu_rdma_unregister_waiting_complete(chunk
);
1362 static uint64_t qemu_rdma_make_wrid(uint64_t wr_id
, uint64_t index
,
1365 uint64_t result
= wr_id
& RDMA_WRID_TYPE_MASK
;
1367 result
|= (index
<< RDMA_WRID_BLOCK_SHIFT
);
1368 result
|= (chunk
<< RDMA_WRID_CHUNK_SHIFT
);
1374 * Set bit for unregistration in the next iteration.
1375 * We cannot transmit right here, but will unpin later.
1377 static void qemu_rdma_signal_unregister(RDMAContext
*rdma
, uint64_t index
,
1378 uint64_t chunk
, uint64_t wr_id
)
1380 if (rdma
->unregistrations
[rdma
->unregister_next
] != 0) {
1381 error_report("rdma migration: queue is full");
1383 RDMALocalBlock
*block
= &(rdma
->local_ram_blocks
.block
[index
]);
1385 if (!test_and_set_bit(chunk
, block
->unregister_bitmap
)) {
1386 trace_qemu_rdma_signal_unregister_append(chunk
,
1387 rdma
->unregister_next
);
1389 rdma
->unregistrations
[rdma
->unregister_next
++] =
1390 qemu_rdma_make_wrid(wr_id
, index
, chunk
);
1392 if (rdma
->unregister_next
== RDMA_SIGNALED_SEND_MAX
) {
1393 rdma
->unregister_next
= 0;
1396 trace_qemu_rdma_signal_unregister_already(chunk
);
1402 * Consult the connection manager to see a work request
1403 * (of any kind) has completed.
1404 * Return the work request ID that completed.
1406 static uint64_t qemu_rdma_poll(RDMAContext
*rdma
, uint64_t *wr_id_out
,
1413 ret
= ibv_poll_cq(rdma
->cq
, 1, &wc
);
1416 *wr_id_out
= RDMA_WRID_NONE
;
1421 error_report("ibv_poll_cq return %d", ret
);
1425 wr_id
= wc
.wr_id
& RDMA_WRID_TYPE_MASK
;
1427 if (wc
.status
!= IBV_WC_SUCCESS
) {
1428 fprintf(stderr
, "ibv_poll_cq wc.status=%d %s!\n",
1429 wc
.status
, ibv_wc_status_str(wc
.status
));
1430 fprintf(stderr
, "ibv_poll_cq wrid=%s!\n", wrid_desc
[wr_id
]);
1435 if (rdma
->control_ready_expected
&&
1436 (wr_id
>= RDMA_WRID_RECV_CONTROL
)) {
1437 trace_qemu_rdma_poll_recv(wrid_desc
[RDMA_WRID_RECV_CONTROL
],
1438 wr_id
- RDMA_WRID_RECV_CONTROL
, wr_id
, rdma
->nb_sent
);
1439 rdma
->control_ready_expected
= 0;
1442 if (wr_id
== RDMA_WRID_RDMA_WRITE
) {
1444 (wc
.wr_id
& RDMA_WRID_CHUNK_MASK
) >> RDMA_WRID_CHUNK_SHIFT
;
1446 (wc
.wr_id
& RDMA_WRID_BLOCK_MASK
) >> RDMA_WRID_BLOCK_SHIFT
;
1447 RDMALocalBlock
*block
= &(rdma
->local_ram_blocks
.block
[index
]);
1449 trace_qemu_rdma_poll_write(print_wrid(wr_id
), wr_id
, rdma
->nb_sent
,
1450 index
, chunk
, block
->local_host_addr
,
1451 (void *)(uintptr_t)block
->remote_host_addr
);
1453 clear_bit(chunk
, block
->transit_bitmap
);
1455 if (rdma
->nb_sent
> 0) {
1459 if (!rdma
->pin_all
) {
1461 * FYI: If one wanted to signal a specific chunk to be unregistered
1462 * using LRU or workload-specific information, this is the function
1463 * you would call to do so. That chunk would then get asynchronously
1464 * unregistered later.
1466 #ifdef RDMA_UNREGISTRATION_EXAMPLE
1467 qemu_rdma_signal_unregister(rdma
, index
, chunk
, wc
.wr_id
);
1471 trace_qemu_rdma_poll_other(print_wrid(wr_id
), wr_id
, rdma
->nb_sent
);
1474 *wr_id_out
= wc
.wr_id
;
1476 *byte_len
= wc
.byte_len
;
1482 /* Wait for activity on the completion channel.
1483 * Returns 0 on success, none-0 on error.
1485 static int qemu_rdma_wait_comp_channel(RDMAContext
*rdma
)
1488 * Coroutine doesn't start until migration_fd_process_incoming()
1489 * so don't yield unless we know we're running inside of a coroutine.
1491 if (rdma
->migration_started_on_destination
) {
1492 yield_until_fd_readable(rdma
->comp_channel
->fd
);
1494 /* This is the source side, we're in a separate thread
1495 * or destination prior to migration_fd_process_incoming()
1496 * we can't yield; so we have to poll the fd.
1497 * But we need to be able to handle 'cancel' or an error
1498 * without hanging forever.
1500 while (!rdma
->error_state
&& !rdma
->received_error
) {
1502 pfds
[0].fd
= rdma
->comp_channel
->fd
;
1503 pfds
[0].events
= G_IO_IN
| G_IO_HUP
| G_IO_ERR
;
1504 /* 0.1s timeout, should be fine for a 'cancel' */
1505 switch (qemu_poll_ns(pfds
, 1, 100 * 1000 * 1000)) {
1506 case 1: /* fd active */
1509 case 0: /* Timeout, go around again */
1512 default: /* Error of some type -
1513 * I don't trust errno from qemu_poll_ns
1515 error_report("%s: poll failed", __func__
);
1519 if (migrate_get_current()->state
== MIGRATION_STATUS_CANCELLING
) {
1520 /* Bail out and let the cancellation happen */
1526 if (rdma
->received_error
) {
1529 return rdma
->error_state
;
1533 * Block until the next work request has completed.
1535 * First poll to see if a work request has already completed,
1538 * If we encounter completed work requests for IDs other than
1539 * the one we're interested in, then that's generally an error.
1541 * The only exception is actual RDMA Write completions. These
1542 * completions only need to be recorded, but do not actually
1543 * need further processing.
1545 static int qemu_rdma_block_for_wrid(RDMAContext
*rdma
, int wrid_requested
,
1548 int num_cq_events
= 0, ret
= 0;
1551 uint64_t wr_id
= RDMA_WRID_NONE
, wr_id_in
;
1553 if (ibv_req_notify_cq(rdma
->cq
, 0)) {
1557 while (wr_id
!= wrid_requested
) {
1558 ret
= qemu_rdma_poll(rdma
, &wr_id_in
, byte_len
);
1563 wr_id
= wr_id_in
& RDMA_WRID_TYPE_MASK
;
1565 if (wr_id
== RDMA_WRID_NONE
) {
1568 if (wr_id
!= wrid_requested
) {
1569 trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested
),
1570 wrid_requested
, print_wrid(wr_id
), wr_id
);
1574 if (wr_id
== wrid_requested
) {
1579 ret
= qemu_rdma_wait_comp_channel(rdma
);
1581 goto err_block_for_wrid
;
1584 ret
= ibv_get_cq_event(rdma
->comp_channel
, &cq
, &cq_ctx
);
1586 perror("ibv_get_cq_event");
1587 goto err_block_for_wrid
;
1592 ret
= -ibv_req_notify_cq(cq
, 0);
1594 goto err_block_for_wrid
;
1597 while (wr_id
!= wrid_requested
) {
1598 ret
= qemu_rdma_poll(rdma
, &wr_id_in
, byte_len
);
1600 goto err_block_for_wrid
;
1603 wr_id
= wr_id_in
& RDMA_WRID_TYPE_MASK
;
1605 if (wr_id
== RDMA_WRID_NONE
) {
1608 if (wr_id
!= wrid_requested
) {
1609 trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested
),
1610 wrid_requested
, print_wrid(wr_id
), wr_id
);
1614 if (wr_id
== wrid_requested
) {
1615 goto success_block_for_wrid
;
1619 success_block_for_wrid
:
1620 if (num_cq_events
) {
1621 ibv_ack_cq_events(cq
, num_cq_events
);
1626 if (num_cq_events
) {
1627 ibv_ack_cq_events(cq
, num_cq_events
);
1630 rdma
->error_state
= ret
;
1635 * Post a SEND message work request for the control channel
1636 * containing some data and block until the post completes.
1638 static int qemu_rdma_post_send_control(RDMAContext
*rdma
, uint8_t *buf
,
1639 RDMAControlHeader
*head
)
1642 RDMAWorkRequestData
*wr
= &rdma
->wr_data
[RDMA_WRID_CONTROL
];
1643 struct ibv_send_wr
*bad_wr
;
1644 struct ibv_sge sge
= {
1645 .addr
= (uintptr_t)(wr
->control
),
1646 .length
= head
->len
+ sizeof(RDMAControlHeader
),
1647 .lkey
= wr
->control_mr
->lkey
,
1649 struct ibv_send_wr send_wr
= {
1650 .wr_id
= RDMA_WRID_SEND_CONTROL
,
1651 .opcode
= IBV_WR_SEND
,
1652 .send_flags
= IBV_SEND_SIGNALED
,
1657 trace_qemu_rdma_post_send_control(control_desc(head
->type
));
1660 * We don't actually need to do a memcpy() in here if we used
1661 * the "sge" properly, but since we're only sending control messages
1662 * (not RAM in a performance-critical path), then its OK for now.
1664 * The copy makes the RDMAControlHeader simpler to manipulate
1665 * for the time being.
1667 assert(head
->len
<= RDMA_CONTROL_MAX_BUFFER
- sizeof(*head
));
1668 memcpy(wr
->control
, head
, sizeof(RDMAControlHeader
));
1669 control_to_network((void *) wr
->control
);
1672 memcpy(wr
->control
+ sizeof(RDMAControlHeader
), buf
, head
->len
);
1676 ret
= ibv_post_send(rdma
->qp
, &send_wr
, &bad_wr
);
1679 error_report("Failed to use post IB SEND for control");
1683 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_SEND_CONTROL
, NULL
);
1685 error_report("rdma migration: send polling control error");
1692 * Post a RECV work request in anticipation of some future receipt
1693 * of data on the control channel.
1695 static int qemu_rdma_post_recv_control(RDMAContext
*rdma
, int idx
)
1697 struct ibv_recv_wr
*bad_wr
;
1698 struct ibv_sge sge
= {
1699 .addr
= (uintptr_t)(rdma
->wr_data
[idx
].control
),
1700 .length
= RDMA_CONTROL_MAX_BUFFER
,
1701 .lkey
= rdma
->wr_data
[idx
].control_mr
->lkey
,
1704 struct ibv_recv_wr recv_wr
= {
1705 .wr_id
= RDMA_WRID_RECV_CONTROL
+ idx
,
1711 if (ibv_post_recv(rdma
->qp
, &recv_wr
, &bad_wr
)) {
1719 * Block and wait for a RECV control channel message to arrive.
1721 static int qemu_rdma_exchange_get_response(RDMAContext
*rdma
,
1722 RDMAControlHeader
*head
, int expecting
, int idx
)
1725 int ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RECV_CONTROL
+ idx
,
1729 error_report("rdma migration: recv polling control error!");
1733 network_to_control((void *) rdma
->wr_data
[idx
].control
);
1734 memcpy(head
, rdma
->wr_data
[idx
].control
, sizeof(RDMAControlHeader
));
1736 trace_qemu_rdma_exchange_get_response_start(control_desc(expecting
));
1738 if (expecting
== RDMA_CONTROL_NONE
) {
1739 trace_qemu_rdma_exchange_get_response_none(control_desc(head
->type
),
1741 } else if (head
->type
!= expecting
|| head
->type
== RDMA_CONTROL_ERROR
) {
1742 error_report("Was expecting a %s (%d) control message"
1743 ", but got: %s (%d), length: %d",
1744 control_desc(expecting
), expecting
,
1745 control_desc(head
->type
), head
->type
, head
->len
);
1746 if (head
->type
== RDMA_CONTROL_ERROR
) {
1747 rdma
->received_error
= true;
1751 if (head
->len
> RDMA_CONTROL_MAX_BUFFER
- sizeof(*head
)) {
1752 error_report("too long length: %d", head
->len
);
1755 if (sizeof(*head
) + head
->len
!= byte_len
) {
1756 error_report("Malformed length: %d byte_len %d", head
->len
, byte_len
);
1764 * When a RECV work request has completed, the work request's
1765 * buffer is pointed at the header.
1767 * This will advance the pointer to the data portion
1768 * of the control message of the work request's buffer that
1769 * was populated after the work request finished.
1771 static void qemu_rdma_move_header(RDMAContext
*rdma
, int idx
,
1772 RDMAControlHeader
*head
)
1774 rdma
->wr_data
[idx
].control_len
= head
->len
;
1775 rdma
->wr_data
[idx
].control_curr
=
1776 rdma
->wr_data
[idx
].control
+ sizeof(RDMAControlHeader
);
1780 * This is an 'atomic' high-level operation to deliver a single, unified
1781 * control-channel message.
1783 * Additionally, if the user is expecting some kind of reply to this message,
1784 * they can request a 'resp' response message be filled in by posting an
1785 * additional work request on behalf of the user and waiting for an additional
1788 * The extra (optional) response is used during registration to us from having
1789 * to perform an *additional* exchange of message just to provide a response by
1790 * instead piggy-backing on the acknowledgement.
1792 static int qemu_rdma_exchange_send(RDMAContext
*rdma
, RDMAControlHeader
*head
,
1793 uint8_t *data
, RDMAControlHeader
*resp
,
1795 int (*callback
)(RDMAContext
*rdma
))
1800 * Wait until the dest is ready before attempting to deliver the message
1801 * by waiting for a READY message.
1803 if (rdma
->control_ready_expected
) {
1804 RDMAControlHeader resp
;
1805 ret
= qemu_rdma_exchange_get_response(rdma
,
1806 &resp
, RDMA_CONTROL_READY
, RDMA_WRID_READY
);
1813 * If the user is expecting a response, post a WR in anticipation of it.
1816 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_DATA
);
1818 error_report("rdma migration: error posting"
1819 " extra control recv for anticipated result!");
1825 * Post a WR to replace the one we just consumed for the READY message.
1827 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
1829 error_report("rdma migration: error posting first control recv!");
1834 * Deliver the control message that was requested.
1836 ret
= qemu_rdma_post_send_control(rdma
, data
, head
);
1839 error_report("Failed to send control buffer!");
1844 * If we're expecting a response, block and wait for it.
1848 trace_qemu_rdma_exchange_send_issue_callback();
1849 ret
= callback(rdma
);
1855 trace_qemu_rdma_exchange_send_waiting(control_desc(resp
->type
));
1856 ret
= qemu_rdma_exchange_get_response(rdma
, resp
,
1857 resp
->type
, RDMA_WRID_DATA
);
1863 qemu_rdma_move_header(rdma
, RDMA_WRID_DATA
, resp
);
1865 *resp_idx
= RDMA_WRID_DATA
;
1867 trace_qemu_rdma_exchange_send_received(control_desc(resp
->type
));
1870 rdma
->control_ready_expected
= 1;
1876 * This is an 'atomic' high-level operation to receive a single, unified
1877 * control-channel message.
1879 static int qemu_rdma_exchange_recv(RDMAContext
*rdma
, RDMAControlHeader
*head
,
1882 RDMAControlHeader ready
= {
1884 .type
= RDMA_CONTROL_READY
,
1890 * Inform the source that we're ready to receive a message.
1892 ret
= qemu_rdma_post_send_control(rdma
, NULL
, &ready
);
1895 error_report("Failed to send control buffer!");
1900 * Block and wait for the message.
1902 ret
= qemu_rdma_exchange_get_response(rdma
, head
,
1903 expecting
, RDMA_WRID_READY
);
1909 qemu_rdma_move_header(rdma
, RDMA_WRID_READY
, head
);
1912 * Post a new RECV work request to replace the one we just consumed.
1914 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
1916 error_report("rdma migration: error posting second control recv!");
1924 * Write an actual chunk of memory using RDMA.
1926 * If we're using dynamic registration on the dest-side, we have to
1927 * send a registration command first.
1929 static int qemu_rdma_write_one(QEMUFile
*f
, RDMAContext
*rdma
,
1930 int current_index
, uint64_t current_addr
,
1934 struct ibv_send_wr send_wr
= { 0 };
1935 struct ibv_send_wr
*bad_wr
;
1936 int reg_result_idx
, ret
, count
= 0;
1937 uint64_t chunk
, chunks
;
1938 uint8_t *chunk_start
, *chunk_end
;
1939 RDMALocalBlock
*block
= &(rdma
->local_ram_blocks
.block
[current_index
]);
1941 RDMARegisterResult
*reg_result
;
1942 RDMAControlHeader resp
= { .type
= RDMA_CONTROL_REGISTER_RESULT
};
1943 RDMAControlHeader head
= { .len
= sizeof(RDMARegister
),
1944 .type
= RDMA_CONTROL_REGISTER_REQUEST
,
1949 sge
.addr
= (uintptr_t)(block
->local_host_addr
+
1950 (current_addr
- block
->offset
));
1951 sge
.length
= length
;
1953 chunk
= ram_chunk_index(block
->local_host_addr
,
1954 (uint8_t *)(uintptr_t)sge
.addr
);
1955 chunk_start
= ram_chunk_start(block
, chunk
);
1957 if (block
->is_ram_block
) {
1958 chunks
= length
/ (1UL << RDMA_REG_CHUNK_SHIFT
);
1960 if (chunks
&& ((length
% (1UL << RDMA_REG_CHUNK_SHIFT
)) == 0)) {
1964 chunks
= block
->length
/ (1UL << RDMA_REG_CHUNK_SHIFT
);
1966 if (chunks
&& ((block
->length
% (1UL << RDMA_REG_CHUNK_SHIFT
)) == 0)) {
1971 trace_qemu_rdma_write_one_top(chunks
+ 1,
1973 (1UL << RDMA_REG_CHUNK_SHIFT
) / 1024 / 1024);
1975 chunk_end
= ram_chunk_end(block
, chunk
+ chunks
);
1977 if (!rdma
->pin_all
) {
1978 #ifdef RDMA_UNREGISTRATION_EXAMPLE
1979 qemu_rdma_unregister_waiting(rdma
);
1983 while (test_bit(chunk
, block
->transit_bitmap
)) {
1985 trace_qemu_rdma_write_one_block(count
++, current_index
, chunk
,
1986 sge
.addr
, length
, rdma
->nb_sent
, block
->nb_chunks
);
1988 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RDMA_WRITE
, NULL
);
1991 error_report("Failed to Wait for previous write to complete "
1992 "block %d chunk %" PRIu64
1993 " current %" PRIu64
" len %" PRIu64
" %d",
1994 current_index
, chunk
, sge
.addr
, length
, rdma
->nb_sent
);
1999 if (!rdma
->pin_all
|| !block
->is_ram_block
) {
2000 if (!block
->remote_keys
[chunk
]) {
2002 * This chunk has not yet been registered, so first check to see
2003 * if the entire chunk is zero. If so, tell the other size to
2004 * memset() + madvise() the entire chunk without RDMA.
2007 if (buffer_is_zero((void *)(uintptr_t)sge
.addr
, length
)) {
2008 RDMACompress comp
= {
2009 .offset
= current_addr
,
2011 .block_idx
= current_index
,
2015 head
.len
= sizeof(comp
);
2016 head
.type
= RDMA_CONTROL_COMPRESS
;
2018 trace_qemu_rdma_write_one_zero(chunk
, sge
.length
,
2019 current_index
, current_addr
);
2021 compress_to_network(rdma
, &comp
);
2022 ret
= qemu_rdma_exchange_send(rdma
, &head
,
2023 (uint8_t *) &comp
, NULL
, NULL
, NULL
);
2029 acct_update_position(f
, sge
.length
, true);
2035 * Otherwise, tell other side to register.
2037 reg
.current_index
= current_index
;
2038 if (block
->is_ram_block
) {
2039 reg
.key
.current_addr
= current_addr
;
2041 reg
.key
.chunk
= chunk
;
2043 reg
.chunks
= chunks
;
2045 trace_qemu_rdma_write_one_sendreg(chunk
, sge
.length
, current_index
,
2048 register_to_network(rdma
, ®
);
2049 ret
= qemu_rdma_exchange_send(rdma
, &head
, (uint8_t *) ®
,
2050 &resp
, ®_result_idx
, NULL
);
2055 /* try to overlap this single registration with the one we sent. */
2056 if (qemu_rdma_register_and_get_keys(rdma
, block
, sge
.addr
,
2057 &sge
.lkey
, NULL
, chunk
,
2058 chunk_start
, chunk_end
)) {
2059 error_report("cannot get lkey");
2063 reg_result
= (RDMARegisterResult
*)
2064 rdma
->wr_data
[reg_result_idx
].control_curr
;
2066 network_to_result(reg_result
);
2068 trace_qemu_rdma_write_one_recvregres(block
->remote_keys
[chunk
],
2069 reg_result
->rkey
, chunk
);
2071 block
->remote_keys
[chunk
] = reg_result
->rkey
;
2072 block
->remote_host_addr
= reg_result
->host_addr
;
2074 /* already registered before */
2075 if (qemu_rdma_register_and_get_keys(rdma
, block
, sge
.addr
,
2076 &sge
.lkey
, NULL
, chunk
,
2077 chunk_start
, chunk_end
)) {
2078 error_report("cannot get lkey!");
2083 send_wr
.wr
.rdma
.rkey
= block
->remote_keys
[chunk
];
2085 send_wr
.wr
.rdma
.rkey
= block
->remote_rkey
;
2087 if (qemu_rdma_register_and_get_keys(rdma
, block
, sge
.addr
,
2088 &sge
.lkey
, NULL
, chunk
,
2089 chunk_start
, chunk_end
)) {
2090 error_report("cannot get lkey!");
2096 * Encode the ram block index and chunk within this wrid.
2097 * We will use this information at the time of completion
2098 * to figure out which bitmap to check against and then which
2099 * chunk in the bitmap to look for.
2101 send_wr
.wr_id
= qemu_rdma_make_wrid(RDMA_WRID_RDMA_WRITE
,
2102 current_index
, chunk
);
2104 send_wr
.opcode
= IBV_WR_RDMA_WRITE
;
2105 send_wr
.send_flags
= IBV_SEND_SIGNALED
;
2106 send_wr
.sg_list
= &sge
;
2107 send_wr
.num_sge
= 1;
2108 send_wr
.wr
.rdma
.remote_addr
= block
->remote_host_addr
+
2109 (current_addr
- block
->offset
);
2111 trace_qemu_rdma_write_one_post(chunk
, sge
.addr
, send_wr
.wr
.rdma
.remote_addr
,
2115 * ibv_post_send() does not return negative error numbers,
2116 * per the specification they are positive - no idea why.
2118 ret
= ibv_post_send(rdma
->qp
, &send_wr
, &bad_wr
);
2120 if (ret
== ENOMEM
) {
2121 trace_qemu_rdma_write_one_queue_full();
2122 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RDMA_WRITE
, NULL
);
2124 error_report("rdma migration: failed to make "
2125 "room in full send queue! %d", ret
);
2131 } else if (ret
> 0) {
2132 perror("rdma migration: post rdma write failed");
2136 set_bit(chunk
, block
->transit_bitmap
);
2137 acct_update_position(f
, sge
.length
, false);
2138 rdma
->total_writes
++;
2144 * Push out any unwritten RDMA operations.
2146 * We support sending out multiple chunks at the same time.
2147 * Not all of them need to get signaled in the completion queue.
2149 static int qemu_rdma_write_flush(QEMUFile
*f
, RDMAContext
*rdma
)
2153 if (!rdma
->current_length
) {
2157 ret
= qemu_rdma_write_one(f
, rdma
,
2158 rdma
->current_index
, rdma
->current_addr
, rdma
->current_length
);
2166 trace_qemu_rdma_write_flush(rdma
->nb_sent
);
2169 rdma
->current_length
= 0;
2170 rdma
->current_addr
= 0;
2175 static inline int qemu_rdma_buffer_mergable(RDMAContext
*rdma
,
2176 uint64_t offset
, uint64_t len
)
2178 RDMALocalBlock
*block
;
2182 if (rdma
->current_index
< 0) {
2186 if (rdma
->current_chunk
< 0) {
2190 block
= &(rdma
->local_ram_blocks
.block
[rdma
->current_index
]);
2191 host_addr
= block
->local_host_addr
+ (offset
- block
->offset
);
2192 chunk_end
= ram_chunk_end(block
, rdma
->current_chunk
);
2194 if (rdma
->current_length
== 0) {
2199 * Only merge into chunk sequentially.
2201 if (offset
!= (rdma
->current_addr
+ rdma
->current_length
)) {
2205 if (offset
< block
->offset
) {
2209 if ((offset
+ len
) > (block
->offset
+ block
->length
)) {
2213 if ((host_addr
+ len
) > chunk_end
) {
2221 * We're not actually writing here, but doing three things:
2223 * 1. Identify the chunk the buffer belongs to.
2224 * 2. If the chunk is full or the buffer doesn't belong to the current
2225 * chunk, then start a new chunk and flush() the old chunk.
2226 * 3. To keep the hardware busy, we also group chunks into batches
2227 * and only require that a batch gets acknowledged in the completion
2228 * qeueue instead of each individual chunk.
2230 static int qemu_rdma_write(QEMUFile
*f
, RDMAContext
*rdma
,
2231 uint64_t block_offset
, uint64_t offset
,
2234 uint64_t current_addr
= block_offset
+ offset
;
2235 uint64_t index
= rdma
->current_index
;
2236 uint64_t chunk
= rdma
->current_chunk
;
2239 /* If we cannot merge it, we flush the current buffer first. */
2240 if (!qemu_rdma_buffer_mergable(rdma
, current_addr
, len
)) {
2241 ret
= qemu_rdma_write_flush(f
, rdma
);
2245 rdma
->current_length
= 0;
2246 rdma
->current_addr
= current_addr
;
2248 ret
= qemu_rdma_search_ram_block(rdma
, block_offset
,
2249 offset
, len
, &index
, &chunk
);
2251 error_report("ram block search failed");
2254 rdma
->current_index
= index
;
2255 rdma
->current_chunk
= chunk
;
2259 rdma
->current_length
+= len
;
2261 /* flush it if buffer is too large */
2262 if (rdma
->current_length
>= RDMA_MERGE_MAX
) {
2263 return qemu_rdma_write_flush(f
, rdma
);
2269 static void qemu_rdma_cleanup(RDMAContext
*rdma
)
2271 struct rdma_cm_event
*cm_event
;
2274 if (rdma
->cm_id
&& rdma
->connected
) {
2275 if ((rdma
->error_state
||
2276 migrate_get_current()->state
== MIGRATION_STATUS_CANCELLING
) &&
2277 !rdma
->received_error
) {
2278 RDMAControlHeader head
= { .len
= 0,
2279 .type
= RDMA_CONTROL_ERROR
,
2282 error_report("Early error. Sending error.");
2283 qemu_rdma_post_send_control(rdma
, NULL
, &head
);
2286 ret
= rdma_disconnect(rdma
->cm_id
);
2288 trace_qemu_rdma_cleanup_waiting_for_disconnect();
2289 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
2291 rdma_ack_cm_event(cm_event
);
2294 trace_qemu_rdma_cleanup_disconnect();
2295 rdma
->connected
= false;
2298 g_free(rdma
->dest_blocks
);
2299 rdma
->dest_blocks
= NULL
;
2301 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2302 if (rdma
->wr_data
[idx
].control_mr
) {
2303 rdma
->total_registrations
--;
2304 ibv_dereg_mr(rdma
->wr_data
[idx
].control_mr
);
2306 rdma
->wr_data
[idx
].control_mr
= NULL
;
2309 if (rdma
->local_ram_blocks
.block
) {
2310 while (rdma
->local_ram_blocks
.nb_blocks
) {
2311 rdma_delete_block(rdma
, &rdma
->local_ram_blocks
.block
[0]);
2316 rdma_destroy_qp(rdma
->cm_id
);
2320 ibv_destroy_cq(rdma
->cq
);
2323 if (rdma
->comp_channel
) {
2324 ibv_destroy_comp_channel(rdma
->comp_channel
);
2325 rdma
->comp_channel
= NULL
;
2328 ibv_dealloc_pd(rdma
->pd
);
2332 rdma_destroy_id(rdma
->cm_id
);
2335 if (rdma
->listen_id
) {
2336 rdma_destroy_id(rdma
->listen_id
);
2337 rdma
->listen_id
= NULL
;
2339 if (rdma
->channel
) {
2340 rdma_destroy_event_channel(rdma
->channel
);
2341 rdma
->channel
= NULL
;
2348 static int qemu_rdma_source_init(RDMAContext
*rdma
, bool pin_all
, Error
**errp
)
2351 Error
*local_err
= NULL
, **temp
= &local_err
;
2354 * Will be validated against destination's actual capabilities
2355 * after the connect() completes.
2357 rdma
->pin_all
= pin_all
;
2359 ret
= qemu_rdma_resolve_host(rdma
, temp
);
2361 goto err_rdma_source_init
;
2364 ret
= qemu_rdma_alloc_pd_cq(rdma
);
2366 ERROR(temp
, "rdma migration: error allocating pd and cq! Your mlock()"
2367 " limits may be too low. Please check $ ulimit -a # and "
2368 "search for 'ulimit -l' in the output");
2369 goto err_rdma_source_init
;
2372 ret
= qemu_rdma_alloc_qp(rdma
);
2374 ERROR(temp
, "rdma migration: error allocating qp!");
2375 goto err_rdma_source_init
;
2378 ret
= qemu_rdma_init_ram_blocks(rdma
);
2380 ERROR(temp
, "rdma migration: error initializing ram blocks!");
2381 goto err_rdma_source_init
;
2384 /* Build the hash that maps from offset to RAMBlock */
2385 rdma
->blockmap
= g_hash_table_new(g_direct_hash
, g_direct_equal
);
2386 for (idx
= 0; idx
< rdma
->local_ram_blocks
.nb_blocks
; idx
++) {
2387 g_hash_table_insert(rdma
->blockmap
,
2388 (void *)(uintptr_t)rdma
->local_ram_blocks
.block
[idx
].offset
,
2389 &rdma
->local_ram_blocks
.block
[idx
]);
2392 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2393 ret
= qemu_rdma_reg_control(rdma
, idx
);
2395 ERROR(temp
, "rdma migration: error registering %d control!",
2397 goto err_rdma_source_init
;
2403 err_rdma_source_init
:
2404 error_propagate(errp
, local_err
);
2405 qemu_rdma_cleanup(rdma
);
2409 static int qemu_rdma_connect(RDMAContext
*rdma
, Error
**errp
)
2411 RDMACapabilities cap
= {
2412 .version
= RDMA_CONTROL_VERSION_CURRENT
,
2415 struct rdma_conn_param conn_param
= { .initiator_depth
= 2,
2417 .private_data
= &cap
,
2418 .private_data_len
= sizeof(cap
),
2420 struct rdma_cm_event
*cm_event
;
2424 * Only negotiate the capability with destination if the user
2425 * on the source first requested the capability.
2427 if (rdma
->pin_all
) {
2428 trace_qemu_rdma_connect_pin_all_requested();
2429 cap
.flags
|= RDMA_CAPABILITY_PIN_ALL
;
2432 caps_to_network(&cap
);
2434 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
2436 ERROR(errp
, "posting second control recv");
2437 goto err_rdma_source_connect
;
2440 ret
= rdma_connect(rdma
->cm_id
, &conn_param
);
2442 perror("rdma_connect");
2443 ERROR(errp
, "connecting to destination!");
2444 goto err_rdma_source_connect
;
2447 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
2449 perror("rdma_get_cm_event after rdma_connect");
2450 ERROR(errp
, "connecting to destination!");
2451 rdma_ack_cm_event(cm_event
);
2452 goto err_rdma_source_connect
;
2455 if (cm_event
->event
!= RDMA_CM_EVENT_ESTABLISHED
) {
2456 perror("rdma_get_cm_event != EVENT_ESTABLISHED after rdma_connect");
2457 ERROR(errp
, "connecting to destination!");
2458 rdma_ack_cm_event(cm_event
);
2459 goto err_rdma_source_connect
;
2461 rdma
->connected
= true;
2463 memcpy(&cap
, cm_event
->param
.conn
.private_data
, sizeof(cap
));
2464 network_to_caps(&cap
);
2467 * Verify that the *requested* capabilities are supported by the destination
2468 * and disable them otherwise.
2470 if (rdma
->pin_all
&& !(cap
.flags
& RDMA_CAPABILITY_PIN_ALL
)) {
2471 ERROR(errp
, "Server cannot support pinning all memory. "
2472 "Will register memory dynamically.");
2473 rdma
->pin_all
= false;
2476 trace_qemu_rdma_connect_pin_all_outcome(rdma
->pin_all
);
2478 rdma_ack_cm_event(cm_event
);
2480 rdma
->control_ready_expected
= 1;
2484 err_rdma_source_connect
:
2485 qemu_rdma_cleanup(rdma
);
2489 static int qemu_rdma_dest_init(RDMAContext
*rdma
, Error
**errp
)
2492 struct rdma_cm_id
*listen_id
;
2493 char ip
[40] = "unknown";
2494 struct rdma_addrinfo
*res
, *e
;
2497 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2498 rdma
->wr_data
[idx
].control_len
= 0;
2499 rdma
->wr_data
[idx
].control_curr
= NULL
;
2502 if (!rdma
->host
|| !rdma
->host
[0]) {
2503 ERROR(errp
, "RDMA host is not set!");
2504 rdma
->error_state
= -EINVAL
;
2507 /* create CM channel */
2508 rdma
->channel
= rdma_create_event_channel();
2509 if (!rdma
->channel
) {
2510 ERROR(errp
, "could not create rdma event channel");
2511 rdma
->error_state
= -EINVAL
;
2516 ret
= rdma_create_id(rdma
->channel
, &listen_id
, NULL
, RDMA_PS_TCP
);
2518 ERROR(errp
, "could not create cm_id!");
2519 goto err_dest_init_create_listen_id
;
2522 snprintf(port_str
, 16, "%d", rdma
->port
);
2523 port_str
[15] = '\0';
2525 ret
= rdma_getaddrinfo(rdma
->host
, port_str
, NULL
, &res
);
2527 ERROR(errp
, "could not rdma_getaddrinfo address %s", rdma
->host
);
2528 goto err_dest_init_bind_addr
;
2531 for (e
= res
; e
!= NULL
; e
= e
->ai_next
) {
2532 inet_ntop(e
->ai_family
,
2533 &((struct sockaddr_in
*) e
->ai_dst_addr
)->sin_addr
, ip
, sizeof ip
);
2534 trace_qemu_rdma_dest_init_trying(rdma
->host
, ip
);
2535 ret
= rdma_bind_addr(listen_id
, e
->ai_dst_addr
);
2539 if (e
->ai_family
== AF_INET6
) {
2540 ret
= qemu_rdma_broken_ipv6_kernel(listen_id
->verbs
, errp
);
2549 ERROR(errp
, "Error: could not rdma_bind_addr!");
2550 goto err_dest_init_bind_addr
;
2553 rdma
->listen_id
= listen_id
;
2554 qemu_rdma_dump_gid("dest_init", listen_id
);
2557 err_dest_init_bind_addr
:
2558 rdma_destroy_id(listen_id
);
2559 err_dest_init_create_listen_id
:
2560 rdma_destroy_event_channel(rdma
->channel
);
2561 rdma
->channel
= NULL
;
2562 rdma
->error_state
= ret
;
2567 static void *qemu_rdma_data_init(const char *host_port
, Error
**errp
)
2569 RDMAContext
*rdma
= NULL
;
2570 InetSocketAddress
*addr
;
2573 rdma
= g_new0(RDMAContext
, 1);
2574 rdma
->current_index
= -1;
2575 rdma
->current_chunk
= -1;
2577 addr
= g_new(InetSocketAddress
, 1);
2578 if (!inet_parse(addr
, host_port
, NULL
)) {
2579 rdma
->port
= atoi(addr
->port
);
2580 rdma
->host
= g_strdup(addr
->host
);
2582 ERROR(errp
, "bad RDMA migration address '%s'", host_port
);
2587 qapi_free_InetSocketAddress(addr
);
2594 * QEMUFile interface to the control channel.
2595 * SEND messages for control only.
2596 * VM's ram is handled with regular RDMA messages.
2598 static ssize_t
qio_channel_rdma_writev(QIOChannel
*ioc
,
2599 const struct iovec
*iov
,
2605 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2606 QEMUFile
*f
= rioc
->file
;
2607 RDMAContext
*rdma
= rioc
->rdma
;
2612 CHECK_ERROR_STATE();
2615 * Push out any writes that
2616 * we're queued up for VM's ram.
2618 ret
= qemu_rdma_write_flush(f
, rdma
);
2620 rdma
->error_state
= ret
;
2624 for (i
= 0; i
< niov
; i
++) {
2625 size_t remaining
= iov
[i
].iov_len
;
2626 uint8_t * data
= (void *)iov
[i
].iov_base
;
2628 RDMAControlHeader head
;
2630 rioc
->len
= MIN(remaining
, RDMA_SEND_INCREMENT
);
2631 remaining
-= rioc
->len
;
2633 head
.len
= rioc
->len
;
2634 head
.type
= RDMA_CONTROL_QEMU_FILE
;
2636 ret
= qemu_rdma_exchange_send(rdma
, &head
, data
, NULL
, NULL
, NULL
);
2639 rdma
->error_state
= ret
;
2651 static size_t qemu_rdma_fill(RDMAContext
*rdma
, uint8_t *buf
,
2652 size_t size
, int idx
)
2656 if (rdma
->wr_data
[idx
].control_len
) {
2657 trace_qemu_rdma_fill(rdma
->wr_data
[idx
].control_len
, size
);
2659 len
= MIN(size
, rdma
->wr_data
[idx
].control_len
);
2660 memcpy(buf
, rdma
->wr_data
[idx
].control_curr
, len
);
2661 rdma
->wr_data
[idx
].control_curr
+= len
;
2662 rdma
->wr_data
[idx
].control_len
-= len
;
2669 * QEMUFile interface to the control channel.
2670 * RDMA links don't use bytestreams, so we have to
2671 * return bytes to QEMUFile opportunistically.
2673 static ssize_t
qio_channel_rdma_readv(QIOChannel
*ioc
,
2674 const struct iovec
*iov
,
2680 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2681 RDMAContext
*rdma
= rioc
->rdma
;
2682 RDMAControlHeader head
;
2687 CHECK_ERROR_STATE();
2689 for (i
= 0; i
< niov
; i
++) {
2690 size_t want
= iov
[i
].iov_len
;
2691 uint8_t *data
= (void *)iov
[i
].iov_base
;
2694 * First, we hold on to the last SEND message we
2695 * were given and dish out the bytes until we run
2698 ret
= qemu_rdma_fill(rioc
->rdma
, data
, want
, 0);
2701 /* Got what we needed, so go to next iovec */
2706 /* If we got any data so far, then don't wait
2707 * for more, just return what we have */
2713 /* We've got nothing at all, so lets wait for
2716 ret
= qemu_rdma_exchange_recv(rdma
, &head
, RDMA_CONTROL_QEMU_FILE
);
2719 rdma
->error_state
= ret
;
2724 * SEND was received with new bytes, now try again.
2726 ret
= qemu_rdma_fill(rioc
->rdma
, data
, want
, 0);
2730 /* Still didn't get enough, so lets just return */
2733 return QIO_CHANNEL_ERR_BLOCK
;
2744 * Block until all the outstanding chunks have been delivered by the hardware.
2746 static int qemu_rdma_drain_cq(QEMUFile
*f
, RDMAContext
*rdma
)
2750 if (qemu_rdma_write_flush(f
, rdma
) < 0) {
2754 while (rdma
->nb_sent
) {
2755 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RDMA_WRITE
, NULL
);
2757 error_report("rdma migration: complete polling error!");
2762 qemu_rdma_unregister_waiting(rdma
);
2768 static int qio_channel_rdma_set_blocking(QIOChannel
*ioc
,
2772 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2773 /* XXX we should make readv/writev actually honour this :-) */
2774 rioc
->blocking
= blocking
;
2779 typedef struct QIOChannelRDMASource QIOChannelRDMASource
;
2780 struct QIOChannelRDMASource
{
2782 QIOChannelRDMA
*rioc
;
2783 GIOCondition condition
;
2787 qio_channel_rdma_source_prepare(GSource
*source
,
2790 QIOChannelRDMASource
*rsource
= (QIOChannelRDMASource
*)source
;
2791 RDMAContext
*rdma
= rsource
->rioc
->rdma
;
2792 GIOCondition cond
= 0;
2795 if (rdma
->wr_data
[0].control_len
) {
2800 return cond
& rsource
->condition
;
2804 qio_channel_rdma_source_check(GSource
*source
)
2806 QIOChannelRDMASource
*rsource
= (QIOChannelRDMASource
*)source
;
2807 RDMAContext
*rdma
= rsource
->rioc
->rdma
;
2808 GIOCondition cond
= 0;
2810 if (rdma
->wr_data
[0].control_len
) {
2815 return cond
& rsource
->condition
;
2819 qio_channel_rdma_source_dispatch(GSource
*source
,
2820 GSourceFunc callback
,
2823 QIOChannelFunc func
= (QIOChannelFunc
)callback
;
2824 QIOChannelRDMASource
*rsource
= (QIOChannelRDMASource
*)source
;
2825 RDMAContext
*rdma
= rsource
->rioc
->rdma
;
2826 GIOCondition cond
= 0;
2828 if (rdma
->wr_data
[0].control_len
) {
2833 return (*func
)(QIO_CHANNEL(rsource
->rioc
),
2834 (cond
& rsource
->condition
),
2839 qio_channel_rdma_source_finalize(GSource
*source
)
2841 QIOChannelRDMASource
*ssource
= (QIOChannelRDMASource
*)source
;
2843 object_unref(OBJECT(ssource
->rioc
));
2846 GSourceFuncs qio_channel_rdma_source_funcs
= {
2847 qio_channel_rdma_source_prepare
,
2848 qio_channel_rdma_source_check
,
2849 qio_channel_rdma_source_dispatch
,
2850 qio_channel_rdma_source_finalize
2853 static GSource
*qio_channel_rdma_create_watch(QIOChannel
*ioc
,
2854 GIOCondition condition
)
2856 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2857 QIOChannelRDMASource
*ssource
;
2860 source
= g_source_new(&qio_channel_rdma_source_funcs
,
2861 sizeof(QIOChannelRDMASource
));
2862 ssource
= (QIOChannelRDMASource
*)source
;
2864 ssource
->rioc
= rioc
;
2865 object_ref(OBJECT(rioc
));
2867 ssource
->condition
= condition
;
2873 static int qio_channel_rdma_close(QIOChannel
*ioc
,
2876 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2877 trace_qemu_rdma_close();
2879 if (!rioc
->rdma
->error_state
) {
2880 rioc
->rdma
->error_state
= qemu_file_get_error(rioc
->file
);
2882 qemu_rdma_cleanup(rioc
->rdma
);
2892 * This means that 'block_offset' is a full virtual address that does not
2893 * belong to a RAMBlock of the virtual machine and instead
2894 * represents a private malloc'd memory area that the caller wishes to
2898 * Offset is an offset to be added to block_offset and used
2899 * to also lookup the corresponding RAMBlock.
2902 * Initiate an transfer this size.
2905 * A 'hint' or 'advice' that means that we wish to speculatively
2906 * and asynchronously unregister this memory. In this case, there is no
2907 * guarantee that the unregister will actually happen, for example,
2908 * if the memory is being actively transmitted. Additionally, the memory
2909 * may be re-registered at any future time if a write within the same
2910 * chunk was requested again, even if you attempted to unregister it
2913 * @size < 0 : TODO, not yet supported
2914 * Unregister the memory NOW. This means that the caller does not
2915 * expect there to be any future RDMA transfers and we just want to clean
2916 * things up. This is used in case the upper layer owns the memory and
2917 * cannot wait for qemu_fclose() to occur.
2919 * @bytes_sent : User-specificed pointer to indicate how many bytes were
2920 * sent. Usually, this will not be more than a few bytes of
2921 * the protocol because most transfers are sent asynchronously.
2923 static size_t qemu_rdma_save_page(QEMUFile
*f
, void *opaque
,
2924 ram_addr_t block_offset
, ram_addr_t offset
,
2925 size_t size
, uint64_t *bytes_sent
)
2927 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
2928 RDMAContext
*rdma
= rioc
->rdma
;
2931 CHECK_ERROR_STATE();
2937 * Add this page to the current 'chunk'. If the chunk
2938 * is full, or the page doen't belong to the current chunk,
2939 * an actual RDMA write will occur and a new chunk will be formed.
2941 ret
= qemu_rdma_write(f
, rdma
, block_offset
, offset
, size
);
2943 error_report("rdma migration: write error! %d", ret
);
2948 * We always return 1 bytes because the RDMA
2949 * protocol is completely asynchronous. We do not yet know
2950 * whether an identified chunk is zero or not because we're
2951 * waiting for other pages to potentially be merged with
2952 * the current chunk. So, we have to call qemu_update_position()
2953 * later on when the actual write occurs.
2959 uint64_t index
, chunk
;
2961 /* TODO: Change QEMUFileOps prototype to be signed: size_t => long
2963 ret = qemu_rdma_drain_cq(f, rdma);
2965 fprintf(stderr, "rdma: failed to synchronously drain"
2966 " completion queue before unregistration.\n");
2972 ret
= qemu_rdma_search_ram_block(rdma
, block_offset
,
2973 offset
, size
, &index
, &chunk
);
2976 error_report("ram block search failed");
2980 qemu_rdma_signal_unregister(rdma
, index
, chunk
, 0);
2983 * TODO: Synchronous, guaranteed unregistration (should not occur during
2984 * fast-path). Otherwise, unregisters will process on the next call to
2985 * qemu_rdma_drain_cq()
2987 qemu_rdma_unregister_waiting(rdma);
2993 * Drain the Completion Queue if possible, but do not block,
2996 * If nothing to poll, the end of the iteration will do this
2997 * again to make sure we don't overflow the request queue.
3000 uint64_t wr_id
, wr_id_in
;
3001 int ret
= qemu_rdma_poll(rdma
, &wr_id_in
, NULL
);
3003 error_report("rdma migration: polling error! %d", ret
);
3007 wr_id
= wr_id_in
& RDMA_WRID_TYPE_MASK
;
3009 if (wr_id
== RDMA_WRID_NONE
) {
3014 return RAM_SAVE_CONTROL_DELAYED
;
3016 rdma
->error_state
= ret
;
3020 static int qemu_rdma_accept(RDMAContext
*rdma
)
3022 RDMACapabilities cap
;
3023 struct rdma_conn_param conn_param
= {
3024 .responder_resources
= 2,
3025 .private_data
= &cap
,
3026 .private_data_len
= sizeof(cap
),
3028 struct rdma_cm_event
*cm_event
;
3029 struct ibv_context
*verbs
;
3033 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
3035 goto err_rdma_dest_wait
;
3038 if (cm_event
->event
!= RDMA_CM_EVENT_CONNECT_REQUEST
) {
3039 rdma_ack_cm_event(cm_event
);
3040 goto err_rdma_dest_wait
;
3043 memcpy(&cap
, cm_event
->param
.conn
.private_data
, sizeof(cap
));
3045 network_to_caps(&cap
);
3047 if (cap
.version
< 1 || cap
.version
> RDMA_CONTROL_VERSION_CURRENT
) {
3048 error_report("Unknown source RDMA version: %d, bailing...",
3050 rdma_ack_cm_event(cm_event
);
3051 goto err_rdma_dest_wait
;
3055 * Respond with only the capabilities this version of QEMU knows about.
3057 cap
.flags
&= known_capabilities
;
3060 * Enable the ones that we do know about.
3061 * Add other checks here as new ones are introduced.
3063 if (cap
.flags
& RDMA_CAPABILITY_PIN_ALL
) {
3064 rdma
->pin_all
= true;
3067 rdma
->cm_id
= cm_event
->id
;
3068 verbs
= cm_event
->id
->verbs
;
3070 rdma_ack_cm_event(cm_event
);
3072 trace_qemu_rdma_accept_pin_state(rdma
->pin_all
);
3074 caps_to_network(&cap
);
3076 trace_qemu_rdma_accept_pin_verbsc(verbs
);
3079 rdma
->verbs
= verbs
;
3080 } else if (rdma
->verbs
!= verbs
) {
3081 error_report("ibv context not matching %p, %p!", rdma
->verbs
,
3083 goto err_rdma_dest_wait
;
3086 qemu_rdma_dump_id("dest_init", verbs
);
3088 ret
= qemu_rdma_alloc_pd_cq(rdma
);
3090 error_report("rdma migration: error allocating pd and cq!");
3091 goto err_rdma_dest_wait
;
3094 ret
= qemu_rdma_alloc_qp(rdma
);
3096 error_report("rdma migration: error allocating qp!");
3097 goto err_rdma_dest_wait
;
3100 ret
= qemu_rdma_init_ram_blocks(rdma
);
3102 error_report("rdma migration: error initializing ram blocks!");
3103 goto err_rdma_dest_wait
;
3106 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
3107 ret
= qemu_rdma_reg_control(rdma
, idx
);
3109 error_report("rdma: error registering %d control", idx
);
3110 goto err_rdma_dest_wait
;
3114 qemu_set_fd_handler(rdma
->channel
->fd
, NULL
, NULL
, NULL
);
3116 ret
= rdma_accept(rdma
->cm_id
, &conn_param
);
3118 error_report("rdma_accept returns %d", ret
);
3119 goto err_rdma_dest_wait
;
3122 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
3124 error_report("rdma_accept get_cm_event failed %d", ret
);
3125 goto err_rdma_dest_wait
;
3128 if (cm_event
->event
!= RDMA_CM_EVENT_ESTABLISHED
) {
3129 error_report("rdma_accept not event established");
3130 rdma_ack_cm_event(cm_event
);
3131 goto err_rdma_dest_wait
;
3134 rdma_ack_cm_event(cm_event
);
3135 rdma
->connected
= true;
3137 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
3139 error_report("rdma migration: error posting second control recv");
3140 goto err_rdma_dest_wait
;
3143 qemu_rdma_dump_gid("dest_connect", rdma
->cm_id
);
3148 rdma
->error_state
= ret
;
3149 qemu_rdma_cleanup(rdma
);
3153 static int dest_ram_sort_func(const void *a
, const void *b
)
3155 unsigned int a_index
= ((const RDMALocalBlock
*)a
)->src_index
;
3156 unsigned int b_index
= ((const RDMALocalBlock
*)b
)->src_index
;
3158 return (a_index
< b_index
) ? -1 : (a_index
!= b_index
);
3162 * During each iteration of the migration, we listen for instructions
3163 * by the source VM to perform dynamic page registrations before they
3164 * can perform RDMA operations.
3166 * We respond with the 'rkey'.
3168 * Keep doing this until the source tells us to stop.
3170 static int qemu_rdma_registration_handle(QEMUFile
*f
, void *opaque
)
3172 RDMAControlHeader reg_resp
= { .len
= sizeof(RDMARegisterResult
),
3173 .type
= RDMA_CONTROL_REGISTER_RESULT
,
3176 RDMAControlHeader unreg_resp
= { .len
= 0,
3177 .type
= RDMA_CONTROL_UNREGISTER_FINISHED
,
3180 RDMAControlHeader blocks
= { .type
= RDMA_CONTROL_RAM_BLOCKS_RESULT
,
3182 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
3183 RDMAContext
*rdma
= rioc
->rdma
;
3184 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
3185 RDMAControlHeader head
;
3186 RDMARegister
*reg
, *registers
;
3188 RDMARegisterResult
*reg_result
;
3189 static RDMARegisterResult results
[RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE
];
3190 RDMALocalBlock
*block
;
3197 CHECK_ERROR_STATE();
3200 trace_qemu_rdma_registration_handle_wait();
3202 ret
= qemu_rdma_exchange_recv(rdma
, &head
, RDMA_CONTROL_NONE
);
3208 if (head
.repeat
> RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE
) {
3209 error_report("rdma: Too many requests in this message (%d)."
3210 "Bailing.", head
.repeat
);
3215 switch (head
.type
) {
3216 case RDMA_CONTROL_COMPRESS
:
3217 comp
= (RDMACompress
*) rdma
->wr_data
[idx
].control_curr
;
3218 network_to_compress(comp
);
3220 trace_qemu_rdma_registration_handle_compress(comp
->length
,
3223 if (comp
->block_idx
>= rdma
->local_ram_blocks
.nb_blocks
) {
3224 error_report("rdma: 'compress' bad block index %u (vs %d)",
3225 (unsigned int)comp
->block_idx
,
3226 rdma
->local_ram_blocks
.nb_blocks
);
3230 block
= &(rdma
->local_ram_blocks
.block
[comp
->block_idx
]);
3232 host_addr
= block
->local_host_addr
+
3233 (comp
->offset
- block
->offset
);
3235 ram_handle_compressed(host_addr
, comp
->value
, comp
->length
);
3238 case RDMA_CONTROL_REGISTER_FINISHED
:
3239 trace_qemu_rdma_registration_handle_finished();
3242 case RDMA_CONTROL_RAM_BLOCKS_REQUEST
:
3243 trace_qemu_rdma_registration_handle_ram_blocks();
3245 /* Sort our local RAM Block list so it's the same as the source,
3246 * we can do this since we've filled in a src_index in the list
3247 * as we received the RAMBlock list earlier.
3249 qsort(rdma
->local_ram_blocks
.block
,
3250 rdma
->local_ram_blocks
.nb_blocks
,
3251 sizeof(RDMALocalBlock
), dest_ram_sort_func
);
3252 for (i
= 0; i
< local
->nb_blocks
; i
++) {
3253 local
->block
[i
].index
= i
;
3256 if (rdma
->pin_all
) {
3257 ret
= qemu_rdma_reg_whole_ram_blocks(rdma
);
3259 error_report("rdma migration: error dest "
3260 "registering ram blocks");
3266 * Dest uses this to prepare to transmit the RAMBlock descriptions
3267 * to the source VM after connection setup.
3268 * Both sides use the "remote" structure to communicate and update
3269 * their "local" descriptions with what was sent.
3271 for (i
= 0; i
< local
->nb_blocks
; i
++) {
3272 rdma
->dest_blocks
[i
].remote_host_addr
=
3273 (uintptr_t)(local
->block
[i
].local_host_addr
);
3275 if (rdma
->pin_all
) {
3276 rdma
->dest_blocks
[i
].remote_rkey
= local
->block
[i
].mr
->rkey
;
3279 rdma
->dest_blocks
[i
].offset
= local
->block
[i
].offset
;
3280 rdma
->dest_blocks
[i
].length
= local
->block
[i
].length
;
3282 dest_block_to_network(&rdma
->dest_blocks
[i
]);
3283 trace_qemu_rdma_registration_handle_ram_blocks_loop(
3284 local
->block
[i
].block_name
,
3285 local
->block
[i
].offset
,
3286 local
->block
[i
].length
,
3287 local
->block
[i
].local_host_addr
,
3288 local
->block
[i
].src_index
);
3291 blocks
.len
= rdma
->local_ram_blocks
.nb_blocks
3292 * sizeof(RDMADestBlock
);
3295 ret
= qemu_rdma_post_send_control(rdma
,
3296 (uint8_t *) rdma
->dest_blocks
, &blocks
);
3299 error_report("rdma migration: error sending remote info");
3304 case RDMA_CONTROL_REGISTER_REQUEST
:
3305 trace_qemu_rdma_registration_handle_register(head
.repeat
);
3307 reg_resp
.repeat
= head
.repeat
;
3308 registers
= (RDMARegister
*) rdma
->wr_data
[idx
].control_curr
;
3310 for (count
= 0; count
< head
.repeat
; count
++) {
3312 uint8_t *chunk_start
, *chunk_end
;
3314 reg
= ®isters
[count
];
3315 network_to_register(reg
);
3317 reg_result
= &results
[count
];
3319 trace_qemu_rdma_registration_handle_register_loop(count
,
3320 reg
->current_index
, reg
->key
.current_addr
, reg
->chunks
);
3322 if (reg
->current_index
>= rdma
->local_ram_blocks
.nb_blocks
) {
3323 error_report("rdma: 'register' bad block index %u (vs %d)",
3324 (unsigned int)reg
->current_index
,
3325 rdma
->local_ram_blocks
.nb_blocks
);
3329 block
= &(rdma
->local_ram_blocks
.block
[reg
->current_index
]);
3330 if (block
->is_ram_block
) {
3331 if (block
->offset
> reg
->key
.current_addr
) {
3332 error_report("rdma: bad register address for block %s"
3333 " offset: %" PRIx64
" current_addr: %" PRIx64
,
3334 block
->block_name
, block
->offset
,
3335 reg
->key
.current_addr
);
3339 host_addr
= (block
->local_host_addr
+
3340 (reg
->key
.current_addr
- block
->offset
));
3341 chunk
= ram_chunk_index(block
->local_host_addr
,
3342 (uint8_t *) host_addr
);
3344 chunk
= reg
->key
.chunk
;
3345 host_addr
= block
->local_host_addr
+
3346 (reg
->key
.chunk
* (1UL << RDMA_REG_CHUNK_SHIFT
));
3347 /* Check for particularly bad chunk value */
3348 if (host_addr
< (void *)block
->local_host_addr
) {
3349 error_report("rdma: bad chunk for block %s"
3351 block
->block_name
, reg
->key
.chunk
);
3356 chunk_start
= ram_chunk_start(block
, chunk
);
3357 chunk_end
= ram_chunk_end(block
, chunk
+ reg
->chunks
);
3358 if (qemu_rdma_register_and_get_keys(rdma
, block
,
3359 (uintptr_t)host_addr
, NULL
, ®_result
->rkey
,
3360 chunk
, chunk_start
, chunk_end
)) {
3361 error_report("cannot get rkey");
3366 reg_result
->host_addr
= (uintptr_t)block
->local_host_addr
;
3368 trace_qemu_rdma_registration_handle_register_rkey(
3371 result_to_network(reg_result
);
3374 ret
= qemu_rdma_post_send_control(rdma
,
3375 (uint8_t *) results
, ®_resp
);
3378 error_report("Failed to send control buffer");
3382 case RDMA_CONTROL_UNREGISTER_REQUEST
:
3383 trace_qemu_rdma_registration_handle_unregister(head
.repeat
);
3384 unreg_resp
.repeat
= head
.repeat
;
3385 registers
= (RDMARegister
*) rdma
->wr_data
[idx
].control_curr
;
3387 for (count
= 0; count
< head
.repeat
; count
++) {
3388 reg
= ®isters
[count
];
3389 network_to_register(reg
);
3391 trace_qemu_rdma_registration_handle_unregister_loop(count
,
3392 reg
->current_index
, reg
->key
.chunk
);
3394 block
= &(rdma
->local_ram_blocks
.block
[reg
->current_index
]);
3396 ret
= ibv_dereg_mr(block
->pmr
[reg
->key
.chunk
]);
3397 block
->pmr
[reg
->key
.chunk
] = NULL
;
3400 perror("rdma unregistration chunk failed");
3405 rdma
->total_registrations
--;
3407 trace_qemu_rdma_registration_handle_unregister_success(
3411 ret
= qemu_rdma_post_send_control(rdma
, NULL
, &unreg_resp
);
3414 error_report("Failed to send control buffer");
3418 case RDMA_CONTROL_REGISTER_RESULT
:
3419 error_report("Invalid RESULT message at dest.");
3423 error_report("Unknown control message %s", control_desc(head
.type
));
3430 rdma
->error_state
= ret
;
3436 * Called via a ram_control_load_hook during the initial RAM load section which
3437 * lists the RAMBlocks by name. This lets us know the order of the RAMBlocks
3439 * We've already built our local RAMBlock list, but not yet sent the list to
3443 rdma_block_notification_handle(QIOChannelRDMA
*rioc
, const char *name
)
3445 RDMAContext
*rdma
= rioc
->rdma
;
3449 /* Find the matching RAMBlock in our local list */
3450 for (curr
= 0; curr
< rdma
->local_ram_blocks
.nb_blocks
; curr
++) {
3451 if (!strcmp(rdma
->local_ram_blocks
.block
[curr
].block_name
, name
)) {
3458 error_report("RAMBlock '%s' not found on destination", name
);
3462 rdma
->local_ram_blocks
.block
[curr
].src_index
= rdma
->next_src_index
;
3463 trace_rdma_block_notification_handle(name
, rdma
->next_src_index
);
3464 rdma
->next_src_index
++;
3469 static int rdma_load_hook(QEMUFile
*f
, void *opaque
, uint64_t flags
, void *data
)
3472 case RAM_CONTROL_BLOCK_REG
:
3473 return rdma_block_notification_handle(opaque
, data
);
3475 case RAM_CONTROL_HOOK
:
3476 return qemu_rdma_registration_handle(f
, opaque
);
3479 /* Shouldn't be called with any other values */
3484 static int qemu_rdma_registration_start(QEMUFile
*f
, void *opaque
,
3485 uint64_t flags
, void *data
)
3487 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
3488 RDMAContext
*rdma
= rioc
->rdma
;
3490 CHECK_ERROR_STATE();
3492 trace_qemu_rdma_registration_start(flags
);
3493 qemu_put_be64(f
, RAM_SAVE_FLAG_HOOK
);
3500 * Inform dest that dynamic registrations are done for now.
3501 * First, flush writes, if any.
3503 static int qemu_rdma_registration_stop(QEMUFile
*f
, void *opaque
,
3504 uint64_t flags
, void *data
)
3506 Error
*local_err
= NULL
, **errp
= &local_err
;
3507 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
3508 RDMAContext
*rdma
= rioc
->rdma
;
3509 RDMAControlHeader head
= { .len
= 0, .repeat
= 1 };
3512 CHECK_ERROR_STATE();
3515 ret
= qemu_rdma_drain_cq(f
, rdma
);
3521 if (flags
== RAM_CONTROL_SETUP
) {
3522 RDMAControlHeader resp
= {.type
= RDMA_CONTROL_RAM_BLOCKS_RESULT
};
3523 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
3524 int reg_result_idx
, i
, nb_dest_blocks
;
3526 head
.type
= RDMA_CONTROL_RAM_BLOCKS_REQUEST
;
3527 trace_qemu_rdma_registration_stop_ram();
3530 * Make sure that we parallelize the pinning on both sides.
3531 * For very large guests, doing this serially takes a really
3532 * long time, so we have to 'interleave' the pinning locally
3533 * with the control messages by performing the pinning on this
3534 * side before we receive the control response from the other
3535 * side that the pinning has completed.
3537 ret
= qemu_rdma_exchange_send(rdma
, &head
, NULL
, &resp
,
3538 ®_result_idx
, rdma
->pin_all
?
3539 qemu_rdma_reg_whole_ram_blocks
: NULL
);
3541 ERROR(errp
, "receiving remote info!");
3545 nb_dest_blocks
= resp
.len
/ sizeof(RDMADestBlock
);
3548 * The protocol uses two different sets of rkeys (mutually exclusive):
3549 * 1. One key to represent the virtual address of the entire ram block.
3550 * (dynamic chunk registration disabled - pin everything with one rkey.)
3551 * 2. One to represent individual chunks within a ram block.
3552 * (dynamic chunk registration enabled - pin individual chunks.)
3554 * Once the capability is successfully negotiated, the destination transmits
3555 * the keys to use (or sends them later) including the virtual addresses
3556 * and then propagates the remote ram block descriptions to his local copy.
3559 if (local
->nb_blocks
!= nb_dest_blocks
) {
3560 ERROR(errp
, "ram blocks mismatch (Number of blocks %d vs %d) "
3561 "Your QEMU command line parameters are probably "
3562 "not identical on both the source and destination.",
3563 local
->nb_blocks
, nb_dest_blocks
);
3564 rdma
->error_state
= -EINVAL
;
3568 qemu_rdma_move_header(rdma
, reg_result_idx
, &resp
);
3569 memcpy(rdma
->dest_blocks
,
3570 rdma
->wr_data
[reg_result_idx
].control_curr
, resp
.len
);
3571 for (i
= 0; i
< nb_dest_blocks
; i
++) {
3572 network_to_dest_block(&rdma
->dest_blocks
[i
]);
3574 /* We require that the blocks are in the same order */
3575 if (rdma
->dest_blocks
[i
].length
!= local
->block
[i
].length
) {
3576 ERROR(errp
, "Block %s/%d has a different length %" PRIu64
3577 "vs %" PRIu64
, local
->block
[i
].block_name
, i
,
3578 local
->block
[i
].length
,
3579 rdma
->dest_blocks
[i
].length
);
3580 rdma
->error_state
= -EINVAL
;
3583 local
->block
[i
].remote_host_addr
=
3584 rdma
->dest_blocks
[i
].remote_host_addr
;
3585 local
->block
[i
].remote_rkey
= rdma
->dest_blocks
[i
].remote_rkey
;
3589 trace_qemu_rdma_registration_stop(flags
);
3591 head
.type
= RDMA_CONTROL_REGISTER_FINISHED
;
3592 ret
= qemu_rdma_exchange_send(rdma
, &head
, NULL
, NULL
, NULL
, NULL
);
3600 rdma
->error_state
= ret
;
3604 static const QEMUFileHooks rdma_read_hooks
= {
3605 .hook_ram_load
= rdma_load_hook
,
3608 static const QEMUFileHooks rdma_write_hooks
= {
3609 .before_ram_iterate
= qemu_rdma_registration_start
,
3610 .after_ram_iterate
= qemu_rdma_registration_stop
,
3611 .save_page
= qemu_rdma_save_page
,
3615 static void qio_channel_rdma_finalize(Object
*obj
)
3617 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(obj
);
3619 qemu_rdma_cleanup(rioc
->rdma
);
3625 static void qio_channel_rdma_class_init(ObjectClass
*klass
,
3626 void *class_data G_GNUC_UNUSED
)
3628 QIOChannelClass
*ioc_klass
= QIO_CHANNEL_CLASS(klass
);
3630 ioc_klass
->io_writev
= qio_channel_rdma_writev
;
3631 ioc_klass
->io_readv
= qio_channel_rdma_readv
;
3632 ioc_klass
->io_set_blocking
= qio_channel_rdma_set_blocking
;
3633 ioc_klass
->io_close
= qio_channel_rdma_close
;
3634 ioc_klass
->io_create_watch
= qio_channel_rdma_create_watch
;
3637 static const TypeInfo qio_channel_rdma_info
= {
3638 .parent
= TYPE_QIO_CHANNEL
,
3639 .name
= TYPE_QIO_CHANNEL_RDMA
,
3640 .instance_size
= sizeof(QIOChannelRDMA
),
3641 .instance_finalize
= qio_channel_rdma_finalize
,
3642 .class_init
= qio_channel_rdma_class_init
,
3645 static void qio_channel_rdma_register_types(void)
3647 type_register_static(&qio_channel_rdma_info
);
3650 type_init(qio_channel_rdma_register_types
);
3652 static QEMUFile
*qemu_fopen_rdma(RDMAContext
*rdma
, const char *mode
)
3654 QIOChannelRDMA
*rioc
;
3656 if (qemu_file_mode_is_not_valid(mode
)) {
3660 rioc
= QIO_CHANNEL_RDMA(object_new(TYPE_QIO_CHANNEL_RDMA
));
3663 if (mode
[0] == 'w') {
3664 rioc
->file
= qemu_fopen_channel_output(QIO_CHANNEL(rioc
));
3665 qemu_file_set_hooks(rioc
->file
, &rdma_write_hooks
);
3667 rioc
->file
= qemu_fopen_channel_input(QIO_CHANNEL(rioc
));
3668 qemu_file_set_hooks(rioc
->file
, &rdma_read_hooks
);
3674 static void rdma_accept_incoming_migration(void *opaque
)
3676 RDMAContext
*rdma
= opaque
;
3679 Error
*local_err
= NULL
, **errp
= &local_err
;
3681 trace_qemu_rdma_accept_incoming_migration();
3682 ret
= qemu_rdma_accept(rdma
);
3685 ERROR(errp
, "RDMA Migration initialization failed!");
3689 trace_qemu_rdma_accept_incoming_migration_accepted();
3691 f
= qemu_fopen_rdma(rdma
, "rb");
3693 ERROR(errp
, "could not qemu_fopen_rdma!");
3694 qemu_rdma_cleanup(rdma
);
3698 rdma
->migration_started_on_destination
= 1;
3699 migration_fd_process_incoming(f
);
3702 void rdma_start_incoming_migration(const char *host_port
, Error
**errp
)
3706 Error
*local_err
= NULL
;
3708 trace_rdma_start_incoming_migration();
3709 rdma
= qemu_rdma_data_init(host_port
, &local_err
);
3715 ret
= qemu_rdma_dest_init(rdma
, &local_err
);
3721 trace_rdma_start_incoming_migration_after_dest_init();
3723 ret
= rdma_listen(rdma
->listen_id
, 5);
3726 ERROR(errp
, "listening on socket!");
3730 trace_rdma_start_incoming_migration_after_rdma_listen();
3732 qemu_set_fd_handler(rdma
->channel
->fd
, rdma_accept_incoming_migration
,
3733 NULL
, (void *)(intptr_t)rdma
);
3736 error_propagate(errp
, local_err
);
3740 void rdma_start_outgoing_migration(void *opaque
,
3741 const char *host_port
, Error
**errp
)
3743 MigrationState
*s
= opaque
;
3744 RDMAContext
*rdma
= qemu_rdma_data_init(host_port
, errp
);
3751 ret
= qemu_rdma_source_init(rdma
,
3752 s
->enabled_capabilities
[MIGRATION_CAPABILITY_RDMA_PIN_ALL
], errp
);
3758 trace_rdma_start_outgoing_migration_after_rdma_source_init();
3759 ret
= qemu_rdma_connect(rdma
, errp
);
3765 trace_rdma_start_outgoing_migration_after_rdma_connect();
3767 s
->to_dst_file
= qemu_fopen_rdma(rdma
, "wb");
3768 migrate_fd_connect(s
, NULL
);