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"
20 #include "migration/migration.h"
21 #include "migration/qemu-file.h"
22 #include "exec/cpu-common.h"
23 #include "qemu/error-report.h"
24 #include "qemu/main-loop.h"
25 #include "qemu/sockets.h"
26 #include "qemu/bitmap.h"
27 #include "qemu/coroutine.h"
28 #include <sys/socket.h>
30 #include <arpa/inet.h>
31 #include <rdma/rdma_cma.h>
35 * Print and error on both the Monitor and the Log file.
37 #define ERROR(errp, fmt, ...) \
39 fprintf(stderr, "RDMA ERROR: " fmt "\n", ## __VA_ARGS__); \
40 if (errp && (*(errp) == NULL)) { \
41 error_setg(errp, "RDMA ERROR: " fmt, ## __VA_ARGS__); \
45 #define RDMA_RESOLVE_TIMEOUT_MS 10000
47 /* Do not merge data if larger than this. */
48 #define RDMA_MERGE_MAX (2 * 1024 * 1024)
49 #define RDMA_SIGNALED_SEND_MAX (RDMA_MERGE_MAX / 4096)
51 #define RDMA_REG_CHUNK_SHIFT 20 /* 1 MB */
54 * This is only for non-live state being migrated.
55 * Instead of RDMA_WRITE messages, we use RDMA_SEND
56 * messages for that state, which requires a different
57 * delivery design than main memory.
59 #define RDMA_SEND_INCREMENT 32768
62 * Maximum size infiniband SEND message
64 #define RDMA_CONTROL_MAX_BUFFER (512 * 1024)
65 #define RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE 4096
67 #define RDMA_CONTROL_VERSION_CURRENT 1
69 * Capabilities for negotiation.
71 #define RDMA_CAPABILITY_PIN_ALL 0x01
74 * Add the other flags above to this list of known capabilities
75 * as they are introduced.
77 static uint32_t known_capabilities
= RDMA_CAPABILITY_PIN_ALL
;
79 #define CHECK_ERROR_STATE() \
81 if (rdma->error_state) { \
82 if (!rdma->error_reported) { \
83 error_report("RDMA is in an error state waiting migration" \
85 rdma->error_reported = 1; \
87 return rdma->error_state; \
92 * A work request ID is 64-bits and we split up these bits
95 * bits 0-15 : type of control message, 2^16
96 * bits 16-29: ram block index, 2^14
97 * bits 30-63: ram block chunk number, 2^34
99 * The last two bit ranges are only used for RDMA writes,
100 * in order to track their completion and potentially
101 * also track unregistration status of the message.
103 #define RDMA_WRID_TYPE_SHIFT 0UL
104 #define RDMA_WRID_BLOCK_SHIFT 16UL
105 #define RDMA_WRID_CHUNK_SHIFT 30UL
107 #define RDMA_WRID_TYPE_MASK \
108 ((1UL << RDMA_WRID_BLOCK_SHIFT) - 1UL)
110 #define RDMA_WRID_BLOCK_MASK \
111 (~RDMA_WRID_TYPE_MASK & ((1UL << RDMA_WRID_CHUNK_SHIFT) - 1UL))
113 #define RDMA_WRID_CHUNK_MASK (~RDMA_WRID_BLOCK_MASK & ~RDMA_WRID_TYPE_MASK)
116 * RDMA migration protocol:
117 * 1. RDMA Writes (data messages, i.e. RAM)
118 * 2. IB Send/Recv (control channel messages)
122 RDMA_WRID_RDMA_WRITE
= 1,
123 RDMA_WRID_SEND_CONTROL
= 2000,
124 RDMA_WRID_RECV_CONTROL
= 4000,
127 static const char *wrid_desc
[] = {
128 [RDMA_WRID_NONE
] = "NONE",
129 [RDMA_WRID_RDMA_WRITE
] = "WRITE RDMA",
130 [RDMA_WRID_SEND_CONTROL
] = "CONTROL SEND",
131 [RDMA_WRID_RECV_CONTROL
] = "CONTROL RECV",
135 * Work request IDs for IB SEND messages only (not RDMA writes).
136 * This is used by the migration protocol to transmit
137 * control messages (such as device state and registration commands)
139 * We could use more WRs, but we have enough for now.
149 * SEND/RECV IB Control Messages.
152 RDMA_CONTROL_NONE
= 0,
154 RDMA_CONTROL_READY
, /* ready to receive */
155 RDMA_CONTROL_QEMU_FILE
, /* QEMUFile-transmitted bytes */
156 RDMA_CONTROL_RAM_BLOCKS_REQUEST
, /* RAMBlock synchronization */
157 RDMA_CONTROL_RAM_BLOCKS_RESULT
, /* RAMBlock synchronization */
158 RDMA_CONTROL_COMPRESS
, /* page contains repeat values */
159 RDMA_CONTROL_REGISTER_REQUEST
, /* dynamic page registration */
160 RDMA_CONTROL_REGISTER_RESULT
, /* key to use after registration */
161 RDMA_CONTROL_REGISTER_FINISHED
, /* current iteration finished */
162 RDMA_CONTROL_UNREGISTER_REQUEST
, /* dynamic UN-registration */
163 RDMA_CONTROL_UNREGISTER_FINISHED
, /* unpinning finished */
166 static const char *control_desc
[] = {
167 [RDMA_CONTROL_NONE
] = "NONE",
168 [RDMA_CONTROL_ERROR
] = "ERROR",
169 [RDMA_CONTROL_READY
] = "READY",
170 [RDMA_CONTROL_QEMU_FILE
] = "QEMU FILE",
171 [RDMA_CONTROL_RAM_BLOCKS_REQUEST
] = "RAM BLOCKS REQUEST",
172 [RDMA_CONTROL_RAM_BLOCKS_RESULT
] = "RAM BLOCKS RESULT",
173 [RDMA_CONTROL_COMPRESS
] = "COMPRESS",
174 [RDMA_CONTROL_REGISTER_REQUEST
] = "REGISTER REQUEST",
175 [RDMA_CONTROL_REGISTER_RESULT
] = "REGISTER RESULT",
176 [RDMA_CONTROL_REGISTER_FINISHED
] = "REGISTER FINISHED",
177 [RDMA_CONTROL_UNREGISTER_REQUEST
] = "UNREGISTER REQUEST",
178 [RDMA_CONTROL_UNREGISTER_FINISHED
] = "UNREGISTER FINISHED",
182 * Memory and MR structures used to represent an IB Send/Recv work request.
183 * This is *not* used for RDMA writes, only IB Send/Recv.
186 uint8_t control
[RDMA_CONTROL_MAX_BUFFER
]; /* actual buffer to register */
187 struct ibv_mr
*control_mr
; /* registration metadata */
188 size_t control_len
; /* length of the message */
189 uint8_t *control_curr
; /* start of unconsumed bytes */
190 } RDMAWorkRequestData
;
193 * Negotiate RDMA capabilities during connection-setup time.
200 static void caps_to_network(RDMACapabilities
*cap
)
202 cap
->version
= htonl(cap
->version
);
203 cap
->flags
= htonl(cap
->flags
);
206 static void network_to_caps(RDMACapabilities
*cap
)
208 cap
->version
= ntohl(cap
->version
);
209 cap
->flags
= ntohl(cap
->flags
);
213 * Representation of a RAMBlock from an RDMA perspective.
214 * This is not transmitted, only local.
215 * This and subsequent structures cannot be linked lists
216 * because we're using a single IB message to transmit
217 * the information. It's small anyway, so a list is overkill.
219 typedef struct RDMALocalBlock
{
221 uint8_t *local_host_addr
; /* local virtual address */
222 uint64_t remote_host_addr
; /* remote virtual address */
225 struct ibv_mr
**pmr
; /* MRs for chunk-level registration */
226 struct ibv_mr
*mr
; /* MR for non-chunk-level registration */
227 uint32_t *remote_keys
; /* rkeys for chunk-level registration */
228 uint32_t remote_rkey
; /* rkeys for non-chunk-level registration */
229 int index
; /* which block are we */
230 unsigned int src_index
; /* (Only used on dest) */
233 unsigned long *transit_bitmap
;
234 unsigned long *unregister_bitmap
;
238 * Also represents a RAMblock, but only on the dest.
239 * This gets transmitted by the dest during connection-time
240 * to the source VM and then is used to populate the
241 * corresponding RDMALocalBlock with
242 * the information needed to perform the actual RDMA.
244 typedef struct QEMU_PACKED RDMADestBlock
{
245 uint64_t remote_host_addr
;
248 uint32_t remote_rkey
;
252 static uint64_t htonll(uint64_t v
)
254 union { uint32_t lv
[2]; uint64_t llv
; } u
;
255 u
.lv
[0] = htonl(v
>> 32);
256 u
.lv
[1] = htonl(v
& 0xFFFFFFFFULL
);
260 static uint64_t ntohll(uint64_t v
) {
261 union { uint32_t lv
[2]; uint64_t llv
; } u
;
263 return ((uint64_t)ntohl(u
.lv
[0]) << 32) | (uint64_t) ntohl(u
.lv
[1]);
266 static void dest_block_to_network(RDMADestBlock
*db
)
268 db
->remote_host_addr
= htonll(db
->remote_host_addr
);
269 db
->offset
= htonll(db
->offset
);
270 db
->length
= htonll(db
->length
);
271 db
->remote_rkey
= htonl(db
->remote_rkey
);
274 static void network_to_dest_block(RDMADestBlock
*db
)
276 db
->remote_host_addr
= ntohll(db
->remote_host_addr
);
277 db
->offset
= ntohll(db
->offset
);
278 db
->length
= ntohll(db
->length
);
279 db
->remote_rkey
= ntohl(db
->remote_rkey
);
283 * Virtual address of the above structures used for transmitting
284 * the RAMBlock descriptions at connection-time.
285 * This structure is *not* transmitted.
287 typedef struct RDMALocalBlocks
{
289 bool init
; /* main memory init complete */
290 RDMALocalBlock
*block
;
294 * Main data structure for RDMA state.
295 * While there is only one copy of this structure being allocated right now,
296 * this is the place where one would start if you wanted to consider
297 * having more than one RDMA connection open at the same time.
299 typedef struct RDMAContext
{
303 RDMAWorkRequestData wr_data
[RDMA_WRID_MAX
];
306 * This is used by *_exchange_send() to figure out whether or not
307 * the initial "READY" message has already been received or not.
308 * This is because other functions may potentially poll() and detect
309 * the READY message before send() does, in which case we need to
310 * know if it completed.
312 int control_ready_expected
;
314 /* number of outstanding writes */
317 /* store info about current buffer so that we can
318 merge it with future sends */
319 uint64_t current_addr
;
320 uint64_t current_length
;
321 /* index of ram block the current buffer belongs to */
323 /* index of the chunk in the current ram block */
329 * infiniband-specific variables for opening the device
330 * and maintaining connection state and so forth.
332 * cm_id also has ibv_context, rdma_event_channel, and ibv_qp in
333 * cm_id->verbs, cm_id->channel, and cm_id->qp.
335 struct rdma_cm_id
*cm_id
; /* connection manager ID */
336 struct rdma_cm_id
*listen_id
;
339 struct ibv_context
*verbs
;
340 struct rdma_event_channel
*channel
;
341 struct ibv_qp
*qp
; /* queue pair */
342 struct ibv_comp_channel
*comp_channel
; /* completion channel */
343 struct ibv_pd
*pd
; /* protection domain */
344 struct ibv_cq
*cq
; /* completion queue */
347 * If a previous write failed (perhaps because of a failed
348 * memory registration, then do not attempt any future work
349 * and remember the error state.
355 * Description of ram blocks used throughout the code.
357 RDMALocalBlocks local_ram_blocks
;
358 RDMADestBlock
*dest_blocks
;
360 /* Index of the next RAMBlock received during block registration */
361 unsigned int next_src_index
;
364 * Migration on *destination* started.
365 * Then use coroutine yield function.
366 * Source runs in a thread, so we don't care.
368 int migration_started_on_destination
;
370 int total_registrations
;
373 int unregister_current
, unregister_next
;
374 uint64_t unregistrations
[RDMA_SIGNALED_SEND_MAX
];
376 GHashTable
*blockmap
;
379 #define TYPE_QIO_CHANNEL_RDMA "qio-channel-rdma"
380 #define QIO_CHANNEL_RDMA(obj) \
381 OBJECT_CHECK(QIOChannelRDMA, (obj), TYPE_QIO_CHANNEL_RDMA)
383 typedef struct QIOChannelRDMA QIOChannelRDMA
;
386 struct QIOChannelRDMA
{
391 bool blocking
; /* XXX we don't actually honour this yet */
395 * Main structure for IB Send/Recv control messages.
396 * This gets prepended at the beginning of every Send/Recv.
398 typedef struct QEMU_PACKED
{
399 uint32_t len
; /* Total length of data portion */
400 uint32_t type
; /* which control command to perform */
401 uint32_t repeat
; /* number of commands in data portion of same type */
405 static void control_to_network(RDMAControlHeader
*control
)
407 control
->type
= htonl(control
->type
);
408 control
->len
= htonl(control
->len
);
409 control
->repeat
= htonl(control
->repeat
);
412 static void network_to_control(RDMAControlHeader
*control
)
414 control
->type
= ntohl(control
->type
);
415 control
->len
= ntohl(control
->len
);
416 control
->repeat
= ntohl(control
->repeat
);
420 * Register a single Chunk.
421 * Information sent by the source VM to inform the dest
422 * to register an single chunk of memory before we can perform
423 * the actual RDMA operation.
425 typedef struct QEMU_PACKED
{
427 uint64_t current_addr
; /* offset into the ram_addr_t space */
428 uint64_t chunk
; /* chunk to lookup if unregistering */
430 uint32_t current_index
; /* which ramblock the chunk belongs to */
432 uint64_t chunks
; /* how many sequential chunks to register */
435 static void register_to_network(RDMAContext
*rdma
, RDMARegister
*reg
)
437 RDMALocalBlock
*local_block
;
438 local_block
= &rdma
->local_ram_blocks
.block
[reg
->current_index
];
440 if (local_block
->is_ram_block
) {
442 * current_addr as passed in is an address in the local ram_addr_t
443 * space, we need to translate this for the destination
445 reg
->key
.current_addr
-= local_block
->offset
;
446 reg
->key
.current_addr
+= rdma
->dest_blocks
[reg
->current_index
].offset
;
448 reg
->key
.current_addr
= htonll(reg
->key
.current_addr
);
449 reg
->current_index
= htonl(reg
->current_index
);
450 reg
->chunks
= htonll(reg
->chunks
);
453 static void network_to_register(RDMARegister
*reg
)
455 reg
->key
.current_addr
= ntohll(reg
->key
.current_addr
);
456 reg
->current_index
= ntohl(reg
->current_index
);
457 reg
->chunks
= ntohll(reg
->chunks
);
460 typedef struct QEMU_PACKED
{
461 uint32_t value
; /* if zero, we will madvise() */
462 uint32_t block_idx
; /* which ram block index */
463 uint64_t offset
; /* Address in remote ram_addr_t space */
464 uint64_t length
; /* length of the chunk */
467 static void compress_to_network(RDMAContext
*rdma
, RDMACompress
*comp
)
469 comp
->value
= htonl(comp
->value
);
471 * comp->offset as passed in is an address in the local ram_addr_t
472 * space, we need to translate this for the destination
474 comp
->offset
-= rdma
->local_ram_blocks
.block
[comp
->block_idx
].offset
;
475 comp
->offset
+= rdma
->dest_blocks
[comp
->block_idx
].offset
;
476 comp
->block_idx
= htonl(comp
->block_idx
);
477 comp
->offset
= htonll(comp
->offset
);
478 comp
->length
= htonll(comp
->length
);
481 static void network_to_compress(RDMACompress
*comp
)
483 comp
->value
= ntohl(comp
->value
);
484 comp
->block_idx
= ntohl(comp
->block_idx
);
485 comp
->offset
= ntohll(comp
->offset
);
486 comp
->length
= ntohll(comp
->length
);
490 * The result of the dest's memory registration produces an "rkey"
491 * which the source VM must reference in order to perform
492 * the RDMA operation.
494 typedef struct QEMU_PACKED
{
498 } RDMARegisterResult
;
500 static void result_to_network(RDMARegisterResult
*result
)
502 result
->rkey
= htonl(result
->rkey
);
503 result
->host_addr
= htonll(result
->host_addr
);
506 static void network_to_result(RDMARegisterResult
*result
)
508 result
->rkey
= ntohl(result
->rkey
);
509 result
->host_addr
= ntohll(result
->host_addr
);
512 const char *print_wrid(int wrid
);
513 static int qemu_rdma_exchange_send(RDMAContext
*rdma
, RDMAControlHeader
*head
,
514 uint8_t *data
, RDMAControlHeader
*resp
,
516 int (*callback
)(RDMAContext
*rdma
));
518 static inline uint64_t ram_chunk_index(const uint8_t *start
,
521 return ((uintptr_t) host
- (uintptr_t) start
) >> RDMA_REG_CHUNK_SHIFT
;
524 static inline uint8_t *ram_chunk_start(const RDMALocalBlock
*rdma_ram_block
,
527 return (uint8_t *)(uintptr_t)(rdma_ram_block
->local_host_addr
+
528 (i
<< RDMA_REG_CHUNK_SHIFT
));
531 static inline uint8_t *ram_chunk_end(const RDMALocalBlock
*rdma_ram_block
,
534 uint8_t *result
= ram_chunk_start(rdma_ram_block
, i
) +
535 (1UL << RDMA_REG_CHUNK_SHIFT
);
537 if (result
> (rdma_ram_block
->local_host_addr
+ rdma_ram_block
->length
)) {
538 result
= rdma_ram_block
->local_host_addr
+ rdma_ram_block
->length
;
544 static int rdma_add_block(RDMAContext
*rdma
, const char *block_name
,
546 ram_addr_t block_offset
, uint64_t length
)
548 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
549 RDMALocalBlock
*block
;
550 RDMALocalBlock
*old
= local
->block
;
552 local
->block
= g_new0(RDMALocalBlock
, local
->nb_blocks
+ 1);
554 if (local
->nb_blocks
) {
557 if (rdma
->blockmap
) {
558 for (x
= 0; x
< local
->nb_blocks
; x
++) {
559 g_hash_table_remove(rdma
->blockmap
,
560 (void *)(uintptr_t)old
[x
].offset
);
561 g_hash_table_insert(rdma
->blockmap
,
562 (void *)(uintptr_t)old
[x
].offset
,
566 memcpy(local
->block
, old
, sizeof(RDMALocalBlock
) * local
->nb_blocks
);
570 block
= &local
->block
[local
->nb_blocks
];
572 block
->block_name
= g_strdup(block_name
);
573 block
->local_host_addr
= host_addr
;
574 block
->offset
= block_offset
;
575 block
->length
= length
;
576 block
->index
= local
->nb_blocks
;
577 block
->src_index
= ~0U; /* Filled in by the receipt of the block list */
578 block
->nb_chunks
= ram_chunk_index(host_addr
, host_addr
+ length
) + 1UL;
579 block
->transit_bitmap
= bitmap_new(block
->nb_chunks
);
580 bitmap_clear(block
->transit_bitmap
, 0, block
->nb_chunks
);
581 block
->unregister_bitmap
= bitmap_new(block
->nb_chunks
);
582 bitmap_clear(block
->unregister_bitmap
, 0, block
->nb_chunks
);
583 block
->remote_keys
= g_new0(uint32_t, block
->nb_chunks
);
585 block
->is_ram_block
= local
->init
? false : true;
587 if (rdma
->blockmap
) {
588 g_hash_table_insert(rdma
->blockmap
, (void *)(uintptr_t)block_offset
, block
);
591 trace_rdma_add_block(block_name
, local
->nb_blocks
,
592 (uintptr_t) block
->local_host_addr
,
593 block
->offset
, block
->length
,
594 (uintptr_t) (block
->local_host_addr
+ block
->length
),
595 BITS_TO_LONGS(block
->nb_chunks
) *
596 sizeof(unsigned long) * 8,
605 * Memory regions need to be registered with the device and queue pairs setup
606 * in advanced before the migration starts. This tells us where the RAM blocks
607 * are so that we can register them individually.
609 static int qemu_rdma_init_one_block(const char *block_name
, void *host_addr
,
610 ram_addr_t block_offset
, ram_addr_t length
, void *opaque
)
612 return rdma_add_block(opaque
, block_name
, host_addr
, block_offset
, length
);
616 * Identify the RAMBlocks and their quantity. They will be references to
617 * identify chunk boundaries inside each RAMBlock and also be referenced
618 * during dynamic page registration.
620 static int qemu_rdma_init_ram_blocks(RDMAContext
*rdma
)
622 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
624 assert(rdma
->blockmap
== NULL
);
625 memset(local
, 0, sizeof *local
);
626 qemu_ram_foreach_block(qemu_rdma_init_one_block
, rdma
);
627 trace_qemu_rdma_init_ram_blocks(local
->nb_blocks
);
628 rdma
->dest_blocks
= g_new0(RDMADestBlock
,
629 rdma
->local_ram_blocks
.nb_blocks
);
635 * Note: If used outside of cleanup, the caller must ensure that the destination
636 * block structures are also updated
638 static int rdma_delete_block(RDMAContext
*rdma
, RDMALocalBlock
*block
)
640 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
641 RDMALocalBlock
*old
= local
->block
;
644 if (rdma
->blockmap
) {
645 g_hash_table_remove(rdma
->blockmap
, (void *)(uintptr_t)block
->offset
);
650 for (j
= 0; j
< block
->nb_chunks
; j
++) {
651 if (!block
->pmr
[j
]) {
654 ibv_dereg_mr(block
->pmr
[j
]);
655 rdma
->total_registrations
--;
662 ibv_dereg_mr(block
->mr
);
663 rdma
->total_registrations
--;
667 g_free(block
->transit_bitmap
);
668 block
->transit_bitmap
= NULL
;
670 g_free(block
->unregister_bitmap
);
671 block
->unregister_bitmap
= NULL
;
673 g_free(block
->remote_keys
);
674 block
->remote_keys
= NULL
;
676 g_free(block
->block_name
);
677 block
->block_name
= NULL
;
679 if (rdma
->blockmap
) {
680 for (x
= 0; x
< local
->nb_blocks
; x
++) {
681 g_hash_table_remove(rdma
->blockmap
,
682 (void *)(uintptr_t)old
[x
].offset
);
686 if (local
->nb_blocks
> 1) {
688 local
->block
= g_new0(RDMALocalBlock
, local
->nb_blocks
- 1);
691 memcpy(local
->block
, old
, sizeof(RDMALocalBlock
) * block
->index
);
694 if (block
->index
< (local
->nb_blocks
- 1)) {
695 memcpy(local
->block
+ block
->index
, old
+ (block
->index
+ 1),
696 sizeof(RDMALocalBlock
) *
697 (local
->nb_blocks
- (block
->index
+ 1)));
700 assert(block
== local
->block
);
704 trace_rdma_delete_block(block
, (uintptr_t)block
->local_host_addr
,
705 block
->offset
, block
->length
,
706 (uintptr_t)(block
->local_host_addr
+ block
->length
),
707 BITS_TO_LONGS(block
->nb_chunks
) *
708 sizeof(unsigned long) * 8, block
->nb_chunks
);
714 if (local
->nb_blocks
&& rdma
->blockmap
) {
715 for (x
= 0; x
< local
->nb_blocks
; x
++) {
716 g_hash_table_insert(rdma
->blockmap
,
717 (void *)(uintptr_t)local
->block
[x
].offset
,
726 * Put in the log file which RDMA device was opened and the details
727 * associated with that device.
729 static void qemu_rdma_dump_id(const char *who
, struct ibv_context
*verbs
)
731 struct ibv_port_attr port
;
733 if (ibv_query_port(verbs
, 1, &port
)) {
734 error_report("Failed to query port information");
738 printf("%s RDMA Device opened: kernel name %s "
739 "uverbs device name %s, "
740 "infiniband_verbs class device path %s, "
741 "infiniband class device path %s, "
742 "transport: (%d) %s\n",
745 verbs
->device
->dev_name
,
746 verbs
->device
->dev_path
,
747 verbs
->device
->ibdev_path
,
749 (port
.link_layer
== IBV_LINK_LAYER_INFINIBAND
) ? "Infiniband" :
750 ((port
.link_layer
== IBV_LINK_LAYER_ETHERNET
)
751 ? "Ethernet" : "Unknown"));
755 * Put in the log file the RDMA gid addressing information,
756 * useful for folks who have trouble understanding the
757 * RDMA device hierarchy in the kernel.
759 static void qemu_rdma_dump_gid(const char *who
, struct rdma_cm_id
*id
)
763 inet_ntop(AF_INET6
, &id
->route
.addr
.addr
.ibaddr
.sgid
, sgid
, sizeof sgid
);
764 inet_ntop(AF_INET6
, &id
->route
.addr
.addr
.ibaddr
.dgid
, dgid
, sizeof dgid
);
765 trace_qemu_rdma_dump_gid(who
, sgid
, dgid
);
769 * As of now, IPv6 over RoCE / iWARP is not supported by linux.
770 * We will try the next addrinfo struct, and fail if there are
771 * no other valid addresses to bind against.
773 * If user is listening on '[::]', then we will not have a opened a device
774 * yet and have no way of verifying if the device is RoCE or not.
776 * In this case, the source VM will throw an error for ALL types of
777 * connections (both IPv4 and IPv6) if the destination machine does not have
778 * a regular infiniband network available for use.
780 * The only way to guarantee that an error is thrown for broken kernels is
781 * for the management software to choose a *specific* interface at bind time
782 * and validate what time of hardware it is.
784 * Unfortunately, this puts the user in a fix:
786 * If the source VM connects with an IPv4 address without knowing that the
787 * destination has bound to '[::]' the migration will unconditionally fail
788 * unless the management software is explicitly listening on the IPv4
789 * address while using a RoCE-based device.
791 * If the source VM connects with an IPv6 address, then we're OK because we can
792 * throw an error on the source (and similarly on the destination).
794 * But in mixed environments, this will be broken for a while until it is fixed
797 * We do provide a *tiny* bit of help in this function: We can list all of the
798 * devices in the system and check to see if all the devices are RoCE or
801 * If we detect that we have a *pure* RoCE environment, then we can safely
802 * thrown an error even if the management software has specified '[::]' as the
805 * However, if there is are multiple hetergeneous devices, then we cannot make
806 * this assumption and the user just has to be sure they know what they are
809 * Patches are being reviewed on linux-rdma.
811 static int qemu_rdma_broken_ipv6_kernel(Error
**errp
, struct ibv_context
*verbs
)
813 struct ibv_port_attr port_attr
;
815 /* This bug only exists in linux, to our knowledge. */
819 * Verbs are only NULL if management has bound to '[::]'.
821 * Let's iterate through all the devices and see if there any pure IB
822 * devices (non-ethernet).
824 * If not, then we can safely proceed with the migration.
825 * Otherwise, there are no guarantees until the bug is fixed in linux.
829 struct ibv_device
** dev_list
= ibv_get_device_list(&num_devices
);
830 bool roce_found
= false;
831 bool ib_found
= false;
833 for (x
= 0; x
< num_devices
; x
++) {
834 verbs
= ibv_open_device(dev_list
[x
]);
836 if (errno
== EPERM
) {
843 if (ibv_query_port(verbs
, 1, &port_attr
)) {
844 ibv_close_device(verbs
);
845 ERROR(errp
, "Could not query initial IB port");
849 if (port_attr
.link_layer
== IBV_LINK_LAYER_INFINIBAND
) {
851 } else if (port_attr
.link_layer
== IBV_LINK_LAYER_ETHERNET
) {
855 ibv_close_device(verbs
);
861 fprintf(stderr
, "WARN: migrations may fail:"
862 " IPv6 over RoCE / iWARP in linux"
863 " is broken. But since you appear to have a"
864 " mixed RoCE / IB environment, be sure to only"
865 " migrate over the IB fabric until the kernel "
866 " fixes the bug.\n");
868 ERROR(errp
, "You only have RoCE / iWARP devices in your systems"
869 " and your management software has specified '[::]'"
870 ", but IPv6 over RoCE / iWARP is not supported in Linux.");
879 * If we have a verbs context, that means that some other than '[::]' was
880 * used by the management software for binding. In which case we can
881 * actually warn the user about a potentially broken kernel.
884 /* IB ports start with 1, not 0 */
885 if (ibv_query_port(verbs
, 1, &port_attr
)) {
886 ERROR(errp
, "Could not query initial IB port");
890 if (port_attr
.link_layer
== IBV_LINK_LAYER_ETHERNET
) {
891 ERROR(errp
, "Linux kernel's RoCE / iWARP does not support IPv6 "
892 "(but patches on linux-rdma in progress)");
902 * Figure out which RDMA device corresponds to the requested IP hostname
903 * Also create the initial connection manager identifiers for opening
906 static int qemu_rdma_resolve_host(RDMAContext
*rdma
, Error
**errp
)
909 struct rdma_addrinfo
*res
;
911 struct rdma_cm_event
*cm_event
;
912 char ip
[40] = "unknown";
913 struct rdma_addrinfo
*e
;
915 if (rdma
->host
== NULL
|| !strcmp(rdma
->host
, "")) {
916 ERROR(errp
, "RDMA hostname has not been set");
920 /* create CM channel */
921 rdma
->channel
= rdma_create_event_channel();
922 if (!rdma
->channel
) {
923 ERROR(errp
, "could not create CM channel");
928 ret
= rdma_create_id(rdma
->channel
, &rdma
->cm_id
, NULL
, RDMA_PS_TCP
);
930 ERROR(errp
, "could not create channel id");
931 goto err_resolve_create_id
;
934 snprintf(port_str
, 16, "%d", rdma
->port
);
937 ret
= rdma_getaddrinfo(rdma
->host
, port_str
, NULL
, &res
);
939 ERROR(errp
, "could not rdma_getaddrinfo address %s", rdma
->host
);
940 goto err_resolve_get_addr
;
943 for (e
= res
; e
!= NULL
; e
= e
->ai_next
) {
944 inet_ntop(e
->ai_family
,
945 &((struct sockaddr_in
*) e
->ai_dst_addr
)->sin_addr
, ip
, sizeof ip
);
946 trace_qemu_rdma_resolve_host_trying(rdma
->host
, ip
);
948 ret
= rdma_resolve_addr(rdma
->cm_id
, NULL
, e
->ai_dst_addr
,
949 RDMA_RESOLVE_TIMEOUT_MS
);
951 if (e
->ai_family
== AF_INET6
) {
952 ret
= qemu_rdma_broken_ipv6_kernel(errp
, rdma
->cm_id
->verbs
);
961 ERROR(errp
, "could not resolve address %s", rdma
->host
);
962 goto err_resolve_get_addr
;
965 qemu_rdma_dump_gid("source_resolve_addr", rdma
->cm_id
);
967 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
969 ERROR(errp
, "could not perform event_addr_resolved");
970 goto err_resolve_get_addr
;
973 if (cm_event
->event
!= RDMA_CM_EVENT_ADDR_RESOLVED
) {
974 ERROR(errp
, "result not equal to event_addr_resolved %s",
975 rdma_event_str(cm_event
->event
));
976 perror("rdma_resolve_addr");
977 rdma_ack_cm_event(cm_event
);
979 goto err_resolve_get_addr
;
981 rdma_ack_cm_event(cm_event
);
984 ret
= rdma_resolve_route(rdma
->cm_id
, RDMA_RESOLVE_TIMEOUT_MS
);
986 ERROR(errp
, "could not resolve rdma route");
987 goto err_resolve_get_addr
;
990 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
992 ERROR(errp
, "could not perform event_route_resolved");
993 goto err_resolve_get_addr
;
995 if (cm_event
->event
!= RDMA_CM_EVENT_ROUTE_RESOLVED
) {
996 ERROR(errp
, "result not equal to event_route_resolved: %s",
997 rdma_event_str(cm_event
->event
));
998 rdma_ack_cm_event(cm_event
);
1000 goto err_resolve_get_addr
;
1002 rdma_ack_cm_event(cm_event
);
1003 rdma
->verbs
= rdma
->cm_id
->verbs
;
1004 qemu_rdma_dump_id("source_resolve_host", rdma
->cm_id
->verbs
);
1005 qemu_rdma_dump_gid("source_resolve_host", rdma
->cm_id
);
1008 err_resolve_get_addr
:
1009 rdma_destroy_id(rdma
->cm_id
);
1011 err_resolve_create_id
:
1012 rdma_destroy_event_channel(rdma
->channel
);
1013 rdma
->channel
= NULL
;
1018 * Create protection domain and completion queues
1020 static int qemu_rdma_alloc_pd_cq(RDMAContext
*rdma
)
1023 rdma
->pd
= ibv_alloc_pd(rdma
->verbs
);
1025 error_report("failed to allocate protection domain");
1029 /* create completion channel */
1030 rdma
->comp_channel
= ibv_create_comp_channel(rdma
->verbs
);
1031 if (!rdma
->comp_channel
) {
1032 error_report("failed to allocate completion channel");
1033 goto err_alloc_pd_cq
;
1037 * Completion queue can be filled by both read and write work requests,
1038 * so must reflect the sum of both possible queue sizes.
1040 rdma
->cq
= ibv_create_cq(rdma
->verbs
, (RDMA_SIGNALED_SEND_MAX
* 3),
1041 NULL
, rdma
->comp_channel
, 0);
1043 error_report("failed to allocate completion queue");
1044 goto err_alloc_pd_cq
;
1051 ibv_dealloc_pd(rdma
->pd
);
1053 if (rdma
->comp_channel
) {
1054 ibv_destroy_comp_channel(rdma
->comp_channel
);
1057 rdma
->comp_channel
= NULL
;
1063 * Create queue pairs.
1065 static int qemu_rdma_alloc_qp(RDMAContext
*rdma
)
1067 struct ibv_qp_init_attr attr
= { 0 };
1070 attr
.cap
.max_send_wr
= RDMA_SIGNALED_SEND_MAX
;
1071 attr
.cap
.max_recv_wr
= 3;
1072 attr
.cap
.max_send_sge
= 1;
1073 attr
.cap
.max_recv_sge
= 1;
1074 attr
.send_cq
= rdma
->cq
;
1075 attr
.recv_cq
= rdma
->cq
;
1076 attr
.qp_type
= IBV_QPT_RC
;
1078 ret
= rdma_create_qp(rdma
->cm_id
, rdma
->pd
, &attr
);
1083 rdma
->qp
= rdma
->cm_id
->qp
;
1087 static int qemu_rdma_reg_whole_ram_blocks(RDMAContext
*rdma
)
1090 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
1092 for (i
= 0; i
< local
->nb_blocks
; i
++) {
1093 local
->block
[i
].mr
=
1094 ibv_reg_mr(rdma
->pd
,
1095 local
->block
[i
].local_host_addr
,
1096 local
->block
[i
].length
,
1097 IBV_ACCESS_LOCAL_WRITE
|
1098 IBV_ACCESS_REMOTE_WRITE
1100 if (!local
->block
[i
].mr
) {
1101 perror("Failed to register local dest ram block!\n");
1104 rdma
->total_registrations
++;
1107 if (i
>= local
->nb_blocks
) {
1111 for (i
--; i
>= 0; i
--) {
1112 ibv_dereg_mr(local
->block
[i
].mr
);
1113 rdma
->total_registrations
--;
1121 * Find the ram block that corresponds to the page requested to be
1122 * transmitted by QEMU.
1124 * Once the block is found, also identify which 'chunk' within that
1125 * block that the page belongs to.
1127 * This search cannot fail or the migration will fail.
1129 static int qemu_rdma_search_ram_block(RDMAContext
*rdma
,
1130 uintptr_t block_offset
,
1133 uint64_t *block_index
,
1134 uint64_t *chunk_index
)
1136 uint64_t current_addr
= block_offset
+ offset
;
1137 RDMALocalBlock
*block
= g_hash_table_lookup(rdma
->blockmap
,
1138 (void *) block_offset
);
1140 assert(current_addr
>= block
->offset
);
1141 assert((current_addr
+ length
) <= (block
->offset
+ block
->length
));
1143 *block_index
= block
->index
;
1144 *chunk_index
= ram_chunk_index(block
->local_host_addr
,
1145 block
->local_host_addr
+ (current_addr
- block
->offset
));
1151 * Register a chunk with IB. If the chunk was already registered
1152 * previously, then skip.
1154 * Also return the keys associated with the registration needed
1155 * to perform the actual RDMA operation.
1157 static int qemu_rdma_register_and_get_keys(RDMAContext
*rdma
,
1158 RDMALocalBlock
*block
, uintptr_t host_addr
,
1159 uint32_t *lkey
, uint32_t *rkey
, int chunk
,
1160 uint8_t *chunk_start
, uint8_t *chunk_end
)
1164 *lkey
= block
->mr
->lkey
;
1167 *rkey
= block
->mr
->rkey
;
1172 /* allocate memory to store chunk MRs */
1174 block
->pmr
= g_new0(struct ibv_mr
*, block
->nb_chunks
);
1178 * If 'rkey', then we're the destination, so grant access to the source.
1180 * If 'lkey', then we're the source VM, so grant access only to ourselves.
1182 if (!block
->pmr
[chunk
]) {
1183 uint64_t len
= chunk_end
- chunk_start
;
1185 trace_qemu_rdma_register_and_get_keys(len
, chunk_start
);
1187 block
->pmr
[chunk
] = ibv_reg_mr(rdma
->pd
,
1189 (rkey
? (IBV_ACCESS_LOCAL_WRITE
|
1190 IBV_ACCESS_REMOTE_WRITE
) : 0));
1192 if (!block
->pmr
[chunk
]) {
1193 perror("Failed to register chunk!");
1194 fprintf(stderr
, "Chunk details: block: %d chunk index %d"
1195 " start %" PRIuPTR
" end %" PRIuPTR
1197 " local %" PRIuPTR
" registrations: %d\n",
1198 block
->index
, chunk
, (uintptr_t)chunk_start
,
1199 (uintptr_t)chunk_end
, host_addr
,
1200 (uintptr_t)block
->local_host_addr
,
1201 rdma
->total_registrations
);
1204 rdma
->total_registrations
++;
1208 *lkey
= block
->pmr
[chunk
]->lkey
;
1211 *rkey
= block
->pmr
[chunk
]->rkey
;
1217 * Register (at connection time) the memory used for control
1220 static int qemu_rdma_reg_control(RDMAContext
*rdma
, int idx
)
1222 rdma
->wr_data
[idx
].control_mr
= ibv_reg_mr(rdma
->pd
,
1223 rdma
->wr_data
[idx
].control
, RDMA_CONTROL_MAX_BUFFER
,
1224 IBV_ACCESS_LOCAL_WRITE
| IBV_ACCESS_REMOTE_WRITE
);
1225 if (rdma
->wr_data
[idx
].control_mr
) {
1226 rdma
->total_registrations
++;
1229 error_report("qemu_rdma_reg_control failed");
1233 const char *print_wrid(int wrid
)
1235 if (wrid
>= RDMA_WRID_RECV_CONTROL
) {
1236 return wrid_desc
[RDMA_WRID_RECV_CONTROL
];
1238 return wrid_desc
[wrid
];
1242 * RDMA requires memory registration (mlock/pinning), but this is not good for
1245 * In preparation for the future where LRU information or workload-specific
1246 * writable writable working set memory access behavior is available to QEMU
1247 * it would be nice to have in place the ability to UN-register/UN-pin
1248 * particular memory regions from the RDMA hardware when it is determine that
1249 * those regions of memory will likely not be accessed again in the near future.
1251 * While we do not yet have such information right now, the following
1252 * compile-time option allows us to perform a non-optimized version of this
1255 * By uncommenting this option, you will cause *all* RDMA transfers to be
1256 * unregistered immediately after the transfer completes on both sides of the
1257 * connection. This has no effect in 'rdma-pin-all' mode, only regular mode.
1259 * This will have a terrible impact on migration performance, so until future
1260 * workload information or LRU information is available, do not attempt to use
1261 * this feature except for basic testing.
1263 //#define RDMA_UNREGISTRATION_EXAMPLE
1266 * Perform a non-optimized memory unregistration after every transfer
1267 * for demonstration purposes, only if pin-all is not requested.
1269 * Potential optimizations:
1270 * 1. Start a new thread to run this function continuously
1272 - and for receipt of unregister messages
1274 * 3. Use workload hints.
1276 static int qemu_rdma_unregister_waiting(RDMAContext
*rdma
)
1278 while (rdma
->unregistrations
[rdma
->unregister_current
]) {
1280 uint64_t wr_id
= rdma
->unregistrations
[rdma
->unregister_current
];
1282 (wr_id
& RDMA_WRID_CHUNK_MASK
) >> RDMA_WRID_CHUNK_SHIFT
;
1284 (wr_id
& RDMA_WRID_BLOCK_MASK
) >> RDMA_WRID_BLOCK_SHIFT
;
1285 RDMALocalBlock
*block
=
1286 &(rdma
->local_ram_blocks
.block
[index
]);
1287 RDMARegister reg
= { .current_index
= index
};
1288 RDMAControlHeader resp
= { .type
= RDMA_CONTROL_UNREGISTER_FINISHED
,
1290 RDMAControlHeader head
= { .len
= sizeof(RDMARegister
),
1291 .type
= RDMA_CONTROL_UNREGISTER_REQUEST
,
1295 trace_qemu_rdma_unregister_waiting_proc(chunk
,
1296 rdma
->unregister_current
);
1298 rdma
->unregistrations
[rdma
->unregister_current
] = 0;
1299 rdma
->unregister_current
++;
1301 if (rdma
->unregister_current
== RDMA_SIGNALED_SEND_MAX
) {
1302 rdma
->unregister_current
= 0;
1307 * Unregistration is speculative (because migration is single-threaded
1308 * and we cannot break the protocol's inifinband message ordering).
1309 * Thus, if the memory is currently being used for transmission,
1310 * then abort the attempt to unregister and try again
1311 * later the next time a completion is received for this memory.
1313 clear_bit(chunk
, block
->unregister_bitmap
);
1315 if (test_bit(chunk
, block
->transit_bitmap
)) {
1316 trace_qemu_rdma_unregister_waiting_inflight(chunk
);
1320 trace_qemu_rdma_unregister_waiting_send(chunk
);
1322 ret
= ibv_dereg_mr(block
->pmr
[chunk
]);
1323 block
->pmr
[chunk
] = NULL
;
1324 block
->remote_keys
[chunk
] = 0;
1327 perror("unregistration chunk failed");
1330 rdma
->total_registrations
--;
1332 reg
.key
.chunk
= chunk
;
1333 register_to_network(rdma
, ®
);
1334 ret
= qemu_rdma_exchange_send(rdma
, &head
, (uint8_t *) ®
,
1340 trace_qemu_rdma_unregister_waiting_complete(chunk
);
1346 static uint64_t qemu_rdma_make_wrid(uint64_t wr_id
, uint64_t index
,
1349 uint64_t result
= wr_id
& RDMA_WRID_TYPE_MASK
;
1351 result
|= (index
<< RDMA_WRID_BLOCK_SHIFT
);
1352 result
|= (chunk
<< RDMA_WRID_CHUNK_SHIFT
);
1358 * Set bit for unregistration in the next iteration.
1359 * We cannot transmit right here, but will unpin later.
1361 static void qemu_rdma_signal_unregister(RDMAContext
*rdma
, uint64_t index
,
1362 uint64_t chunk
, uint64_t wr_id
)
1364 if (rdma
->unregistrations
[rdma
->unregister_next
] != 0) {
1365 error_report("rdma migration: queue is full");
1367 RDMALocalBlock
*block
= &(rdma
->local_ram_blocks
.block
[index
]);
1369 if (!test_and_set_bit(chunk
, block
->unregister_bitmap
)) {
1370 trace_qemu_rdma_signal_unregister_append(chunk
,
1371 rdma
->unregister_next
);
1373 rdma
->unregistrations
[rdma
->unregister_next
++] =
1374 qemu_rdma_make_wrid(wr_id
, index
, chunk
);
1376 if (rdma
->unregister_next
== RDMA_SIGNALED_SEND_MAX
) {
1377 rdma
->unregister_next
= 0;
1380 trace_qemu_rdma_signal_unregister_already(chunk
);
1386 * Consult the connection manager to see a work request
1387 * (of any kind) has completed.
1388 * Return the work request ID that completed.
1390 static uint64_t qemu_rdma_poll(RDMAContext
*rdma
, uint64_t *wr_id_out
,
1397 ret
= ibv_poll_cq(rdma
->cq
, 1, &wc
);
1400 *wr_id_out
= RDMA_WRID_NONE
;
1405 error_report("ibv_poll_cq return %d", ret
);
1409 wr_id
= wc
.wr_id
& RDMA_WRID_TYPE_MASK
;
1411 if (wc
.status
!= IBV_WC_SUCCESS
) {
1412 fprintf(stderr
, "ibv_poll_cq wc.status=%d %s!\n",
1413 wc
.status
, ibv_wc_status_str(wc
.status
));
1414 fprintf(stderr
, "ibv_poll_cq wrid=%s!\n", wrid_desc
[wr_id
]);
1419 if (rdma
->control_ready_expected
&&
1420 (wr_id
>= RDMA_WRID_RECV_CONTROL
)) {
1421 trace_qemu_rdma_poll_recv(wrid_desc
[RDMA_WRID_RECV_CONTROL
],
1422 wr_id
- RDMA_WRID_RECV_CONTROL
, wr_id
, rdma
->nb_sent
);
1423 rdma
->control_ready_expected
= 0;
1426 if (wr_id
== RDMA_WRID_RDMA_WRITE
) {
1428 (wc
.wr_id
& RDMA_WRID_CHUNK_MASK
) >> RDMA_WRID_CHUNK_SHIFT
;
1430 (wc
.wr_id
& RDMA_WRID_BLOCK_MASK
) >> RDMA_WRID_BLOCK_SHIFT
;
1431 RDMALocalBlock
*block
= &(rdma
->local_ram_blocks
.block
[index
]);
1433 trace_qemu_rdma_poll_write(print_wrid(wr_id
), wr_id
, rdma
->nb_sent
,
1434 index
, chunk
, block
->local_host_addr
,
1435 (void *)(uintptr_t)block
->remote_host_addr
);
1437 clear_bit(chunk
, block
->transit_bitmap
);
1439 if (rdma
->nb_sent
> 0) {
1443 if (!rdma
->pin_all
) {
1445 * FYI: If one wanted to signal a specific chunk to be unregistered
1446 * using LRU or workload-specific information, this is the function
1447 * you would call to do so. That chunk would then get asynchronously
1448 * unregistered later.
1450 #ifdef RDMA_UNREGISTRATION_EXAMPLE
1451 qemu_rdma_signal_unregister(rdma
, index
, chunk
, wc
.wr_id
);
1455 trace_qemu_rdma_poll_other(print_wrid(wr_id
), wr_id
, rdma
->nb_sent
);
1458 *wr_id_out
= wc
.wr_id
;
1460 *byte_len
= wc
.byte_len
;
1467 * Block until the next work request has completed.
1469 * First poll to see if a work request has already completed,
1472 * If we encounter completed work requests for IDs other than
1473 * the one we're interested in, then that's generally an error.
1475 * The only exception is actual RDMA Write completions. These
1476 * completions only need to be recorded, but do not actually
1477 * need further processing.
1479 static int qemu_rdma_block_for_wrid(RDMAContext
*rdma
, int wrid_requested
,
1482 int num_cq_events
= 0, ret
= 0;
1485 uint64_t wr_id
= RDMA_WRID_NONE
, wr_id_in
;
1487 if (ibv_req_notify_cq(rdma
->cq
, 0)) {
1491 while (wr_id
!= wrid_requested
) {
1492 ret
= qemu_rdma_poll(rdma
, &wr_id_in
, byte_len
);
1497 wr_id
= wr_id_in
& RDMA_WRID_TYPE_MASK
;
1499 if (wr_id
== RDMA_WRID_NONE
) {
1502 if (wr_id
!= wrid_requested
) {
1503 trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested
),
1504 wrid_requested
, print_wrid(wr_id
), wr_id
);
1508 if (wr_id
== wrid_requested
) {
1514 * Coroutine doesn't start until migration_fd_process_incoming()
1515 * so don't yield unless we know we're running inside of a coroutine.
1517 if (rdma
->migration_started_on_destination
) {
1518 yield_until_fd_readable(rdma
->comp_channel
->fd
);
1521 if (ibv_get_cq_event(rdma
->comp_channel
, &cq
, &cq_ctx
)) {
1522 perror("ibv_get_cq_event");
1523 goto err_block_for_wrid
;
1528 if (ibv_req_notify_cq(cq
, 0)) {
1529 goto err_block_for_wrid
;
1532 while (wr_id
!= wrid_requested
) {
1533 ret
= qemu_rdma_poll(rdma
, &wr_id_in
, byte_len
);
1535 goto err_block_for_wrid
;
1538 wr_id
= wr_id_in
& RDMA_WRID_TYPE_MASK
;
1540 if (wr_id
== RDMA_WRID_NONE
) {
1543 if (wr_id
!= wrid_requested
) {
1544 trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested
),
1545 wrid_requested
, print_wrid(wr_id
), wr_id
);
1549 if (wr_id
== wrid_requested
) {
1550 goto success_block_for_wrid
;
1554 success_block_for_wrid
:
1555 if (num_cq_events
) {
1556 ibv_ack_cq_events(cq
, num_cq_events
);
1561 if (num_cq_events
) {
1562 ibv_ack_cq_events(cq
, num_cq_events
);
1568 * Post a SEND message work request for the control channel
1569 * containing some data and block until the post completes.
1571 static int qemu_rdma_post_send_control(RDMAContext
*rdma
, uint8_t *buf
,
1572 RDMAControlHeader
*head
)
1575 RDMAWorkRequestData
*wr
= &rdma
->wr_data
[RDMA_WRID_CONTROL
];
1576 struct ibv_send_wr
*bad_wr
;
1577 struct ibv_sge sge
= {
1578 .addr
= (uintptr_t)(wr
->control
),
1579 .length
= head
->len
+ sizeof(RDMAControlHeader
),
1580 .lkey
= wr
->control_mr
->lkey
,
1582 struct ibv_send_wr send_wr
= {
1583 .wr_id
= RDMA_WRID_SEND_CONTROL
,
1584 .opcode
= IBV_WR_SEND
,
1585 .send_flags
= IBV_SEND_SIGNALED
,
1590 trace_qemu_rdma_post_send_control(control_desc
[head
->type
]);
1593 * We don't actually need to do a memcpy() in here if we used
1594 * the "sge" properly, but since we're only sending control messages
1595 * (not RAM in a performance-critical path), then its OK for now.
1597 * The copy makes the RDMAControlHeader simpler to manipulate
1598 * for the time being.
1600 assert(head
->len
<= RDMA_CONTROL_MAX_BUFFER
- sizeof(*head
));
1601 memcpy(wr
->control
, head
, sizeof(RDMAControlHeader
));
1602 control_to_network((void *) wr
->control
);
1605 memcpy(wr
->control
+ sizeof(RDMAControlHeader
), buf
, head
->len
);
1609 ret
= ibv_post_send(rdma
->qp
, &send_wr
, &bad_wr
);
1612 error_report("Failed to use post IB SEND for control");
1616 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_SEND_CONTROL
, NULL
);
1618 error_report("rdma migration: send polling control error");
1625 * Post a RECV work request in anticipation of some future receipt
1626 * of data on the control channel.
1628 static int qemu_rdma_post_recv_control(RDMAContext
*rdma
, int idx
)
1630 struct ibv_recv_wr
*bad_wr
;
1631 struct ibv_sge sge
= {
1632 .addr
= (uintptr_t)(rdma
->wr_data
[idx
].control
),
1633 .length
= RDMA_CONTROL_MAX_BUFFER
,
1634 .lkey
= rdma
->wr_data
[idx
].control_mr
->lkey
,
1637 struct ibv_recv_wr recv_wr
= {
1638 .wr_id
= RDMA_WRID_RECV_CONTROL
+ idx
,
1644 if (ibv_post_recv(rdma
->qp
, &recv_wr
, &bad_wr
)) {
1652 * Block and wait for a RECV control channel message to arrive.
1654 static int qemu_rdma_exchange_get_response(RDMAContext
*rdma
,
1655 RDMAControlHeader
*head
, int expecting
, int idx
)
1658 int ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RECV_CONTROL
+ idx
,
1662 error_report("rdma migration: recv polling control error!");
1666 network_to_control((void *) rdma
->wr_data
[idx
].control
);
1667 memcpy(head
, rdma
->wr_data
[idx
].control
, sizeof(RDMAControlHeader
));
1669 trace_qemu_rdma_exchange_get_response_start(control_desc
[expecting
]);
1671 if (expecting
== RDMA_CONTROL_NONE
) {
1672 trace_qemu_rdma_exchange_get_response_none(control_desc
[head
->type
],
1674 } else if (head
->type
!= expecting
|| head
->type
== RDMA_CONTROL_ERROR
) {
1675 error_report("Was expecting a %s (%d) control message"
1676 ", but got: %s (%d), length: %d",
1677 control_desc
[expecting
], expecting
,
1678 control_desc
[head
->type
], head
->type
, head
->len
);
1681 if (head
->len
> RDMA_CONTROL_MAX_BUFFER
- sizeof(*head
)) {
1682 error_report("too long length: %d", head
->len
);
1685 if (sizeof(*head
) + head
->len
!= byte_len
) {
1686 error_report("Malformed length: %d byte_len %d", head
->len
, byte_len
);
1694 * When a RECV work request has completed, the work request's
1695 * buffer is pointed at the header.
1697 * This will advance the pointer to the data portion
1698 * of the control message of the work request's buffer that
1699 * was populated after the work request finished.
1701 static void qemu_rdma_move_header(RDMAContext
*rdma
, int idx
,
1702 RDMAControlHeader
*head
)
1704 rdma
->wr_data
[idx
].control_len
= head
->len
;
1705 rdma
->wr_data
[idx
].control_curr
=
1706 rdma
->wr_data
[idx
].control
+ sizeof(RDMAControlHeader
);
1710 * This is an 'atomic' high-level operation to deliver a single, unified
1711 * control-channel message.
1713 * Additionally, if the user is expecting some kind of reply to this message,
1714 * they can request a 'resp' response message be filled in by posting an
1715 * additional work request on behalf of the user and waiting for an additional
1718 * The extra (optional) response is used during registration to us from having
1719 * to perform an *additional* exchange of message just to provide a response by
1720 * instead piggy-backing on the acknowledgement.
1722 static int qemu_rdma_exchange_send(RDMAContext
*rdma
, RDMAControlHeader
*head
,
1723 uint8_t *data
, RDMAControlHeader
*resp
,
1725 int (*callback
)(RDMAContext
*rdma
))
1730 * Wait until the dest is ready before attempting to deliver the message
1731 * by waiting for a READY message.
1733 if (rdma
->control_ready_expected
) {
1734 RDMAControlHeader resp
;
1735 ret
= qemu_rdma_exchange_get_response(rdma
,
1736 &resp
, RDMA_CONTROL_READY
, RDMA_WRID_READY
);
1743 * If the user is expecting a response, post a WR in anticipation of it.
1746 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_DATA
);
1748 error_report("rdma migration: error posting"
1749 " extra control recv for anticipated result!");
1755 * Post a WR to replace the one we just consumed for the READY message.
1757 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
1759 error_report("rdma migration: error posting first control recv!");
1764 * Deliver the control message that was requested.
1766 ret
= qemu_rdma_post_send_control(rdma
, data
, head
);
1769 error_report("Failed to send control buffer!");
1774 * If we're expecting a response, block and wait for it.
1778 trace_qemu_rdma_exchange_send_issue_callback();
1779 ret
= callback(rdma
);
1785 trace_qemu_rdma_exchange_send_waiting(control_desc
[resp
->type
]);
1786 ret
= qemu_rdma_exchange_get_response(rdma
, resp
,
1787 resp
->type
, RDMA_WRID_DATA
);
1793 qemu_rdma_move_header(rdma
, RDMA_WRID_DATA
, resp
);
1795 *resp_idx
= RDMA_WRID_DATA
;
1797 trace_qemu_rdma_exchange_send_received(control_desc
[resp
->type
]);
1800 rdma
->control_ready_expected
= 1;
1806 * This is an 'atomic' high-level operation to receive a single, unified
1807 * control-channel message.
1809 static int qemu_rdma_exchange_recv(RDMAContext
*rdma
, RDMAControlHeader
*head
,
1812 RDMAControlHeader ready
= {
1814 .type
= RDMA_CONTROL_READY
,
1820 * Inform the source that we're ready to receive a message.
1822 ret
= qemu_rdma_post_send_control(rdma
, NULL
, &ready
);
1825 error_report("Failed to send control buffer!");
1830 * Block and wait for the message.
1832 ret
= qemu_rdma_exchange_get_response(rdma
, head
,
1833 expecting
, RDMA_WRID_READY
);
1839 qemu_rdma_move_header(rdma
, RDMA_WRID_READY
, head
);
1842 * Post a new RECV work request to replace the one we just consumed.
1844 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
1846 error_report("rdma migration: error posting second control recv!");
1854 * Write an actual chunk of memory using RDMA.
1856 * If we're using dynamic registration on the dest-side, we have to
1857 * send a registration command first.
1859 static int qemu_rdma_write_one(QEMUFile
*f
, RDMAContext
*rdma
,
1860 int current_index
, uint64_t current_addr
,
1864 struct ibv_send_wr send_wr
= { 0 };
1865 struct ibv_send_wr
*bad_wr
;
1866 int reg_result_idx
, ret
, count
= 0;
1867 uint64_t chunk
, chunks
;
1868 uint8_t *chunk_start
, *chunk_end
;
1869 RDMALocalBlock
*block
= &(rdma
->local_ram_blocks
.block
[current_index
]);
1871 RDMARegisterResult
*reg_result
;
1872 RDMAControlHeader resp
= { .type
= RDMA_CONTROL_REGISTER_RESULT
};
1873 RDMAControlHeader head
= { .len
= sizeof(RDMARegister
),
1874 .type
= RDMA_CONTROL_REGISTER_REQUEST
,
1879 sge
.addr
= (uintptr_t)(block
->local_host_addr
+
1880 (current_addr
- block
->offset
));
1881 sge
.length
= length
;
1883 chunk
= ram_chunk_index(block
->local_host_addr
,
1884 (uint8_t *)(uintptr_t)sge
.addr
);
1885 chunk_start
= ram_chunk_start(block
, chunk
);
1887 if (block
->is_ram_block
) {
1888 chunks
= length
/ (1UL << RDMA_REG_CHUNK_SHIFT
);
1890 if (chunks
&& ((length
% (1UL << RDMA_REG_CHUNK_SHIFT
)) == 0)) {
1894 chunks
= block
->length
/ (1UL << RDMA_REG_CHUNK_SHIFT
);
1896 if (chunks
&& ((block
->length
% (1UL << RDMA_REG_CHUNK_SHIFT
)) == 0)) {
1901 trace_qemu_rdma_write_one_top(chunks
+ 1,
1903 (1UL << RDMA_REG_CHUNK_SHIFT
) / 1024 / 1024);
1905 chunk_end
= ram_chunk_end(block
, chunk
+ chunks
);
1907 if (!rdma
->pin_all
) {
1908 #ifdef RDMA_UNREGISTRATION_EXAMPLE
1909 qemu_rdma_unregister_waiting(rdma
);
1913 while (test_bit(chunk
, block
->transit_bitmap
)) {
1915 trace_qemu_rdma_write_one_block(count
++, current_index
, chunk
,
1916 sge
.addr
, length
, rdma
->nb_sent
, block
->nb_chunks
);
1918 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RDMA_WRITE
, NULL
);
1921 error_report("Failed to Wait for previous write to complete "
1922 "block %d chunk %" PRIu64
1923 " current %" PRIu64
" len %" PRIu64
" %d",
1924 current_index
, chunk
, sge
.addr
, length
, rdma
->nb_sent
);
1929 if (!rdma
->pin_all
|| !block
->is_ram_block
) {
1930 if (!block
->remote_keys
[chunk
]) {
1932 * This chunk has not yet been registered, so first check to see
1933 * if the entire chunk is zero. If so, tell the other size to
1934 * memset() + madvise() the entire chunk without RDMA.
1937 if (buffer_is_zero((void *)(uintptr_t)sge
.addr
, length
)) {
1938 RDMACompress comp
= {
1939 .offset
= current_addr
,
1941 .block_idx
= current_index
,
1945 head
.len
= sizeof(comp
);
1946 head
.type
= RDMA_CONTROL_COMPRESS
;
1948 trace_qemu_rdma_write_one_zero(chunk
, sge
.length
,
1949 current_index
, current_addr
);
1951 compress_to_network(rdma
, &comp
);
1952 ret
= qemu_rdma_exchange_send(rdma
, &head
,
1953 (uint8_t *) &comp
, NULL
, NULL
, NULL
);
1959 acct_update_position(f
, sge
.length
, true);
1965 * Otherwise, tell other side to register.
1967 reg
.current_index
= current_index
;
1968 if (block
->is_ram_block
) {
1969 reg
.key
.current_addr
= current_addr
;
1971 reg
.key
.chunk
= chunk
;
1973 reg
.chunks
= chunks
;
1975 trace_qemu_rdma_write_one_sendreg(chunk
, sge
.length
, current_index
,
1978 register_to_network(rdma
, ®
);
1979 ret
= qemu_rdma_exchange_send(rdma
, &head
, (uint8_t *) ®
,
1980 &resp
, ®_result_idx
, NULL
);
1985 /* try to overlap this single registration with the one we sent. */
1986 if (qemu_rdma_register_and_get_keys(rdma
, block
, sge
.addr
,
1987 &sge
.lkey
, NULL
, chunk
,
1988 chunk_start
, chunk_end
)) {
1989 error_report("cannot get lkey");
1993 reg_result
= (RDMARegisterResult
*)
1994 rdma
->wr_data
[reg_result_idx
].control_curr
;
1996 network_to_result(reg_result
);
1998 trace_qemu_rdma_write_one_recvregres(block
->remote_keys
[chunk
],
1999 reg_result
->rkey
, chunk
);
2001 block
->remote_keys
[chunk
] = reg_result
->rkey
;
2002 block
->remote_host_addr
= reg_result
->host_addr
;
2004 /* already registered before */
2005 if (qemu_rdma_register_and_get_keys(rdma
, block
, sge
.addr
,
2006 &sge
.lkey
, NULL
, chunk
,
2007 chunk_start
, chunk_end
)) {
2008 error_report("cannot get lkey!");
2013 send_wr
.wr
.rdma
.rkey
= block
->remote_keys
[chunk
];
2015 send_wr
.wr
.rdma
.rkey
= block
->remote_rkey
;
2017 if (qemu_rdma_register_and_get_keys(rdma
, block
, sge
.addr
,
2018 &sge
.lkey
, NULL
, chunk
,
2019 chunk_start
, chunk_end
)) {
2020 error_report("cannot get lkey!");
2026 * Encode the ram block index and chunk within this wrid.
2027 * We will use this information at the time of completion
2028 * to figure out which bitmap to check against and then which
2029 * chunk in the bitmap to look for.
2031 send_wr
.wr_id
= qemu_rdma_make_wrid(RDMA_WRID_RDMA_WRITE
,
2032 current_index
, chunk
);
2034 send_wr
.opcode
= IBV_WR_RDMA_WRITE
;
2035 send_wr
.send_flags
= IBV_SEND_SIGNALED
;
2036 send_wr
.sg_list
= &sge
;
2037 send_wr
.num_sge
= 1;
2038 send_wr
.wr
.rdma
.remote_addr
= block
->remote_host_addr
+
2039 (current_addr
- block
->offset
);
2041 trace_qemu_rdma_write_one_post(chunk
, sge
.addr
, send_wr
.wr
.rdma
.remote_addr
,
2045 * ibv_post_send() does not return negative error numbers,
2046 * per the specification they are positive - no idea why.
2048 ret
= ibv_post_send(rdma
->qp
, &send_wr
, &bad_wr
);
2050 if (ret
== ENOMEM
) {
2051 trace_qemu_rdma_write_one_queue_full();
2052 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RDMA_WRITE
, NULL
);
2054 error_report("rdma migration: failed to make "
2055 "room in full send queue! %d", ret
);
2061 } else if (ret
> 0) {
2062 perror("rdma migration: post rdma write failed");
2066 set_bit(chunk
, block
->transit_bitmap
);
2067 acct_update_position(f
, sge
.length
, false);
2068 rdma
->total_writes
++;
2074 * Push out any unwritten RDMA operations.
2076 * We support sending out multiple chunks at the same time.
2077 * Not all of them need to get signaled in the completion queue.
2079 static int qemu_rdma_write_flush(QEMUFile
*f
, RDMAContext
*rdma
)
2083 if (!rdma
->current_length
) {
2087 ret
= qemu_rdma_write_one(f
, rdma
,
2088 rdma
->current_index
, rdma
->current_addr
, rdma
->current_length
);
2096 trace_qemu_rdma_write_flush(rdma
->nb_sent
);
2099 rdma
->current_length
= 0;
2100 rdma
->current_addr
= 0;
2105 static inline int qemu_rdma_buffer_mergable(RDMAContext
*rdma
,
2106 uint64_t offset
, uint64_t len
)
2108 RDMALocalBlock
*block
;
2112 if (rdma
->current_index
< 0) {
2116 if (rdma
->current_chunk
< 0) {
2120 block
= &(rdma
->local_ram_blocks
.block
[rdma
->current_index
]);
2121 host_addr
= block
->local_host_addr
+ (offset
- block
->offset
);
2122 chunk_end
= ram_chunk_end(block
, rdma
->current_chunk
);
2124 if (rdma
->current_length
== 0) {
2129 * Only merge into chunk sequentially.
2131 if (offset
!= (rdma
->current_addr
+ rdma
->current_length
)) {
2135 if (offset
< block
->offset
) {
2139 if ((offset
+ len
) > (block
->offset
+ block
->length
)) {
2143 if ((host_addr
+ len
) > chunk_end
) {
2151 * We're not actually writing here, but doing three things:
2153 * 1. Identify the chunk the buffer belongs to.
2154 * 2. If the chunk is full or the buffer doesn't belong to the current
2155 * chunk, then start a new chunk and flush() the old chunk.
2156 * 3. To keep the hardware busy, we also group chunks into batches
2157 * and only require that a batch gets acknowledged in the completion
2158 * qeueue instead of each individual chunk.
2160 static int qemu_rdma_write(QEMUFile
*f
, RDMAContext
*rdma
,
2161 uint64_t block_offset
, uint64_t offset
,
2164 uint64_t current_addr
= block_offset
+ offset
;
2165 uint64_t index
= rdma
->current_index
;
2166 uint64_t chunk
= rdma
->current_chunk
;
2169 /* If we cannot merge it, we flush the current buffer first. */
2170 if (!qemu_rdma_buffer_mergable(rdma
, current_addr
, len
)) {
2171 ret
= qemu_rdma_write_flush(f
, rdma
);
2175 rdma
->current_length
= 0;
2176 rdma
->current_addr
= current_addr
;
2178 ret
= qemu_rdma_search_ram_block(rdma
, block_offset
,
2179 offset
, len
, &index
, &chunk
);
2181 error_report("ram block search failed");
2184 rdma
->current_index
= index
;
2185 rdma
->current_chunk
= chunk
;
2189 rdma
->current_length
+= len
;
2191 /* flush it if buffer is too large */
2192 if (rdma
->current_length
>= RDMA_MERGE_MAX
) {
2193 return qemu_rdma_write_flush(f
, rdma
);
2199 static void qemu_rdma_cleanup(RDMAContext
*rdma
)
2201 struct rdma_cm_event
*cm_event
;
2204 if (rdma
->cm_id
&& rdma
->connected
) {
2205 if (rdma
->error_state
) {
2206 RDMAControlHeader head
= { .len
= 0,
2207 .type
= RDMA_CONTROL_ERROR
,
2210 error_report("Early error. Sending error.");
2211 qemu_rdma_post_send_control(rdma
, NULL
, &head
);
2214 ret
= rdma_disconnect(rdma
->cm_id
);
2216 trace_qemu_rdma_cleanup_waiting_for_disconnect();
2217 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
2219 rdma_ack_cm_event(cm_event
);
2222 trace_qemu_rdma_cleanup_disconnect();
2223 rdma
->connected
= false;
2226 g_free(rdma
->dest_blocks
);
2227 rdma
->dest_blocks
= NULL
;
2229 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2230 if (rdma
->wr_data
[idx
].control_mr
) {
2231 rdma
->total_registrations
--;
2232 ibv_dereg_mr(rdma
->wr_data
[idx
].control_mr
);
2234 rdma
->wr_data
[idx
].control_mr
= NULL
;
2237 if (rdma
->local_ram_blocks
.block
) {
2238 while (rdma
->local_ram_blocks
.nb_blocks
) {
2239 rdma_delete_block(rdma
, &rdma
->local_ram_blocks
.block
[0]);
2244 rdma_destroy_qp(rdma
->cm_id
);
2248 ibv_destroy_cq(rdma
->cq
);
2251 if (rdma
->comp_channel
) {
2252 ibv_destroy_comp_channel(rdma
->comp_channel
);
2253 rdma
->comp_channel
= NULL
;
2256 ibv_dealloc_pd(rdma
->pd
);
2260 rdma_destroy_id(rdma
->cm_id
);
2263 if (rdma
->listen_id
) {
2264 rdma_destroy_id(rdma
->listen_id
);
2265 rdma
->listen_id
= NULL
;
2267 if (rdma
->channel
) {
2268 rdma_destroy_event_channel(rdma
->channel
);
2269 rdma
->channel
= NULL
;
2276 static int qemu_rdma_source_init(RDMAContext
*rdma
, Error
**errp
, bool pin_all
)
2279 Error
*local_err
= NULL
, **temp
= &local_err
;
2282 * Will be validated against destination's actual capabilities
2283 * after the connect() completes.
2285 rdma
->pin_all
= pin_all
;
2287 ret
= qemu_rdma_resolve_host(rdma
, temp
);
2289 goto err_rdma_source_init
;
2292 ret
= qemu_rdma_alloc_pd_cq(rdma
);
2294 ERROR(temp
, "rdma migration: error allocating pd and cq! Your mlock()"
2295 " limits may be too low. Please check $ ulimit -a # and "
2296 "search for 'ulimit -l' in the output");
2297 goto err_rdma_source_init
;
2300 ret
= qemu_rdma_alloc_qp(rdma
);
2302 ERROR(temp
, "rdma migration: error allocating qp!");
2303 goto err_rdma_source_init
;
2306 ret
= qemu_rdma_init_ram_blocks(rdma
);
2308 ERROR(temp
, "rdma migration: error initializing ram blocks!");
2309 goto err_rdma_source_init
;
2312 /* Build the hash that maps from offset to RAMBlock */
2313 rdma
->blockmap
= g_hash_table_new(g_direct_hash
, g_direct_equal
);
2314 for (idx
= 0; idx
< rdma
->local_ram_blocks
.nb_blocks
; idx
++) {
2315 g_hash_table_insert(rdma
->blockmap
,
2316 (void *)(uintptr_t)rdma
->local_ram_blocks
.block
[idx
].offset
,
2317 &rdma
->local_ram_blocks
.block
[idx
]);
2320 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2321 ret
= qemu_rdma_reg_control(rdma
, idx
);
2323 ERROR(temp
, "rdma migration: error registering %d control!",
2325 goto err_rdma_source_init
;
2331 err_rdma_source_init
:
2332 error_propagate(errp
, local_err
);
2333 qemu_rdma_cleanup(rdma
);
2337 static int qemu_rdma_connect(RDMAContext
*rdma
, Error
**errp
)
2339 RDMACapabilities cap
= {
2340 .version
= RDMA_CONTROL_VERSION_CURRENT
,
2343 struct rdma_conn_param conn_param
= { .initiator_depth
= 2,
2345 .private_data
= &cap
,
2346 .private_data_len
= sizeof(cap
),
2348 struct rdma_cm_event
*cm_event
;
2352 * Only negotiate the capability with destination if the user
2353 * on the source first requested the capability.
2355 if (rdma
->pin_all
) {
2356 trace_qemu_rdma_connect_pin_all_requested();
2357 cap
.flags
|= RDMA_CAPABILITY_PIN_ALL
;
2360 caps_to_network(&cap
);
2362 ret
= rdma_connect(rdma
->cm_id
, &conn_param
);
2364 perror("rdma_connect");
2365 ERROR(errp
, "connecting to destination!");
2366 goto err_rdma_source_connect
;
2369 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
2371 perror("rdma_get_cm_event after rdma_connect");
2372 ERROR(errp
, "connecting to destination!");
2373 rdma_ack_cm_event(cm_event
);
2374 goto err_rdma_source_connect
;
2377 if (cm_event
->event
!= RDMA_CM_EVENT_ESTABLISHED
) {
2378 perror("rdma_get_cm_event != EVENT_ESTABLISHED after rdma_connect");
2379 ERROR(errp
, "connecting to destination!");
2380 rdma_ack_cm_event(cm_event
);
2381 goto err_rdma_source_connect
;
2383 rdma
->connected
= true;
2385 memcpy(&cap
, cm_event
->param
.conn
.private_data
, sizeof(cap
));
2386 network_to_caps(&cap
);
2389 * Verify that the *requested* capabilities are supported by the destination
2390 * and disable them otherwise.
2392 if (rdma
->pin_all
&& !(cap
.flags
& RDMA_CAPABILITY_PIN_ALL
)) {
2393 ERROR(errp
, "Server cannot support pinning all memory. "
2394 "Will register memory dynamically.");
2395 rdma
->pin_all
= false;
2398 trace_qemu_rdma_connect_pin_all_outcome(rdma
->pin_all
);
2400 rdma_ack_cm_event(cm_event
);
2402 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
2404 ERROR(errp
, "posting second control recv!");
2405 goto err_rdma_source_connect
;
2408 rdma
->control_ready_expected
= 1;
2412 err_rdma_source_connect
:
2413 qemu_rdma_cleanup(rdma
);
2417 static int qemu_rdma_dest_init(RDMAContext
*rdma
, Error
**errp
)
2420 struct rdma_cm_id
*listen_id
;
2421 char ip
[40] = "unknown";
2422 struct rdma_addrinfo
*res
, *e
;
2425 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2426 rdma
->wr_data
[idx
].control_len
= 0;
2427 rdma
->wr_data
[idx
].control_curr
= NULL
;
2430 if (!rdma
->host
|| !rdma
->host
[0]) {
2431 ERROR(errp
, "RDMA host is not set!");
2432 rdma
->error_state
= -EINVAL
;
2435 /* create CM channel */
2436 rdma
->channel
= rdma_create_event_channel();
2437 if (!rdma
->channel
) {
2438 ERROR(errp
, "could not create rdma event channel");
2439 rdma
->error_state
= -EINVAL
;
2444 ret
= rdma_create_id(rdma
->channel
, &listen_id
, NULL
, RDMA_PS_TCP
);
2446 ERROR(errp
, "could not create cm_id!");
2447 goto err_dest_init_create_listen_id
;
2450 snprintf(port_str
, 16, "%d", rdma
->port
);
2451 port_str
[15] = '\0';
2453 ret
= rdma_getaddrinfo(rdma
->host
, port_str
, NULL
, &res
);
2455 ERROR(errp
, "could not rdma_getaddrinfo address %s", rdma
->host
);
2456 goto err_dest_init_bind_addr
;
2459 for (e
= res
; e
!= NULL
; e
= e
->ai_next
) {
2460 inet_ntop(e
->ai_family
,
2461 &((struct sockaddr_in
*) e
->ai_dst_addr
)->sin_addr
, ip
, sizeof ip
);
2462 trace_qemu_rdma_dest_init_trying(rdma
->host
, ip
);
2463 ret
= rdma_bind_addr(listen_id
, e
->ai_dst_addr
);
2467 if (e
->ai_family
== AF_INET6
) {
2468 ret
= qemu_rdma_broken_ipv6_kernel(errp
, listen_id
->verbs
);
2477 ERROR(errp
, "Error: could not rdma_bind_addr!");
2478 goto err_dest_init_bind_addr
;
2481 rdma
->listen_id
= listen_id
;
2482 qemu_rdma_dump_gid("dest_init", listen_id
);
2485 err_dest_init_bind_addr
:
2486 rdma_destroy_id(listen_id
);
2487 err_dest_init_create_listen_id
:
2488 rdma_destroy_event_channel(rdma
->channel
);
2489 rdma
->channel
= NULL
;
2490 rdma
->error_state
= ret
;
2495 static void *qemu_rdma_data_init(const char *host_port
, Error
**errp
)
2497 RDMAContext
*rdma
= NULL
;
2498 InetSocketAddress
*addr
;
2501 rdma
= g_new0(RDMAContext
, 1);
2502 rdma
->current_index
= -1;
2503 rdma
->current_chunk
= -1;
2505 addr
= inet_parse(host_port
, NULL
);
2507 rdma
->port
= atoi(addr
->port
);
2508 rdma
->host
= g_strdup(addr
->host
);
2510 ERROR(errp
, "bad RDMA migration address '%s'", host_port
);
2515 qapi_free_InetSocketAddress(addr
);
2522 * QEMUFile interface to the control channel.
2523 * SEND messages for control only.
2524 * VM's ram is handled with regular RDMA messages.
2526 static ssize_t
qio_channel_rdma_writev(QIOChannel
*ioc
,
2527 const struct iovec
*iov
,
2533 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2534 QEMUFile
*f
= rioc
->file
;
2535 RDMAContext
*rdma
= rioc
->rdma
;
2540 CHECK_ERROR_STATE();
2543 * Push out any writes that
2544 * we're queued up for VM's ram.
2546 ret
= qemu_rdma_write_flush(f
, rdma
);
2548 rdma
->error_state
= ret
;
2552 for (i
= 0; i
< niov
; i
++) {
2553 size_t remaining
= iov
[i
].iov_len
;
2554 uint8_t * data
= (void *)iov
[i
].iov_base
;
2556 RDMAControlHeader head
;
2558 rioc
->len
= MIN(remaining
, RDMA_SEND_INCREMENT
);
2559 remaining
-= rioc
->len
;
2561 head
.len
= rioc
->len
;
2562 head
.type
= RDMA_CONTROL_QEMU_FILE
;
2564 ret
= qemu_rdma_exchange_send(rdma
, &head
, data
, NULL
, NULL
, NULL
);
2567 rdma
->error_state
= ret
;
2579 static size_t qemu_rdma_fill(RDMAContext
*rdma
, uint8_t *buf
,
2580 size_t size
, int idx
)
2584 if (rdma
->wr_data
[idx
].control_len
) {
2585 trace_qemu_rdma_fill(rdma
->wr_data
[idx
].control_len
, size
);
2587 len
= MIN(size
, rdma
->wr_data
[idx
].control_len
);
2588 memcpy(buf
, rdma
->wr_data
[idx
].control_curr
, len
);
2589 rdma
->wr_data
[idx
].control_curr
+= len
;
2590 rdma
->wr_data
[idx
].control_len
-= len
;
2597 * QEMUFile interface to the control channel.
2598 * RDMA links don't use bytestreams, so we have to
2599 * return bytes to QEMUFile opportunistically.
2601 static ssize_t
qio_channel_rdma_readv(QIOChannel
*ioc
,
2602 const struct iovec
*iov
,
2608 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2609 RDMAContext
*rdma
= rioc
->rdma
;
2610 RDMAControlHeader head
;
2615 CHECK_ERROR_STATE();
2617 for (i
= 0; i
< niov
; i
++) {
2618 size_t want
= iov
[i
].iov_len
;
2619 uint8_t *data
= (void *)iov
[i
].iov_base
;
2622 * First, we hold on to the last SEND message we
2623 * were given and dish out the bytes until we run
2626 ret
= qemu_rdma_fill(rioc
->rdma
, data
, want
, 0);
2629 /* Got what we needed, so go to next iovec */
2634 /* If we got any data so far, then don't wait
2635 * for more, just return what we have */
2641 /* We've got nothing at all, so lets wait for
2644 ret
= qemu_rdma_exchange_recv(rdma
, &head
, RDMA_CONTROL_QEMU_FILE
);
2647 rdma
->error_state
= ret
;
2652 * SEND was received with new bytes, now try again.
2654 ret
= qemu_rdma_fill(rioc
->rdma
, data
, want
, 0);
2658 /* Still didn't get enough, so lets just return */
2661 return QIO_CHANNEL_ERR_BLOCK
;
2672 * Block until all the outstanding chunks have been delivered by the hardware.
2674 static int qemu_rdma_drain_cq(QEMUFile
*f
, RDMAContext
*rdma
)
2678 if (qemu_rdma_write_flush(f
, rdma
) < 0) {
2682 while (rdma
->nb_sent
) {
2683 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RDMA_WRITE
, NULL
);
2685 error_report("rdma migration: complete polling error!");
2690 qemu_rdma_unregister_waiting(rdma
);
2696 static int qio_channel_rdma_set_blocking(QIOChannel
*ioc
,
2700 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2701 /* XXX we should make readv/writev actually honour this :-) */
2702 rioc
->blocking
= blocking
;
2707 typedef struct QIOChannelRDMASource QIOChannelRDMASource
;
2708 struct QIOChannelRDMASource
{
2710 QIOChannelRDMA
*rioc
;
2711 GIOCondition condition
;
2715 qio_channel_rdma_source_prepare(GSource
*source
,
2718 QIOChannelRDMASource
*rsource
= (QIOChannelRDMASource
*)source
;
2719 RDMAContext
*rdma
= rsource
->rioc
->rdma
;
2720 GIOCondition cond
= 0;
2723 if (rdma
->wr_data
[0].control_len
) {
2728 return cond
& rsource
->condition
;
2732 qio_channel_rdma_source_check(GSource
*source
)
2734 QIOChannelRDMASource
*rsource
= (QIOChannelRDMASource
*)source
;
2735 RDMAContext
*rdma
= rsource
->rioc
->rdma
;
2736 GIOCondition cond
= 0;
2738 if (rdma
->wr_data
[0].control_len
) {
2743 return cond
& rsource
->condition
;
2747 qio_channel_rdma_source_dispatch(GSource
*source
,
2748 GSourceFunc callback
,
2751 QIOChannelFunc func
= (QIOChannelFunc
)callback
;
2752 QIOChannelRDMASource
*rsource
= (QIOChannelRDMASource
*)source
;
2753 RDMAContext
*rdma
= rsource
->rioc
->rdma
;
2754 GIOCondition cond
= 0;
2756 if (rdma
->wr_data
[0].control_len
) {
2761 return (*func
)(QIO_CHANNEL(rsource
->rioc
),
2762 (cond
& rsource
->condition
),
2767 qio_channel_rdma_source_finalize(GSource
*source
)
2769 QIOChannelRDMASource
*ssource
= (QIOChannelRDMASource
*)source
;
2771 object_unref(OBJECT(ssource
->rioc
));
2774 GSourceFuncs qio_channel_rdma_source_funcs
= {
2775 qio_channel_rdma_source_prepare
,
2776 qio_channel_rdma_source_check
,
2777 qio_channel_rdma_source_dispatch
,
2778 qio_channel_rdma_source_finalize
2781 static GSource
*qio_channel_rdma_create_watch(QIOChannel
*ioc
,
2782 GIOCondition condition
)
2784 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2785 QIOChannelRDMASource
*ssource
;
2788 source
= g_source_new(&qio_channel_rdma_source_funcs
,
2789 sizeof(QIOChannelRDMASource
));
2790 ssource
= (QIOChannelRDMASource
*)source
;
2792 ssource
->rioc
= rioc
;
2793 object_ref(OBJECT(rioc
));
2795 ssource
->condition
= condition
;
2801 static int qio_channel_rdma_close(QIOChannel
*ioc
,
2804 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2805 trace_qemu_rdma_close();
2807 qemu_rdma_cleanup(rioc
->rdma
);
2817 * This means that 'block_offset' is a full virtual address that does not
2818 * belong to a RAMBlock of the virtual machine and instead
2819 * represents a private malloc'd memory area that the caller wishes to
2823 * Offset is an offset to be added to block_offset and used
2824 * to also lookup the corresponding RAMBlock.
2827 * Initiate an transfer this size.
2830 * A 'hint' or 'advice' that means that we wish to speculatively
2831 * and asynchronously unregister this memory. In this case, there is no
2832 * guarantee that the unregister will actually happen, for example,
2833 * if the memory is being actively transmitted. Additionally, the memory
2834 * may be re-registered at any future time if a write within the same
2835 * chunk was requested again, even if you attempted to unregister it
2838 * @size < 0 : TODO, not yet supported
2839 * Unregister the memory NOW. This means that the caller does not
2840 * expect there to be any future RDMA transfers and we just want to clean
2841 * things up. This is used in case the upper layer owns the memory and
2842 * cannot wait for qemu_fclose() to occur.
2844 * @bytes_sent : User-specificed pointer to indicate how many bytes were
2845 * sent. Usually, this will not be more than a few bytes of
2846 * the protocol because most transfers are sent asynchronously.
2848 static size_t qemu_rdma_save_page(QEMUFile
*f
, void *opaque
,
2849 ram_addr_t block_offset
, ram_addr_t offset
,
2850 size_t size
, uint64_t *bytes_sent
)
2852 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
2853 RDMAContext
*rdma
= rioc
->rdma
;
2856 CHECK_ERROR_STATE();
2862 * Add this page to the current 'chunk'. If the chunk
2863 * is full, or the page doen't belong to the current chunk,
2864 * an actual RDMA write will occur and a new chunk will be formed.
2866 ret
= qemu_rdma_write(f
, rdma
, block_offset
, offset
, size
);
2868 error_report("rdma migration: write error! %d", ret
);
2873 * We always return 1 bytes because the RDMA
2874 * protocol is completely asynchronous. We do not yet know
2875 * whether an identified chunk is zero or not because we're
2876 * waiting for other pages to potentially be merged with
2877 * the current chunk. So, we have to call qemu_update_position()
2878 * later on when the actual write occurs.
2884 uint64_t index
, chunk
;
2886 /* TODO: Change QEMUFileOps prototype to be signed: size_t => long
2888 ret = qemu_rdma_drain_cq(f, rdma);
2890 fprintf(stderr, "rdma: failed to synchronously drain"
2891 " completion queue before unregistration.\n");
2897 ret
= qemu_rdma_search_ram_block(rdma
, block_offset
,
2898 offset
, size
, &index
, &chunk
);
2901 error_report("ram block search failed");
2905 qemu_rdma_signal_unregister(rdma
, index
, chunk
, 0);
2908 * TODO: Synchronous, guaranteed unregistration (should not occur during
2909 * fast-path). Otherwise, unregisters will process on the next call to
2910 * qemu_rdma_drain_cq()
2912 qemu_rdma_unregister_waiting(rdma);
2918 * Drain the Completion Queue if possible, but do not block,
2921 * If nothing to poll, the end of the iteration will do this
2922 * again to make sure we don't overflow the request queue.
2925 uint64_t wr_id
, wr_id_in
;
2926 int ret
= qemu_rdma_poll(rdma
, &wr_id_in
, NULL
);
2928 error_report("rdma migration: polling error! %d", ret
);
2932 wr_id
= wr_id_in
& RDMA_WRID_TYPE_MASK
;
2934 if (wr_id
== RDMA_WRID_NONE
) {
2939 return RAM_SAVE_CONTROL_DELAYED
;
2941 rdma
->error_state
= ret
;
2945 static int qemu_rdma_accept(RDMAContext
*rdma
)
2947 RDMACapabilities cap
;
2948 struct rdma_conn_param conn_param
= {
2949 .responder_resources
= 2,
2950 .private_data
= &cap
,
2951 .private_data_len
= sizeof(cap
),
2953 struct rdma_cm_event
*cm_event
;
2954 struct ibv_context
*verbs
;
2958 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
2960 goto err_rdma_dest_wait
;
2963 if (cm_event
->event
!= RDMA_CM_EVENT_CONNECT_REQUEST
) {
2964 rdma_ack_cm_event(cm_event
);
2965 goto err_rdma_dest_wait
;
2968 memcpy(&cap
, cm_event
->param
.conn
.private_data
, sizeof(cap
));
2970 network_to_caps(&cap
);
2972 if (cap
.version
< 1 || cap
.version
> RDMA_CONTROL_VERSION_CURRENT
) {
2973 error_report("Unknown source RDMA version: %d, bailing...",
2975 rdma_ack_cm_event(cm_event
);
2976 goto err_rdma_dest_wait
;
2980 * Respond with only the capabilities this version of QEMU knows about.
2982 cap
.flags
&= known_capabilities
;
2985 * Enable the ones that we do know about.
2986 * Add other checks here as new ones are introduced.
2988 if (cap
.flags
& RDMA_CAPABILITY_PIN_ALL
) {
2989 rdma
->pin_all
= true;
2992 rdma
->cm_id
= cm_event
->id
;
2993 verbs
= cm_event
->id
->verbs
;
2995 rdma_ack_cm_event(cm_event
);
2997 trace_qemu_rdma_accept_pin_state(rdma
->pin_all
);
2999 caps_to_network(&cap
);
3001 trace_qemu_rdma_accept_pin_verbsc(verbs
);
3004 rdma
->verbs
= verbs
;
3005 } else if (rdma
->verbs
!= verbs
) {
3006 error_report("ibv context not matching %p, %p!", rdma
->verbs
,
3008 goto err_rdma_dest_wait
;
3011 qemu_rdma_dump_id("dest_init", verbs
);
3013 ret
= qemu_rdma_alloc_pd_cq(rdma
);
3015 error_report("rdma migration: error allocating pd and cq!");
3016 goto err_rdma_dest_wait
;
3019 ret
= qemu_rdma_alloc_qp(rdma
);
3021 error_report("rdma migration: error allocating qp!");
3022 goto err_rdma_dest_wait
;
3025 ret
= qemu_rdma_init_ram_blocks(rdma
);
3027 error_report("rdma migration: error initializing ram blocks!");
3028 goto err_rdma_dest_wait
;
3031 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
3032 ret
= qemu_rdma_reg_control(rdma
, idx
);
3034 error_report("rdma: error registering %d control", idx
);
3035 goto err_rdma_dest_wait
;
3039 qemu_set_fd_handler(rdma
->channel
->fd
, NULL
, NULL
, NULL
);
3041 ret
= rdma_accept(rdma
->cm_id
, &conn_param
);
3043 error_report("rdma_accept returns %d", ret
);
3044 goto err_rdma_dest_wait
;
3047 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
3049 error_report("rdma_accept get_cm_event failed %d", ret
);
3050 goto err_rdma_dest_wait
;
3053 if (cm_event
->event
!= RDMA_CM_EVENT_ESTABLISHED
) {
3054 error_report("rdma_accept not event established");
3055 rdma_ack_cm_event(cm_event
);
3056 goto err_rdma_dest_wait
;
3059 rdma_ack_cm_event(cm_event
);
3060 rdma
->connected
= true;
3062 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
3064 error_report("rdma migration: error posting second control recv");
3065 goto err_rdma_dest_wait
;
3068 qemu_rdma_dump_gid("dest_connect", rdma
->cm_id
);
3073 rdma
->error_state
= ret
;
3074 qemu_rdma_cleanup(rdma
);
3078 static int dest_ram_sort_func(const void *a
, const void *b
)
3080 unsigned int a_index
= ((const RDMALocalBlock
*)a
)->src_index
;
3081 unsigned int b_index
= ((const RDMALocalBlock
*)b
)->src_index
;
3083 return (a_index
< b_index
) ? -1 : (a_index
!= b_index
);
3087 * During each iteration of the migration, we listen for instructions
3088 * by the source VM to perform dynamic page registrations before they
3089 * can perform RDMA operations.
3091 * We respond with the 'rkey'.
3093 * Keep doing this until the source tells us to stop.
3095 static int qemu_rdma_registration_handle(QEMUFile
*f
, void *opaque
)
3097 RDMAControlHeader reg_resp
= { .len
= sizeof(RDMARegisterResult
),
3098 .type
= RDMA_CONTROL_REGISTER_RESULT
,
3101 RDMAControlHeader unreg_resp
= { .len
= 0,
3102 .type
= RDMA_CONTROL_UNREGISTER_FINISHED
,
3105 RDMAControlHeader blocks
= { .type
= RDMA_CONTROL_RAM_BLOCKS_RESULT
,
3107 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
3108 RDMAContext
*rdma
= rioc
->rdma
;
3109 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
3110 RDMAControlHeader head
;
3111 RDMARegister
*reg
, *registers
;
3113 RDMARegisterResult
*reg_result
;
3114 static RDMARegisterResult results
[RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE
];
3115 RDMALocalBlock
*block
;
3122 CHECK_ERROR_STATE();
3125 trace_qemu_rdma_registration_handle_wait();
3127 ret
= qemu_rdma_exchange_recv(rdma
, &head
, RDMA_CONTROL_NONE
);
3133 if (head
.repeat
> RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE
) {
3134 error_report("rdma: Too many requests in this message (%d)."
3135 "Bailing.", head
.repeat
);
3140 switch (head
.type
) {
3141 case RDMA_CONTROL_COMPRESS
:
3142 comp
= (RDMACompress
*) rdma
->wr_data
[idx
].control_curr
;
3143 network_to_compress(comp
);
3145 trace_qemu_rdma_registration_handle_compress(comp
->length
,
3148 if (comp
->block_idx
>= rdma
->local_ram_blocks
.nb_blocks
) {
3149 error_report("rdma: 'compress' bad block index %u (vs %d)",
3150 (unsigned int)comp
->block_idx
,
3151 rdma
->local_ram_blocks
.nb_blocks
);
3155 block
= &(rdma
->local_ram_blocks
.block
[comp
->block_idx
]);
3157 host_addr
= block
->local_host_addr
+
3158 (comp
->offset
- block
->offset
);
3160 ram_handle_compressed(host_addr
, comp
->value
, comp
->length
);
3163 case RDMA_CONTROL_REGISTER_FINISHED
:
3164 trace_qemu_rdma_registration_handle_finished();
3167 case RDMA_CONTROL_RAM_BLOCKS_REQUEST
:
3168 trace_qemu_rdma_registration_handle_ram_blocks();
3170 /* Sort our local RAM Block list so it's the same as the source,
3171 * we can do this since we've filled in a src_index in the list
3172 * as we received the RAMBlock list earlier.
3174 qsort(rdma
->local_ram_blocks
.block
,
3175 rdma
->local_ram_blocks
.nb_blocks
,
3176 sizeof(RDMALocalBlock
), dest_ram_sort_func
);
3177 if (rdma
->pin_all
) {
3178 ret
= qemu_rdma_reg_whole_ram_blocks(rdma
);
3180 error_report("rdma migration: error dest "
3181 "registering ram blocks");
3187 * Dest uses this to prepare to transmit the RAMBlock descriptions
3188 * to the source VM after connection setup.
3189 * Both sides use the "remote" structure to communicate and update
3190 * their "local" descriptions with what was sent.
3192 for (i
= 0; i
< local
->nb_blocks
; i
++) {
3193 rdma
->dest_blocks
[i
].remote_host_addr
=
3194 (uintptr_t)(local
->block
[i
].local_host_addr
);
3196 if (rdma
->pin_all
) {
3197 rdma
->dest_blocks
[i
].remote_rkey
= local
->block
[i
].mr
->rkey
;
3200 rdma
->dest_blocks
[i
].offset
= local
->block
[i
].offset
;
3201 rdma
->dest_blocks
[i
].length
= local
->block
[i
].length
;
3203 dest_block_to_network(&rdma
->dest_blocks
[i
]);
3204 trace_qemu_rdma_registration_handle_ram_blocks_loop(
3205 local
->block
[i
].block_name
,
3206 local
->block
[i
].offset
,
3207 local
->block
[i
].length
,
3208 local
->block
[i
].local_host_addr
,
3209 local
->block
[i
].src_index
);
3212 blocks
.len
= rdma
->local_ram_blocks
.nb_blocks
3213 * sizeof(RDMADestBlock
);
3216 ret
= qemu_rdma_post_send_control(rdma
,
3217 (uint8_t *) rdma
->dest_blocks
, &blocks
);
3220 error_report("rdma migration: error sending remote info");
3225 case RDMA_CONTROL_REGISTER_REQUEST
:
3226 trace_qemu_rdma_registration_handle_register(head
.repeat
);
3228 reg_resp
.repeat
= head
.repeat
;
3229 registers
= (RDMARegister
*) rdma
->wr_data
[idx
].control_curr
;
3231 for (count
= 0; count
< head
.repeat
; count
++) {
3233 uint8_t *chunk_start
, *chunk_end
;
3235 reg
= ®isters
[count
];
3236 network_to_register(reg
);
3238 reg_result
= &results
[count
];
3240 trace_qemu_rdma_registration_handle_register_loop(count
,
3241 reg
->current_index
, reg
->key
.current_addr
, reg
->chunks
);
3243 if (reg
->current_index
>= rdma
->local_ram_blocks
.nb_blocks
) {
3244 error_report("rdma: 'register' bad block index %u (vs %d)",
3245 (unsigned int)reg
->current_index
,
3246 rdma
->local_ram_blocks
.nb_blocks
);
3250 block
= &(rdma
->local_ram_blocks
.block
[reg
->current_index
]);
3251 if (block
->is_ram_block
) {
3252 if (block
->offset
> reg
->key
.current_addr
) {
3253 error_report("rdma: bad register address for block %s"
3254 " offset: %" PRIx64
" current_addr: %" PRIx64
,
3255 block
->block_name
, block
->offset
,
3256 reg
->key
.current_addr
);
3260 host_addr
= (block
->local_host_addr
+
3261 (reg
->key
.current_addr
- block
->offset
));
3262 chunk
= ram_chunk_index(block
->local_host_addr
,
3263 (uint8_t *) host_addr
);
3265 chunk
= reg
->key
.chunk
;
3266 host_addr
= block
->local_host_addr
+
3267 (reg
->key
.chunk
* (1UL << RDMA_REG_CHUNK_SHIFT
));
3268 /* Check for particularly bad chunk value */
3269 if (host_addr
< (void *)block
->local_host_addr
) {
3270 error_report("rdma: bad chunk for block %s"
3272 block
->block_name
, reg
->key
.chunk
);
3277 chunk_start
= ram_chunk_start(block
, chunk
);
3278 chunk_end
= ram_chunk_end(block
, chunk
+ reg
->chunks
);
3279 if (qemu_rdma_register_and_get_keys(rdma
, block
,
3280 (uintptr_t)host_addr
, NULL
, ®_result
->rkey
,
3281 chunk
, chunk_start
, chunk_end
)) {
3282 error_report("cannot get rkey");
3287 reg_result
->host_addr
= (uintptr_t)block
->local_host_addr
;
3289 trace_qemu_rdma_registration_handle_register_rkey(
3292 result_to_network(reg_result
);
3295 ret
= qemu_rdma_post_send_control(rdma
,
3296 (uint8_t *) results
, ®_resp
);
3299 error_report("Failed to send control buffer");
3303 case RDMA_CONTROL_UNREGISTER_REQUEST
:
3304 trace_qemu_rdma_registration_handle_unregister(head
.repeat
);
3305 unreg_resp
.repeat
= head
.repeat
;
3306 registers
= (RDMARegister
*) rdma
->wr_data
[idx
].control_curr
;
3308 for (count
= 0; count
< head
.repeat
; count
++) {
3309 reg
= ®isters
[count
];
3310 network_to_register(reg
);
3312 trace_qemu_rdma_registration_handle_unregister_loop(count
,
3313 reg
->current_index
, reg
->key
.chunk
);
3315 block
= &(rdma
->local_ram_blocks
.block
[reg
->current_index
]);
3317 ret
= ibv_dereg_mr(block
->pmr
[reg
->key
.chunk
]);
3318 block
->pmr
[reg
->key
.chunk
] = NULL
;
3321 perror("rdma unregistration chunk failed");
3326 rdma
->total_registrations
--;
3328 trace_qemu_rdma_registration_handle_unregister_success(
3332 ret
= qemu_rdma_post_send_control(rdma
, NULL
, &unreg_resp
);
3335 error_report("Failed to send control buffer");
3339 case RDMA_CONTROL_REGISTER_RESULT
:
3340 error_report("Invalid RESULT message at dest.");
3344 error_report("Unknown control message %s", control_desc
[head
.type
]);
3351 rdma
->error_state
= ret
;
3357 * Called via a ram_control_load_hook during the initial RAM load section which
3358 * lists the RAMBlocks by name. This lets us know the order of the RAMBlocks
3360 * We've already built our local RAMBlock list, but not yet sent the list to
3364 rdma_block_notification_handle(QIOChannelRDMA
*rioc
, const char *name
)
3366 RDMAContext
*rdma
= rioc
->rdma
;
3370 /* Find the matching RAMBlock in our local list */
3371 for (curr
= 0; curr
< rdma
->local_ram_blocks
.nb_blocks
; curr
++) {
3372 if (!strcmp(rdma
->local_ram_blocks
.block
[curr
].block_name
, name
)) {
3379 error_report("RAMBlock '%s' not found on destination", name
);
3383 rdma
->local_ram_blocks
.block
[curr
].src_index
= rdma
->next_src_index
;
3384 trace_rdma_block_notification_handle(name
, rdma
->next_src_index
);
3385 rdma
->next_src_index
++;
3390 static int rdma_load_hook(QEMUFile
*f
, void *opaque
, uint64_t flags
, void *data
)
3393 case RAM_CONTROL_BLOCK_REG
:
3394 return rdma_block_notification_handle(opaque
, data
);
3396 case RAM_CONTROL_HOOK
:
3397 return qemu_rdma_registration_handle(f
, opaque
);
3400 /* Shouldn't be called with any other values */
3405 static int qemu_rdma_registration_start(QEMUFile
*f
, void *opaque
,
3406 uint64_t flags
, void *data
)
3408 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
3409 RDMAContext
*rdma
= rioc
->rdma
;
3411 CHECK_ERROR_STATE();
3413 trace_qemu_rdma_registration_start(flags
);
3414 qemu_put_be64(f
, RAM_SAVE_FLAG_HOOK
);
3421 * Inform dest that dynamic registrations are done for now.
3422 * First, flush writes, if any.
3424 static int qemu_rdma_registration_stop(QEMUFile
*f
, void *opaque
,
3425 uint64_t flags
, void *data
)
3427 Error
*local_err
= NULL
, **errp
= &local_err
;
3428 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
3429 RDMAContext
*rdma
= rioc
->rdma
;
3430 RDMAControlHeader head
= { .len
= 0, .repeat
= 1 };
3433 CHECK_ERROR_STATE();
3436 ret
= qemu_rdma_drain_cq(f
, rdma
);
3442 if (flags
== RAM_CONTROL_SETUP
) {
3443 RDMAControlHeader resp
= {.type
= RDMA_CONTROL_RAM_BLOCKS_RESULT
};
3444 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
3445 int reg_result_idx
, i
, nb_dest_blocks
;
3447 head
.type
= RDMA_CONTROL_RAM_BLOCKS_REQUEST
;
3448 trace_qemu_rdma_registration_stop_ram();
3451 * Make sure that we parallelize the pinning on both sides.
3452 * For very large guests, doing this serially takes a really
3453 * long time, so we have to 'interleave' the pinning locally
3454 * with the control messages by performing the pinning on this
3455 * side before we receive the control response from the other
3456 * side that the pinning has completed.
3458 ret
= qemu_rdma_exchange_send(rdma
, &head
, NULL
, &resp
,
3459 ®_result_idx
, rdma
->pin_all
?
3460 qemu_rdma_reg_whole_ram_blocks
: NULL
);
3462 ERROR(errp
, "receiving remote info!");
3466 nb_dest_blocks
= resp
.len
/ sizeof(RDMADestBlock
);
3469 * The protocol uses two different sets of rkeys (mutually exclusive):
3470 * 1. One key to represent the virtual address of the entire ram block.
3471 * (dynamic chunk registration disabled - pin everything with one rkey.)
3472 * 2. One to represent individual chunks within a ram block.
3473 * (dynamic chunk registration enabled - pin individual chunks.)
3475 * Once the capability is successfully negotiated, the destination transmits
3476 * the keys to use (or sends them later) including the virtual addresses
3477 * and then propagates the remote ram block descriptions to his local copy.
3480 if (local
->nb_blocks
!= nb_dest_blocks
) {
3481 ERROR(errp
, "ram blocks mismatch (Number of blocks %d vs %d) "
3482 "Your QEMU command line parameters are probably "
3483 "not identical on both the source and destination.",
3484 local
->nb_blocks
, nb_dest_blocks
);
3485 rdma
->error_state
= -EINVAL
;
3489 qemu_rdma_move_header(rdma
, reg_result_idx
, &resp
);
3490 memcpy(rdma
->dest_blocks
,
3491 rdma
->wr_data
[reg_result_idx
].control_curr
, resp
.len
);
3492 for (i
= 0; i
< nb_dest_blocks
; i
++) {
3493 network_to_dest_block(&rdma
->dest_blocks
[i
]);
3495 /* We require that the blocks are in the same order */
3496 if (rdma
->dest_blocks
[i
].length
!= local
->block
[i
].length
) {
3497 ERROR(errp
, "Block %s/%d has a different length %" PRIu64
3498 "vs %" PRIu64
, local
->block
[i
].block_name
, i
,
3499 local
->block
[i
].length
,
3500 rdma
->dest_blocks
[i
].length
);
3501 rdma
->error_state
= -EINVAL
;
3504 local
->block
[i
].remote_host_addr
=
3505 rdma
->dest_blocks
[i
].remote_host_addr
;
3506 local
->block
[i
].remote_rkey
= rdma
->dest_blocks
[i
].remote_rkey
;
3510 trace_qemu_rdma_registration_stop(flags
);
3512 head
.type
= RDMA_CONTROL_REGISTER_FINISHED
;
3513 ret
= qemu_rdma_exchange_send(rdma
, &head
, NULL
, NULL
, NULL
, NULL
);
3521 rdma
->error_state
= ret
;
3525 static const QEMUFileHooks rdma_read_hooks
= {
3526 .hook_ram_load
= rdma_load_hook
,
3529 static const QEMUFileHooks rdma_write_hooks
= {
3530 .before_ram_iterate
= qemu_rdma_registration_start
,
3531 .after_ram_iterate
= qemu_rdma_registration_stop
,
3532 .save_page
= qemu_rdma_save_page
,
3536 static void qio_channel_rdma_finalize(Object
*obj
)
3538 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(obj
);
3540 qemu_rdma_cleanup(rioc
->rdma
);
3546 static void qio_channel_rdma_class_init(ObjectClass
*klass
,
3547 void *class_data G_GNUC_UNUSED
)
3549 QIOChannelClass
*ioc_klass
= QIO_CHANNEL_CLASS(klass
);
3551 ioc_klass
->io_writev
= qio_channel_rdma_writev
;
3552 ioc_klass
->io_readv
= qio_channel_rdma_readv
;
3553 ioc_klass
->io_set_blocking
= qio_channel_rdma_set_blocking
;
3554 ioc_klass
->io_close
= qio_channel_rdma_close
;
3555 ioc_klass
->io_create_watch
= qio_channel_rdma_create_watch
;
3558 static const TypeInfo qio_channel_rdma_info
= {
3559 .parent
= TYPE_QIO_CHANNEL
,
3560 .name
= TYPE_QIO_CHANNEL_RDMA
,
3561 .instance_size
= sizeof(QIOChannelRDMA
),
3562 .instance_finalize
= qio_channel_rdma_finalize
,
3563 .class_init
= qio_channel_rdma_class_init
,
3566 static void qio_channel_rdma_register_types(void)
3568 type_register_static(&qio_channel_rdma_info
);
3571 type_init(qio_channel_rdma_register_types
);
3573 static QEMUFile
*qemu_fopen_rdma(RDMAContext
*rdma
, const char *mode
)
3575 QIOChannelRDMA
*rioc
;
3577 if (qemu_file_mode_is_not_valid(mode
)) {
3581 rioc
= QIO_CHANNEL_RDMA(object_new(TYPE_QIO_CHANNEL_RDMA
));
3584 if (mode
[0] == 'w') {
3585 rioc
->file
= qemu_fopen_channel_output(QIO_CHANNEL(rioc
));
3586 qemu_file_set_hooks(rioc
->file
, &rdma_write_hooks
);
3588 rioc
->file
= qemu_fopen_channel_input(QIO_CHANNEL(rioc
));
3589 qemu_file_set_hooks(rioc
->file
, &rdma_read_hooks
);
3595 static void rdma_accept_incoming_migration(void *opaque
)
3597 RDMAContext
*rdma
= opaque
;
3600 Error
*local_err
= NULL
, **errp
= &local_err
;
3602 trace_qemu_rdma_accept_incoming_migration();
3603 ret
= qemu_rdma_accept(rdma
);
3606 ERROR(errp
, "RDMA Migration initialization failed!");
3610 trace_qemu_rdma_accept_incoming_migration_accepted();
3612 f
= qemu_fopen_rdma(rdma
, "rb");
3614 ERROR(errp
, "could not qemu_fopen_rdma!");
3615 qemu_rdma_cleanup(rdma
);
3619 rdma
->migration_started_on_destination
= 1;
3620 migration_fd_process_incoming(f
);
3623 void rdma_start_incoming_migration(const char *host_port
, Error
**errp
)
3627 Error
*local_err
= NULL
;
3629 trace_rdma_start_incoming_migration();
3630 rdma
= qemu_rdma_data_init(host_port
, &local_err
);
3636 ret
= qemu_rdma_dest_init(rdma
, &local_err
);
3642 trace_rdma_start_incoming_migration_after_dest_init();
3644 ret
= rdma_listen(rdma
->listen_id
, 5);
3647 ERROR(errp
, "listening on socket!");
3651 trace_rdma_start_incoming_migration_after_rdma_listen();
3653 qemu_set_fd_handler(rdma
->channel
->fd
, rdma_accept_incoming_migration
,
3654 NULL
, (void *)(intptr_t)rdma
);
3657 error_propagate(errp
, local_err
);
3661 void rdma_start_outgoing_migration(void *opaque
,
3662 const char *host_port
, Error
**errp
)
3664 MigrationState
*s
= opaque
;
3665 RDMAContext
*rdma
= qemu_rdma_data_init(host_port
, errp
);
3672 ret
= qemu_rdma_source_init(rdma
, errp
,
3673 s
->enabled_capabilities
[MIGRATION_CAPABILITY_RDMA_PIN_ALL
]);
3679 trace_rdma_start_outgoing_migration_after_rdma_source_init();
3680 ret
= qemu_rdma_connect(rdma
, errp
);
3686 trace_rdma_start_outgoing_migration_after_rdma_connect();
3688 s
->to_dst_file
= qemu_fopen_rdma(rdma
, "wb");
3689 migrate_fd_connect(s
);