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 */
168 static const char *control_desc
[] = {
169 [RDMA_CONTROL_NONE
] = "NONE",
170 [RDMA_CONTROL_ERROR
] = "ERROR",
171 [RDMA_CONTROL_READY
] = "READY",
172 [RDMA_CONTROL_QEMU_FILE
] = "QEMU FILE",
173 [RDMA_CONTROL_RAM_BLOCKS_REQUEST
] = "RAM BLOCKS REQUEST",
174 [RDMA_CONTROL_RAM_BLOCKS_RESULT
] = "RAM BLOCKS RESULT",
175 [RDMA_CONTROL_COMPRESS
] = "COMPRESS",
176 [RDMA_CONTROL_REGISTER_REQUEST
] = "REGISTER REQUEST",
177 [RDMA_CONTROL_REGISTER_RESULT
] = "REGISTER RESULT",
178 [RDMA_CONTROL_REGISTER_FINISHED
] = "REGISTER FINISHED",
179 [RDMA_CONTROL_UNREGISTER_REQUEST
] = "UNREGISTER REQUEST",
180 [RDMA_CONTROL_UNREGISTER_FINISHED
] = "UNREGISTER FINISHED",
184 * Memory and MR structures used to represent an IB Send/Recv work request.
185 * This is *not* used for RDMA writes, only IB Send/Recv.
188 uint8_t control
[RDMA_CONTROL_MAX_BUFFER
]; /* actual buffer to register */
189 struct ibv_mr
*control_mr
; /* registration metadata */
190 size_t control_len
; /* length of the message */
191 uint8_t *control_curr
; /* start of unconsumed bytes */
192 } RDMAWorkRequestData
;
195 * Negotiate RDMA capabilities during connection-setup time.
202 static void caps_to_network(RDMACapabilities
*cap
)
204 cap
->version
= htonl(cap
->version
);
205 cap
->flags
= htonl(cap
->flags
);
208 static void network_to_caps(RDMACapabilities
*cap
)
210 cap
->version
= ntohl(cap
->version
);
211 cap
->flags
= ntohl(cap
->flags
);
215 * Representation of a RAMBlock from an RDMA perspective.
216 * This is not transmitted, only local.
217 * This and subsequent structures cannot be linked lists
218 * because we're using a single IB message to transmit
219 * the information. It's small anyway, so a list is overkill.
221 typedef struct RDMALocalBlock
{
223 uint8_t *local_host_addr
; /* local virtual address */
224 uint64_t remote_host_addr
; /* remote virtual address */
227 struct ibv_mr
**pmr
; /* MRs for chunk-level registration */
228 struct ibv_mr
*mr
; /* MR for non-chunk-level registration */
229 uint32_t *remote_keys
; /* rkeys for chunk-level registration */
230 uint32_t remote_rkey
; /* rkeys for non-chunk-level registration */
231 int index
; /* which block are we */
232 unsigned int src_index
; /* (Only used on dest) */
235 unsigned long *transit_bitmap
;
236 unsigned long *unregister_bitmap
;
240 * Also represents a RAMblock, but only on the dest.
241 * This gets transmitted by the dest during connection-time
242 * to the source VM and then is used to populate the
243 * corresponding RDMALocalBlock with
244 * the information needed to perform the actual RDMA.
246 typedef struct QEMU_PACKED RDMADestBlock
{
247 uint64_t remote_host_addr
;
250 uint32_t remote_rkey
;
254 static uint64_t htonll(uint64_t v
)
256 union { uint32_t lv
[2]; uint64_t llv
; } u
;
257 u
.lv
[0] = htonl(v
>> 32);
258 u
.lv
[1] = htonl(v
& 0xFFFFFFFFULL
);
262 static uint64_t ntohll(uint64_t v
) {
263 union { uint32_t lv
[2]; uint64_t llv
; } u
;
265 return ((uint64_t)ntohl(u
.lv
[0]) << 32) | (uint64_t) ntohl(u
.lv
[1]);
268 static void dest_block_to_network(RDMADestBlock
*db
)
270 db
->remote_host_addr
= htonll(db
->remote_host_addr
);
271 db
->offset
= htonll(db
->offset
);
272 db
->length
= htonll(db
->length
);
273 db
->remote_rkey
= htonl(db
->remote_rkey
);
276 static void network_to_dest_block(RDMADestBlock
*db
)
278 db
->remote_host_addr
= ntohll(db
->remote_host_addr
);
279 db
->offset
= ntohll(db
->offset
);
280 db
->length
= ntohll(db
->length
);
281 db
->remote_rkey
= ntohl(db
->remote_rkey
);
285 * Virtual address of the above structures used for transmitting
286 * the RAMBlock descriptions at connection-time.
287 * This structure is *not* transmitted.
289 typedef struct RDMALocalBlocks
{
291 bool init
; /* main memory init complete */
292 RDMALocalBlock
*block
;
296 * Main data structure for RDMA state.
297 * While there is only one copy of this structure being allocated right now,
298 * this is the place where one would start if you wanted to consider
299 * having more than one RDMA connection open at the same time.
301 typedef struct RDMAContext
{
305 RDMAWorkRequestData wr_data
[RDMA_WRID_MAX
];
308 * This is used by *_exchange_send() to figure out whether or not
309 * the initial "READY" message has already been received or not.
310 * This is because other functions may potentially poll() and detect
311 * the READY message before send() does, in which case we need to
312 * know if it completed.
314 int control_ready_expected
;
316 /* number of outstanding writes */
319 /* store info about current buffer so that we can
320 merge it with future sends */
321 uint64_t current_addr
;
322 uint64_t current_length
;
323 /* index of ram block the current buffer belongs to */
325 /* index of the chunk in the current ram block */
331 * infiniband-specific variables for opening the device
332 * and maintaining connection state and so forth.
334 * cm_id also has ibv_context, rdma_event_channel, and ibv_qp in
335 * cm_id->verbs, cm_id->channel, and cm_id->qp.
337 struct rdma_cm_id
*cm_id
; /* connection manager ID */
338 struct rdma_cm_id
*listen_id
;
341 struct ibv_context
*verbs
;
342 struct rdma_event_channel
*channel
;
343 struct ibv_qp
*qp
; /* queue pair */
344 struct ibv_comp_channel
*comp_channel
; /* completion channel */
345 struct ibv_pd
*pd
; /* protection domain */
346 struct ibv_cq
*cq
; /* completion queue */
349 * If a previous write failed (perhaps because of a failed
350 * memory registration, then do not attempt any future work
351 * and remember the error state.
358 * Description of ram blocks used throughout the code.
360 RDMALocalBlocks local_ram_blocks
;
361 RDMADestBlock
*dest_blocks
;
363 /* Index of the next RAMBlock received during block registration */
364 unsigned int next_src_index
;
367 * Migration on *destination* started.
368 * Then use coroutine yield function.
369 * Source runs in a thread, so we don't care.
371 int migration_started_on_destination
;
373 int total_registrations
;
376 int unregister_current
, unregister_next
;
377 uint64_t unregistrations
[RDMA_SIGNALED_SEND_MAX
];
379 GHashTable
*blockmap
;
382 #define TYPE_QIO_CHANNEL_RDMA "qio-channel-rdma"
383 #define QIO_CHANNEL_RDMA(obj) \
384 OBJECT_CHECK(QIOChannelRDMA, (obj), TYPE_QIO_CHANNEL_RDMA)
386 typedef struct QIOChannelRDMA QIOChannelRDMA
;
389 struct QIOChannelRDMA
{
394 bool blocking
; /* XXX we don't actually honour this yet */
398 * Main structure for IB Send/Recv control messages.
399 * This gets prepended at the beginning of every Send/Recv.
401 typedef struct QEMU_PACKED
{
402 uint32_t len
; /* Total length of data portion */
403 uint32_t type
; /* which control command to perform */
404 uint32_t repeat
; /* number of commands in data portion of same type */
408 static void control_to_network(RDMAControlHeader
*control
)
410 control
->type
= htonl(control
->type
);
411 control
->len
= htonl(control
->len
);
412 control
->repeat
= htonl(control
->repeat
);
415 static void network_to_control(RDMAControlHeader
*control
)
417 control
->type
= ntohl(control
->type
);
418 control
->len
= ntohl(control
->len
);
419 control
->repeat
= ntohl(control
->repeat
);
423 * Register a single Chunk.
424 * Information sent by the source VM to inform the dest
425 * to register an single chunk of memory before we can perform
426 * the actual RDMA operation.
428 typedef struct QEMU_PACKED
{
430 uint64_t current_addr
; /* offset into the ram_addr_t space */
431 uint64_t chunk
; /* chunk to lookup if unregistering */
433 uint32_t current_index
; /* which ramblock the chunk belongs to */
435 uint64_t chunks
; /* how many sequential chunks to register */
438 static void register_to_network(RDMAContext
*rdma
, RDMARegister
*reg
)
440 RDMALocalBlock
*local_block
;
441 local_block
= &rdma
->local_ram_blocks
.block
[reg
->current_index
];
443 if (local_block
->is_ram_block
) {
445 * current_addr as passed in is an address in the local ram_addr_t
446 * space, we need to translate this for the destination
448 reg
->key
.current_addr
-= local_block
->offset
;
449 reg
->key
.current_addr
+= rdma
->dest_blocks
[reg
->current_index
].offset
;
451 reg
->key
.current_addr
= htonll(reg
->key
.current_addr
);
452 reg
->current_index
= htonl(reg
->current_index
);
453 reg
->chunks
= htonll(reg
->chunks
);
456 static void network_to_register(RDMARegister
*reg
)
458 reg
->key
.current_addr
= ntohll(reg
->key
.current_addr
);
459 reg
->current_index
= ntohl(reg
->current_index
);
460 reg
->chunks
= ntohll(reg
->chunks
);
463 typedef struct QEMU_PACKED
{
464 uint32_t value
; /* if zero, we will madvise() */
465 uint32_t block_idx
; /* which ram block index */
466 uint64_t offset
; /* Address in remote ram_addr_t space */
467 uint64_t length
; /* length of the chunk */
470 static void compress_to_network(RDMAContext
*rdma
, RDMACompress
*comp
)
472 comp
->value
= htonl(comp
->value
);
474 * comp->offset as passed in is an address in the local ram_addr_t
475 * space, we need to translate this for the destination
477 comp
->offset
-= rdma
->local_ram_blocks
.block
[comp
->block_idx
].offset
;
478 comp
->offset
+= rdma
->dest_blocks
[comp
->block_idx
].offset
;
479 comp
->block_idx
= htonl(comp
->block_idx
);
480 comp
->offset
= htonll(comp
->offset
);
481 comp
->length
= htonll(comp
->length
);
484 static void network_to_compress(RDMACompress
*comp
)
486 comp
->value
= ntohl(comp
->value
);
487 comp
->block_idx
= ntohl(comp
->block_idx
);
488 comp
->offset
= ntohll(comp
->offset
);
489 comp
->length
= ntohll(comp
->length
);
493 * The result of the dest's memory registration produces an "rkey"
494 * which the source VM must reference in order to perform
495 * the RDMA operation.
497 typedef struct QEMU_PACKED
{
501 } RDMARegisterResult
;
503 static void result_to_network(RDMARegisterResult
*result
)
505 result
->rkey
= htonl(result
->rkey
);
506 result
->host_addr
= htonll(result
->host_addr
);
509 static void network_to_result(RDMARegisterResult
*result
)
511 result
->rkey
= ntohl(result
->rkey
);
512 result
->host_addr
= ntohll(result
->host_addr
);
515 const char *print_wrid(int wrid
);
516 static int qemu_rdma_exchange_send(RDMAContext
*rdma
, RDMAControlHeader
*head
,
517 uint8_t *data
, RDMAControlHeader
*resp
,
519 int (*callback
)(RDMAContext
*rdma
));
521 static inline uint64_t ram_chunk_index(const uint8_t *start
,
524 return ((uintptr_t) host
- (uintptr_t) start
) >> RDMA_REG_CHUNK_SHIFT
;
527 static inline uint8_t *ram_chunk_start(const RDMALocalBlock
*rdma_ram_block
,
530 return (uint8_t *)(uintptr_t)(rdma_ram_block
->local_host_addr
+
531 (i
<< RDMA_REG_CHUNK_SHIFT
));
534 static inline uint8_t *ram_chunk_end(const RDMALocalBlock
*rdma_ram_block
,
537 uint8_t *result
= ram_chunk_start(rdma_ram_block
, i
) +
538 (1UL << RDMA_REG_CHUNK_SHIFT
);
540 if (result
> (rdma_ram_block
->local_host_addr
+ rdma_ram_block
->length
)) {
541 result
= rdma_ram_block
->local_host_addr
+ rdma_ram_block
->length
;
547 static int rdma_add_block(RDMAContext
*rdma
, const char *block_name
,
549 ram_addr_t block_offset
, uint64_t length
)
551 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
552 RDMALocalBlock
*block
;
553 RDMALocalBlock
*old
= local
->block
;
555 local
->block
= g_new0(RDMALocalBlock
, local
->nb_blocks
+ 1);
557 if (local
->nb_blocks
) {
560 if (rdma
->blockmap
) {
561 for (x
= 0; x
< local
->nb_blocks
; x
++) {
562 g_hash_table_remove(rdma
->blockmap
,
563 (void *)(uintptr_t)old
[x
].offset
);
564 g_hash_table_insert(rdma
->blockmap
,
565 (void *)(uintptr_t)old
[x
].offset
,
569 memcpy(local
->block
, old
, sizeof(RDMALocalBlock
) * local
->nb_blocks
);
573 block
= &local
->block
[local
->nb_blocks
];
575 block
->block_name
= g_strdup(block_name
);
576 block
->local_host_addr
= host_addr
;
577 block
->offset
= block_offset
;
578 block
->length
= length
;
579 block
->index
= local
->nb_blocks
;
580 block
->src_index
= ~0U; /* Filled in by the receipt of the block list */
581 block
->nb_chunks
= ram_chunk_index(host_addr
, host_addr
+ length
) + 1UL;
582 block
->transit_bitmap
= bitmap_new(block
->nb_chunks
);
583 bitmap_clear(block
->transit_bitmap
, 0, block
->nb_chunks
);
584 block
->unregister_bitmap
= bitmap_new(block
->nb_chunks
);
585 bitmap_clear(block
->unregister_bitmap
, 0, block
->nb_chunks
);
586 block
->remote_keys
= g_new0(uint32_t, block
->nb_chunks
);
588 block
->is_ram_block
= local
->init
? false : true;
590 if (rdma
->blockmap
) {
591 g_hash_table_insert(rdma
->blockmap
, (void *)(uintptr_t)block_offset
, block
);
594 trace_rdma_add_block(block_name
, local
->nb_blocks
,
595 (uintptr_t) block
->local_host_addr
,
596 block
->offset
, block
->length
,
597 (uintptr_t) (block
->local_host_addr
+ block
->length
),
598 BITS_TO_LONGS(block
->nb_chunks
) *
599 sizeof(unsigned long) * 8,
608 * Memory regions need to be registered with the device and queue pairs setup
609 * in advanced before the migration starts. This tells us where the RAM blocks
610 * are so that we can register them individually.
612 static int qemu_rdma_init_one_block(const char *block_name
, void *host_addr
,
613 ram_addr_t block_offset
, ram_addr_t length
, void *opaque
)
615 return rdma_add_block(opaque
, block_name
, host_addr
, block_offset
, length
);
619 * Identify the RAMBlocks and their quantity. They will be references to
620 * identify chunk boundaries inside each RAMBlock and also be referenced
621 * during dynamic page registration.
623 static int qemu_rdma_init_ram_blocks(RDMAContext
*rdma
)
625 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
627 assert(rdma
->blockmap
== NULL
);
628 memset(local
, 0, sizeof *local
);
629 qemu_ram_foreach_block(qemu_rdma_init_one_block
, rdma
);
630 trace_qemu_rdma_init_ram_blocks(local
->nb_blocks
);
631 rdma
->dest_blocks
= g_new0(RDMADestBlock
,
632 rdma
->local_ram_blocks
.nb_blocks
);
638 * Note: If used outside of cleanup, the caller must ensure that the destination
639 * block structures are also updated
641 static int rdma_delete_block(RDMAContext
*rdma
, RDMALocalBlock
*block
)
643 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
644 RDMALocalBlock
*old
= local
->block
;
647 if (rdma
->blockmap
) {
648 g_hash_table_remove(rdma
->blockmap
, (void *)(uintptr_t)block
->offset
);
653 for (j
= 0; j
< block
->nb_chunks
; j
++) {
654 if (!block
->pmr
[j
]) {
657 ibv_dereg_mr(block
->pmr
[j
]);
658 rdma
->total_registrations
--;
665 ibv_dereg_mr(block
->mr
);
666 rdma
->total_registrations
--;
670 g_free(block
->transit_bitmap
);
671 block
->transit_bitmap
= NULL
;
673 g_free(block
->unregister_bitmap
);
674 block
->unregister_bitmap
= NULL
;
676 g_free(block
->remote_keys
);
677 block
->remote_keys
= NULL
;
679 g_free(block
->block_name
);
680 block
->block_name
= NULL
;
682 if (rdma
->blockmap
) {
683 for (x
= 0; x
< local
->nb_blocks
; x
++) {
684 g_hash_table_remove(rdma
->blockmap
,
685 (void *)(uintptr_t)old
[x
].offset
);
689 if (local
->nb_blocks
> 1) {
691 local
->block
= g_new0(RDMALocalBlock
, local
->nb_blocks
- 1);
694 memcpy(local
->block
, old
, sizeof(RDMALocalBlock
) * block
->index
);
697 if (block
->index
< (local
->nb_blocks
- 1)) {
698 memcpy(local
->block
+ block
->index
, old
+ (block
->index
+ 1),
699 sizeof(RDMALocalBlock
) *
700 (local
->nb_blocks
- (block
->index
+ 1)));
703 assert(block
== local
->block
);
707 trace_rdma_delete_block(block
, (uintptr_t)block
->local_host_addr
,
708 block
->offset
, block
->length
,
709 (uintptr_t)(block
->local_host_addr
+ block
->length
),
710 BITS_TO_LONGS(block
->nb_chunks
) *
711 sizeof(unsigned long) * 8, block
->nb_chunks
);
717 if (local
->nb_blocks
&& rdma
->blockmap
) {
718 for (x
= 0; x
< local
->nb_blocks
; x
++) {
719 g_hash_table_insert(rdma
->blockmap
,
720 (void *)(uintptr_t)local
->block
[x
].offset
,
729 * Put in the log file which RDMA device was opened and the details
730 * associated with that device.
732 static void qemu_rdma_dump_id(const char *who
, struct ibv_context
*verbs
)
734 struct ibv_port_attr port
;
736 if (ibv_query_port(verbs
, 1, &port
)) {
737 error_report("Failed to query port information");
741 printf("%s RDMA Device opened: kernel name %s "
742 "uverbs device name %s, "
743 "infiniband_verbs class device path %s, "
744 "infiniband class device path %s, "
745 "transport: (%d) %s\n",
748 verbs
->device
->dev_name
,
749 verbs
->device
->dev_path
,
750 verbs
->device
->ibdev_path
,
752 (port
.link_layer
== IBV_LINK_LAYER_INFINIBAND
) ? "Infiniband" :
753 ((port
.link_layer
== IBV_LINK_LAYER_ETHERNET
)
754 ? "Ethernet" : "Unknown"));
758 * Put in the log file the RDMA gid addressing information,
759 * useful for folks who have trouble understanding the
760 * RDMA device hierarchy in the kernel.
762 static void qemu_rdma_dump_gid(const char *who
, struct rdma_cm_id
*id
)
766 inet_ntop(AF_INET6
, &id
->route
.addr
.addr
.ibaddr
.sgid
, sgid
, sizeof sgid
);
767 inet_ntop(AF_INET6
, &id
->route
.addr
.addr
.ibaddr
.dgid
, dgid
, sizeof dgid
);
768 trace_qemu_rdma_dump_gid(who
, sgid
, dgid
);
772 * As of now, IPv6 over RoCE / iWARP is not supported by linux.
773 * We will try the next addrinfo struct, and fail if there are
774 * no other valid addresses to bind against.
776 * If user is listening on '[::]', then we will not have a opened a device
777 * yet and have no way of verifying if the device is RoCE or not.
779 * In this case, the source VM will throw an error for ALL types of
780 * connections (both IPv4 and IPv6) if the destination machine does not have
781 * a regular infiniband network available for use.
783 * The only way to guarantee that an error is thrown for broken kernels is
784 * for the management software to choose a *specific* interface at bind time
785 * and validate what time of hardware it is.
787 * Unfortunately, this puts the user in a fix:
789 * If the source VM connects with an IPv4 address without knowing that the
790 * destination has bound to '[::]' the migration will unconditionally fail
791 * unless the management software is explicitly listening on the IPv4
792 * address while using a RoCE-based device.
794 * If the source VM connects with an IPv6 address, then we're OK because we can
795 * throw an error on the source (and similarly on the destination).
797 * But in mixed environments, this will be broken for a while until it is fixed
800 * We do provide a *tiny* bit of help in this function: We can list all of the
801 * devices in the system and check to see if all the devices are RoCE or
804 * If we detect that we have a *pure* RoCE environment, then we can safely
805 * thrown an error even if the management software has specified '[::]' as the
808 * However, if there is are multiple hetergeneous devices, then we cannot make
809 * this assumption and the user just has to be sure they know what they are
812 * Patches are being reviewed on linux-rdma.
814 static int qemu_rdma_broken_ipv6_kernel(struct ibv_context
*verbs
, Error
**errp
)
816 struct ibv_port_attr port_attr
;
818 /* This bug only exists in linux, to our knowledge. */
822 * Verbs are only NULL if management has bound to '[::]'.
824 * Let's iterate through all the devices and see if there any pure IB
825 * devices (non-ethernet).
827 * If not, then we can safely proceed with the migration.
828 * Otherwise, there are no guarantees until the bug is fixed in linux.
832 struct ibv_device
** dev_list
= ibv_get_device_list(&num_devices
);
833 bool roce_found
= false;
834 bool ib_found
= false;
836 for (x
= 0; x
< num_devices
; x
++) {
837 verbs
= ibv_open_device(dev_list
[x
]);
839 if (errno
== EPERM
) {
846 if (ibv_query_port(verbs
, 1, &port_attr
)) {
847 ibv_close_device(verbs
);
848 ERROR(errp
, "Could not query initial IB port");
852 if (port_attr
.link_layer
== IBV_LINK_LAYER_INFINIBAND
) {
854 } else if (port_attr
.link_layer
== IBV_LINK_LAYER_ETHERNET
) {
858 ibv_close_device(verbs
);
864 fprintf(stderr
, "WARN: migrations may fail:"
865 " IPv6 over RoCE / iWARP in linux"
866 " is broken. But since you appear to have a"
867 " mixed RoCE / IB environment, be sure to only"
868 " migrate over the IB fabric until the kernel "
869 " fixes the bug.\n");
871 ERROR(errp
, "You only have RoCE / iWARP devices in your systems"
872 " and your management software has specified '[::]'"
873 ", but IPv6 over RoCE / iWARP is not supported in Linux.");
882 * If we have a verbs context, that means that some other than '[::]' was
883 * used by the management software for binding. In which case we can
884 * actually warn the user about a potentially broken kernel.
887 /* IB ports start with 1, not 0 */
888 if (ibv_query_port(verbs
, 1, &port_attr
)) {
889 ERROR(errp
, "Could not query initial IB port");
893 if (port_attr
.link_layer
== IBV_LINK_LAYER_ETHERNET
) {
894 ERROR(errp
, "Linux kernel's RoCE / iWARP does not support IPv6 "
895 "(but patches on linux-rdma in progress)");
905 * Figure out which RDMA device corresponds to the requested IP hostname
906 * Also create the initial connection manager identifiers for opening
909 static int qemu_rdma_resolve_host(RDMAContext
*rdma
, Error
**errp
)
912 struct rdma_addrinfo
*res
;
914 struct rdma_cm_event
*cm_event
;
915 char ip
[40] = "unknown";
916 struct rdma_addrinfo
*e
;
918 if (rdma
->host
== NULL
|| !strcmp(rdma
->host
, "")) {
919 ERROR(errp
, "RDMA hostname has not been set");
923 /* create CM channel */
924 rdma
->channel
= rdma_create_event_channel();
925 if (!rdma
->channel
) {
926 ERROR(errp
, "could not create CM channel");
931 ret
= rdma_create_id(rdma
->channel
, &rdma
->cm_id
, NULL
, RDMA_PS_TCP
);
933 ERROR(errp
, "could not create channel id");
934 goto err_resolve_create_id
;
937 snprintf(port_str
, 16, "%d", rdma
->port
);
940 ret
= rdma_getaddrinfo(rdma
->host
, port_str
, NULL
, &res
);
942 ERROR(errp
, "could not rdma_getaddrinfo address %s", rdma
->host
);
943 goto err_resolve_get_addr
;
946 for (e
= res
; e
!= NULL
; e
= e
->ai_next
) {
947 inet_ntop(e
->ai_family
,
948 &((struct sockaddr_in
*) e
->ai_dst_addr
)->sin_addr
, ip
, sizeof ip
);
949 trace_qemu_rdma_resolve_host_trying(rdma
->host
, ip
);
951 ret
= rdma_resolve_addr(rdma
->cm_id
, NULL
, e
->ai_dst_addr
,
952 RDMA_RESOLVE_TIMEOUT_MS
);
954 if (e
->ai_family
== AF_INET6
) {
955 ret
= qemu_rdma_broken_ipv6_kernel(rdma
->cm_id
->verbs
, errp
);
964 ERROR(errp
, "could not resolve address %s", rdma
->host
);
965 goto err_resolve_get_addr
;
968 qemu_rdma_dump_gid("source_resolve_addr", rdma
->cm_id
);
970 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
972 ERROR(errp
, "could not perform event_addr_resolved");
973 goto err_resolve_get_addr
;
976 if (cm_event
->event
!= RDMA_CM_EVENT_ADDR_RESOLVED
) {
977 ERROR(errp
, "result not equal to event_addr_resolved %s",
978 rdma_event_str(cm_event
->event
));
979 perror("rdma_resolve_addr");
980 rdma_ack_cm_event(cm_event
);
982 goto err_resolve_get_addr
;
984 rdma_ack_cm_event(cm_event
);
987 ret
= rdma_resolve_route(rdma
->cm_id
, RDMA_RESOLVE_TIMEOUT_MS
);
989 ERROR(errp
, "could not resolve rdma route");
990 goto err_resolve_get_addr
;
993 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
995 ERROR(errp
, "could not perform event_route_resolved");
996 goto err_resolve_get_addr
;
998 if (cm_event
->event
!= RDMA_CM_EVENT_ROUTE_RESOLVED
) {
999 ERROR(errp
, "result not equal to event_route_resolved: %s",
1000 rdma_event_str(cm_event
->event
));
1001 rdma_ack_cm_event(cm_event
);
1003 goto err_resolve_get_addr
;
1005 rdma_ack_cm_event(cm_event
);
1006 rdma
->verbs
= rdma
->cm_id
->verbs
;
1007 qemu_rdma_dump_id("source_resolve_host", rdma
->cm_id
->verbs
);
1008 qemu_rdma_dump_gid("source_resolve_host", rdma
->cm_id
);
1011 err_resolve_get_addr
:
1012 rdma_destroy_id(rdma
->cm_id
);
1014 err_resolve_create_id
:
1015 rdma_destroy_event_channel(rdma
->channel
);
1016 rdma
->channel
= NULL
;
1021 * Create protection domain and completion queues
1023 static int qemu_rdma_alloc_pd_cq(RDMAContext
*rdma
)
1026 rdma
->pd
= ibv_alloc_pd(rdma
->verbs
);
1028 error_report("failed to allocate protection domain");
1032 /* create completion channel */
1033 rdma
->comp_channel
= ibv_create_comp_channel(rdma
->verbs
);
1034 if (!rdma
->comp_channel
) {
1035 error_report("failed to allocate completion channel");
1036 goto err_alloc_pd_cq
;
1040 * Completion queue can be filled by both read and write work requests,
1041 * so must reflect the sum of both possible queue sizes.
1043 rdma
->cq
= ibv_create_cq(rdma
->verbs
, (RDMA_SIGNALED_SEND_MAX
* 3),
1044 NULL
, rdma
->comp_channel
, 0);
1046 error_report("failed to allocate completion queue");
1047 goto err_alloc_pd_cq
;
1054 ibv_dealloc_pd(rdma
->pd
);
1056 if (rdma
->comp_channel
) {
1057 ibv_destroy_comp_channel(rdma
->comp_channel
);
1060 rdma
->comp_channel
= NULL
;
1066 * Create queue pairs.
1068 static int qemu_rdma_alloc_qp(RDMAContext
*rdma
)
1070 struct ibv_qp_init_attr attr
= { 0 };
1073 attr
.cap
.max_send_wr
= RDMA_SIGNALED_SEND_MAX
;
1074 attr
.cap
.max_recv_wr
= 3;
1075 attr
.cap
.max_send_sge
= 1;
1076 attr
.cap
.max_recv_sge
= 1;
1077 attr
.send_cq
= rdma
->cq
;
1078 attr
.recv_cq
= rdma
->cq
;
1079 attr
.qp_type
= IBV_QPT_RC
;
1081 ret
= rdma_create_qp(rdma
->cm_id
, rdma
->pd
, &attr
);
1086 rdma
->qp
= rdma
->cm_id
->qp
;
1090 static int qemu_rdma_reg_whole_ram_blocks(RDMAContext
*rdma
)
1093 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
1095 for (i
= 0; i
< local
->nb_blocks
; i
++) {
1096 local
->block
[i
].mr
=
1097 ibv_reg_mr(rdma
->pd
,
1098 local
->block
[i
].local_host_addr
,
1099 local
->block
[i
].length
,
1100 IBV_ACCESS_LOCAL_WRITE
|
1101 IBV_ACCESS_REMOTE_WRITE
1103 if (!local
->block
[i
].mr
) {
1104 perror("Failed to register local dest ram block!\n");
1107 rdma
->total_registrations
++;
1110 if (i
>= local
->nb_blocks
) {
1114 for (i
--; i
>= 0; i
--) {
1115 ibv_dereg_mr(local
->block
[i
].mr
);
1116 rdma
->total_registrations
--;
1124 * Find the ram block that corresponds to the page requested to be
1125 * transmitted by QEMU.
1127 * Once the block is found, also identify which 'chunk' within that
1128 * block that the page belongs to.
1130 * This search cannot fail or the migration will fail.
1132 static int qemu_rdma_search_ram_block(RDMAContext
*rdma
,
1133 uintptr_t block_offset
,
1136 uint64_t *block_index
,
1137 uint64_t *chunk_index
)
1139 uint64_t current_addr
= block_offset
+ offset
;
1140 RDMALocalBlock
*block
= g_hash_table_lookup(rdma
->blockmap
,
1141 (void *) block_offset
);
1143 assert(current_addr
>= block
->offset
);
1144 assert((current_addr
+ length
) <= (block
->offset
+ block
->length
));
1146 *block_index
= block
->index
;
1147 *chunk_index
= ram_chunk_index(block
->local_host_addr
,
1148 block
->local_host_addr
+ (current_addr
- block
->offset
));
1154 * Register a chunk with IB. If the chunk was already registered
1155 * previously, then skip.
1157 * Also return the keys associated with the registration needed
1158 * to perform the actual RDMA operation.
1160 static int qemu_rdma_register_and_get_keys(RDMAContext
*rdma
,
1161 RDMALocalBlock
*block
, uintptr_t host_addr
,
1162 uint32_t *lkey
, uint32_t *rkey
, int chunk
,
1163 uint8_t *chunk_start
, uint8_t *chunk_end
)
1167 *lkey
= block
->mr
->lkey
;
1170 *rkey
= block
->mr
->rkey
;
1175 /* allocate memory to store chunk MRs */
1177 block
->pmr
= g_new0(struct ibv_mr
*, block
->nb_chunks
);
1181 * If 'rkey', then we're the destination, so grant access to the source.
1183 * If 'lkey', then we're the source VM, so grant access only to ourselves.
1185 if (!block
->pmr
[chunk
]) {
1186 uint64_t len
= chunk_end
- chunk_start
;
1188 trace_qemu_rdma_register_and_get_keys(len
, chunk_start
);
1190 block
->pmr
[chunk
] = ibv_reg_mr(rdma
->pd
,
1192 (rkey
? (IBV_ACCESS_LOCAL_WRITE
|
1193 IBV_ACCESS_REMOTE_WRITE
) : 0));
1195 if (!block
->pmr
[chunk
]) {
1196 perror("Failed to register chunk!");
1197 fprintf(stderr
, "Chunk details: block: %d chunk index %d"
1198 " start %" PRIuPTR
" end %" PRIuPTR
1200 " local %" PRIuPTR
" registrations: %d\n",
1201 block
->index
, chunk
, (uintptr_t)chunk_start
,
1202 (uintptr_t)chunk_end
, host_addr
,
1203 (uintptr_t)block
->local_host_addr
,
1204 rdma
->total_registrations
);
1207 rdma
->total_registrations
++;
1211 *lkey
= block
->pmr
[chunk
]->lkey
;
1214 *rkey
= block
->pmr
[chunk
]->rkey
;
1220 * Register (at connection time) the memory used for control
1223 static int qemu_rdma_reg_control(RDMAContext
*rdma
, int idx
)
1225 rdma
->wr_data
[idx
].control_mr
= ibv_reg_mr(rdma
->pd
,
1226 rdma
->wr_data
[idx
].control
, RDMA_CONTROL_MAX_BUFFER
,
1227 IBV_ACCESS_LOCAL_WRITE
| IBV_ACCESS_REMOTE_WRITE
);
1228 if (rdma
->wr_data
[idx
].control_mr
) {
1229 rdma
->total_registrations
++;
1232 error_report("qemu_rdma_reg_control failed");
1236 const char *print_wrid(int wrid
)
1238 if (wrid
>= RDMA_WRID_RECV_CONTROL
) {
1239 return wrid_desc
[RDMA_WRID_RECV_CONTROL
];
1241 return wrid_desc
[wrid
];
1245 * RDMA requires memory registration (mlock/pinning), but this is not good for
1248 * In preparation for the future where LRU information or workload-specific
1249 * writable writable working set memory access behavior is available to QEMU
1250 * it would be nice to have in place the ability to UN-register/UN-pin
1251 * particular memory regions from the RDMA hardware when it is determine that
1252 * those regions of memory will likely not be accessed again in the near future.
1254 * While we do not yet have such information right now, the following
1255 * compile-time option allows us to perform a non-optimized version of this
1258 * By uncommenting this option, you will cause *all* RDMA transfers to be
1259 * unregistered immediately after the transfer completes on both sides of the
1260 * connection. This has no effect in 'rdma-pin-all' mode, only regular mode.
1262 * This will have a terrible impact on migration performance, so until future
1263 * workload information or LRU information is available, do not attempt to use
1264 * this feature except for basic testing.
1266 //#define RDMA_UNREGISTRATION_EXAMPLE
1269 * Perform a non-optimized memory unregistration after every transfer
1270 * for demonstration purposes, only if pin-all is not requested.
1272 * Potential optimizations:
1273 * 1. Start a new thread to run this function continuously
1275 - and for receipt of unregister messages
1277 * 3. Use workload hints.
1279 static int qemu_rdma_unregister_waiting(RDMAContext
*rdma
)
1281 while (rdma
->unregistrations
[rdma
->unregister_current
]) {
1283 uint64_t wr_id
= rdma
->unregistrations
[rdma
->unregister_current
];
1285 (wr_id
& RDMA_WRID_CHUNK_MASK
) >> RDMA_WRID_CHUNK_SHIFT
;
1287 (wr_id
& RDMA_WRID_BLOCK_MASK
) >> RDMA_WRID_BLOCK_SHIFT
;
1288 RDMALocalBlock
*block
=
1289 &(rdma
->local_ram_blocks
.block
[index
]);
1290 RDMARegister reg
= { .current_index
= index
};
1291 RDMAControlHeader resp
= { .type
= RDMA_CONTROL_UNREGISTER_FINISHED
,
1293 RDMAControlHeader head
= { .len
= sizeof(RDMARegister
),
1294 .type
= RDMA_CONTROL_UNREGISTER_REQUEST
,
1298 trace_qemu_rdma_unregister_waiting_proc(chunk
,
1299 rdma
->unregister_current
);
1301 rdma
->unregistrations
[rdma
->unregister_current
] = 0;
1302 rdma
->unregister_current
++;
1304 if (rdma
->unregister_current
== RDMA_SIGNALED_SEND_MAX
) {
1305 rdma
->unregister_current
= 0;
1310 * Unregistration is speculative (because migration is single-threaded
1311 * and we cannot break the protocol's inifinband message ordering).
1312 * Thus, if the memory is currently being used for transmission,
1313 * then abort the attempt to unregister and try again
1314 * later the next time a completion is received for this memory.
1316 clear_bit(chunk
, block
->unregister_bitmap
);
1318 if (test_bit(chunk
, block
->transit_bitmap
)) {
1319 trace_qemu_rdma_unregister_waiting_inflight(chunk
);
1323 trace_qemu_rdma_unregister_waiting_send(chunk
);
1325 ret
= ibv_dereg_mr(block
->pmr
[chunk
]);
1326 block
->pmr
[chunk
] = NULL
;
1327 block
->remote_keys
[chunk
] = 0;
1330 perror("unregistration chunk failed");
1333 rdma
->total_registrations
--;
1335 reg
.key
.chunk
= chunk
;
1336 register_to_network(rdma
, ®
);
1337 ret
= qemu_rdma_exchange_send(rdma
, &head
, (uint8_t *) ®
,
1343 trace_qemu_rdma_unregister_waiting_complete(chunk
);
1349 static uint64_t qemu_rdma_make_wrid(uint64_t wr_id
, uint64_t index
,
1352 uint64_t result
= wr_id
& RDMA_WRID_TYPE_MASK
;
1354 result
|= (index
<< RDMA_WRID_BLOCK_SHIFT
);
1355 result
|= (chunk
<< RDMA_WRID_CHUNK_SHIFT
);
1361 * Set bit for unregistration in the next iteration.
1362 * We cannot transmit right here, but will unpin later.
1364 static void qemu_rdma_signal_unregister(RDMAContext
*rdma
, uint64_t index
,
1365 uint64_t chunk
, uint64_t wr_id
)
1367 if (rdma
->unregistrations
[rdma
->unregister_next
] != 0) {
1368 error_report("rdma migration: queue is full");
1370 RDMALocalBlock
*block
= &(rdma
->local_ram_blocks
.block
[index
]);
1372 if (!test_and_set_bit(chunk
, block
->unregister_bitmap
)) {
1373 trace_qemu_rdma_signal_unregister_append(chunk
,
1374 rdma
->unregister_next
);
1376 rdma
->unregistrations
[rdma
->unregister_next
++] =
1377 qemu_rdma_make_wrid(wr_id
, index
, chunk
);
1379 if (rdma
->unregister_next
== RDMA_SIGNALED_SEND_MAX
) {
1380 rdma
->unregister_next
= 0;
1383 trace_qemu_rdma_signal_unregister_already(chunk
);
1389 * Consult the connection manager to see a work request
1390 * (of any kind) has completed.
1391 * Return the work request ID that completed.
1393 static uint64_t qemu_rdma_poll(RDMAContext
*rdma
, uint64_t *wr_id_out
,
1400 ret
= ibv_poll_cq(rdma
->cq
, 1, &wc
);
1403 *wr_id_out
= RDMA_WRID_NONE
;
1408 error_report("ibv_poll_cq return %d", ret
);
1412 wr_id
= wc
.wr_id
& RDMA_WRID_TYPE_MASK
;
1414 if (wc
.status
!= IBV_WC_SUCCESS
) {
1415 fprintf(stderr
, "ibv_poll_cq wc.status=%d %s!\n",
1416 wc
.status
, ibv_wc_status_str(wc
.status
));
1417 fprintf(stderr
, "ibv_poll_cq wrid=%s!\n", wrid_desc
[wr_id
]);
1422 if (rdma
->control_ready_expected
&&
1423 (wr_id
>= RDMA_WRID_RECV_CONTROL
)) {
1424 trace_qemu_rdma_poll_recv(wrid_desc
[RDMA_WRID_RECV_CONTROL
],
1425 wr_id
- RDMA_WRID_RECV_CONTROL
, wr_id
, rdma
->nb_sent
);
1426 rdma
->control_ready_expected
= 0;
1429 if (wr_id
== RDMA_WRID_RDMA_WRITE
) {
1431 (wc
.wr_id
& RDMA_WRID_CHUNK_MASK
) >> RDMA_WRID_CHUNK_SHIFT
;
1433 (wc
.wr_id
& RDMA_WRID_BLOCK_MASK
) >> RDMA_WRID_BLOCK_SHIFT
;
1434 RDMALocalBlock
*block
= &(rdma
->local_ram_blocks
.block
[index
]);
1436 trace_qemu_rdma_poll_write(print_wrid(wr_id
), wr_id
, rdma
->nb_sent
,
1437 index
, chunk
, block
->local_host_addr
,
1438 (void *)(uintptr_t)block
->remote_host_addr
);
1440 clear_bit(chunk
, block
->transit_bitmap
);
1442 if (rdma
->nb_sent
> 0) {
1446 if (!rdma
->pin_all
) {
1448 * FYI: If one wanted to signal a specific chunk to be unregistered
1449 * using LRU or workload-specific information, this is the function
1450 * you would call to do so. That chunk would then get asynchronously
1451 * unregistered later.
1453 #ifdef RDMA_UNREGISTRATION_EXAMPLE
1454 qemu_rdma_signal_unregister(rdma
, index
, chunk
, wc
.wr_id
);
1458 trace_qemu_rdma_poll_other(print_wrid(wr_id
), wr_id
, rdma
->nb_sent
);
1461 *wr_id_out
= wc
.wr_id
;
1463 *byte_len
= wc
.byte_len
;
1470 * Block until the next work request has completed.
1472 * First poll to see if a work request has already completed,
1475 * If we encounter completed work requests for IDs other than
1476 * the one we're interested in, then that's generally an error.
1478 * The only exception is actual RDMA Write completions. These
1479 * completions only need to be recorded, but do not actually
1480 * need further processing.
1482 static int qemu_rdma_block_for_wrid(RDMAContext
*rdma
, int wrid_requested
,
1485 int num_cq_events
= 0, ret
= 0;
1488 uint64_t wr_id
= RDMA_WRID_NONE
, wr_id_in
;
1490 if (ibv_req_notify_cq(rdma
->cq
, 0)) {
1494 while (wr_id
!= wrid_requested
) {
1495 ret
= qemu_rdma_poll(rdma
, &wr_id_in
, byte_len
);
1500 wr_id
= wr_id_in
& RDMA_WRID_TYPE_MASK
;
1502 if (wr_id
== RDMA_WRID_NONE
) {
1505 if (wr_id
!= wrid_requested
) {
1506 trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested
),
1507 wrid_requested
, print_wrid(wr_id
), wr_id
);
1511 if (wr_id
== wrid_requested
) {
1517 * Coroutine doesn't start until migration_fd_process_incoming()
1518 * so don't yield unless we know we're running inside of a coroutine.
1520 if (rdma
->migration_started_on_destination
) {
1521 yield_until_fd_readable(rdma
->comp_channel
->fd
);
1524 ret
= ibv_get_cq_event(rdma
->comp_channel
, &cq
, &cq_ctx
);
1526 perror("ibv_get_cq_event");
1527 goto err_block_for_wrid
;
1532 ret
= -ibv_req_notify_cq(cq
, 0);
1534 goto err_block_for_wrid
;
1537 while (wr_id
!= wrid_requested
) {
1538 ret
= qemu_rdma_poll(rdma
, &wr_id_in
, byte_len
);
1540 goto err_block_for_wrid
;
1543 wr_id
= wr_id_in
& RDMA_WRID_TYPE_MASK
;
1545 if (wr_id
== RDMA_WRID_NONE
) {
1548 if (wr_id
!= wrid_requested
) {
1549 trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested
),
1550 wrid_requested
, print_wrid(wr_id
), wr_id
);
1554 if (wr_id
== wrid_requested
) {
1555 goto success_block_for_wrid
;
1559 success_block_for_wrid
:
1560 if (num_cq_events
) {
1561 ibv_ack_cq_events(cq
, num_cq_events
);
1566 if (num_cq_events
) {
1567 ibv_ack_cq_events(cq
, num_cq_events
);
1570 rdma
->error_state
= ret
;
1575 * Post a SEND message work request for the control channel
1576 * containing some data and block until the post completes.
1578 static int qemu_rdma_post_send_control(RDMAContext
*rdma
, uint8_t *buf
,
1579 RDMAControlHeader
*head
)
1582 RDMAWorkRequestData
*wr
= &rdma
->wr_data
[RDMA_WRID_CONTROL
];
1583 struct ibv_send_wr
*bad_wr
;
1584 struct ibv_sge sge
= {
1585 .addr
= (uintptr_t)(wr
->control
),
1586 .length
= head
->len
+ sizeof(RDMAControlHeader
),
1587 .lkey
= wr
->control_mr
->lkey
,
1589 struct ibv_send_wr send_wr
= {
1590 .wr_id
= RDMA_WRID_SEND_CONTROL
,
1591 .opcode
= IBV_WR_SEND
,
1592 .send_flags
= IBV_SEND_SIGNALED
,
1597 trace_qemu_rdma_post_send_control(control_desc
[head
->type
]);
1600 * We don't actually need to do a memcpy() in here if we used
1601 * the "sge" properly, but since we're only sending control messages
1602 * (not RAM in a performance-critical path), then its OK for now.
1604 * The copy makes the RDMAControlHeader simpler to manipulate
1605 * for the time being.
1607 assert(head
->len
<= RDMA_CONTROL_MAX_BUFFER
- sizeof(*head
));
1608 memcpy(wr
->control
, head
, sizeof(RDMAControlHeader
));
1609 control_to_network((void *) wr
->control
);
1612 memcpy(wr
->control
+ sizeof(RDMAControlHeader
), buf
, head
->len
);
1616 ret
= ibv_post_send(rdma
->qp
, &send_wr
, &bad_wr
);
1619 error_report("Failed to use post IB SEND for control");
1623 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_SEND_CONTROL
, NULL
);
1625 error_report("rdma migration: send polling control error");
1632 * Post a RECV work request in anticipation of some future receipt
1633 * of data on the control channel.
1635 static int qemu_rdma_post_recv_control(RDMAContext
*rdma
, int idx
)
1637 struct ibv_recv_wr
*bad_wr
;
1638 struct ibv_sge sge
= {
1639 .addr
= (uintptr_t)(rdma
->wr_data
[idx
].control
),
1640 .length
= RDMA_CONTROL_MAX_BUFFER
,
1641 .lkey
= rdma
->wr_data
[idx
].control_mr
->lkey
,
1644 struct ibv_recv_wr recv_wr
= {
1645 .wr_id
= RDMA_WRID_RECV_CONTROL
+ idx
,
1651 if (ibv_post_recv(rdma
->qp
, &recv_wr
, &bad_wr
)) {
1659 * Block and wait for a RECV control channel message to arrive.
1661 static int qemu_rdma_exchange_get_response(RDMAContext
*rdma
,
1662 RDMAControlHeader
*head
, int expecting
, int idx
)
1665 int ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RECV_CONTROL
+ idx
,
1669 error_report("rdma migration: recv polling control error!");
1673 network_to_control((void *) rdma
->wr_data
[idx
].control
);
1674 memcpy(head
, rdma
->wr_data
[idx
].control
, sizeof(RDMAControlHeader
));
1676 trace_qemu_rdma_exchange_get_response_start(control_desc
[expecting
]);
1678 if (expecting
== RDMA_CONTROL_NONE
) {
1679 trace_qemu_rdma_exchange_get_response_none(control_desc
[head
->type
],
1681 } else if (head
->type
!= expecting
|| head
->type
== RDMA_CONTROL_ERROR
) {
1682 error_report("Was expecting a %s (%d) control message"
1683 ", but got: %s (%d), length: %d",
1684 control_desc
[expecting
], expecting
,
1685 control_desc
[head
->type
], head
->type
, head
->len
);
1686 if (head
->type
== RDMA_CONTROL_ERROR
) {
1687 rdma
->received_error
= true;
1691 if (head
->len
> RDMA_CONTROL_MAX_BUFFER
- sizeof(*head
)) {
1692 error_report("too long length: %d", head
->len
);
1695 if (sizeof(*head
) + head
->len
!= byte_len
) {
1696 error_report("Malformed length: %d byte_len %d", head
->len
, byte_len
);
1704 * When a RECV work request has completed, the work request's
1705 * buffer is pointed at the header.
1707 * This will advance the pointer to the data portion
1708 * of the control message of the work request's buffer that
1709 * was populated after the work request finished.
1711 static void qemu_rdma_move_header(RDMAContext
*rdma
, int idx
,
1712 RDMAControlHeader
*head
)
1714 rdma
->wr_data
[idx
].control_len
= head
->len
;
1715 rdma
->wr_data
[idx
].control_curr
=
1716 rdma
->wr_data
[idx
].control
+ sizeof(RDMAControlHeader
);
1720 * This is an 'atomic' high-level operation to deliver a single, unified
1721 * control-channel message.
1723 * Additionally, if the user is expecting some kind of reply to this message,
1724 * they can request a 'resp' response message be filled in by posting an
1725 * additional work request on behalf of the user and waiting for an additional
1728 * The extra (optional) response is used during registration to us from having
1729 * to perform an *additional* exchange of message just to provide a response by
1730 * instead piggy-backing on the acknowledgement.
1732 static int qemu_rdma_exchange_send(RDMAContext
*rdma
, RDMAControlHeader
*head
,
1733 uint8_t *data
, RDMAControlHeader
*resp
,
1735 int (*callback
)(RDMAContext
*rdma
))
1740 * Wait until the dest is ready before attempting to deliver the message
1741 * by waiting for a READY message.
1743 if (rdma
->control_ready_expected
) {
1744 RDMAControlHeader resp
;
1745 ret
= qemu_rdma_exchange_get_response(rdma
,
1746 &resp
, RDMA_CONTROL_READY
, RDMA_WRID_READY
);
1753 * If the user is expecting a response, post a WR in anticipation of it.
1756 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_DATA
);
1758 error_report("rdma migration: error posting"
1759 " extra control recv for anticipated result!");
1765 * Post a WR to replace the one we just consumed for the READY message.
1767 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
1769 error_report("rdma migration: error posting first control recv!");
1774 * Deliver the control message that was requested.
1776 ret
= qemu_rdma_post_send_control(rdma
, data
, head
);
1779 error_report("Failed to send control buffer!");
1784 * If we're expecting a response, block and wait for it.
1788 trace_qemu_rdma_exchange_send_issue_callback();
1789 ret
= callback(rdma
);
1795 trace_qemu_rdma_exchange_send_waiting(control_desc
[resp
->type
]);
1796 ret
= qemu_rdma_exchange_get_response(rdma
, resp
,
1797 resp
->type
, RDMA_WRID_DATA
);
1803 qemu_rdma_move_header(rdma
, RDMA_WRID_DATA
, resp
);
1805 *resp_idx
= RDMA_WRID_DATA
;
1807 trace_qemu_rdma_exchange_send_received(control_desc
[resp
->type
]);
1810 rdma
->control_ready_expected
= 1;
1816 * This is an 'atomic' high-level operation to receive a single, unified
1817 * control-channel message.
1819 static int qemu_rdma_exchange_recv(RDMAContext
*rdma
, RDMAControlHeader
*head
,
1822 RDMAControlHeader ready
= {
1824 .type
= RDMA_CONTROL_READY
,
1830 * Inform the source that we're ready to receive a message.
1832 ret
= qemu_rdma_post_send_control(rdma
, NULL
, &ready
);
1835 error_report("Failed to send control buffer!");
1840 * Block and wait for the message.
1842 ret
= qemu_rdma_exchange_get_response(rdma
, head
,
1843 expecting
, RDMA_WRID_READY
);
1849 qemu_rdma_move_header(rdma
, RDMA_WRID_READY
, head
);
1852 * Post a new RECV work request to replace the one we just consumed.
1854 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
1856 error_report("rdma migration: error posting second control recv!");
1864 * Write an actual chunk of memory using RDMA.
1866 * If we're using dynamic registration on the dest-side, we have to
1867 * send a registration command first.
1869 static int qemu_rdma_write_one(QEMUFile
*f
, RDMAContext
*rdma
,
1870 int current_index
, uint64_t current_addr
,
1874 struct ibv_send_wr send_wr
= { 0 };
1875 struct ibv_send_wr
*bad_wr
;
1876 int reg_result_idx
, ret
, count
= 0;
1877 uint64_t chunk
, chunks
;
1878 uint8_t *chunk_start
, *chunk_end
;
1879 RDMALocalBlock
*block
= &(rdma
->local_ram_blocks
.block
[current_index
]);
1881 RDMARegisterResult
*reg_result
;
1882 RDMAControlHeader resp
= { .type
= RDMA_CONTROL_REGISTER_RESULT
};
1883 RDMAControlHeader head
= { .len
= sizeof(RDMARegister
),
1884 .type
= RDMA_CONTROL_REGISTER_REQUEST
,
1889 sge
.addr
= (uintptr_t)(block
->local_host_addr
+
1890 (current_addr
- block
->offset
));
1891 sge
.length
= length
;
1893 chunk
= ram_chunk_index(block
->local_host_addr
,
1894 (uint8_t *)(uintptr_t)sge
.addr
);
1895 chunk_start
= ram_chunk_start(block
, chunk
);
1897 if (block
->is_ram_block
) {
1898 chunks
= length
/ (1UL << RDMA_REG_CHUNK_SHIFT
);
1900 if (chunks
&& ((length
% (1UL << RDMA_REG_CHUNK_SHIFT
)) == 0)) {
1904 chunks
= block
->length
/ (1UL << RDMA_REG_CHUNK_SHIFT
);
1906 if (chunks
&& ((block
->length
% (1UL << RDMA_REG_CHUNK_SHIFT
)) == 0)) {
1911 trace_qemu_rdma_write_one_top(chunks
+ 1,
1913 (1UL << RDMA_REG_CHUNK_SHIFT
) / 1024 / 1024);
1915 chunk_end
= ram_chunk_end(block
, chunk
+ chunks
);
1917 if (!rdma
->pin_all
) {
1918 #ifdef RDMA_UNREGISTRATION_EXAMPLE
1919 qemu_rdma_unregister_waiting(rdma
);
1923 while (test_bit(chunk
, block
->transit_bitmap
)) {
1925 trace_qemu_rdma_write_one_block(count
++, current_index
, chunk
,
1926 sge
.addr
, length
, rdma
->nb_sent
, block
->nb_chunks
);
1928 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RDMA_WRITE
, NULL
);
1931 error_report("Failed to Wait for previous write to complete "
1932 "block %d chunk %" PRIu64
1933 " current %" PRIu64
" len %" PRIu64
" %d",
1934 current_index
, chunk
, sge
.addr
, length
, rdma
->nb_sent
);
1939 if (!rdma
->pin_all
|| !block
->is_ram_block
) {
1940 if (!block
->remote_keys
[chunk
]) {
1942 * This chunk has not yet been registered, so first check to see
1943 * if the entire chunk is zero. If so, tell the other size to
1944 * memset() + madvise() the entire chunk without RDMA.
1947 if (buffer_is_zero((void *)(uintptr_t)sge
.addr
, length
)) {
1948 RDMACompress comp
= {
1949 .offset
= current_addr
,
1951 .block_idx
= current_index
,
1955 head
.len
= sizeof(comp
);
1956 head
.type
= RDMA_CONTROL_COMPRESS
;
1958 trace_qemu_rdma_write_one_zero(chunk
, sge
.length
,
1959 current_index
, current_addr
);
1961 compress_to_network(rdma
, &comp
);
1962 ret
= qemu_rdma_exchange_send(rdma
, &head
,
1963 (uint8_t *) &comp
, NULL
, NULL
, NULL
);
1969 acct_update_position(f
, sge
.length
, true);
1975 * Otherwise, tell other side to register.
1977 reg
.current_index
= current_index
;
1978 if (block
->is_ram_block
) {
1979 reg
.key
.current_addr
= current_addr
;
1981 reg
.key
.chunk
= chunk
;
1983 reg
.chunks
= chunks
;
1985 trace_qemu_rdma_write_one_sendreg(chunk
, sge
.length
, current_index
,
1988 register_to_network(rdma
, ®
);
1989 ret
= qemu_rdma_exchange_send(rdma
, &head
, (uint8_t *) ®
,
1990 &resp
, ®_result_idx
, NULL
);
1995 /* try to overlap this single registration with the one we sent. */
1996 if (qemu_rdma_register_and_get_keys(rdma
, block
, sge
.addr
,
1997 &sge
.lkey
, NULL
, chunk
,
1998 chunk_start
, chunk_end
)) {
1999 error_report("cannot get lkey");
2003 reg_result
= (RDMARegisterResult
*)
2004 rdma
->wr_data
[reg_result_idx
].control_curr
;
2006 network_to_result(reg_result
);
2008 trace_qemu_rdma_write_one_recvregres(block
->remote_keys
[chunk
],
2009 reg_result
->rkey
, chunk
);
2011 block
->remote_keys
[chunk
] = reg_result
->rkey
;
2012 block
->remote_host_addr
= reg_result
->host_addr
;
2014 /* already registered before */
2015 if (qemu_rdma_register_and_get_keys(rdma
, block
, sge
.addr
,
2016 &sge
.lkey
, NULL
, chunk
,
2017 chunk_start
, chunk_end
)) {
2018 error_report("cannot get lkey!");
2023 send_wr
.wr
.rdma
.rkey
= block
->remote_keys
[chunk
];
2025 send_wr
.wr
.rdma
.rkey
= block
->remote_rkey
;
2027 if (qemu_rdma_register_and_get_keys(rdma
, block
, sge
.addr
,
2028 &sge
.lkey
, NULL
, chunk
,
2029 chunk_start
, chunk_end
)) {
2030 error_report("cannot get lkey!");
2036 * Encode the ram block index and chunk within this wrid.
2037 * We will use this information at the time of completion
2038 * to figure out which bitmap to check against and then which
2039 * chunk in the bitmap to look for.
2041 send_wr
.wr_id
= qemu_rdma_make_wrid(RDMA_WRID_RDMA_WRITE
,
2042 current_index
, chunk
);
2044 send_wr
.opcode
= IBV_WR_RDMA_WRITE
;
2045 send_wr
.send_flags
= IBV_SEND_SIGNALED
;
2046 send_wr
.sg_list
= &sge
;
2047 send_wr
.num_sge
= 1;
2048 send_wr
.wr
.rdma
.remote_addr
= block
->remote_host_addr
+
2049 (current_addr
- block
->offset
);
2051 trace_qemu_rdma_write_one_post(chunk
, sge
.addr
, send_wr
.wr
.rdma
.remote_addr
,
2055 * ibv_post_send() does not return negative error numbers,
2056 * per the specification they are positive - no idea why.
2058 ret
= ibv_post_send(rdma
->qp
, &send_wr
, &bad_wr
);
2060 if (ret
== ENOMEM
) {
2061 trace_qemu_rdma_write_one_queue_full();
2062 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RDMA_WRITE
, NULL
);
2064 error_report("rdma migration: failed to make "
2065 "room in full send queue! %d", ret
);
2071 } else if (ret
> 0) {
2072 perror("rdma migration: post rdma write failed");
2076 set_bit(chunk
, block
->transit_bitmap
);
2077 acct_update_position(f
, sge
.length
, false);
2078 rdma
->total_writes
++;
2084 * Push out any unwritten RDMA operations.
2086 * We support sending out multiple chunks at the same time.
2087 * Not all of them need to get signaled in the completion queue.
2089 static int qemu_rdma_write_flush(QEMUFile
*f
, RDMAContext
*rdma
)
2093 if (!rdma
->current_length
) {
2097 ret
= qemu_rdma_write_one(f
, rdma
,
2098 rdma
->current_index
, rdma
->current_addr
, rdma
->current_length
);
2106 trace_qemu_rdma_write_flush(rdma
->nb_sent
);
2109 rdma
->current_length
= 0;
2110 rdma
->current_addr
= 0;
2115 static inline int qemu_rdma_buffer_mergable(RDMAContext
*rdma
,
2116 uint64_t offset
, uint64_t len
)
2118 RDMALocalBlock
*block
;
2122 if (rdma
->current_index
< 0) {
2126 if (rdma
->current_chunk
< 0) {
2130 block
= &(rdma
->local_ram_blocks
.block
[rdma
->current_index
]);
2131 host_addr
= block
->local_host_addr
+ (offset
- block
->offset
);
2132 chunk_end
= ram_chunk_end(block
, rdma
->current_chunk
);
2134 if (rdma
->current_length
== 0) {
2139 * Only merge into chunk sequentially.
2141 if (offset
!= (rdma
->current_addr
+ rdma
->current_length
)) {
2145 if (offset
< block
->offset
) {
2149 if ((offset
+ len
) > (block
->offset
+ block
->length
)) {
2153 if ((host_addr
+ len
) > chunk_end
) {
2161 * We're not actually writing here, but doing three things:
2163 * 1. Identify the chunk the buffer belongs to.
2164 * 2. If the chunk is full or the buffer doesn't belong to the current
2165 * chunk, then start a new chunk and flush() the old chunk.
2166 * 3. To keep the hardware busy, we also group chunks into batches
2167 * and only require that a batch gets acknowledged in the completion
2168 * qeueue instead of each individual chunk.
2170 static int qemu_rdma_write(QEMUFile
*f
, RDMAContext
*rdma
,
2171 uint64_t block_offset
, uint64_t offset
,
2174 uint64_t current_addr
= block_offset
+ offset
;
2175 uint64_t index
= rdma
->current_index
;
2176 uint64_t chunk
= rdma
->current_chunk
;
2179 /* If we cannot merge it, we flush the current buffer first. */
2180 if (!qemu_rdma_buffer_mergable(rdma
, current_addr
, len
)) {
2181 ret
= qemu_rdma_write_flush(f
, rdma
);
2185 rdma
->current_length
= 0;
2186 rdma
->current_addr
= current_addr
;
2188 ret
= qemu_rdma_search_ram_block(rdma
, block_offset
,
2189 offset
, len
, &index
, &chunk
);
2191 error_report("ram block search failed");
2194 rdma
->current_index
= index
;
2195 rdma
->current_chunk
= chunk
;
2199 rdma
->current_length
+= len
;
2201 /* flush it if buffer is too large */
2202 if (rdma
->current_length
>= RDMA_MERGE_MAX
) {
2203 return qemu_rdma_write_flush(f
, rdma
);
2209 static void qemu_rdma_cleanup(RDMAContext
*rdma
)
2211 struct rdma_cm_event
*cm_event
;
2214 if (rdma
->cm_id
&& rdma
->connected
) {
2215 if (rdma
->error_state
&& !rdma
->received_error
) {
2216 RDMAControlHeader head
= { .len
= 0,
2217 .type
= RDMA_CONTROL_ERROR
,
2220 error_report("Early error. Sending error.");
2221 qemu_rdma_post_send_control(rdma
, NULL
, &head
);
2224 ret
= rdma_disconnect(rdma
->cm_id
);
2226 trace_qemu_rdma_cleanup_waiting_for_disconnect();
2227 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
2229 rdma_ack_cm_event(cm_event
);
2232 trace_qemu_rdma_cleanup_disconnect();
2233 rdma
->connected
= false;
2236 g_free(rdma
->dest_blocks
);
2237 rdma
->dest_blocks
= NULL
;
2239 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2240 if (rdma
->wr_data
[idx
].control_mr
) {
2241 rdma
->total_registrations
--;
2242 ibv_dereg_mr(rdma
->wr_data
[idx
].control_mr
);
2244 rdma
->wr_data
[idx
].control_mr
= NULL
;
2247 if (rdma
->local_ram_blocks
.block
) {
2248 while (rdma
->local_ram_blocks
.nb_blocks
) {
2249 rdma_delete_block(rdma
, &rdma
->local_ram_blocks
.block
[0]);
2254 rdma_destroy_qp(rdma
->cm_id
);
2258 ibv_destroy_cq(rdma
->cq
);
2261 if (rdma
->comp_channel
) {
2262 ibv_destroy_comp_channel(rdma
->comp_channel
);
2263 rdma
->comp_channel
= NULL
;
2266 ibv_dealloc_pd(rdma
->pd
);
2270 rdma_destroy_id(rdma
->cm_id
);
2273 if (rdma
->listen_id
) {
2274 rdma_destroy_id(rdma
->listen_id
);
2275 rdma
->listen_id
= NULL
;
2277 if (rdma
->channel
) {
2278 rdma_destroy_event_channel(rdma
->channel
);
2279 rdma
->channel
= NULL
;
2286 static int qemu_rdma_source_init(RDMAContext
*rdma
, bool pin_all
, Error
**errp
)
2289 Error
*local_err
= NULL
, **temp
= &local_err
;
2292 * Will be validated against destination's actual capabilities
2293 * after the connect() completes.
2295 rdma
->pin_all
= pin_all
;
2297 ret
= qemu_rdma_resolve_host(rdma
, temp
);
2299 goto err_rdma_source_init
;
2302 ret
= qemu_rdma_alloc_pd_cq(rdma
);
2304 ERROR(temp
, "rdma migration: error allocating pd and cq! Your mlock()"
2305 " limits may be too low. Please check $ ulimit -a # and "
2306 "search for 'ulimit -l' in the output");
2307 goto err_rdma_source_init
;
2310 ret
= qemu_rdma_alloc_qp(rdma
);
2312 ERROR(temp
, "rdma migration: error allocating qp!");
2313 goto err_rdma_source_init
;
2316 ret
= qemu_rdma_init_ram_blocks(rdma
);
2318 ERROR(temp
, "rdma migration: error initializing ram blocks!");
2319 goto err_rdma_source_init
;
2322 /* Build the hash that maps from offset to RAMBlock */
2323 rdma
->blockmap
= g_hash_table_new(g_direct_hash
, g_direct_equal
);
2324 for (idx
= 0; idx
< rdma
->local_ram_blocks
.nb_blocks
; idx
++) {
2325 g_hash_table_insert(rdma
->blockmap
,
2326 (void *)(uintptr_t)rdma
->local_ram_blocks
.block
[idx
].offset
,
2327 &rdma
->local_ram_blocks
.block
[idx
]);
2330 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2331 ret
= qemu_rdma_reg_control(rdma
, idx
);
2333 ERROR(temp
, "rdma migration: error registering %d control!",
2335 goto err_rdma_source_init
;
2341 err_rdma_source_init
:
2342 error_propagate(errp
, local_err
);
2343 qemu_rdma_cleanup(rdma
);
2347 static int qemu_rdma_connect(RDMAContext
*rdma
, Error
**errp
)
2349 RDMACapabilities cap
= {
2350 .version
= RDMA_CONTROL_VERSION_CURRENT
,
2353 struct rdma_conn_param conn_param
= { .initiator_depth
= 2,
2355 .private_data
= &cap
,
2356 .private_data_len
= sizeof(cap
),
2358 struct rdma_cm_event
*cm_event
;
2362 * Only negotiate the capability with destination if the user
2363 * on the source first requested the capability.
2365 if (rdma
->pin_all
) {
2366 trace_qemu_rdma_connect_pin_all_requested();
2367 cap
.flags
|= RDMA_CAPABILITY_PIN_ALL
;
2370 caps_to_network(&cap
);
2372 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
2374 ERROR(errp
, "posting second control recv");
2375 goto err_rdma_source_connect
;
2378 ret
= rdma_connect(rdma
->cm_id
, &conn_param
);
2380 perror("rdma_connect");
2381 ERROR(errp
, "connecting to destination!");
2382 goto err_rdma_source_connect
;
2385 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
2387 perror("rdma_get_cm_event after rdma_connect");
2388 ERROR(errp
, "connecting to destination!");
2389 rdma_ack_cm_event(cm_event
);
2390 goto err_rdma_source_connect
;
2393 if (cm_event
->event
!= RDMA_CM_EVENT_ESTABLISHED
) {
2394 perror("rdma_get_cm_event != EVENT_ESTABLISHED after rdma_connect");
2395 ERROR(errp
, "connecting to destination!");
2396 rdma_ack_cm_event(cm_event
);
2397 goto err_rdma_source_connect
;
2399 rdma
->connected
= true;
2401 memcpy(&cap
, cm_event
->param
.conn
.private_data
, sizeof(cap
));
2402 network_to_caps(&cap
);
2405 * Verify that the *requested* capabilities are supported by the destination
2406 * and disable them otherwise.
2408 if (rdma
->pin_all
&& !(cap
.flags
& RDMA_CAPABILITY_PIN_ALL
)) {
2409 ERROR(errp
, "Server cannot support pinning all memory. "
2410 "Will register memory dynamically.");
2411 rdma
->pin_all
= false;
2414 trace_qemu_rdma_connect_pin_all_outcome(rdma
->pin_all
);
2416 rdma_ack_cm_event(cm_event
);
2418 rdma
->control_ready_expected
= 1;
2422 err_rdma_source_connect
:
2423 qemu_rdma_cleanup(rdma
);
2427 static int qemu_rdma_dest_init(RDMAContext
*rdma
, Error
**errp
)
2430 struct rdma_cm_id
*listen_id
;
2431 char ip
[40] = "unknown";
2432 struct rdma_addrinfo
*res
, *e
;
2435 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2436 rdma
->wr_data
[idx
].control_len
= 0;
2437 rdma
->wr_data
[idx
].control_curr
= NULL
;
2440 if (!rdma
->host
|| !rdma
->host
[0]) {
2441 ERROR(errp
, "RDMA host is not set!");
2442 rdma
->error_state
= -EINVAL
;
2445 /* create CM channel */
2446 rdma
->channel
= rdma_create_event_channel();
2447 if (!rdma
->channel
) {
2448 ERROR(errp
, "could not create rdma event channel");
2449 rdma
->error_state
= -EINVAL
;
2454 ret
= rdma_create_id(rdma
->channel
, &listen_id
, NULL
, RDMA_PS_TCP
);
2456 ERROR(errp
, "could not create cm_id!");
2457 goto err_dest_init_create_listen_id
;
2460 snprintf(port_str
, 16, "%d", rdma
->port
);
2461 port_str
[15] = '\0';
2463 ret
= rdma_getaddrinfo(rdma
->host
, port_str
, NULL
, &res
);
2465 ERROR(errp
, "could not rdma_getaddrinfo address %s", rdma
->host
);
2466 goto err_dest_init_bind_addr
;
2469 for (e
= res
; e
!= NULL
; e
= e
->ai_next
) {
2470 inet_ntop(e
->ai_family
,
2471 &((struct sockaddr_in
*) e
->ai_dst_addr
)->sin_addr
, ip
, sizeof ip
);
2472 trace_qemu_rdma_dest_init_trying(rdma
->host
, ip
);
2473 ret
= rdma_bind_addr(listen_id
, e
->ai_dst_addr
);
2477 if (e
->ai_family
== AF_INET6
) {
2478 ret
= qemu_rdma_broken_ipv6_kernel(listen_id
->verbs
, errp
);
2487 ERROR(errp
, "Error: could not rdma_bind_addr!");
2488 goto err_dest_init_bind_addr
;
2491 rdma
->listen_id
= listen_id
;
2492 qemu_rdma_dump_gid("dest_init", listen_id
);
2495 err_dest_init_bind_addr
:
2496 rdma_destroy_id(listen_id
);
2497 err_dest_init_create_listen_id
:
2498 rdma_destroy_event_channel(rdma
->channel
);
2499 rdma
->channel
= NULL
;
2500 rdma
->error_state
= ret
;
2505 static void *qemu_rdma_data_init(const char *host_port
, Error
**errp
)
2507 RDMAContext
*rdma
= NULL
;
2508 InetSocketAddress
*addr
;
2511 rdma
= g_new0(RDMAContext
, 1);
2512 rdma
->current_index
= -1;
2513 rdma
->current_chunk
= -1;
2515 addr
= g_new(InetSocketAddress
, 1);
2516 if (!inet_parse(addr
, host_port
, NULL
)) {
2517 rdma
->port
= atoi(addr
->port
);
2518 rdma
->host
= g_strdup(addr
->host
);
2520 ERROR(errp
, "bad RDMA migration address '%s'", host_port
);
2525 qapi_free_InetSocketAddress(addr
);
2532 * QEMUFile interface to the control channel.
2533 * SEND messages for control only.
2534 * VM's ram is handled with regular RDMA messages.
2536 static ssize_t
qio_channel_rdma_writev(QIOChannel
*ioc
,
2537 const struct iovec
*iov
,
2543 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2544 QEMUFile
*f
= rioc
->file
;
2545 RDMAContext
*rdma
= rioc
->rdma
;
2550 CHECK_ERROR_STATE();
2553 * Push out any writes that
2554 * we're queued up for VM's ram.
2556 ret
= qemu_rdma_write_flush(f
, rdma
);
2558 rdma
->error_state
= ret
;
2562 for (i
= 0; i
< niov
; i
++) {
2563 size_t remaining
= iov
[i
].iov_len
;
2564 uint8_t * data
= (void *)iov
[i
].iov_base
;
2566 RDMAControlHeader head
;
2568 rioc
->len
= MIN(remaining
, RDMA_SEND_INCREMENT
);
2569 remaining
-= rioc
->len
;
2571 head
.len
= rioc
->len
;
2572 head
.type
= RDMA_CONTROL_QEMU_FILE
;
2574 ret
= qemu_rdma_exchange_send(rdma
, &head
, data
, NULL
, NULL
, NULL
);
2577 rdma
->error_state
= ret
;
2589 static size_t qemu_rdma_fill(RDMAContext
*rdma
, uint8_t *buf
,
2590 size_t size
, int idx
)
2594 if (rdma
->wr_data
[idx
].control_len
) {
2595 trace_qemu_rdma_fill(rdma
->wr_data
[idx
].control_len
, size
);
2597 len
= MIN(size
, rdma
->wr_data
[idx
].control_len
);
2598 memcpy(buf
, rdma
->wr_data
[idx
].control_curr
, len
);
2599 rdma
->wr_data
[idx
].control_curr
+= len
;
2600 rdma
->wr_data
[idx
].control_len
-= len
;
2607 * QEMUFile interface to the control channel.
2608 * RDMA links don't use bytestreams, so we have to
2609 * return bytes to QEMUFile opportunistically.
2611 static ssize_t
qio_channel_rdma_readv(QIOChannel
*ioc
,
2612 const struct iovec
*iov
,
2618 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2619 RDMAContext
*rdma
= rioc
->rdma
;
2620 RDMAControlHeader head
;
2625 CHECK_ERROR_STATE();
2627 for (i
= 0; i
< niov
; i
++) {
2628 size_t want
= iov
[i
].iov_len
;
2629 uint8_t *data
= (void *)iov
[i
].iov_base
;
2632 * First, we hold on to the last SEND message we
2633 * were given and dish out the bytes until we run
2636 ret
= qemu_rdma_fill(rioc
->rdma
, data
, want
, 0);
2639 /* Got what we needed, so go to next iovec */
2644 /* If we got any data so far, then don't wait
2645 * for more, just return what we have */
2651 /* We've got nothing at all, so lets wait for
2654 ret
= qemu_rdma_exchange_recv(rdma
, &head
, RDMA_CONTROL_QEMU_FILE
);
2657 rdma
->error_state
= ret
;
2662 * SEND was received with new bytes, now try again.
2664 ret
= qemu_rdma_fill(rioc
->rdma
, data
, want
, 0);
2668 /* Still didn't get enough, so lets just return */
2671 return QIO_CHANNEL_ERR_BLOCK
;
2682 * Block until all the outstanding chunks have been delivered by the hardware.
2684 static int qemu_rdma_drain_cq(QEMUFile
*f
, RDMAContext
*rdma
)
2688 if (qemu_rdma_write_flush(f
, rdma
) < 0) {
2692 while (rdma
->nb_sent
) {
2693 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RDMA_WRITE
, NULL
);
2695 error_report("rdma migration: complete polling error!");
2700 qemu_rdma_unregister_waiting(rdma
);
2706 static int qio_channel_rdma_set_blocking(QIOChannel
*ioc
,
2710 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2711 /* XXX we should make readv/writev actually honour this :-) */
2712 rioc
->blocking
= blocking
;
2717 typedef struct QIOChannelRDMASource QIOChannelRDMASource
;
2718 struct QIOChannelRDMASource
{
2720 QIOChannelRDMA
*rioc
;
2721 GIOCondition condition
;
2725 qio_channel_rdma_source_prepare(GSource
*source
,
2728 QIOChannelRDMASource
*rsource
= (QIOChannelRDMASource
*)source
;
2729 RDMAContext
*rdma
= rsource
->rioc
->rdma
;
2730 GIOCondition cond
= 0;
2733 if (rdma
->wr_data
[0].control_len
) {
2738 return cond
& rsource
->condition
;
2742 qio_channel_rdma_source_check(GSource
*source
)
2744 QIOChannelRDMASource
*rsource
= (QIOChannelRDMASource
*)source
;
2745 RDMAContext
*rdma
= rsource
->rioc
->rdma
;
2746 GIOCondition cond
= 0;
2748 if (rdma
->wr_data
[0].control_len
) {
2753 return cond
& rsource
->condition
;
2757 qio_channel_rdma_source_dispatch(GSource
*source
,
2758 GSourceFunc callback
,
2761 QIOChannelFunc func
= (QIOChannelFunc
)callback
;
2762 QIOChannelRDMASource
*rsource
= (QIOChannelRDMASource
*)source
;
2763 RDMAContext
*rdma
= rsource
->rioc
->rdma
;
2764 GIOCondition cond
= 0;
2766 if (rdma
->wr_data
[0].control_len
) {
2771 return (*func
)(QIO_CHANNEL(rsource
->rioc
),
2772 (cond
& rsource
->condition
),
2777 qio_channel_rdma_source_finalize(GSource
*source
)
2779 QIOChannelRDMASource
*ssource
= (QIOChannelRDMASource
*)source
;
2781 object_unref(OBJECT(ssource
->rioc
));
2784 GSourceFuncs qio_channel_rdma_source_funcs
= {
2785 qio_channel_rdma_source_prepare
,
2786 qio_channel_rdma_source_check
,
2787 qio_channel_rdma_source_dispatch
,
2788 qio_channel_rdma_source_finalize
2791 static GSource
*qio_channel_rdma_create_watch(QIOChannel
*ioc
,
2792 GIOCondition condition
)
2794 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2795 QIOChannelRDMASource
*ssource
;
2798 source
= g_source_new(&qio_channel_rdma_source_funcs
,
2799 sizeof(QIOChannelRDMASource
));
2800 ssource
= (QIOChannelRDMASource
*)source
;
2802 ssource
->rioc
= rioc
;
2803 object_ref(OBJECT(rioc
));
2805 ssource
->condition
= condition
;
2811 static int qio_channel_rdma_close(QIOChannel
*ioc
,
2814 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2815 trace_qemu_rdma_close();
2817 if (!rioc
->rdma
->error_state
) {
2818 rioc
->rdma
->error_state
= qemu_file_get_error(rioc
->file
);
2820 qemu_rdma_cleanup(rioc
->rdma
);
2830 * This means that 'block_offset' is a full virtual address that does not
2831 * belong to a RAMBlock of the virtual machine and instead
2832 * represents a private malloc'd memory area that the caller wishes to
2836 * Offset is an offset to be added to block_offset and used
2837 * to also lookup the corresponding RAMBlock.
2840 * Initiate an transfer this size.
2843 * A 'hint' or 'advice' that means that we wish to speculatively
2844 * and asynchronously unregister this memory. In this case, there is no
2845 * guarantee that the unregister will actually happen, for example,
2846 * if the memory is being actively transmitted. Additionally, the memory
2847 * may be re-registered at any future time if a write within the same
2848 * chunk was requested again, even if you attempted to unregister it
2851 * @size < 0 : TODO, not yet supported
2852 * Unregister the memory NOW. This means that the caller does not
2853 * expect there to be any future RDMA transfers and we just want to clean
2854 * things up. This is used in case the upper layer owns the memory and
2855 * cannot wait for qemu_fclose() to occur.
2857 * @bytes_sent : User-specificed pointer to indicate how many bytes were
2858 * sent. Usually, this will not be more than a few bytes of
2859 * the protocol because most transfers are sent asynchronously.
2861 static size_t qemu_rdma_save_page(QEMUFile
*f
, void *opaque
,
2862 ram_addr_t block_offset
, ram_addr_t offset
,
2863 size_t size
, uint64_t *bytes_sent
)
2865 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
2866 RDMAContext
*rdma
= rioc
->rdma
;
2869 CHECK_ERROR_STATE();
2875 * Add this page to the current 'chunk'. If the chunk
2876 * is full, or the page doen't belong to the current chunk,
2877 * an actual RDMA write will occur and a new chunk will be formed.
2879 ret
= qemu_rdma_write(f
, rdma
, block_offset
, offset
, size
);
2881 error_report("rdma migration: write error! %d", ret
);
2886 * We always return 1 bytes because the RDMA
2887 * protocol is completely asynchronous. We do not yet know
2888 * whether an identified chunk is zero or not because we're
2889 * waiting for other pages to potentially be merged with
2890 * the current chunk. So, we have to call qemu_update_position()
2891 * later on when the actual write occurs.
2897 uint64_t index
, chunk
;
2899 /* TODO: Change QEMUFileOps prototype to be signed: size_t => long
2901 ret = qemu_rdma_drain_cq(f, rdma);
2903 fprintf(stderr, "rdma: failed to synchronously drain"
2904 " completion queue before unregistration.\n");
2910 ret
= qemu_rdma_search_ram_block(rdma
, block_offset
,
2911 offset
, size
, &index
, &chunk
);
2914 error_report("ram block search failed");
2918 qemu_rdma_signal_unregister(rdma
, index
, chunk
, 0);
2921 * TODO: Synchronous, guaranteed unregistration (should not occur during
2922 * fast-path). Otherwise, unregisters will process on the next call to
2923 * qemu_rdma_drain_cq()
2925 qemu_rdma_unregister_waiting(rdma);
2931 * Drain the Completion Queue if possible, but do not block,
2934 * If nothing to poll, the end of the iteration will do this
2935 * again to make sure we don't overflow the request queue.
2938 uint64_t wr_id
, wr_id_in
;
2939 int ret
= qemu_rdma_poll(rdma
, &wr_id_in
, NULL
);
2941 error_report("rdma migration: polling error! %d", ret
);
2945 wr_id
= wr_id_in
& RDMA_WRID_TYPE_MASK
;
2947 if (wr_id
== RDMA_WRID_NONE
) {
2952 return RAM_SAVE_CONTROL_DELAYED
;
2954 rdma
->error_state
= ret
;
2958 static int qemu_rdma_accept(RDMAContext
*rdma
)
2960 RDMACapabilities cap
;
2961 struct rdma_conn_param conn_param
= {
2962 .responder_resources
= 2,
2963 .private_data
= &cap
,
2964 .private_data_len
= sizeof(cap
),
2966 struct rdma_cm_event
*cm_event
;
2967 struct ibv_context
*verbs
;
2971 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
2973 goto err_rdma_dest_wait
;
2976 if (cm_event
->event
!= RDMA_CM_EVENT_CONNECT_REQUEST
) {
2977 rdma_ack_cm_event(cm_event
);
2978 goto err_rdma_dest_wait
;
2981 memcpy(&cap
, cm_event
->param
.conn
.private_data
, sizeof(cap
));
2983 network_to_caps(&cap
);
2985 if (cap
.version
< 1 || cap
.version
> RDMA_CONTROL_VERSION_CURRENT
) {
2986 error_report("Unknown source RDMA version: %d, bailing...",
2988 rdma_ack_cm_event(cm_event
);
2989 goto err_rdma_dest_wait
;
2993 * Respond with only the capabilities this version of QEMU knows about.
2995 cap
.flags
&= known_capabilities
;
2998 * Enable the ones that we do know about.
2999 * Add other checks here as new ones are introduced.
3001 if (cap
.flags
& RDMA_CAPABILITY_PIN_ALL
) {
3002 rdma
->pin_all
= true;
3005 rdma
->cm_id
= cm_event
->id
;
3006 verbs
= cm_event
->id
->verbs
;
3008 rdma_ack_cm_event(cm_event
);
3010 trace_qemu_rdma_accept_pin_state(rdma
->pin_all
);
3012 caps_to_network(&cap
);
3014 trace_qemu_rdma_accept_pin_verbsc(verbs
);
3017 rdma
->verbs
= verbs
;
3018 } else if (rdma
->verbs
!= verbs
) {
3019 error_report("ibv context not matching %p, %p!", rdma
->verbs
,
3021 goto err_rdma_dest_wait
;
3024 qemu_rdma_dump_id("dest_init", verbs
);
3026 ret
= qemu_rdma_alloc_pd_cq(rdma
);
3028 error_report("rdma migration: error allocating pd and cq!");
3029 goto err_rdma_dest_wait
;
3032 ret
= qemu_rdma_alloc_qp(rdma
);
3034 error_report("rdma migration: error allocating qp!");
3035 goto err_rdma_dest_wait
;
3038 ret
= qemu_rdma_init_ram_blocks(rdma
);
3040 error_report("rdma migration: error initializing ram blocks!");
3041 goto err_rdma_dest_wait
;
3044 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
3045 ret
= qemu_rdma_reg_control(rdma
, idx
);
3047 error_report("rdma: error registering %d control", idx
);
3048 goto err_rdma_dest_wait
;
3052 qemu_set_fd_handler(rdma
->channel
->fd
, NULL
, NULL
, NULL
);
3054 ret
= rdma_accept(rdma
->cm_id
, &conn_param
);
3056 error_report("rdma_accept returns %d", ret
);
3057 goto err_rdma_dest_wait
;
3060 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
3062 error_report("rdma_accept get_cm_event failed %d", ret
);
3063 goto err_rdma_dest_wait
;
3066 if (cm_event
->event
!= RDMA_CM_EVENT_ESTABLISHED
) {
3067 error_report("rdma_accept not event established");
3068 rdma_ack_cm_event(cm_event
);
3069 goto err_rdma_dest_wait
;
3072 rdma_ack_cm_event(cm_event
);
3073 rdma
->connected
= true;
3075 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
3077 error_report("rdma migration: error posting second control recv");
3078 goto err_rdma_dest_wait
;
3081 qemu_rdma_dump_gid("dest_connect", rdma
->cm_id
);
3086 rdma
->error_state
= ret
;
3087 qemu_rdma_cleanup(rdma
);
3091 static int dest_ram_sort_func(const void *a
, const void *b
)
3093 unsigned int a_index
= ((const RDMALocalBlock
*)a
)->src_index
;
3094 unsigned int b_index
= ((const RDMALocalBlock
*)b
)->src_index
;
3096 return (a_index
< b_index
) ? -1 : (a_index
!= b_index
);
3100 * During each iteration of the migration, we listen for instructions
3101 * by the source VM to perform dynamic page registrations before they
3102 * can perform RDMA operations.
3104 * We respond with the 'rkey'.
3106 * Keep doing this until the source tells us to stop.
3108 static int qemu_rdma_registration_handle(QEMUFile
*f
, void *opaque
)
3110 RDMAControlHeader reg_resp
= { .len
= sizeof(RDMARegisterResult
),
3111 .type
= RDMA_CONTROL_REGISTER_RESULT
,
3114 RDMAControlHeader unreg_resp
= { .len
= 0,
3115 .type
= RDMA_CONTROL_UNREGISTER_FINISHED
,
3118 RDMAControlHeader blocks
= { .type
= RDMA_CONTROL_RAM_BLOCKS_RESULT
,
3120 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
3121 RDMAContext
*rdma
= rioc
->rdma
;
3122 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
3123 RDMAControlHeader head
;
3124 RDMARegister
*reg
, *registers
;
3126 RDMARegisterResult
*reg_result
;
3127 static RDMARegisterResult results
[RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE
];
3128 RDMALocalBlock
*block
;
3135 CHECK_ERROR_STATE();
3138 trace_qemu_rdma_registration_handle_wait();
3140 ret
= qemu_rdma_exchange_recv(rdma
, &head
, RDMA_CONTROL_NONE
);
3146 if (head
.repeat
> RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE
) {
3147 error_report("rdma: Too many requests in this message (%d)."
3148 "Bailing.", head
.repeat
);
3153 switch (head
.type
) {
3154 case RDMA_CONTROL_COMPRESS
:
3155 comp
= (RDMACompress
*) rdma
->wr_data
[idx
].control_curr
;
3156 network_to_compress(comp
);
3158 trace_qemu_rdma_registration_handle_compress(comp
->length
,
3161 if (comp
->block_idx
>= rdma
->local_ram_blocks
.nb_blocks
) {
3162 error_report("rdma: 'compress' bad block index %u (vs %d)",
3163 (unsigned int)comp
->block_idx
,
3164 rdma
->local_ram_blocks
.nb_blocks
);
3168 block
= &(rdma
->local_ram_blocks
.block
[comp
->block_idx
]);
3170 host_addr
= block
->local_host_addr
+
3171 (comp
->offset
- block
->offset
);
3173 ram_handle_compressed(host_addr
, comp
->value
, comp
->length
);
3176 case RDMA_CONTROL_REGISTER_FINISHED
:
3177 trace_qemu_rdma_registration_handle_finished();
3180 case RDMA_CONTROL_RAM_BLOCKS_REQUEST
:
3181 trace_qemu_rdma_registration_handle_ram_blocks();
3183 /* Sort our local RAM Block list so it's the same as the source,
3184 * we can do this since we've filled in a src_index in the list
3185 * as we received the RAMBlock list earlier.
3187 qsort(rdma
->local_ram_blocks
.block
,
3188 rdma
->local_ram_blocks
.nb_blocks
,
3189 sizeof(RDMALocalBlock
), dest_ram_sort_func
);
3190 if (rdma
->pin_all
) {
3191 ret
= qemu_rdma_reg_whole_ram_blocks(rdma
);
3193 error_report("rdma migration: error dest "
3194 "registering ram blocks");
3200 * Dest uses this to prepare to transmit the RAMBlock descriptions
3201 * to the source VM after connection setup.
3202 * Both sides use the "remote" structure to communicate and update
3203 * their "local" descriptions with what was sent.
3205 for (i
= 0; i
< local
->nb_blocks
; i
++) {
3206 rdma
->dest_blocks
[i
].remote_host_addr
=
3207 (uintptr_t)(local
->block
[i
].local_host_addr
);
3209 if (rdma
->pin_all
) {
3210 rdma
->dest_blocks
[i
].remote_rkey
= local
->block
[i
].mr
->rkey
;
3213 rdma
->dest_blocks
[i
].offset
= local
->block
[i
].offset
;
3214 rdma
->dest_blocks
[i
].length
= local
->block
[i
].length
;
3216 dest_block_to_network(&rdma
->dest_blocks
[i
]);
3217 trace_qemu_rdma_registration_handle_ram_blocks_loop(
3218 local
->block
[i
].block_name
,
3219 local
->block
[i
].offset
,
3220 local
->block
[i
].length
,
3221 local
->block
[i
].local_host_addr
,
3222 local
->block
[i
].src_index
);
3225 blocks
.len
= rdma
->local_ram_blocks
.nb_blocks
3226 * sizeof(RDMADestBlock
);
3229 ret
= qemu_rdma_post_send_control(rdma
,
3230 (uint8_t *) rdma
->dest_blocks
, &blocks
);
3233 error_report("rdma migration: error sending remote info");
3238 case RDMA_CONTROL_REGISTER_REQUEST
:
3239 trace_qemu_rdma_registration_handle_register(head
.repeat
);
3241 reg_resp
.repeat
= head
.repeat
;
3242 registers
= (RDMARegister
*) rdma
->wr_data
[idx
].control_curr
;
3244 for (count
= 0; count
< head
.repeat
; count
++) {
3246 uint8_t *chunk_start
, *chunk_end
;
3248 reg
= ®isters
[count
];
3249 network_to_register(reg
);
3251 reg_result
= &results
[count
];
3253 trace_qemu_rdma_registration_handle_register_loop(count
,
3254 reg
->current_index
, reg
->key
.current_addr
, reg
->chunks
);
3256 if (reg
->current_index
>= rdma
->local_ram_blocks
.nb_blocks
) {
3257 error_report("rdma: 'register' bad block index %u (vs %d)",
3258 (unsigned int)reg
->current_index
,
3259 rdma
->local_ram_blocks
.nb_blocks
);
3263 block
= &(rdma
->local_ram_blocks
.block
[reg
->current_index
]);
3264 if (block
->is_ram_block
) {
3265 if (block
->offset
> reg
->key
.current_addr
) {
3266 error_report("rdma: bad register address for block %s"
3267 " offset: %" PRIx64
" current_addr: %" PRIx64
,
3268 block
->block_name
, block
->offset
,
3269 reg
->key
.current_addr
);
3273 host_addr
= (block
->local_host_addr
+
3274 (reg
->key
.current_addr
- block
->offset
));
3275 chunk
= ram_chunk_index(block
->local_host_addr
,
3276 (uint8_t *) host_addr
);
3278 chunk
= reg
->key
.chunk
;
3279 host_addr
= block
->local_host_addr
+
3280 (reg
->key
.chunk
* (1UL << RDMA_REG_CHUNK_SHIFT
));
3281 /* Check for particularly bad chunk value */
3282 if (host_addr
< (void *)block
->local_host_addr
) {
3283 error_report("rdma: bad chunk for block %s"
3285 block
->block_name
, reg
->key
.chunk
);
3290 chunk_start
= ram_chunk_start(block
, chunk
);
3291 chunk_end
= ram_chunk_end(block
, chunk
+ reg
->chunks
);
3292 if (qemu_rdma_register_and_get_keys(rdma
, block
,
3293 (uintptr_t)host_addr
, NULL
, ®_result
->rkey
,
3294 chunk
, chunk_start
, chunk_end
)) {
3295 error_report("cannot get rkey");
3300 reg_result
->host_addr
= (uintptr_t)block
->local_host_addr
;
3302 trace_qemu_rdma_registration_handle_register_rkey(
3305 result_to_network(reg_result
);
3308 ret
= qemu_rdma_post_send_control(rdma
,
3309 (uint8_t *) results
, ®_resp
);
3312 error_report("Failed to send control buffer");
3316 case RDMA_CONTROL_UNREGISTER_REQUEST
:
3317 trace_qemu_rdma_registration_handle_unregister(head
.repeat
);
3318 unreg_resp
.repeat
= head
.repeat
;
3319 registers
= (RDMARegister
*) rdma
->wr_data
[idx
].control_curr
;
3321 for (count
= 0; count
< head
.repeat
; count
++) {
3322 reg
= ®isters
[count
];
3323 network_to_register(reg
);
3325 trace_qemu_rdma_registration_handle_unregister_loop(count
,
3326 reg
->current_index
, reg
->key
.chunk
);
3328 block
= &(rdma
->local_ram_blocks
.block
[reg
->current_index
]);
3330 ret
= ibv_dereg_mr(block
->pmr
[reg
->key
.chunk
]);
3331 block
->pmr
[reg
->key
.chunk
] = NULL
;
3334 perror("rdma unregistration chunk failed");
3339 rdma
->total_registrations
--;
3341 trace_qemu_rdma_registration_handle_unregister_success(
3345 ret
= qemu_rdma_post_send_control(rdma
, NULL
, &unreg_resp
);
3348 error_report("Failed to send control buffer");
3352 case RDMA_CONTROL_REGISTER_RESULT
:
3353 error_report("Invalid RESULT message at dest.");
3357 error_report("Unknown control message %s", control_desc
[head
.type
]);
3364 rdma
->error_state
= ret
;
3370 * Called via a ram_control_load_hook during the initial RAM load section which
3371 * lists the RAMBlocks by name. This lets us know the order of the RAMBlocks
3373 * We've already built our local RAMBlock list, but not yet sent the list to
3377 rdma_block_notification_handle(QIOChannelRDMA
*rioc
, const char *name
)
3379 RDMAContext
*rdma
= rioc
->rdma
;
3383 /* Find the matching RAMBlock in our local list */
3384 for (curr
= 0; curr
< rdma
->local_ram_blocks
.nb_blocks
; curr
++) {
3385 if (!strcmp(rdma
->local_ram_blocks
.block
[curr
].block_name
, name
)) {
3392 error_report("RAMBlock '%s' not found on destination", name
);
3396 rdma
->local_ram_blocks
.block
[curr
].src_index
= rdma
->next_src_index
;
3397 trace_rdma_block_notification_handle(name
, rdma
->next_src_index
);
3398 rdma
->next_src_index
++;
3403 static int rdma_load_hook(QEMUFile
*f
, void *opaque
, uint64_t flags
, void *data
)
3406 case RAM_CONTROL_BLOCK_REG
:
3407 return rdma_block_notification_handle(opaque
, data
);
3409 case RAM_CONTROL_HOOK
:
3410 return qemu_rdma_registration_handle(f
, opaque
);
3413 /* Shouldn't be called with any other values */
3418 static int qemu_rdma_registration_start(QEMUFile
*f
, void *opaque
,
3419 uint64_t flags
, void *data
)
3421 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
3422 RDMAContext
*rdma
= rioc
->rdma
;
3424 CHECK_ERROR_STATE();
3426 trace_qemu_rdma_registration_start(flags
);
3427 qemu_put_be64(f
, RAM_SAVE_FLAG_HOOK
);
3434 * Inform dest that dynamic registrations are done for now.
3435 * First, flush writes, if any.
3437 static int qemu_rdma_registration_stop(QEMUFile
*f
, void *opaque
,
3438 uint64_t flags
, void *data
)
3440 Error
*local_err
= NULL
, **errp
= &local_err
;
3441 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
3442 RDMAContext
*rdma
= rioc
->rdma
;
3443 RDMAControlHeader head
= { .len
= 0, .repeat
= 1 };
3446 CHECK_ERROR_STATE();
3449 ret
= qemu_rdma_drain_cq(f
, rdma
);
3455 if (flags
== RAM_CONTROL_SETUP
) {
3456 RDMAControlHeader resp
= {.type
= RDMA_CONTROL_RAM_BLOCKS_RESULT
};
3457 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
3458 int reg_result_idx
, i
, nb_dest_blocks
;
3460 head
.type
= RDMA_CONTROL_RAM_BLOCKS_REQUEST
;
3461 trace_qemu_rdma_registration_stop_ram();
3464 * Make sure that we parallelize the pinning on both sides.
3465 * For very large guests, doing this serially takes a really
3466 * long time, so we have to 'interleave' the pinning locally
3467 * with the control messages by performing the pinning on this
3468 * side before we receive the control response from the other
3469 * side that the pinning has completed.
3471 ret
= qemu_rdma_exchange_send(rdma
, &head
, NULL
, &resp
,
3472 ®_result_idx
, rdma
->pin_all
?
3473 qemu_rdma_reg_whole_ram_blocks
: NULL
);
3475 ERROR(errp
, "receiving remote info!");
3479 nb_dest_blocks
= resp
.len
/ sizeof(RDMADestBlock
);
3482 * The protocol uses two different sets of rkeys (mutually exclusive):
3483 * 1. One key to represent the virtual address of the entire ram block.
3484 * (dynamic chunk registration disabled - pin everything with one rkey.)
3485 * 2. One to represent individual chunks within a ram block.
3486 * (dynamic chunk registration enabled - pin individual chunks.)
3488 * Once the capability is successfully negotiated, the destination transmits
3489 * the keys to use (or sends them later) including the virtual addresses
3490 * and then propagates the remote ram block descriptions to his local copy.
3493 if (local
->nb_blocks
!= nb_dest_blocks
) {
3494 ERROR(errp
, "ram blocks mismatch (Number of blocks %d vs %d) "
3495 "Your QEMU command line parameters are probably "
3496 "not identical on both the source and destination.",
3497 local
->nb_blocks
, nb_dest_blocks
);
3498 rdma
->error_state
= -EINVAL
;
3502 qemu_rdma_move_header(rdma
, reg_result_idx
, &resp
);
3503 memcpy(rdma
->dest_blocks
,
3504 rdma
->wr_data
[reg_result_idx
].control_curr
, resp
.len
);
3505 for (i
= 0; i
< nb_dest_blocks
; i
++) {
3506 network_to_dest_block(&rdma
->dest_blocks
[i
]);
3508 /* We require that the blocks are in the same order */
3509 if (rdma
->dest_blocks
[i
].length
!= local
->block
[i
].length
) {
3510 ERROR(errp
, "Block %s/%d has a different length %" PRIu64
3511 "vs %" PRIu64
, local
->block
[i
].block_name
, i
,
3512 local
->block
[i
].length
,
3513 rdma
->dest_blocks
[i
].length
);
3514 rdma
->error_state
= -EINVAL
;
3517 local
->block
[i
].remote_host_addr
=
3518 rdma
->dest_blocks
[i
].remote_host_addr
;
3519 local
->block
[i
].remote_rkey
= rdma
->dest_blocks
[i
].remote_rkey
;
3523 trace_qemu_rdma_registration_stop(flags
);
3525 head
.type
= RDMA_CONTROL_REGISTER_FINISHED
;
3526 ret
= qemu_rdma_exchange_send(rdma
, &head
, NULL
, NULL
, NULL
, NULL
);
3534 rdma
->error_state
= ret
;
3538 static const QEMUFileHooks rdma_read_hooks
= {
3539 .hook_ram_load
= rdma_load_hook
,
3542 static const QEMUFileHooks rdma_write_hooks
= {
3543 .before_ram_iterate
= qemu_rdma_registration_start
,
3544 .after_ram_iterate
= qemu_rdma_registration_stop
,
3545 .save_page
= qemu_rdma_save_page
,
3549 static void qio_channel_rdma_finalize(Object
*obj
)
3551 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(obj
);
3553 qemu_rdma_cleanup(rioc
->rdma
);
3559 static void qio_channel_rdma_class_init(ObjectClass
*klass
,
3560 void *class_data G_GNUC_UNUSED
)
3562 QIOChannelClass
*ioc_klass
= QIO_CHANNEL_CLASS(klass
);
3564 ioc_klass
->io_writev
= qio_channel_rdma_writev
;
3565 ioc_klass
->io_readv
= qio_channel_rdma_readv
;
3566 ioc_klass
->io_set_blocking
= qio_channel_rdma_set_blocking
;
3567 ioc_klass
->io_close
= qio_channel_rdma_close
;
3568 ioc_klass
->io_create_watch
= qio_channel_rdma_create_watch
;
3571 static const TypeInfo qio_channel_rdma_info
= {
3572 .parent
= TYPE_QIO_CHANNEL
,
3573 .name
= TYPE_QIO_CHANNEL_RDMA
,
3574 .instance_size
= sizeof(QIOChannelRDMA
),
3575 .instance_finalize
= qio_channel_rdma_finalize
,
3576 .class_init
= qio_channel_rdma_class_init
,
3579 static void qio_channel_rdma_register_types(void)
3581 type_register_static(&qio_channel_rdma_info
);
3584 type_init(qio_channel_rdma_register_types
);
3586 static QEMUFile
*qemu_fopen_rdma(RDMAContext
*rdma
, const char *mode
)
3588 QIOChannelRDMA
*rioc
;
3590 if (qemu_file_mode_is_not_valid(mode
)) {
3594 rioc
= QIO_CHANNEL_RDMA(object_new(TYPE_QIO_CHANNEL_RDMA
));
3597 if (mode
[0] == 'w') {
3598 rioc
->file
= qemu_fopen_channel_output(QIO_CHANNEL(rioc
));
3599 qemu_file_set_hooks(rioc
->file
, &rdma_write_hooks
);
3601 rioc
->file
= qemu_fopen_channel_input(QIO_CHANNEL(rioc
));
3602 qemu_file_set_hooks(rioc
->file
, &rdma_read_hooks
);
3608 static void rdma_accept_incoming_migration(void *opaque
)
3610 RDMAContext
*rdma
= opaque
;
3613 Error
*local_err
= NULL
, **errp
= &local_err
;
3615 trace_qemu_rdma_accept_incoming_migration();
3616 ret
= qemu_rdma_accept(rdma
);
3619 ERROR(errp
, "RDMA Migration initialization failed!");
3623 trace_qemu_rdma_accept_incoming_migration_accepted();
3625 f
= qemu_fopen_rdma(rdma
, "rb");
3627 ERROR(errp
, "could not qemu_fopen_rdma!");
3628 qemu_rdma_cleanup(rdma
);
3632 rdma
->migration_started_on_destination
= 1;
3633 migration_fd_process_incoming(f
);
3636 void rdma_start_incoming_migration(const char *host_port
, Error
**errp
)
3640 Error
*local_err
= NULL
;
3642 trace_rdma_start_incoming_migration();
3643 rdma
= qemu_rdma_data_init(host_port
, &local_err
);
3649 ret
= qemu_rdma_dest_init(rdma
, &local_err
);
3655 trace_rdma_start_incoming_migration_after_dest_init();
3657 ret
= rdma_listen(rdma
->listen_id
, 5);
3660 ERROR(errp
, "listening on socket!");
3664 trace_rdma_start_incoming_migration_after_rdma_listen();
3666 qemu_set_fd_handler(rdma
->channel
->fd
, rdma_accept_incoming_migration
,
3667 NULL
, (void *)(intptr_t)rdma
);
3670 error_propagate(errp
, local_err
);
3674 void rdma_start_outgoing_migration(void *opaque
,
3675 const char *host_port
, Error
**errp
)
3677 MigrationState
*s
= opaque
;
3678 RDMAContext
*rdma
= qemu_rdma_data_init(host_port
, errp
);
3685 ret
= qemu_rdma_source_init(rdma
,
3686 s
->enabled_capabilities
[MIGRATION_CAPABILITY_RDMA_PIN_ALL
], errp
);
3692 trace_rdma_start_outgoing_migration_after_rdma_source_init();
3693 ret
= qemu_rdma_connect(rdma
, errp
);
3699 trace_rdma_start_outgoing_migration_after_rdma_connect();
3701 s
->to_dst_file
= qemu_fopen_rdma(rdma
, "wb");
3702 migrate_fd_connect(s
);