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; \
90 return rdma->error_state; \
95 * A work request ID is 64-bits and we split up these bits
98 * bits 0-15 : type of control message, 2^16
99 * bits 16-29: ram block index, 2^14
100 * bits 30-63: ram block chunk number, 2^34
102 * The last two bit ranges are only used for RDMA writes,
103 * in order to track their completion and potentially
104 * also track unregistration status of the message.
106 #define RDMA_WRID_TYPE_SHIFT 0UL
107 #define RDMA_WRID_BLOCK_SHIFT 16UL
108 #define RDMA_WRID_CHUNK_SHIFT 30UL
110 #define RDMA_WRID_TYPE_MASK \
111 ((1UL << RDMA_WRID_BLOCK_SHIFT) - 1UL)
113 #define RDMA_WRID_BLOCK_MASK \
114 (~RDMA_WRID_TYPE_MASK & ((1UL << RDMA_WRID_CHUNK_SHIFT) - 1UL))
116 #define RDMA_WRID_CHUNK_MASK (~RDMA_WRID_BLOCK_MASK & ~RDMA_WRID_TYPE_MASK)
119 * RDMA migration protocol:
120 * 1. RDMA Writes (data messages, i.e. RAM)
121 * 2. IB Send/Recv (control channel messages)
125 RDMA_WRID_RDMA_WRITE
= 1,
126 RDMA_WRID_SEND_CONTROL
= 2000,
127 RDMA_WRID_RECV_CONTROL
= 4000,
130 static const char *wrid_desc
[] = {
131 [RDMA_WRID_NONE
] = "NONE",
132 [RDMA_WRID_RDMA_WRITE
] = "WRITE RDMA",
133 [RDMA_WRID_SEND_CONTROL
] = "CONTROL SEND",
134 [RDMA_WRID_RECV_CONTROL
] = "CONTROL RECV",
138 * Work request IDs for IB SEND messages only (not RDMA writes).
139 * This is used by the migration protocol to transmit
140 * control messages (such as device state and registration commands)
142 * We could use more WRs, but we have enough for now.
152 * SEND/RECV IB Control Messages.
155 RDMA_CONTROL_NONE
= 0,
157 RDMA_CONTROL_READY
, /* ready to receive */
158 RDMA_CONTROL_QEMU_FILE
, /* QEMUFile-transmitted bytes */
159 RDMA_CONTROL_RAM_BLOCKS_REQUEST
, /* RAMBlock synchronization */
160 RDMA_CONTROL_RAM_BLOCKS_RESULT
, /* RAMBlock synchronization */
161 RDMA_CONTROL_COMPRESS
, /* page contains repeat values */
162 RDMA_CONTROL_REGISTER_REQUEST
, /* dynamic page registration */
163 RDMA_CONTROL_REGISTER_RESULT
, /* key to use after registration */
164 RDMA_CONTROL_REGISTER_FINISHED
, /* current iteration finished */
165 RDMA_CONTROL_UNREGISTER_REQUEST
, /* dynamic UN-registration */
166 RDMA_CONTROL_UNREGISTER_FINISHED
, /* unpinning finished */
171 * Memory and MR structures used to represent an IB Send/Recv work request.
172 * This is *not* used for RDMA writes, only IB Send/Recv.
175 uint8_t control
[RDMA_CONTROL_MAX_BUFFER
]; /* actual buffer to register */
176 struct ibv_mr
*control_mr
; /* registration metadata */
177 size_t control_len
; /* length of the message */
178 uint8_t *control_curr
; /* start of unconsumed bytes */
179 } RDMAWorkRequestData
;
182 * Negotiate RDMA capabilities during connection-setup time.
189 static void caps_to_network(RDMACapabilities
*cap
)
191 cap
->version
= htonl(cap
->version
);
192 cap
->flags
= htonl(cap
->flags
);
195 static void network_to_caps(RDMACapabilities
*cap
)
197 cap
->version
= ntohl(cap
->version
);
198 cap
->flags
= ntohl(cap
->flags
);
202 * Representation of a RAMBlock from an RDMA perspective.
203 * This is not transmitted, only local.
204 * This and subsequent structures cannot be linked lists
205 * because we're using a single IB message to transmit
206 * the information. It's small anyway, so a list is overkill.
208 typedef struct RDMALocalBlock
{
210 uint8_t *local_host_addr
; /* local virtual address */
211 uint64_t remote_host_addr
; /* remote virtual address */
214 struct ibv_mr
**pmr
; /* MRs for chunk-level registration */
215 struct ibv_mr
*mr
; /* MR for non-chunk-level registration */
216 uint32_t *remote_keys
; /* rkeys for chunk-level registration */
217 uint32_t remote_rkey
; /* rkeys for non-chunk-level registration */
218 int index
; /* which block are we */
219 unsigned int src_index
; /* (Only used on dest) */
222 unsigned long *transit_bitmap
;
223 unsigned long *unregister_bitmap
;
227 * Also represents a RAMblock, but only on the dest.
228 * This gets transmitted by the dest during connection-time
229 * to the source VM and then is used to populate the
230 * corresponding RDMALocalBlock with
231 * the information needed to perform the actual RDMA.
233 typedef struct QEMU_PACKED RDMADestBlock
{
234 uint64_t remote_host_addr
;
237 uint32_t remote_rkey
;
241 static const char *control_desc(unsigned int rdma_control
)
243 static const char *strs
[] = {
244 [RDMA_CONTROL_NONE
] = "NONE",
245 [RDMA_CONTROL_ERROR
] = "ERROR",
246 [RDMA_CONTROL_READY
] = "READY",
247 [RDMA_CONTROL_QEMU_FILE
] = "QEMU FILE",
248 [RDMA_CONTROL_RAM_BLOCKS_REQUEST
] = "RAM BLOCKS REQUEST",
249 [RDMA_CONTROL_RAM_BLOCKS_RESULT
] = "RAM BLOCKS RESULT",
250 [RDMA_CONTROL_COMPRESS
] = "COMPRESS",
251 [RDMA_CONTROL_REGISTER_REQUEST
] = "REGISTER REQUEST",
252 [RDMA_CONTROL_REGISTER_RESULT
] = "REGISTER RESULT",
253 [RDMA_CONTROL_REGISTER_FINISHED
] = "REGISTER FINISHED",
254 [RDMA_CONTROL_UNREGISTER_REQUEST
] = "UNREGISTER REQUEST",
255 [RDMA_CONTROL_UNREGISTER_FINISHED
] = "UNREGISTER FINISHED",
258 if (rdma_control
> RDMA_CONTROL_UNREGISTER_FINISHED
) {
259 return "??BAD CONTROL VALUE??";
262 return strs
[rdma_control
];
265 static uint64_t htonll(uint64_t v
)
267 union { uint32_t lv
[2]; uint64_t llv
; } u
;
268 u
.lv
[0] = htonl(v
>> 32);
269 u
.lv
[1] = htonl(v
& 0xFFFFFFFFULL
);
273 static uint64_t ntohll(uint64_t v
) {
274 union { uint32_t lv
[2]; uint64_t llv
; } u
;
276 return ((uint64_t)ntohl(u
.lv
[0]) << 32) | (uint64_t) ntohl(u
.lv
[1]);
279 static void dest_block_to_network(RDMADestBlock
*db
)
281 db
->remote_host_addr
= htonll(db
->remote_host_addr
);
282 db
->offset
= htonll(db
->offset
);
283 db
->length
= htonll(db
->length
);
284 db
->remote_rkey
= htonl(db
->remote_rkey
);
287 static void network_to_dest_block(RDMADestBlock
*db
)
289 db
->remote_host_addr
= ntohll(db
->remote_host_addr
);
290 db
->offset
= ntohll(db
->offset
);
291 db
->length
= ntohll(db
->length
);
292 db
->remote_rkey
= ntohl(db
->remote_rkey
);
296 * Virtual address of the above structures used for transmitting
297 * the RAMBlock descriptions at connection-time.
298 * This structure is *not* transmitted.
300 typedef struct RDMALocalBlocks
{
302 bool init
; /* main memory init complete */
303 RDMALocalBlock
*block
;
307 * Main data structure for RDMA state.
308 * While there is only one copy of this structure being allocated right now,
309 * this is the place where one would start if you wanted to consider
310 * having more than one RDMA connection open at the same time.
312 typedef struct RDMAContext
{
316 RDMAWorkRequestData wr_data
[RDMA_WRID_MAX
];
319 * This is used by *_exchange_send() to figure out whether or not
320 * the initial "READY" message has already been received or not.
321 * This is because other functions may potentially poll() and detect
322 * the READY message before send() does, in which case we need to
323 * know if it completed.
325 int control_ready_expected
;
327 /* number of outstanding writes */
330 /* store info about current buffer so that we can
331 merge it with future sends */
332 uint64_t current_addr
;
333 uint64_t current_length
;
334 /* index of ram block the current buffer belongs to */
336 /* index of the chunk in the current ram block */
342 * infiniband-specific variables for opening the device
343 * and maintaining connection state and so forth.
345 * cm_id also has ibv_context, rdma_event_channel, and ibv_qp in
346 * cm_id->verbs, cm_id->channel, and cm_id->qp.
348 struct rdma_cm_id
*cm_id
; /* connection manager ID */
349 struct rdma_cm_id
*listen_id
;
352 struct ibv_context
*verbs
;
353 struct rdma_event_channel
*channel
;
354 struct ibv_qp
*qp
; /* queue pair */
355 struct ibv_comp_channel
*comp_channel
; /* completion channel */
356 struct ibv_pd
*pd
; /* protection domain */
357 struct ibv_cq
*cq
; /* completion queue */
360 * If a previous write failed (perhaps because of a failed
361 * memory registration, then do not attempt any future work
362 * and remember the error state.
369 * Description of ram blocks used throughout the code.
371 RDMALocalBlocks local_ram_blocks
;
372 RDMADestBlock
*dest_blocks
;
374 /* Index of the next RAMBlock received during block registration */
375 unsigned int next_src_index
;
378 * Migration on *destination* started.
379 * Then use coroutine yield function.
380 * Source runs in a thread, so we don't care.
382 int migration_started_on_destination
;
384 int total_registrations
;
387 int unregister_current
, unregister_next
;
388 uint64_t unregistrations
[RDMA_SIGNALED_SEND_MAX
];
390 GHashTable
*blockmap
;
392 /* the RDMAContext for return path */
393 struct RDMAContext
*return_path
;
397 #define TYPE_QIO_CHANNEL_RDMA "qio-channel-rdma"
398 #define QIO_CHANNEL_RDMA(obj) \
399 OBJECT_CHECK(QIOChannelRDMA, (obj), TYPE_QIO_CHANNEL_RDMA)
401 typedef struct QIOChannelRDMA QIOChannelRDMA
;
404 struct QIOChannelRDMA
{
407 RDMAContext
*rdmaout
;
409 bool blocking
; /* XXX we don't actually honour this yet */
413 * Main structure for IB Send/Recv control messages.
414 * This gets prepended at the beginning of every Send/Recv.
416 typedef struct QEMU_PACKED
{
417 uint32_t len
; /* Total length of data portion */
418 uint32_t type
; /* which control command to perform */
419 uint32_t repeat
; /* number of commands in data portion of same type */
423 static void control_to_network(RDMAControlHeader
*control
)
425 control
->type
= htonl(control
->type
);
426 control
->len
= htonl(control
->len
);
427 control
->repeat
= htonl(control
->repeat
);
430 static void network_to_control(RDMAControlHeader
*control
)
432 control
->type
= ntohl(control
->type
);
433 control
->len
= ntohl(control
->len
);
434 control
->repeat
= ntohl(control
->repeat
);
438 * Register a single Chunk.
439 * Information sent by the source VM to inform the dest
440 * to register an single chunk of memory before we can perform
441 * the actual RDMA operation.
443 typedef struct QEMU_PACKED
{
445 uint64_t current_addr
; /* offset into the ram_addr_t space */
446 uint64_t chunk
; /* chunk to lookup if unregistering */
448 uint32_t current_index
; /* which ramblock the chunk belongs to */
450 uint64_t chunks
; /* how many sequential chunks to register */
453 static void register_to_network(RDMAContext
*rdma
, RDMARegister
*reg
)
455 RDMALocalBlock
*local_block
;
456 local_block
= &rdma
->local_ram_blocks
.block
[reg
->current_index
];
458 if (local_block
->is_ram_block
) {
460 * current_addr as passed in is an address in the local ram_addr_t
461 * space, we need to translate this for the destination
463 reg
->key
.current_addr
-= local_block
->offset
;
464 reg
->key
.current_addr
+= rdma
->dest_blocks
[reg
->current_index
].offset
;
466 reg
->key
.current_addr
= htonll(reg
->key
.current_addr
);
467 reg
->current_index
= htonl(reg
->current_index
);
468 reg
->chunks
= htonll(reg
->chunks
);
471 static void network_to_register(RDMARegister
*reg
)
473 reg
->key
.current_addr
= ntohll(reg
->key
.current_addr
);
474 reg
->current_index
= ntohl(reg
->current_index
);
475 reg
->chunks
= ntohll(reg
->chunks
);
478 typedef struct QEMU_PACKED
{
479 uint32_t value
; /* if zero, we will madvise() */
480 uint32_t block_idx
; /* which ram block index */
481 uint64_t offset
; /* Address in remote ram_addr_t space */
482 uint64_t length
; /* length of the chunk */
485 static void compress_to_network(RDMAContext
*rdma
, RDMACompress
*comp
)
487 comp
->value
= htonl(comp
->value
);
489 * comp->offset as passed in is an address in the local ram_addr_t
490 * space, we need to translate this for the destination
492 comp
->offset
-= rdma
->local_ram_blocks
.block
[comp
->block_idx
].offset
;
493 comp
->offset
+= rdma
->dest_blocks
[comp
->block_idx
].offset
;
494 comp
->block_idx
= htonl(comp
->block_idx
);
495 comp
->offset
= htonll(comp
->offset
);
496 comp
->length
= htonll(comp
->length
);
499 static void network_to_compress(RDMACompress
*comp
)
501 comp
->value
= ntohl(comp
->value
);
502 comp
->block_idx
= ntohl(comp
->block_idx
);
503 comp
->offset
= ntohll(comp
->offset
);
504 comp
->length
= ntohll(comp
->length
);
508 * The result of the dest's memory registration produces an "rkey"
509 * which the source VM must reference in order to perform
510 * the RDMA operation.
512 typedef struct QEMU_PACKED
{
516 } RDMARegisterResult
;
518 static void result_to_network(RDMARegisterResult
*result
)
520 result
->rkey
= htonl(result
->rkey
);
521 result
->host_addr
= htonll(result
->host_addr
);
524 static void network_to_result(RDMARegisterResult
*result
)
526 result
->rkey
= ntohl(result
->rkey
);
527 result
->host_addr
= ntohll(result
->host_addr
);
530 const char *print_wrid(int wrid
);
531 static int qemu_rdma_exchange_send(RDMAContext
*rdma
, RDMAControlHeader
*head
,
532 uint8_t *data
, RDMAControlHeader
*resp
,
534 int (*callback
)(RDMAContext
*rdma
));
536 static inline uint64_t ram_chunk_index(const uint8_t *start
,
539 return ((uintptr_t) host
- (uintptr_t) start
) >> RDMA_REG_CHUNK_SHIFT
;
542 static inline uint8_t *ram_chunk_start(const RDMALocalBlock
*rdma_ram_block
,
545 return (uint8_t *)(uintptr_t)(rdma_ram_block
->local_host_addr
+
546 (i
<< RDMA_REG_CHUNK_SHIFT
));
549 static inline uint8_t *ram_chunk_end(const RDMALocalBlock
*rdma_ram_block
,
552 uint8_t *result
= ram_chunk_start(rdma_ram_block
, i
) +
553 (1UL << RDMA_REG_CHUNK_SHIFT
);
555 if (result
> (rdma_ram_block
->local_host_addr
+ rdma_ram_block
->length
)) {
556 result
= rdma_ram_block
->local_host_addr
+ rdma_ram_block
->length
;
562 static int rdma_add_block(RDMAContext
*rdma
, const char *block_name
,
564 ram_addr_t block_offset
, uint64_t length
)
566 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
567 RDMALocalBlock
*block
;
568 RDMALocalBlock
*old
= local
->block
;
570 local
->block
= g_new0(RDMALocalBlock
, local
->nb_blocks
+ 1);
572 if (local
->nb_blocks
) {
575 if (rdma
->blockmap
) {
576 for (x
= 0; x
< local
->nb_blocks
; x
++) {
577 g_hash_table_remove(rdma
->blockmap
,
578 (void *)(uintptr_t)old
[x
].offset
);
579 g_hash_table_insert(rdma
->blockmap
,
580 (void *)(uintptr_t)old
[x
].offset
,
584 memcpy(local
->block
, old
, sizeof(RDMALocalBlock
) * local
->nb_blocks
);
588 block
= &local
->block
[local
->nb_blocks
];
590 block
->block_name
= g_strdup(block_name
);
591 block
->local_host_addr
= host_addr
;
592 block
->offset
= block_offset
;
593 block
->length
= length
;
594 block
->index
= local
->nb_blocks
;
595 block
->src_index
= ~0U; /* Filled in by the receipt of the block list */
596 block
->nb_chunks
= ram_chunk_index(host_addr
, host_addr
+ length
) + 1UL;
597 block
->transit_bitmap
= bitmap_new(block
->nb_chunks
);
598 bitmap_clear(block
->transit_bitmap
, 0, block
->nb_chunks
);
599 block
->unregister_bitmap
= bitmap_new(block
->nb_chunks
);
600 bitmap_clear(block
->unregister_bitmap
, 0, block
->nb_chunks
);
601 block
->remote_keys
= g_new0(uint32_t, block
->nb_chunks
);
603 block
->is_ram_block
= local
->init
? false : true;
605 if (rdma
->blockmap
) {
606 g_hash_table_insert(rdma
->blockmap
, (void *)(uintptr_t)block_offset
, block
);
609 trace_rdma_add_block(block_name
, local
->nb_blocks
,
610 (uintptr_t) block
->local_host_addr
,
611 block
->offset
, block
->length
,
612 (uintptr_t) (block
->local_host_addr
+ block
->length
),
613 BITS_TO_LONGS(block
->nb_chunks
) *
614 sizeof(unsigned long) * 8,
623 * Memory regions need to be registered with the device and queue pairs setup
624 * in advanced before the migration starts. This tells us where the RAM blocks
625 * are so that we can register them individually.
627 static int qemu_rdma_init_one_block(const char *block_name
, void *host_addr
,
628 ram_addr_t block_offset
, ram_addr_t length
, void *opaque
)
630 return rdma_add_block(opaque
, block_name
, host_addr
, block_offset
, length
);
634 * Identify the RAMBlocks and their quantity. They will be references to
635 * identify chunk boundaries inside each RAMBlock and also be referenced
636 * during dynamic page registration.
638 static int qemu_rdma_init_ram_blocks(RDMAContext
*rdma
)
640 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
642 assert(rdma
->blockmap
== NULL
);
643 memset(local
, 0, sizeof *local
);
644 qemu_ram_foreach_migratable_block(qemu_rdma_init_one_block
, rdma
);
645 trace_qemu_rdma_init_ram_blocks(local
->nb_blocks
);
646 rdma
->dest_blocks
= g_new0(RDMADestBlock
,
647 rdma
->local_ram_blocks
.nb_blocks
);
653 * Note: If used outside of cleanup, the caller must ensure that the destination
654 * block structures are also updated
656 static int rdma_delete_block(RDMAContext
*rdma
, RDMALocalBlock
*block
)
658 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
659 RDMALocalBlock
*old
= local
->block
;
662 if (rdma
->blockmap
) {
663 g_hash_table_remove(rdma
->blockmap
, (void *)(uintptr_t)block
->offset
);
668 for (j
= 0; j
< block
->nb_chunks
; j
++) {
669 if (!block
->pmr
[j
]) {
672 ibv_dereg_mr(block
->pmr
[j
]);
673 rdma
->total_registrations
--;
680 ibv_dereg_mr(block
->mr
);
681 rdma
->total_registrations
--;
685 g_free(block
->transit_bitmap
);
686 block
->transit_bitmap
= NULL
;
688 g_free(block
->unregister_bitmap
);
689 block
->unregister_bitmap
= NULL
;
691 g_free(block
->remote_keys
);
692 block
->remote_keys
= NULL
;
694 g_free(block
->block_name
);
695 block
->block_name
= NULL
;
697 if (rdma
->blockmap
) {
698 for (x
= 0; x
< local
->nb_blocks
; x
++) {
699 g_hash_table_remove(rdma
->blockmap
,
700 (void *)(uintptr_t)old
[x
].offset
);
704 if (local
->nb_blocks
> 1) {
706 local
->block
= g_new0(RDMALocalBlock
, local
->nb_blocks
- 1);
709 memcpy(local
->block
, old
, sizeof(RDMALocalBlock
) * block
->index
);
712 if (block
->index
< (local
->nb_blocks
- 1)) {
713 memcpy(local
->block
+ block
->index
, old
+ (block
->index
+ 1),
714 sizeof(RDMALocalBlock
) *
715 (local
->nb_blocks
- (block
->index
+ 1)));
716 for (x
= block
->index
; x
< local
->nb_blocks
- 1; x
++) {
717 local
->block
[x
].index
--;
721 assert(block
== local
->block
);
725 trace_rdma_delete_block(block
, (uintptr_t)block
->local_host_addr
,
726 block
->offset
, block
->length
,
727 (uintptr_t)(block
->local_host_addr
+ block
->length
),
728 BITS_TO_LONGS(block
->nb_chunks
) *
729 sizeof(unsigned long) * 8, block
->nb_chunks
);
735 if (local
->nb_blocks
&& rdma
->blockmap
) {
736 for (x
= 0; x
< local
->nb_blocks
; x
++) {
737 g_hash_table_insert(rdma
->blockmap
,
738 (void *)(uintptr_t)local
->block
[x
].offset
,
747 * Put in the log file which RDMA device was opened and the details
748 * associated with that device.
750 static void qemu_rdma_dump_id(const char *who
, struct ibv_context
*verbs
)
752 struct ibv_port_attr port
;
754 if (ibv_query_port(verbs
, 1, &port
)) {
755 error_report("Failed to query port information");
759 printf("%s RDMA Device opened: kernel name %s "
760 "uverbs device name %s, "
761 "infiniband_verbs class device path %s, "
762 "infiniband class device path %s, "
763 "transport: (%d) %s\n",
766 verbs
->device
->dev_name
,
767 verbs
->device
->dev_path
,
768 verbs
->device
->ibdev_path
,
770 (port
.link_layer
== IBV_LINK_LAYER_INFINIBAND
) ? "Infiniband" :
771 ((port
.link_layer
== IBV_LINK_LAYER_ETHERNET
)
772 ? "Ethernet" : "Unknown"));
776 * Put in the log file the RDMA gid addressing information,
777 * useful for folks who have trouble understanding the
778 * RDMA device hierarchy in the kernel.
780 static void qemu_rdma_dump_gid(const char *who
, struct rdma_cm_id
*id
)
784 inet_ntop(AF_INET6
, &id
->route
.addr
.addr
.ibaddr
.sgid
, sgid
, sizeof sgid
);
785 inet_ntop(AF_INET6
, &id
->route
.addr
.addr
.ibaddr
.dgid
, dgid
, sizeof dgid
);
786 trace_qemu_rdma_dump_gid(who
, sgid
, dgid
);
790 * As of now, IPv6 over RoCE / iWARP is not supported by linux.
791 * We will try the next addrinfo struct, and fail if there are
792 * no other valid addresses to bind against.
794 * If user is listening on '[::]', then we will not have a opened a device
795 * yet and have no way of verifying if the device is RoCE or not.
797 * In this case, the source VM will throw an error for ALL types of
798 * connections (both IPv4 and IPv6) if the destination machine does not have
799 * a regular infiniband network available for use.
801 * The only way to guarantee that an error is thrown for broken kernels is
802 * for the management software to choose a *specific* interface at bind time
803 * and validate what time of hardware it is.
805 * Unfortunately, this puts the user in a fix:
807 * If the source VM connects with an IPv4 address without knowing that the
808 * destination has bound to '[::]' the migration will unconditionally fail
809 * unless the management software is explicitly listening on the IPv4
810 * address while using a RoCE-based device.
812 * If the source VM connects with an IPv6 address, then we're OK because we can
813 * throw an error on the source (and similarly on the destination).
815 * But in mixed environments, this will be broken for a while until it is fixed
818 * We do provide a *tiny* bit of help in this function: We can list all of the
819 * devices in the system and check to see if all the devices are RoCE or
822 * If we detect that we have a *pure* RoCE environment, then we can safely
823 * thrown an error even if the management software has specified '[::]' as the
826 * However, if there is are multiple hetergeneous devices, then we cannot make
827 * this assumption and the user just has to be sure they know what they are
830 * Patches are being reviewed on linux-rdma.
832 static int qemu_rdma_broken_ipv6_kernel(struct ibv_context
*verbs
, Error
**errp
)
834 struct ibv_port_attr port_attr
;
836 /* This bug only exists in linux, to our knowledge. */
840 * Verbs are only NULL if management has bound to '[::]'.
842 * Let's iterate through all the devices and see if there any pure IB
843 * devices (non-ethernet).
845 * If not, then we can safely proceed with the migration.
846 * Otherwise, there are no guarantees until the bug is fixed in linux.
850 struct ibv_device
** dev_list
= ibv_get_device_list(&num_devices
);
851 bool roce_found
= false;
852 bool ib_found
= false;
854 for (x
= 0; x
< num_devices
; x
++) {
855 verbs
= ibv_open_device(dev_list
[x
]);
857 if (errno
== EPERM
) {
864 if (ibv_query_port(verbs
, 1, &port_attr
)) {
865 ibv_close_device(verbs
);
866 ERROR(errp
, "Could not query initial IB port");
870 if (port_attr
.link_layer
== IBV_LINK_LAYER_INFINIBAND
) {
872 } else if (port_attr
.link_layer
== IBV_LINK_LAYER_ETHERNET
) {
876 ibv_close_device(verbs
);
882 fprintf(stderr
, "WARN: migrations may fail:"
883 " IPv6 over RoCE / iWARP in linux"
884 " is broken. But since you appear to have a"
885 " mixed RoCE / IB environment, be sure to only"
886 " migrate over the IB fabric until the kernel "
887 " fixes the bug.\n");
889 ERROR(errp
, "You only have RoCE / iWARP devices in your systems"
890 " and your management software has specified '[::]'"
891 ", but IPv6 over RoCE / iWARP is not supported in Linux.");
900 * If we have a verbs context, that means that some other than '[::]' was
901 * used by the management software for binding. In which case we can
902 * actually warn the user about a potentially broken kernel.
905 /* IB ports start with 1, not 0 */
906 if (ibv_query_port(verbs
, 1, &port_attr
)) {
907 ERROR(errp
, "Could not query initial IB port");
911 if (port_attr
.link_layer
== IBV_LINK_LAYER_ETHERNET
) {
912 ERROR(errp
, "Linux kernel's RoCE / iWARP does not support IPv6 "
913 "(but patches on linux-rdma in progress)");
923 * Figure out which RDMA device corresponds to the requested IP hostname
924 * Also create the initial connection manager identifiers for opening
927 static int qemu_rdma_resolve_host(RDMAContext
*rdma
, Error
**errp
)
930 struct rdma_addrinfo
*res
;
932 struct rdma_cm_event
*cm_event
;
933 char ip
[40] = "unknown";
934 struct rdma_addrinfo
*e
;
936 if (rdma
->host
== NULL
|| !strcmp(rdma
->host
, "")) {
937 ERROR(errp
, "RDMA hostname has not been set");
941 /* create CM channel */
942 rdma
->channel
= rdma_create_event_channel();
943 if (!rdma
->channel
) {
944 ERROR(errp
, "could not create CM channel");
949 ret
= rdma_create_id(rdma
->channel
, &rdma
->cm_id
, NULL
, RDMA_PS_TCP
);
951 ERROR(errp
, "could not create channel id");
952 goto err_resolve_create_id
;
955 snprintf(port_str
, 16, "%d", rdma
->port
);
958 ret
= rdma_getaddrinfo(rdma
->host
, port_str
, NULL
, &res
);
960 ERROR(errp
, "could not rdma_getaddrinfo address %s", rdma
->host
);
961 goto err_resolve_get_addr
;
964 for (e
= res
; e
!= NULL
; e
= e
->ai_next
) {
965 inet_ntop(e
->ai_family
,
966 &((struct sockaddr_in
*) e
->ai_dst_addr
)->sin_addr
, ip
, sizeof ip
);
967 trace_qemu_rdma_resolve_host_trying(rdma
->host
, ip
);
969 ret
= rdma_resolve_addr(rdma
->cm_id
, NULL
, e
->ai_dst_addr
,
970 RDMA_RESOLVE_TIMEOUT_MS
);
972 if (e
->ai_family
== AF_INET6
) {
973 ret
= qemu_rdma_broken_ipv6_kernel(rdma
->cm_id
->verbs
, errp
);
982 ERROR(errp
, "could not resolve address %s", rdma
->host
);
983 goto err_resolve_get_addr
;
986 qemu_rdma_dump_gid("source_resolve_addr", rdma
->cm_id
);
988 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
990 ERROR(errp
, "could not perform event_addr_resolved");
991 goto err_resolve_get_addr
;
994 if (cm_event
->event
!= RDMA_CM_EVENT_ADDR_RESOLVED
) {
995 ERROR(errp
, "result not equal to event_addr_resolved %s",
996 rdma_event_str(cm_event
->event
));
997 perror("rdma_resolve_addr");
998 rdma_ack_cm_event(cm_event
);
1000 goto err_resolve_get_addr
;
1002 rdma_ack_cm_event(cm_event
);
1005 ret
= rdma_resolve_route(rdma
->cm_id
, RDMA_RESOLVE_TIMEOUT_MS
);
1007 ERROR(errp
, "could not resolve rdma route");
1008 goto err_resolve_get_addr
;
1011 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
1013 ERROR(errp
, "could not perform event_route_resolved");
1014 goto err_resolve_get_addr
;
1016 if (cm_event
->event
!= RDMA_CM_EVENT_ROUTE_RESOLVED
) {
1017 ERROR(errp
, "result not equal to event_route_resolved: %s",
1018 rdma_event_str(cm_event
->event
));
1019 rdma_ack_cm_event(cm_event
);
1021 goto err_resolve_get_addr
;
1023 rdma_ack_cm_event(cm_event
);
1024 rdma
->verbs
= rdma
->cm_id
->verbs
;
1025 qemu_rdma_dump_id("source_resolve_host", rdma
->cm_id
->verbs
);
1026 qemu_rdma_dump_gid("source_resolve_host", rdma
->cm_id
);
1029 err_resolve_get_addr
:
1030 rdma_destroy_id(rdma
->cm_id
);
1032 err_resolve_create_id
:
1033 rdma_destroy_event_channel(rdma
->channel
);
1034 rdma
->channel
= NULL
;
1039 * Create protection domain and completion queues
1041 static int qemu_rdma_alloc_pd_cq(RDMAContext
*rdma
)
1044 rdma
->pd
= ibv_alloc_pd(rdma
->verbs
);
1046 error_report("failed to allocate protection domain");
1050 /* create completion channel */
1051 rdma
->comp_channel
= ibv_create_comp_channel(rdma
->verbs
);
1052 if (!rdma
->comp_channel
) {
1053 error_report("failed to allocate completion channel");
1054 goto err_alloc_pd_cq
;
1058 * Completion queue can be filled by both read and write work requests,
1059 * so must reflect the sum of both possible queue sizes.
1061 rdma
->cq
= ibv_create_cq(rdma
->verbs
, (RDMA_SIGNALED_SEND_MAX
* 3),
1062 NULL
, rdma
->comp_channel
, 0);
1064 error_report("failed to allocate completion queue");
1065 goto err_alloc_pd_cq
;
1072 ibv_dealloc_pd(rdma
->pd
);
1074 if (rdma
->comp_channel
) {
1075 ibv_destroy_comp_channel(rdma
->comp_channel
);
1078 rdma
->comp_channel
= NULL
;
1084 * Create queue pairs.
1086 static int qemu_rdma_alloc_qp(RDMAContext
*rdma
)
1088 struct ibv_qp_init_attr attr
= { 0 };
1091 attr
.cap
.max_send_wr
= RDMA_SIGNALED_SEND_MAX
;
1092 attr
.cap
.max_recv_wr
= 3;
1093 attr
.cap
.max_send_sge
= 1;
1094 attr
.cap
.max_recv_sge
= 1;
1095 attr
.send_cq
= rdma
->cq
;
1096 attr
.recv_cq
= rdma
->cq
;
1097 attr
.qp_type
= IBV_QPT_RC
;
1099 ret
= rdma_create_qp(rdma
->cm_id
, rdma
->pd
, &attr
);
1104 rdma
->qp
= rdma
->cm_id
->qp
;
1108 static int qemu_rdma_reg_whole_ram_blocks(RDMAContext
*rdma
)
1111 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
1113 for (i
= 0; i
< local
->nb_blocks
; i
++) {
1114 local
->block
[i
].mr
=
1115 ibv_reg_mr(rdma
->pd
,
1116 local
->block
[i
].local_host_addr
,
1117 local
->block
[i
].length
,
1118 IBV_ACCESS_LOCAL_WRITE
|
1119 IBV_ACCESS_REMOTE_WRITE
1121 if (!local
->block
[i
].mr
) {
1122 perror("Failed to register local dest ram block!\n");
1125 rdma
->total_registrations
++;
1128 if (i
>= local
->nb_blocks
) {
1132 for (i
--; i
>= 0; i
--) {
1133 ibv_dereg_mr(local
->block
[i
].mr
);
1134 rdma
->total_registrations
--;
1142 * Find the ram block that corresponds to the page requested to be
1143 * transmitted by QEMU.
1145 * Once the block is found, also identify which 'chunk' within that
1146 * block that the page belongs to.
1148 * This search cannot fail or the migration will fail.
1150 static int qemu_rdma_search_ram_block(RDMAContext
*rdma
,
1151 uintptr_t block_offset
,
1154 uint64_t *block_index
,
1155 uint64_t *chunk_index
)
1157 uint64_t current_addr
= block_offset
+ offset
;
1158 RDMALocalBlock
*block
= g_hash_table_lookup(rdma
->blockmap
,
1159 (void *) block_offset
);
1161 assert(current_addr
>= block
->offset
);
1162 assert((current_addr
+ length
) <= (block
->offset
+ block
->length
));
1164 *block_index
= block
->index
;
1165 *chunk_index
= ram_chunk_index(block
->local_host_addr
,
1166 block
->local_host_addr
+ (current_addr
- block
->offset
));
1172 * Register a chunk with IB. If the chunk was already registered
1173 * previously, then skip.
1175 * Also return the keys associated with the registration needed
1176 * to perform the actual RDMA operation.
1178 static int qemu_rdma_register_and_get_keys(RDMAContext
*rdma
,
1179 RDMALocalBlock
*block
, uintptr_t host_addr
,
1180 uint32_t *lkey
, uint32_t *rkey
, int chunk
,
1181 uint8_t *chunk_start
, uint8_t *chunk_end
)
1185 *lkey
= block
->mr
->lkey
;
1188 *rkey
= block
->mr
->rkey
;
1193 /* allocate memory to store chunk MRs */
1195 block
->pmr
= g_new0(struct ibv_mr
*, block
->nb_chunks
);
1199 * If 'rkey', then we're the destination, so grant access to the source.
1201 * If 'lkey', then we're the source VM, so grant access only to ourselves.
1203 if (!block
->pmr
[chunk
]) {
1204 uint64_t len
= chunk_end
- chunk_start
;
1206 trace_qemu_rdma_register_and_get_keys(len
, chunk_start
);
1208 block
->pmr
[chunk
] = ibv_reg_mr(rdma
->pd
,
1210 (rkey
? (IBV_ACCESS_LOCAL_WRITE
|
1211 IBV_ACCESS_REMOTE_WRITE
) : 0));
1213 if (!block
->pmr
[chunk
]) {
1214 perror("Failed to register chunk!");
1215 fprintf(stderr
, "Chunk details: block: %d chunk index %d"
1216 " start %" PRIuPTR
" end %" PRIuPTR
1218 " local %" PRIuPTR
" registrations: %d\n",
1219 block
->index
, chunk
, (uintptr_t)chunk_start
,
1220 (uintptr_t)chunk_end
, host_addr
,
1221 (uintptr_t)block
->local_host_addr
,
1222 rdma
->total_registrations
);
1225 rdma
->total_registrations
++;
1229 *lkey
= block
->pmr
[chunk
]->lkey
;
1232 *rkey
= block
->pmr
[chunk
]->rkey
;
1238 * Register (at connection time) the memory used for control
1241 static int qemu_rdma_reg_control(RDMAContext
*rdma
, int idx
)
1243 rdma
->wr_data
[idx
].control_mr
= ibv_reg_mr(rdma
->pd
,
1244 rdma
->wr_data
[idx
].control
, RDMA_CONTROL_MAX_BUFFER
,
1245 IBV_ACCESS_LOCAL_WRITE
| IBV_ACCESS_REMOTE_WRITE
);
1246 if (rdma
->wr_data
[idx
].control_mr
) {
1247 rdma
->total_registrations
++;
1250 error_report("qemu_rdma_reg_control failed");
1254 const char *print_wrid(int wrid
)
1256 if (wrid
>= RDMA_WRID_RECV_CONTROL
) {
1257 return wrid_desc
[RDMA_WRID_RECV_CONTROL
];
1259 return wrid_desc
[wrid
];
1263 * RDMA requires memory registration (mlock/pinning), but this is not good for
1266 * In preparation for the future where LRU information or workload-specific
1267 * writable writable working set memory access behavior is available to QEMU
1268 * it would be nice to have in place the ability to UN-register/UN-pin
1269 * particular memory regions from the RDMA hardware when it is determine that
1270 * those regions of memory will likely not be accessed again in the near future.
1272 * While we do not yet have such information right now, the following
1273 * compile-time option allows us to perform a non-optimized version of this
1276 * By uncommenting this option, you will cause *all* RDMA transfers to be
1277 * unregistered immediately after the transfer completes on both sides of the
1278 * connection. This has no effect in 'rdma-pin-all' mode, only regular mode.
1280 * This will have a terrible impact on migration performance, so until future
1281 * workload information or LRU information is available, do not attempt to use
1282 * this feature except for basic testing.
1284 //#define RDMA_UNREGISTRATION_EXAMPLE
1287 * Perform a non-optimized memory unregistration after every transfer
1288 * for demonstration purposes, only if pin-all is not requested.
1290 * Potential optimizations:
1291 * 1. Start a new thread to run this function continuously
1293 - and for receipt of unregister messages
1295 * 3. Use workload hints.
1297 static int qemu_rdma_unregister_waiting(RDMAContext
*rdma
)
1299 while (rdma
->unregistrations
[rdma
->unregister_current
]) {
1301 uint64_t wr_id
= rdma
->unregistrations
[rdma
->unregister_current
];
1303 (wr_id
& RDMA_WRID_CHUNK_MASK
) >> RDMA_WRID_CHUNK_SHIFT
;
1305 (wr_id
& RDMA_WRID_BLOCK_MASK
) >> RDMA_WRID_BLOCK_SHIFT
;
1306 RDMALocalBlock
*block
=
1307 &(rdma
->local_ram_blocks
.block
[index
]);
1308 RDMARegister reg
= { .current_index
= index
};
1309 RDMAControlHeader resp
= { .type
= RDMA_CONTROL_UNREGISTER_FINISHED
,
1311 RDMAControlHeader head
= { .len
= sizeof(RDMARegister
),
1312 .type
= RDMA_CONTROL_UNREGISTER_REQUEST
,
1316 trace_qemu_rdma_unregister_waiting_proc(chunk
,
1317 rdma
->unregister_current
);
1319 rdma
->unregistrations
[rdma
->unregister_current
] = 0;
1320 rdma
->unregister_current
++;
1322 if (rdma
->unregister_current
== RDMA_SIGNALED_SEND_MAX
) {
1323 rdma
->unregister_current
= 0;
1328 * Unregistration is speculative (because migration is single-threaded
1329 * and we cannot break the protocol's inifinband message ordering).
1330 * Thus, if the memory is currently being used for transmission,
1331 * then abort the attempt to unregister and try again
1332 * later the next time a completion is received for this memory.
1334 clear_bit(chunk
, block
->unregister_bitmap
);
1336 if (test_bit(chunk
, block
->transit_bitmap
)) {
1337 trace_qemu_rdma_unregister_waiting_inflight(chunk
);
1341 trace_qemu_rdma_unregister_waiting_send(chunk
);
1343 ret
= ibv_dereg_mr(block
->pmr
[chunk
]);
1344 block
->pmr
[chunk
] = NULL
;
1345 block
->remote_keys
[chunk
] = 0;
1348 perror("unregistration chunk failed");
1351 rdma
->total_registrations
--;
1353 reg
.key
.chunk
= chunk
;
1354 register_to_network(rdma
, ®
);
1355 ret
= qemu_rdma_exchange_send(rdma
, &head
, (uint8_t *) ®
,
1361 trace_qemu_rdma_unregister_waiting_complete(chunk
);
1367 static uint64_t qemu_rdma_make_wrid(uint64_t wr_id
, uint64_t index
,
1370 uint64_t result
= wr_id
& RDMA_WRID_TYPE_MASK
;
1372 result
|= (index
<< RDMA_WRID_BLOCK_SHIFT
);
1373 result
|= (chunk
<< RDMA_WRID_CHUNK_SHIFT
);
1379 * Set bit for unregistration in the next iteration.
1380 * We cannot transmit right here, but will unpin later.
1382 static void qemu_rdma_signal_unregister(RDMAContext
*rdma
, uint64_t index
,
1383 uint64_t chunk
, uint64_t wr_id
)
1385 if (rdma
->unregistrations
[rdma
->unregister_next
] != 0) {
1386 error_report("rdma migration: queue is full");
1388 RDMALocalBlock
*block
= &(rdma
->local_ram_blocks
.block
[index
]);
1390 if (!test_and_set_bit(chunk
, block
->unregister_bitmap
)) {
1391 trace_qemu_rdma_signal_unregister_append(chunk
,
1392 rdma
->unregister_next
);
1394 rdma
->unregistrations
[rdma
->unregister_next
++] =
1395 qemu_rdma_make_wrid(wr_id
, index
, chunk
);
1397 if (rdma
->unregister_next
== RDMA_SIGNALED_SEND_MAX
) {
1398 rdma
->unregister_next
= 0;
1401 trace_qemu_rdma_signal_unregister_already(chunk
);
1407 * Consult the connection manager to see a work request
1408 * (of any kind) has completed.
1409 * Return the work request ID that completed.
1411 static uint64_t qemu_rdma_poll(RDMAContext
*rdma
, uint64_t *wr_id_out
,
1418 ret
= ibv_poll_cq(rdma
->cq
, 1, &wc
);
1421 *wr_id_out
= RDMA_WRID_NONE
;
1426 error_report("ibv_poll_cq return %d", ret
);
1430 wr_id
= wc
.wr_id
& RDMA_WRID_TYPE_MASK
;
1432 if (wc
.status
!= IBV_WC_SUCCESS
) {
1433 fprintf(stderr
, "ibv_poll_cq wc.status=%d %s!\n",
1434 wc
.status
, ibv_wc_status_str(wc
.status
));
1435 fprintf(stderr
, "ibv_poll_cq wrid=%s!\n", wrid_desc
[wr_id
]);
1440 if (rdma
->control_ready_expected
&&
1441 (wr_id
>= RDMA_WRID_RECV_CONTROL
)) {
1442 trace_qemu_rdma_poll_recv(wrid_desc
[RDMA_WRID_RECV_CONTROL
],
1443 wr_id
- RDMA_WRID_RECV_CONTROL
, wr_id
, rdma
->nb_sent
);
1444 rdma
->control_ready_expected
= 0;
1447 if (wr_id
== RDMA_WRID_RDMA_WRITE
) {
1449 (wc
.wr_id
& RDMA_WRID_CHUNK_MASK
) >> RDMA_WRID_CHUNK_SHIFT
;
1451 (wc
.wr_id
& RDMA_WRID_BLOCK_MASK
) >> RDMA_WRID_BLOCK_SHIFT
;
1452 RDMALocalBlock
*block
= &(rdma
->local_ram_blocks
.block
[index
]);
1454 trace_qemu_rdma_poll_write(print_wrid(wr_id
), wr_id
, rdma
->nb_sent
,
1455 index
, chunk
, block
->local_host_addr
,
1456 (void *)(uintptr_t)block
->remote_host_addr
);
1458 clear_bit(chunk
, block
->transit_bitmap
);
1460 if (rdma
->nb_sent
> 0) {
1464 if (!rdma
->pin_all
) {
1466 * FYI: If one wanted to signal a specific chunk to be unregistered
1467 * using LRU or workload-specific information, this is the function
1468 * you would call to do so. That chunk would then get asynchronously
1469 * unregistered later.
1471 #ifdef RDMA_UNREGISTRATION_EXAMPLE
1472 qemu_rdma_signal_unregister(rdma
, index
, chunk
, wc
.wr_id
);
1476 trace_qemu_rdma_poll_other(print_wrid(wr_id
), wr_id
, rdma
->nb_sent
);
1479 *wr_id_out
= wc
.wr_id
;
1481 *byte_len
= wc
.byte_len
;
1487 /* Wait for activity on the completion channel.
1488 * Returns 0 on success, none-0 on error.
1490 static int qemu_rdma_wait_comp_channel(RDMAContext
*rdma
)
1493 * Coroutine doesn't start until migration_fd_process_incoming()
1494 * so don't yield unless we know we're running inside of a coroutine.
1496 if (rdma
->migration_started_on_destination
) {
1497 yield_until_fd_readable(rdma
->comp_channel
->fd
);
1499 /* This is the source side, we're in a separate thread
1500 * or destination prior to migration_fd_process_incoming()
1501 * we can't yield; so we have to poll the fd.
1502 * But we need to be able to handle 'cancel' or an error
1503 * without hanging forever.
1505 while (!rdma
->error_state
&& !rdma
->received_error
) {
1507 pfds
[0].fd
= rdma
->comp_channel
->fd
;
1508 pfds
[0].events
= G_IO_IN
| G_IO_HUP
| G_IO_ERR
;
1509 /* 0.1s timeout, should be fine for a 'cancel' */
1510 switch (qemu_poll_ns(pfds
, 1, 100 * 1000 * 1000)) {
1511 case 1: /* fd active */
1514 case 0: /* Timeout, go around again */
1517 default: /* Error of some type -
1518 * I don't trust errno from qemu_poll_ns
1520 error_report("%s: poll failed", __func__
);
1524 if (migrate_get_current()->state
== MIGRATION_STATUS_CANCELLING
) {
1525 /* Bail out and let the cancellation happen */
1531 if (rdma
->received_error
) {
1534 return rdma
->error_state
;
1538 * Block until the next work request has completed.
1540 * First poll to see if a work request has already completed,
1543 * If we encounter completed work requests for IDs other than
1544 * the one we're interested in, then that's generally an error.
1546 * The only exception is actual RDMA Write completions. These
1547 * completions only need to be recorded, but do not actually
1548 * need further processing.
1550 static int qemu_rdma_block_for_wrid(RDMAContext
*rdma
, int wrid_requested
,
1553 int num_cq_events
= 0, ret
= 0;
1556 uint64_t wr_id
= RDMA_WRID_NONE
, wr_id_in
;
1558 if (ibv_req_notify_cq(rdma
->cq
, 0)) {
1562 while (wr_id
!= wrid_requested
) {
1563 ret
= qemu_rdma_poll(rdma
, &wr_id_in
, byte_len
);
1568 wr_id
= wr_id_in
& RDMA_WRID_TYPE_MASK
;
1570 if (wr_id
== RDMA_WRID_NONE
) {
1573 if (wr_id
!= wrid_requested
) {
1574 trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested
),
1575 wrid_requested
, print_wrid(wr_id
), wr_id
);
1579 if (wr_id
== wrid_requested
) {
1584 ret
= qemu_rdma_wait_comp_channel(rdma
);
1586 goto err_block_for_wrid
;
1589 ret
= ibv_get_cq_event(rdma
->comp_channel
, &cq
, &cq_ctx
);
1591 perror("ibv_get_cq_event");
1592 goto err_block_for_wrid
;
1597 ret
= -ibv_req_notify_cq(cq
, 0);
1599 goto err_block_for_wrid
;
1602 while (wr_id
!= wrid_requested
) {
1603 ret
= qemu_rdma_poll(rdma
, &wr_id_in
, byte_len
);
1605 goto err_block_for_wrid
;
1608 wr_id
= wr_id_in
& RDMA_WRID_TYPE_MASK
;
1610 if (wr_id
== RDMA_WRID_NONE
) {
1613 if (wr_id
!= wrid_requested
) {
1614 trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested
),
1615 wrid_requested
, print_wrid(wr_id
), wr_id
);
1619 if (wr_id
== wrid_requested
) {
1620 goto success_block_for_wrid
;
1624 success_block_for_wrid
:
1625 if (num_cq_events
) {
1626 ibv_ack_cq_events(cq
, num_cq_events
);
1631 if (num_cq_events
) {
1632 ibv_ack_cq_events(cq
, num_cq_events
);
1635 rdma
->error_state
= ret
;
1640 * Post a SEND message work request for the control channel
1641 * containing some data and block until the post completes.
1643 static int qemu_rdma_post_send_control(RDMAContext
*rdma
, uint8_t *buf
,
1644 RDMAControlHeader
*head
)
1647 RDMAWorkRequestData
*wr
= &rdma
->wr_data
[RDMA_WRID_CONTROL
];
1648 struct ibv_send_wr
*bad_wr
;
1649 struct ibv_sge sge
= {
1650 .addr
= (uintptr_t)(wr
->control
),
1651 .length
= head
->len
+ sizeof(RDMAControlHeader
),
1652 .lkey
= wr
->control_mr
->lkey
,
1654 struct ibv_send_wr send_wr
= {
1655 .wr_id
= RDMA_WRID_SEND_CONTROL
,
1656 .opcode
= IBV_WR_SEND
,
1657 .send_flags
= IBV_SEND_SIGNALED
,
1662 trace_qemu_rdma_post_send_control(control_desc(head
->type
));
1665 * We don't actually need to do a memcpy() in here if we used
1666 * the "sge" properly, but since we're only sending control messages
1667 * (not RAM in a performance-critical path), then its OK for now.
1669 * The copy makes the RDMAControlHeader simpler to manipulate
1670 * for the time being.
1672 assert(head
->len
<= RDMA_CONTROL_MAX_BUFFER
- sizeof(*head
));
1673 memcpy(wr
->control
, head
, sizeof(RDMAControlHeader
));
1674 control_to_network((void *) wr
->control
);
1677 memcpy(wr
->control
+ sizeof(RDMAControlHeader
), buf
, head
->len
);
1681 ret
= ibv_post_send(rdma
->qp
, &send_wr
, &bad_wr
);
1684 error_report("Failed to use post IB SEND for control");
1688 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_SEND_CONTROL
, NULL
);
1690 error_report("rdma migration: send polling control error");
1697 * Post a RECV work request in anticipation of some future receipt
1698 * of data on the control channel.
1700 static int qemu_rdma_post_recv_control(RDMAContext
*rdma
, int idx
)
1702 struct ibv_recv_wr
*bad_wr
;
1703 struct ibv_sge sge
= {
1704 .addr
= (uintptr_t)(rdma
->wr_data
[idx
].control
),
1705 .length
= RDMA_CONTROL_MAX_BUFFER
,
1706 .lkey
= rdma
->wr_data
[idx
].control_mr
->lkey
,
1709 struct ibv_recv_wr recv_wr
= {
1710 .wr_id
= RDMA_WRID_RECV_CONTROL
+ idx
,
1716 if (ibv_post_recv(rdma
->qp
, &recv_wr
, &bad_wr
)) {
1724 * Block and wait for a RECV control channel message to arrive.
1726 static int qemu_rdma_exchange_get_response(RDMAContext
*rdma
,
1727 RDMAControlHeader
*head
, int expecting
, int idx
)
1730 int ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RECV_CONTROL
+ idx
,
1734 error_report("rdma migration: recv polling control error!");
1738 network_to_control((void *) rdma
->wr_data
[idx
].control
);
1739 memcpy(head
, rdma
->wr_data
[idx
].control
, sizeof(RDMAControlHeader
));
1741 trace_qemu_rdma_exchange_get_response_start(control_desc(expecting
));
1743 if (expecting
== RDMA_CONTROL_NONE
) {
1744 trace_qemu_rdma_exchange_get_response_none(control_desc(head
->type
),
1746 } else if (head
->type
!= expecting
|| head
->type
== RDMA_CONTROL_ERROR
) {
1747 error_report("Was expecting a %s (%d) control message"
1748 ", but got: %s (%d), length: %d",
1749 control_desc(expecting
), expecting
,
1750 control_desc(head
->type
), head
->type
, head
->len
);
1751 if (head
->type
== RDMA_CONTROL_ERROR
) {
1752 rdma
->received_error
= true;
1756 if (head
->len
> RDMA_CONTROL_MAX_BUFFER
- sizeof(*head
)) {
1757 error_report("too long length: %d", head
->len
);
1760 if (sizeof(*head
) + head
->len
!= byte_len
) {
1761 error_report("Malformed length: %d byte_len %d", head
->len
, byte_len
);
1769 * When a RECV work request has completed, the work request's
1770 * buffer is pointed at the header.
1772 * This will advance the pointer to the data portion
1773 * of the control message of the work request's buffer that
1774 * was populated after the work request finished.
1776 static void qemu_rdma_move_header(RDMAContext
*rdma
, int idx
,
1777 RDMAControlHeader
*head
)
1779 rdma
->wr_data
[idx
].control_len
= head
->len
;
1780 rdma
->wr_data
[idx
].control_curr
=
1781 rdma
->wr_data
[idx
].control
+ sizeof(RDMAControlHeader
);
1785 * This is an 'atomic' high-level operation to deliver a single, unified
1786 * control-channel message.
1788 * Additionally, if the user is expecting some kind of reply to this message,
1789 * they can request a 'resp' response message be filled in by posting an
1790 * additional work request on behalf of the user and waiting for an additional
1793 * The extra (optional) response is used during registration to us from having
1794 * to perform an *additional* exchange of message just to provide a response by
1795 * instead piggy-backing on the acknowledgement.
1797 static int qemu_rdma_exchange_send(RDMAContext
*rdma
, RDMAControlHeader
*head
,
1798 uint8_t *data
, RDMAControlHeader
*resp
,
1800 int (*callback
)(RDMAContext
*rdma
))
1805 * Wait until the dest is ready before attempting to deliver the message
1806 * by waiting for a READY message.
1808 if (rdma
->control_ready_expected
) {
1809 RDMAControlHeader resp
;
1810 ret
= qemu_rdma_exchange_get_response(rdma
,
1811 &resp
, RDMA_CONTROL_READY
, RDMA_WRID_READY
);
1818 * If the user is expecting a response, post a WR in anticipation of it.
1821 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_DATA
);
1823 error_report("rdma migration: error posting"
1824 " extra control recv for anticipated result!");
1830 * Post a WR to replace the one we just consumed for the READY message.
1832 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
1834 error_report("rdma migration: error posting first control recv!");
1839 * Deliver the control message that was requested.
1841 ret
= qemu_rdma_post_send_control(rdma
, data
, head
);
1844 error_report("Failed to send control buffer!");
1849 * If we're expecting a response, block and wait for it.
1853 trace_qemu_rdma_exchange_send_issue_callback();
1854 ret
= callback(rdma
);
1860 trace_qemu_rdma_exchange_send_waiting(control_desc(resp
->type
));
1861 ret
= qemu_rdma_exchange_get_response(rdma
, resp
,
1862 resp
->type
, RDMA_WRID_DATA
);
1868 qemu_rdma_move_header(rdma
, RDMA_WRID_DATA
, resp
);
1870 *resp_idx
= RDMA_WRID_DATA
;
1872 trace_qemu_rdma_exchange_send_received(control_desc(resp
->type
));
1875 rdma
->control_ready_expected
= 1;
1881 * This is an 'atomic' high-level operation to receive a single, unified
1882 * control-channel message.
1884 static int qemu_rdma_exchange_recv(RDMAContext
*rdma
, RDMAControlHeader
*head
,
1887 RDMAControlHeader ready
= {
1889 .type
= RDMA_CONTROL_READY
,
1895 * Inform the source that we're ready to receive a message.
1897 ret
= qemu_rdma_post_send_control(rdma
, NULL
, &ready
);
1900 error_report("Failed to send control buffer!");
1905 * Block and wait for the message.
1907 ret
= qemu_rdma_exchange_get_response(rdma
, head
,
1908 expecting
, RDMA_WRID_READY
);
1914 qemu_rdma_move_header(rdma
, RDMA_WRID_READY
, head
);
1917 * Post a new RECV work request to replace the one we just consumed.
1919 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
1921 error_report("rdma migration: error posting second control recv!");
1929 * Write an actual chunk of memory using RDMA.
1931 * If we're using dynamic registration on the dest-side, we have to
1932 * send a registration command first.
1934 static int qemu_rdma_write_one(QEMUFile
*f
, RDMAContext
*rdma
,
1935 int current_index
, uint64_t current_addr
,
1939 struct ibv_send_wr send_wr
= { 0 };
1940 struct ibv_send_wr
*bad_wr
;
1941 int reg_result_idx
, ret
, count
= 0;
1942 uint64_t chunk
, chunks
;
1943 uint8_t *chunk_start
, *chunk_end
;
1944 RDMALocalBlock
*block
= &(rdma
->local_ram_blocks
.block
[current_index
]);
1946 RDMARegisterResult
*reg_result
;
1947 RDMAControlHeader resp
= { .type
= RDMA_CONTROL_REGISTER_RESULT
};
1948 RDMAControlHeader head
= { .len
= sizeof(RDMARegister
),
1949 .type
= RDMA_CONTROL_REGISTER_REQUEST
,
1954 sge
.addr
= (uintptr_t)(block
->local_host_addr
+
1955 (current_addr
- block
->offset
));
1956 sge
.length
= length
;
1958 chunk
= ram_chunk_index(block
->local_host_addr
,
1959 (uint8_t *)(uintptr_t)sge
.addr
);
1960 chunk_start
= ram_chunk_start(block
, chunk
);
1962 if (block
->is_ram_block
) {
1963 chunks
= length
/ (1UL << RDMA_REG_CHUNK_SHIFT
);
1965 if (chunks
&& ((length
% (1UL << RDMA_REG_CHUNK_SHIFT
)) == 0)) {
1969 chunks
= block
->length
/ (1UL << RDMA_REG_CHUNK_SHIFT
);
1971 if (chunks
&& ((block
->length
% (1UL << RDMA_REG_CHUNK_SHIFT
)) == 0)) {
1976 trace_qemu_rdma_write_one_top(chunks
+ 1,
1978 (1UL << RDMA_REG_CHUNK_SHIFT
) / 1024 / 1024);
1980 chunk_end
= ram_chunk_end(block
, chunk
+ chunks
);
1982 if (!rdma
->pin_all
) {
1983 #ifdef RDMA_UNREGISTRATION_EXAMPLE
1984 qemu_rdma_unregister_waiting(rdma
);
1988 while (test_bit(chunk
, block
->transit_bitmap
)) {
1990 trace_qemu_rdma_write_one_block(count
++, current_index
, chunk
,
1991 sge
.addr
, length
, rdma
->nb_sent
, block
->nb_chunks
);
1993 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RDMA_WRITE
, NULL
);
1996 error_report("Failed to Wait for previous write to complete "
1997 "block %d chunk %" PRIu64
1998 " current %" PRIu64
" len %" PRIu64
" %d",
1999 current_index
, chunk
, sge
.addr
, length
, rdma
->nb_sent
);
2004 if (!rdma
->pin_all
|| !block
->is_ram_block
) {
2005 if (!block
->remote_keys
[chunk
]) {
2007 * This chunk has not yet been registered, so first check to see
2008 * if the entire chunk is zero. If so, tell the other size to
2009 * memset() + madvise() the entire chunk without RDMA.
2012 if (buffer_is_zero((void *)(uintptr_t)sge
.addr
, length
)) {
2013 RDMACompress comp
= {
2014 .offset
= current_addr
,
2016 .block_idx
= current_index
,
2020 head
.len
= sizeof(comp
);
2021 head
.type
= RDMA_CONTROL_COMPRESS
;
2023 trace_qemu_rdma_write_one_zero(chunk
, sge
.length
,
2024 current_index
, current_addr
);
2026 compress_to_network(rdma
, &comp
);
2027 ret
= qemu_rdma_exchange_send(rdma
, &head
,
2028 (uint8_t *) &comp
, NULL
, NULL
, NULL
);
2034 acct_update_position(f
, sge
.length
, true);
2040 * Otherwise, tell other side to register.
2042 reg
.current_index
= current_index
;
2043 if (block
->is_ram_block
) {
2044 reg
.key
.current_addr
= current_addr
;
2046 reg
.key
.chunk
= chunk
;
2048 reg
.chunks
= chunks
;
2050 trace_qemu_rdma_write_one_sendreg(chunk
, sge
.length
, current_index
,
2053 register_to_network(rdma
, ®
);
2054 ret
= qemu_rdma_exchange_send(rdma
, &head
, (uint8_t *) ®
,
2055 &resp
, ®_result_idx
, NULL
);
2060 /* try to overlap this single registration with the one we sent. */
2061 if (qemu_rdma_register_and_get_keys(rdma
, block
, sge
.addr
,
2062 &sge
.lkey
, NULL
, chunk
,
2063 chunk_start
, chunk_end
)) {
2064 error_report("cannot get lkey");
2068 reg_result
= (RDMARegisterResult
*)
2069 rdma
->wr_data
[reg_result_idx
].control_curr
;
2071 network_to_result(reg_result
);
2073 trace_qemu_rdma_write_one_recvregres(block
->remote_keys
[chunk
],
2074 reg_result
->rkey
, chunk
);
2076 block
->remote_keys
[chunk
] = reg_result
->rkey
;
2077 block
->remote_host_addr
= reg_result
->host_addr
;
2079 /* already registered before */
2080 if (qemu_rdma_register_and_get_keys(rdma
, block
, sge
.addr
,
2081 &sge
.lkey
, NULL
, chunk
,
2082 chunk_start
, chunk_end
)) {
2083 error_report("cannot get lkey!");
2088 send_wr
.wr
.rdma
.rkey
= block
->remote_keys
[chunk
];
2090 send_wr
.wr
.rdma
.rkey
= block
->remote_rkey
;
2092 if (qemu_rdma_register_and_get_keys(rdma
, block
, sge
.addr
,
2093 &sge
.lkey
, NULL
, chunk
,
2094 chunk_start
, chunk_end
)) {
2095 error_report("cannot get lkey!");
2101 * Encode the ram block index and chunk within this wrid.
2102 * We will use this information at the time of completion
2103 * to figure out which bitmap to check against and then which
2104 * chunk in the bitmap to look for.
2106 send_wr
.wr_id
= qemu_rdma_make_wrid(RDMA_WRID_RDMA_WRITE
,
2107 current_index
, chunk
);
2109 send_wr
.opcode
= IBV_WR_RDMA_WRITE
;
2110 send_wr
.send_flags
= IBV_SEND_SIGNALED
;
2111 send_wr
.sg_list
= &sge
;
2112 send_wr
.num_sge
= 1;
2113 send_wr
.wr
.rdma
.remote_addr
= block
->remote_host_addr
+
2114 (current_addr
- block
->offset
);
2116 trace_qemu_rdma_write_one_post(chunk
, sge
.addr
, send_wr
.wr
.rdma
.remote_addr
,
2120 * ibv_post_send() does not return negative error numbers,
2121 * per the specification they are positive - no idea why.
2123 ret
= ibv_post_send(rdma
->qp
, &send_wr
, &bad_wr
);
2125 if (ret
== ENOMEM
) {
2126 trace_qemu_rdma_write_one_queue_full();
2127 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RDMA_WRITE
, NULL
);
2129 error_report("rdma migration: failed to make "
2130 "room in full send queue! %d", ret
);
2136 } else if (ret
> 0) {
2137 perror("rdma migration: post rdma write failed");
2141 set_bit(chunk
, block
->transit_bitmap
);
2142 acct_update_position(f
, sge
.length
, false);
2143 rdma
->total_writes
++;
2149 * Push out any unwritten RDMA operations.
2151 * We support sending out multiple chunks at the same time.
2152 * Not all of them need to get signaled in the completion queue.
2154 static int qemu_rdma_write_flush(QEMUFile
*f
, RDMAContext
*rdma
)
2158 if (!rdma
->current_length
) {
2162 ret
= qemu_rdma_write_one(f
, rdma
,
2163 rdma
->current_index
, rdma
->current_addr
, rdma
->current_length
);
2171 trace_qemu_rdma_write_flush(rdma
->nb_sent
);
2174 rdma
->current_length
= 0;
2175 rdma
->current_addr
= 0;
2180 static inline int qemu_rdma_buffer_mergable(RDMAContext
*rdma
,
2181 uint64_t offset
, uint64_t len
)
2183 RDMALocalBlock
*block
;
2187 if (rdma
->current_index
< 0) {
2191 if (rdma
->current_chunk
< 0) {
2195 block
= &(rdma
->local_ram_blocks
.block
[rdma
->current_index
]);
2196 host_addr
= block
->local_host_addr
+ (offset
- block
->offset
);
2197 chunk_end
= ram_chunk_end(block
, rdma
->current_chunk
);
2199 if (rdma
->current_length
== 0) {
2204 * Only merge into chunk sequentially.
2206 if (offset
!= (rdma
->current_addr
+ rdma
->current_length
)) {
2210 if (offset
< block
->offset
) {
2214 if ((offset
+ len
) > (block
->offset
+ block
->length
)) {
2218 if ((host_addr
+ len
) > chunk_end
) {
2226 * We're not actually writing here, but doing three things:
2228 * 1. Identify the chunk the buffer belongs to.
2229 * 2. If the chunk is full or the buffer doesn't belong to the current
2230 * chunk, then start a new chunk and flush() the old chunk.
2231 * 3. To keep the hardware busy, we also group chunks into batches
2232 * and only require that a batch gets acknowledged in the completion
2233 * qeueue instead of each individual chunk.
2235 static int qemu_rdma_write(QEMUFile
*f
, RDMAContext
*rdma
,
2236 uint64_t block_offset
, uint64_t offset
,
2239 uint64_t current_addr
= block_offset
+ offset
;
2240 uint64_t index
= rdma
->current_index
;
2241 uint64_t chunk
= rdma
->current_chunk
;
2244 /* If we cannot merge it, we flush the current buffer first. */
2245 if (!qemu_rdma_buffer_mergable(rdma
, current_addr
, len
)) {
2246 ret
= qemu_rdma_write_flush(f
, rdma
);
2250 rdma
->current_length
= 0;
2251 rdma
->current_addr
= current_addr
;
2253 ret
= qemu_rdma_search_ram_block(rdma
, block_offset
,
2254 offset
, len
, &index
, &chunk
);
2256 error_report("ram block search failed");
2259 rdma
->current_index
= index
;
2260 rdma
->current_chunk
= chunk
;
2264 rdma
->current_length
+= len
;
2266 /* flush it if buffer is too large */
2267 if (rdma
->current_length
>= RDMA_MERGE_MAX
) {
2268 return qemu_rdma_write_flush(f
, rdma
);
2274 static void qemu_rdma_cleanup(RDMAContext
*rdma
)
2278 if (rdma
->cm_id
&& rdma
->connected
) {
2279 if ((rdma
->error_state
||
2280 migrate_get_current()->state
== MIGRATION_STATUS_CANCELLING
) &&
2281 !rdma
->received_error
) {
2282 RDMAControlHeader head
= { .len
= 0,
2283 .type
= RDMA_CONTROL_ERROR
,
2286 error_report("Early error. Sending error.");
2287 qemu_rdma_post_send_control(rdma
, NULL
, &head
);
2290 rdma_disconnect(rdma
->cm_id
);
2291 trace_qemu_rdma_cleanup_disconnect();
2292 rdma
->connected
= false;
2295 g_free(rdma
->dest_blocks
);
2296 rdma
->dest_blocks
= NULL
;
2298 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2299 if (rdma
->wr_data
[idx
].control_mr
) {
2300 rdma
->total_registrations
--;
2301 ibv_dereg_mr(rdma
->wr_data
[idx
].control_mr
);
2303 rdma
->wr_data
[idx
].control_mr
= NULL
;
2306 if (rdma
->local_ram_blocks
.block
) {
2307 while (rdma
->local_ram_blocks
.nb_blocks
) {
2308 rdma_delete_block(rdma
, &rdma
->local_ram_blocks
.block
[0]);
2313 rdma_destroy_qp(rdma
->cm_id
);
2317 ibv_destroy_cq(rdma
->cq
);
2320 if (rdma
->comp_channel
) {
2321 ibv_destroy_comp_channel(rdma
->comp_channel
);
2322 rdma
->comp_channel
= NULL
;
2325 ibv_dealloc_pd(rdma
->pd
);
2329 rdma_destroy_id(rdma
->cm_id
);
2333 /* the destination side, listen_id and channel is shared */
2334 if (rdma
->listen_id
) {
2335 if (!rdma
->is_return_path
) {
2336 rdma_destroy_id(rdma
->listen_id
);
2338 rdma
->listen_id
= NULL
;
2340 if (rdma
->channel
) {
2341 if (!rdma
->is_return_path
) {
2342 rdma_destroy_event_channel(rdma
->channel
);
2344 rdma
->channel
= NULL
;
2348 if (rdma
->channel
) {
2349 rdma_destroy_event_channel(rdma
->channel
);
2350 rdma
->channel
= NULL
;
2357 static int qemu_rdma_source_init(RDMAContext
*rdma
, bool pin_all
, Error
**errp
)
2360 Error
*local_err
= NULL
, **temp
= &local_err
;
2363 * Will be validated against destination's actual capabilities
2364 * after the connect() completes.
2366 rdma
->pin_all
= pin_all
;
2368 ret
= qemu_rdma_resolve_host(rdma
, temp
);
2370 goto err_rdma_source_init
;
2373 ret
= qemu_rdma_alloc_pd_cq(rdma
);
2375 ERROR(temp
, "rdma migration: error allocating pd and cq! Your mlock()"
2376 " limits may be too low. Please check $ ulimit -a # and "
2377 "search for 'ulimit -l' in the output");
2378 goto err_rdma_source_init
;
2381 ret
= qemu_rdma_alloc_qp(rdma
);
2383 ERROR(temp
, "rdma migration: error allocating qp!");
2384 goto err_rdma_source_init
;
2387 ret
= qemu_rdma_init_ram_blocks(rdma
);
2389 ERROR(temp
, "rdma migration: error initializing ram blocks!");
2390 goto err_rdma_source_init
;
2393 /* Build the hash that maps from offset to RAMBlock */
2394 rdma
->blockmap
= g_hash_table_new(g_direct_hash
, g_direct_equal
);
2395 for (idx
= 0; idx
< rdma
->local_ram_blocks
.nb_blocks
; idx
++) {
2396 g_hash_table_insert(rdma
->blockmap
,
2397 (void *)(uintptr_t)rdma
->local_ram_blocks
.block
[idx
].offset
,
2398 &rdma
->local_ram_blocks
.block
[idx
]);
2401 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2402 ret
= qemu_rdma_reg_control(rdma
, idx
);
2404 ERROR(temp
, "rdma migration: error registering %d control!",
2406 goto err_rdma_source_init
;
2412 err_rdma_source_init
:
2413 error_propagate(errp
, local_err
);
2414 qemu_rdma_cleanup(rdma
);
2418 static int qemu_rdma_connect(RDMAContext
*rdma
, Error
**errp
)
2420 RDMACapabilities cap
= {
2421 .version
= RDMA_CONTROL_VERSION_CURRENT
,
2424 struct rdma_conn_param conn_param
= { .initiator_depth
= 2,
2426 .private_data
= &cap
,
2427 .private_data_len
= sizeof(cap
),
2429 struct rdma_cm_event
*cm_event
;
2433 * Only negotiate the capability with destination if the user
2434 * on the source first requested the capability.
2436 if (rdma
->pin_all
) {
2437 trace_qemu_rdma_connect_pin_all_requested();
2438 cap
.flags
|= RDMA_CAPABILITY_PIN_ALL
;
2441 caps_to_network(&cap
);
2443 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
2445 ERROR(errp
, "posting second control recv");
2446 goto err_rdma_source_connect
;
2449 ret
= rdma_connect(rdma
->cm_id
, &conn_param
);
2451 perror("rdma_connect");
2452 ERROR(errp
, "connecting to destination!");
2453 goto err_rdma_source_connect
;
2456 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
2458 perror("rdma_get_cm_event after rdma_connect");
2459 ERROR(errp
, "connecting to destination!");
2460 rdma_ack_cm_event(cm_event
);
2461 goto err_rdma_source_connect
;
2464 if (cm_event
->event
!= RDMA_CM_EVENT_ESTABLISHED
) {
2465 perror("rdma_get_cm_event != EVENT_ESTABLISHED after rdma_connect");
2466 ERROR(errp
, "connecting to destination!");
2467 rdma_ack_cm_event(cm_event
);
2468 goto err_rdma_source_connect
;
2470 rdma
->connected
= true;
2472 memcpy(&cap
, cm_event
->param
.conn
.private_data
, sizeof(cap
));
2473 network_to_caps(&cap
);
2476 * Verify that the *requested* capabilities are supported by the destination
2477 * and disable them otherwise.
2479 if (rdma
->pin_all
&& !(cap
.flags
& RDMA_CAPABILITY_PIN_ALL
)) {
2480 ERROR(errp
, "Server cannot support pinning all memory. "
2481 "Will register memory dynamically.");
2482 rdma
->pin_all
= false;
2485 trace_qemu_rdma_connect_pin_all_outcome(rdma
->pin_all
);
2487 rdma_ack_cm_event(cm_event
);
2489 rdma
->control_ready_expected
= 1;
2493 err_rdma_source_connect
:
2494 qemu_rdma_cleanup(rdma
);
2498 static int qemu_rdma_dest_init(RDMAContext
*rdma
, Error
**errp
)
2501 struct rdma_cm_id
*listen_id
;
2502 char ip
[40] = "unknown";
2503 struct rdma_addrinfo
*res
, *e
;
2506 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2507 rdma
->wr_data
[idx
].control_len
= 0;
2508 rdma
->wr_data
[idx
].control_curr
= NULL
;
2511 if (!rdma
->host
|| !rdma
->host
[0]) {
2512 ERROR(errp
, "RDMA host is not set!");
2513 rdma
->error_state
= -EINVAL
;
2516 /* create CM channel */
2517 rdma
->channel
= rdma_create_event_channel();
2518 if (!rdma
->channel
) {
2519 ERROR(errp
, "could not create rdma event channel");
2520 rdma
->error_state
= -EINVAL
;
2525 ret
= rdma_create_id(rdma
->channel
, &listen_id
, NULL
, RDMA_PS_TCP
);
2527 ERROR(errp
, "could not create cm_id!");
2528 goto err_dest_init_create_listen_id
;
2531 snprintf(port_str
, 16, "%d", rdma
->port
);
2532 port_str
[15] = '\0';
2534 ret
= rdma_getaddrinfo(rdma
->host
, port_str
, NULL
, &res
);
2536 ERROR(errp
, "could not rdma_getaddrinfo address %s", rdma
->host
);
2537 goto err_dest_init_bind_addr
;
2540 for (e
= res
; e
!= NULL
; e
= e
->ai_next
) {
2541 inet_ntop(e
->ai_family
,
2542 &((struct sockaddr_in
*) e
->ai_dst_addr
)->sin_addr
, ip
, sizeof ip
);
2543 trace_qemu_rdma_dest_init_trying(rdma
->host
, ip
);
2544 ret
= rdma_bind_addr(listen_id
, e
->ai_dst_addr
);
2548 if (e
->ai_family
== AF_INET6
) {
2549 ret
= qemu_rdma_broken_ipv6_kernel(listen_id
->verbs
, errp
);
2558 ERROR(errp
, "Error: could not rdma_bind_addr!");
2559 goto err_dest_init_bind_addr
;
2562 rdma
->listen_id
= listen_id
;
2563 qemu_rdma_dump_gid("dest_init", listen_id
);
2566 err_dest_init_bind_addr
:
2567 rdma_destroy_id(listen_id
);
2568 err_dest_init_create_listen_id
:
2569 rdma_destroy_event_channel(rdma
->channel
);
2570 rdma
->channel
= NULL
;
2571 rdma
->error_state
= ret
;
2576 static void qemu_rdma_return_path_dest_init(RDMAContext
*rdma_return_path
,
2581 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2582 rdma_return_path
->wr_data
[idx
].control_len
= 0;
2583 rdma_return_path
->wr_data
[idx
].control_curr
= NULL
;
2586 /*the CM channel and CM id is shared*/
2587 rdma_return_path
->channel
= rdma
->channel
;
2588 rdma_return_path
->listen_id
= rdma
->listen_id
;
2590 rdma
->return_path
= rdma_return_path
;
2591 rdma_return_path
->return_path
= rdma
;
2592 rdma_return_path
->is_return_path
= true;
2595 static void *qemu_rdma_data_init(const char *host_port
, Error
**errp
)
2597 RDMAContext
*rdma
= NULL
;
2598 InetSocketAddress
*addr
;
2601 rdma
= g_new0(RDMAContext
, 1);
2602 rdma
->current_index
= -1;
2603 rdma
->current_chunk
= -1;
2605 addr
= g_new(InetSocketAddress
, 1);
2606 if (!inet_parse(addr
, host_port
, NULL
)) {
2607 rdma
->port
= atoi(addr
->port
);
2608 rdma
->host
= g_strdup(addr
->host
);
2610 ERROR(errp
, "bad RDMA migration address '%s'", host_port
);
2615 qapi_free_InetSocketAddress(addr
);
2622 * QEMUFile interface to the control channel.
2623 * SEND messages for control only.
2624 * VM's ram is handled with regular RDMA messages.
2626 static ssize_t
qio_channel_rdma_writev(QIOChannel
*ioc
,
2627 const struct iovec
*iov
,
2633 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2634 QEMUFile
*f
= rioc
->file
;
2642 rdma
= atomic_rcu_read(&rioc
->rdmaout
);
2649 CHECK_ERROR_STATE();
2652 * Push out any writes that
2653 * we're queued up for VM's ram.
2655 ret
= qemu_rdma_write_flush(f
, rdma
);
2657 rdma
->error_state
= ret
;
2662 for (i
= 0; i
< niov
; i
++) {
2663 size_t remaining
= iov
[i
].iov_len
;
2664 uint8_t * data
= (void *)iov
[i
].iov_base
;
2666 RDMAControlHeader head
;
2668 len
= MIN(remaining
, RDMA_SEND_INCREMENT
);
2672 head
.type
= RDMA_CONTROL_QEMU_FILE
;
2674 ret
= qemu_rdma_exchange_send(rdma
, &head
, data
, NULL
, NULL
, NULL
);
2677 rdma
->error_state
= ret
;
2691 static size_t qemu_rdma_fill(RDMAContext
*rdma
, uint8_t *buf
,
2692 size_t size
, int idx
)
2696 if (rdma
->wr_data
[idx
].control_len
) {
2697 trace_qemu_rdma_fill(rdma
->wr_data
[idx
].control_len
, size
);
2699 len
= MIN(size
, rdma
->wr_data
[idx
].control_len
);
2700 memcpy(buf
, rdma
->wr_data
[idx
].control_curr
, len
);
2701 rdma
->wr_data
[idx
].control_curr
+= len
;
2702 rdma
->wr_data
[idx
].control_len
-= len
;
2709 * QEMUFile interface to the control channel.
2710 * RDMA links don't use bytestreams, so we have to
2711 * return bytes to QEMUFile opportunistically.
2713 static ssize_t
qio_channel_rdma_readv(QIOChannel
*ioc
,
2714 const struct iovec
*iov
,
2720 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2722 RDMAControlHeader head
;
2728 rdma
= atomic_rcu_read(&rioc
->rdmain
);
2735 CHECK_ERROR_STATE();
2737 for (i
= 0; i
< niov
; i
++) {
2738 size_t want
= iov
[i
].iov_len
;
2739 uint8_t *data
= (void *)iov
[i
].iov_base
;
2742 * First, we hold on to the last SEND message we
2743 * were given and dish out the bytes until we run
2746 ret
= qemu_rdma_fill(rdma
, data
, want
, 0);
2749 /* Got what we needed, so go to next iovec */
2754 /* If we got any data so far, then don't wait
2755 * for more, just return what we have */
2761 /* We've got nothing at all, so lets wait for
2764 ret
= qemu_rdma_exchange_recv(rdma
, &head
, RDMA_CONTROL_QEMU_FILE
);
2767 rdma
->error_state
= ret
;
2773 * SEND was received with new bytes, now try again.
2775 ret
= qemu_rdma_fill(rdma
, data
, want
, 0);
2779 /* Still didn't get enough, so lets just return */
2783 return QIO_CHANNEL_ERR_BLOCK
;
2794 * Block until all the outstanding chunks have been delivered by the hardware.
2796 static int qemu_rdma_drain_cq(QEMUFile
*f
, RDMAContext
*rdma
)
2800 if (qemu_rdma_write_flush(f
, rdma
) < 0) {
2804 while (rdma
->nb_sent
) {
2805 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RDMA_WRITE
, NULL
);
2807 error_report("rdma migration: complete polling error!");
2812 qemu_rdma_unregister_waiting(rdma
);
2818 static int qio_channel_rdma_set_blocking(QIOChannel
*ioc
,
2822 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2823 /* XXX we should make readv/writev actually honour this :-) */
2824 rioc
->blocking
= blocking
;
2829 typedef struct QIOChannelRDMASource QIOChannelRDMASource
;
2830 struct QIOChannelRDMASource
{
2832 QIOChannelRDMA
*rioc
;
2833 GIOCondition condition
;
2837 qio_channel_rdma_source_prepare(GSource
*source
,
2840 QIOChannelRDMASource
*rsource
= (QIOChannelRDMASource
*)source
;
2842 GIOCondition cond
= 0;
2846 if (rsource
->condition
== G_IO_IN
) {
2847 rdma
= atomic_rcu_read(&rsource
->rioc
->rdmain
);
2849 rdma
= atomic_rcu_read(&rsource
->rioc
->rdmaout
);
2853 error_report("RDMAContext is NULL when prepare Gsource");
2858 if (rdma
->wr_data
[0].control_len
) {
2864 return cond
& rsource
->condition
;
2868 qio_channel_rdma_source_check(GSource
*source
)
2870 QIOChannelRDMASource
*rsource
= (QIOChannelRDMASource
*)source
;
2872 GIOCondition cond
= 0;
2875 if (rsource
->condition
== G_IO_IN
) {
2876 rdma
= atomic_rcu_read(&rsource
->rioc
->rdmain
);
2878 rdma
= atomic_rcu_read(&rsource
->rioc
->rdmaout
);
2882 error_report("RDMAContext is NULL when check Gsource");
2887 if (rdma
->wr_data
[0].control_len
) {
2893 return cond
& rsource
->condition
;
2897 qio_channel_rdma_source_dispatch(GSource
*source
,
2898 GSourceFunc callback
,
2901 QIOChannelFunc func
= (QIOChannelFunc
)callback
;
2902 QIOChannelRDMASource
*rsource
= (QIOChannelRDMASource
*)source
;
2904 GIOCondition cond
= 0;
2907 if (rsource
->condition
== G_IO_IN
) {
2908 rdma
= atomic_rcu_read(&rsource
->rioc
->rdmain
);
2910 rdma
= atomic_rcu_read(&rsource
->rioc
->rdmaout
);
2914 error_report("RDMAContext is NULL when dispatch Gsource");
2919 if (rdma
->wr_data
[0].control_len
) {
2925 return (*func
)(QIO_CHANNEL(rsource
->rioc
),
2926 (cond
& rsource
->condition
),
2931 qio_channel_rdma_source_finalize(GSource
*source
)
2933 QIOChannelRDMASource
*ssource
= (QIOChannelRDMASource
*)source
;
2935 object_unref(OBJECT(ssource
->rioc
));
2938 GSourceFuncs qio_channel_rdma_source_funcs
= {
2939 qio_channel_rdma_source_prepare
,
2940 qio_channel_rdma_source_check
,
2941 qio_channel_rdma_source_dispatch
,
2942 qio_channel_rdma_source_finalize
2945 static GSource
*qio_channel_rdma_create_watch(QIOChannel
*ioc
,
2946 GIOCondition condition
)
2948 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2949 QIOChannelRDMASource
*ssource
;
2952 source
= g_source_new(&qio_channel_rdma_source_funcs
,
2953 sizeof(QIOChannelRDMASource
));
2954 ssource
= (QIOChannelRDMASource
*)source
;
2956 ssource
->rioc
= rioc
;
2957 object_ref(OBJECT(rioc
));
2959 ssource
->condition
= condition
;
2965 static int qio_channel_rdma_close(QIOChannel
*ioc
,
2968 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(ioc
);
2969 RDMAContext
*rdmain
, *rdmaout
;
2970 trace_qemu_rdma_close();
2972 rdmain
= rioc
->rdmain
;
2974 atomic_rcu_set(&rioc
->rdmain
, NULL
);
2977 rdmaout
= rioc
->rdmaout
;
2979 atomic_rcu_set(&rioc
->rdmaout
, NULL
);
2985 qemu_rdma_cleanup(rdmain
);
2989 qemu_rdma_cleanup(rdmaout
);
3001 * This means that 'block_offset' is a full virtual address that does not
3002 * belong to a RAMBlock of the virtual machine and instead
3003 * represents a private malloc'd memory area that the caller wishes to
3007 * Offset is an offset to be added to block_offset and used
3008 * to also lookup the corresponding RAMBlock.
3011 * Initiate an transfer this size.
3014 * A 'hint' or 'advice' that means that we wish to speculatively
3015 * and asynchronously unregister this memory. In this case, there is no
3016 * guarantee that the unregister will actually happen, for example,
3017 * if the memory is being actively transmitted. Additionally, the memory
3018 * may be re-registered at any future time if a write within the same
3019 * chunk was requested again, even if you attempted to unregister it
3022 * @size < 0 : TODO, not yet supported
3023 * Unregister the memory NOW. This means that the caller does not
3024 * expect there to be any future RDMA transfers and we just want to clean
3025 * things up. This is used in case the upper layer owns the memory and
3026 * cannot wait for qemu_fclose() to occur.
3028 * @bytes_sent : User-specificed pointer to indicate how many bytes were
3029 * sent. Usually, this will not be more than a few bytes of
3030 * the protocol because most transfers are sent asynchronously.
3032 static size_t qemu_rdma_save_page(QEMUFile
*f
, void *opaque
,
3033 ram_addr_t block_offset
, ram_addr_t offset
,
3034 size_t size
, uint64_t *bytes_sent
)
3036 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
3041 rdma
= atomic_rcu_read(&rioc
->rdmaout
);
3048 CHECK_ERROR_STATE();
3050 if (migrate_get_current()->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
3052 return RAM_SAVE_CONTROL_NOT_SUPP
;
3059 * Add this page to the current 'chunk'. If the chunk
3060 * is full, or the page doen't belong to the current chunk,
3061 * an actual RDMA write will occur and a new chunk will be formed.
3063 ret
= qemu_rdma_write(f
, rdma
, block_offset
, offset
, size
);
3065 error_report("rdma migration: write error! %d", ret
);
3070 * We always return 1 bytes because the RDMA
3071 * protocol is completely asynchronous. We do not yet know
3072 * whether an identified chunk is zero or not because we're
3073 * waiting for other pages to potentially be merged with
3074 * the current chunk. So, we have to call qemu_update_position()
3075 * later on when the actual write occurs.
3081 uint64_t index
, chunk
;
3083 /* TODO: Change QEMUFileOps prototype to be signed: size_t => long
3085 ret = qemu_rdma_drain_cq(f, rdma);
3087 fprintf(stderr, "rdma: failed to synchronously drain"
3088 " completion queue before unregistration.\n");
3094 ret
= qemu_rdma_search_ram_block(rdma
, block_offset
,
3095 offset
, size
, &index
, &chunk
);
3098 error_report("ram block search failed");
3102 qemu_rdma_signal_unregister(rdma
, index
, chunk
, 0);
3105 * TODO: Synchronous, guaranteed unregistration (should not occur during
3106 * fast-path). Otherwise, unregisters will process on the next call to
3107 * qemu_rdma_drain_cq()
3109 qemu_rdma_unregister_waiting(rdma);
3115 * Drain the Completion Queue if possible, but do not block,
3118 * If nothing to poll, the end of the iteration will do this
3119 * again to make sure we don't overflow the request queue.
3122 uint64_t wr_id
, wr_id_in
;
3123 int ret
= qemu_rdma_poll(rdma
, &wr_id_in
, NULL
);
3125 error_report("rdma migration: polling error! %d", ret
);
3129 wr_id
= wr_id_in
& RDMA_WRID_TYPE_MASK
;
3131 if (wr_id
== RDMA_WRID_NONE
) {
3137 return RAM_SAVE_CONTROL_DELAYED
;
3139 rdma
->error_state
= ret
;
3144 static void rdma_accept_incoming_migration(void *opaque
);
3146 static int qemu_rdma_accept(RDMAContext
*rdma
)
3148 RDMACapabilities cap
;
3149 struct rdma_conn_param conn_param
= {
3150 .responder_resources
= 2,
3151 .private_data
= &cap
,
3152 .private_data_len
= sizeof(cap
),
3154 struct rdma_cm_event
*cm_event
;
3155 struct ibv_context
*verbs
;
3159 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
3161 goto err_rdma_dest_wait
;
3164 if (cm_event
->event
!= RDMA_CM_EVENT_CONNECT_REQUEST
) {
3165 rdma_ack_cm_event(cm_event
);
3166 goto err_rdma_dest_wait
;
3169 memcpy(&cap
, cm_event
->param
.conn
.private_data
, sizeof(cap
));
3171 network_to_caps(&cap
);
3173 if (cap
.version
< 1 || cap
.version
> RDMA_CONTROL_VERSION_CURRENT
) {
3174 error_report("Unknown source RDMA version: %d, bailing...",
3176 rdma_ack_cm_event(cm_event
);
3177 goto err_rdma_dest_wait
;
3181 * Respond with only the capabilities this version of QEMU knows about.
3183 cap
.flags
&= known_capabilities
;
3186 * Enable the ones that we do know about.
3187 * Add other checks here as new ones are introduced.
3189 if (cap
.flags
& RDMA_CAPABILITY_PIN_ALL
) {
3190 rdma
->pin_all
= true;
3193 rdma
->cm_id
= cm_event
->id
;
3194 verbs
= cm_event
->id
->verbs
;
3196 rdma_ack_cm_event(cm_event
);
3198 trace_qemu_rdma_accept_pin_state(rdma
->pin_all
);
3200 caps_to_network(&cap
);
3202 trace_qemu_rdma_accept_pin_verbsc(verbs
);
3205 rdma
->verbs
= verbs
;
3206 } else if (rdma
->verbs
!= verbs
) {
3207 error_report("ibv context not matching %p, %p!", rdma
->verbs
,
3209 goto err_rdma_dest_wait
;
3212 qemu_rdma_dump_id("dest_init", verbs
);
3214 ret
= qemu_rdma_alloc_pd_cq(rdma
);
3216 error_report("rdma migration: error allocating pd and cq!");
3217 goto err_rdma_dest_wait
;
3220 ret
= qemu_rdma_alloc_qp(rdma
);
3222 error_report("rdma migration: error allocating qp!");
3223 goto err_rdma_dest_wait
;
3226 ret
= qemu_rdma_init_ram_blocks(rdma
);
3228 error_report("rdma migration: error initializing ram blocks!");
3229 goto err_rdma_dest_wait
;
3232 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
3233 ret
= qemu_rdma_reg_control(rdma
, idx
);
3235 error_report("rdma: error registering %d control", idx
);
3236 goto err_rdma_dest_wait
;
3240 /* Accept the second connection request for return path */
3241 if (migrate_postcopy() && !rdma
->is_return_path
) {
3242 qemu_set_fd_handler(rdma
->channel
->fd
, rdma_accept_incoming_migration
,
3244 (void *)(intptr_t)rdma
->return_path
);
3246 qemu_set_fd_handler(rdma
->channel
->fd
, NULL
, NULL
, NULL
);
3249 ret
= rdma_accept(rdma
->cm_id
, &conn_param
);
3251 error_report("rdma_accept returns %d", ret
);
3252 goto err_rdma_dest_wait
;
3255 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
3257 error_report("rdma_accept get_cm_event failed %d", ret
);
3258 goto err_rdma_dest_wait
;
3261 if (cm_event
->event
!= RDMA_CM_EVENT_ESTABLISHED
) {
3262 error_report("rdma_accept not event established");
3263 rdma_ack_cm_event(cm_event
);
3264 goto err_rdma_dest_wait
;
3267 rdma_ack_cm_event(cm_event
);
3268 rdma
->connected
= true;
3270 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
3272 error_report("rdma migration: error posting second control recv");
3273 goto err_rdma_dest_wait
;
3276 qemu_rdma_dump_gid("dest_connect", rdma
->cm_id
);
3281 rdma
->error_state
= ret
;
3282 qemu_rdma_cleanup(rdma
);
3286 static int dest_ram_sort_func(const void *a
, const void *b
)
3288 unsigned int a_index
= ((const RDMALocalBlock
*)a
)->src_index
;
3289 unsigned int b_index
= ((const RDMALocalBlock
*)b
)->src_index
;
3291 return (a_index
< b_index
) ? -1 : (a_index
!= b_index
);
3295 * During each iteration of the migration, we listen for instructions
3296 * by the source VM to perform dynamic page registrations before they
3297 * can perform RDMA operations.
3299 * We respond with the 'rkey'.
3301 * Keep doing this until the source tells us to stop.
3303 static int qemu_rdma_registration_handle(QEMUFile
*f
, void *opaque
)
3305 RDMAControlHeader reg_resp
= { .len
= sizeof(RDMARegisterResult
),
3306 .type
= RDMA_CONTROL_REGISTER_RESULT
,
3309 RDMAControlHeader unreg_resp
= { .len
= 0,
3310 .type
= RDMA_CONTROL_UNREGISTER_FINISHED
,
3313 RDMAControlHeader blocks
= { .type
= RDMA_CONTROL_RAM_BLOCKS_RESULT
,
3315 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
3317 RDMALocalBlocks
*local
;
3318 RDMAControlHeader head
;
3319 RDMARegister
*reg
, *registers
;
3321 RDMARegisterResult
*reg_result
;
3322 static RDMARegisterResult results
[RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE
];
3323 RDMALocalBlock
*block
;
3331 rdma
= atomic_rcu_read(&rioc
->rdmain
);
3338 CHECK_ERROR_STATE();
3340 local
= &rdma
->local_ram_blocks
;
3342 trace_qemu_rdma_registration_handle_wait();
3344 ret
= qemu_rdma_exchange_recv(rdma
, &head
, RDMA_CONTROL_NONE
);
3350 if (head
.repeat
> RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE
) {
3351 error_report("rdma: Too many requests in this message (%d)."
3352 "Bailing.", head
.repeat
);
3357 switch (head
.type
) {
3358 case RDMA_CONTROL_COMPRESS
:
3359 comp
= (RDMACompress
*) rdma
->wr_data
[idx
].control_curr
;
3360 network_to_compress(comp
);
3362 trace_qemu_rdma_registration_handle_compress(comp
->length
,
3365 if (comp
->block_idx
>= rdma
->local_ram_blocks
.nb_blocks
) {
3366 error_report("rdma: 'compress' bad block index %u (vs %d)",
3367 (unsigned int)comp
->block_idx
,
3368 rdma
->local_ram_blocks
.nb_blocks
);
3372 block
= &(rdma
->local_ram_blocks
.block
[comp
->block_idx
]);
3374 host_addr
= block
->local_host_addr
+
3375 (comp
->offset
- block
->offset
);
3377 ram_handle_compressed(host_addr
, comp
->value
, comp
->length
);
3380 case RDMA_CONTROL_REGISTER_FINISHED
:
3381 trace_qemu_rdma_registration_handle_finished();
3384 case RDMA_CONTROL_RAM_BLOCKS_REQUEST
:
3385 trace_qemu_rdma_registration_handle_ram_blocks();
3387 /* Sort our local RAM Block list so it's the same as the source,
3388 * we can do this since we've filled in a src_index in the list
3389 * as we received the RAMBlock list earlier.
3391 qsort(rdma
->local_ram_blocks
.block
,
3392 rdma
->local_ram_blocks
.nb_blocks
,
3393 sizeof(RDMALocalBlock
), dest_ram_sort_func
);
3394 for (i
= 0; i
< local
->nb_blocks
; i
++) {
3395 local
->block
[i
].index
= i
;
3398 if (rdma
->pin_all
) {
3399 ret
= qemu_rdma_reg_whole_ram_blocks(rdma
);
3401 error_report("rdma migration: error dest "
3402 "registering ram blocks");
3408 * Dest uses this to prepare to transmit the RAMBlock descriptions
3409 * to the source VM after connection setup.
3410 * Both sides use the "remote" structure to communicate and update
3411 * their "local" descriptions with what was sent.
3413 for (i
= 0; i
< local
->nb_blocks
; i
++) {
3414 rdma
->dest_blocks
[i
].remote_host_addr
=
3415 (uintptr_t)(local
->block
[i
].local_host_addr
);
3417 if (rdma
->pin_all
) {
3418 rdma
->dest_blocks
[i
].remote_rkey
= local
->block
[i
].mr
->rkey
;
3421 rdma
->dest_blocks
[i
].offset
= local
->block
[i
].offset
;
3422 rdma
->dest_blocks
[i
].length
= local
->block
[i
].length
;
3424 dest_block_to_network(&rdma
->dest_blocks
[i
]);
3425 trace_qemu_rdma_registration_handle_ram_blocks_loop(
3426 local
->block
[i
].block_name
,
3427 local
->block
[i
].offset
,
3428 local
->block
[i
].length
,
3429 local
->block
[i
].local_host_addr
,
3430 local
->block
[i
].src_index
);
3433 blocks
.len
= rdma
->local_ram_blocks
.nb_blocks
3434 * sizeof(RDMADestBlock
);
3437 ret
= qemu_rdma_post_send_control(rdma
,
3438 (uint8_t *) rdma
->dest_blocks
, &blocks
);
3441 error_report("rdma migration: error sending remote info");
3446 case RDMA_CONTROL_REGISTER_REQUEST
:
3447 trace_qemu_rdma_registration_handle_register(head
.repeat
);
3449 reg_resp
.repeat
= head
.repeat
;
3450 registers
= (RDMARegister
*) rdma
->wr_data
[idx
].control_curr
;
3452 for (count
= 0; count
< head
.repeat
; count
++) {
3454 uint8_t *chunk_start
, *chunk_end
;
3456 reg
= ®isters
[count
];
3457 network_to_register(reg
);
3459 reg_result
= &results
[count
];
3461 trace_qemu_rdma_registration_handle_register_loop(count
,
3462 reg
->current_index
, reg
->key
.current_addr
, reg
->chunks
);
3464 if (reg
->current_index
>= rdma
->local_ram_blocks
.nb_blocks
) {
3465 error_report("rdma: 'register' bad block index %u (vs %d)",
3466 (unsigned int)reg
->current_index
,
3467 rdma
->local_ram_blocks
.nb_blocks
);
3471 block
= &(rdma
->local_ram_blocks
.block
[reg
->current_index
]);
3472 if (block
->is_ram_block
) {
3473 if (block
->offset
> reg
->key
.current_addr
) {
3474 error_report("rdma: bad register address for block %s"
3475 " offset: %" PRIx64
" current_addr: %" PRIx64
,
3476 block
->block_name
, block
->offset
,
3477 reg
->key
.current_addr
);
3481 host_addr
= (block
->local_host_addr
+
3482 (reg
->key
.current_addr
- block
->offset
));
3483 chunk
= ram_chunk_index(block
->local_host_addr
,
3484 (uint8_t *) host_addr
);
3486 chunk
= reg
->key
.chunk
;
3487 host_addr
= block
->local_host_addr
+
3488 (reg
->key
.chunk
* (1UL << RDMA_REG_CHUNK_SHIFT
));
3489 /* Check for particularly bad chunk value */
3490 if (host_addr
< (void *)block
->local_host_addr
) {
3491 error_report("rdma: bad chunk for block %s"
3493 block
->block_name
, reg
->key
.chunk
);
3498 chunk_start
= ram_chunk_start(block
, chunk
);
3499 chunk_end
= ram_chunk_end(block
, chunk
+ reg
->chunks
);
3500 if (qemu_rdma_register_and_get_keys(rdma
, block
,
3501 (uintptr_t)host_addr
, NULL
, ®_result
->rkey
,
3502 chunk
, chunk_start
, chunk_end
)) {
3503 error_report("cannot get rkey");
3508 reg_result
->host_addr
= (uintptr_t)block
->local_host_addr
;
3510 trace_qemu_rdma_registration_handle_register_rkey(
3513 result_to_network(reg_result
);
3516 ret
= qemu_rdma_post_send_control(rdma
,
3517 (uint8_t *) results
, ®_resp
);
3520 error_report("Failed to send control buffer");
3524 case RDMA_CONTROL_UNREGISTER_REQUEST
:
3525 trace_qemu_rdma_registration_handle_unregister(head
.repeat
);
3526 unreg_resp
.repeat
= head
.repeat
;
3527 registers
= (RDMARegister
*) rdma
->wr_data
[idx
].control_curr
;
3529 for (count
= 0; count
< head
.repeat
; count
++) {
3530 reg
= ®isters
[count
];
3531 network_to_register(reg
);
3533 trace_qemu_rdma_registration_handle_unregister_loop(count
,
3534 reg
->current_index
, reg
->key
.chunk
);
3536 block
= &(rdma
->local_ram_blocks
.block
[reg
->current_index
]);
3538 ret
= ibv_dereg_mr(block
->pmr
[reg
->key
.chunk
]);
3539 block
->pmr
[reg
->key
.chunk
] = NULL
;
3542 perror("rdma unregistration chunk failed");
3547 rdma
->total_registrations
--;
3549 trace_qemu_rdma_registration_handle_unregister_success(
3553 ret
= qemu_rdma_post_send_control(rdma
, NULL
, &unreg_resp
);
3556 error_report("Failed to send control buffer");
3560 case RDMA_CONTROL_REGISTER_RESULT
:
3561 error_report("Invalid RESULT message at dest.");
3565 error_report("Unknown control message %s", control_desc(head
.type
));
3572 rdma
->error_state
= ret
;
3579 * Called via a ram_control_load_hook during the initial RAM load section which
3580 * lists the RAMBlocks by name. This lets us know the order of the RAMBlocks
3582 * We've already built our local RAMBlock list, but not yet sent the list to
3586 rdma_block_notification_handle(QIOChannelRDMA
*rioc
, const char *name
)
3593 rdma
= atomic_rcu_read(&rioc
->rdmain
);
3600 /* Find the matching RAMBlock in our local list */
3601 for (curr
= 0; curr
< rdma
->local_ram_blocks
.nb_blocks
; curr
++) {
3602 if (!strcmp(rdma
->local_ram_blocks
.block
[curr
].block_name
, name
)) {
3609 error_report("RAMBlock '%s' not found on destination", name
);
3614 rdma
->local_ram_blocks
.block
[curr
].src_index
= rdma
->next_src_index
;
3615 trace_rdma_block_notification_handle(name
, rdma
->next_src_index
);
3616 rdma
->next_src_index
++;
3622 static int rdma_load_hook(QEMUFile
*f
, void *opaque
, uint64_t flags
, void *data
)
3625 case RAM_CONTROL_BLOCK_REG
:
3626 return rdma_block_notification_handle(opaque
, data
);
3628 case RAM_CONTROL_HOOK
:
3629 return qemu_rdma_registration_handle(f
, opaque
);
3632 /* Shouldn't be called with any other values */
3637 static int qemu_rdma_registration_start(QEMUFile
*f
, void *opaque
,
3638 uint64_t flags
, void *data
)
3640 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
3644 rdma
= atomic_rcu_read(&rioc
->rdmaout
);
3650 CHECK_ERROR_STATE();
3652 if (migrate_get_current()->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
3657 trace_qemu_rdma_registration_start(flags
);
3658 qemu_put_be64(f
, RAM_SAVE_FLAG_HOOK
);
3666 * Inform dest that dynamic registrations are done for now.
3667 * First, flush writes, if any.
3669 static int qemu_rdma_registration_stop(QEMUFile
*f
, void *opaque
,
3670 uint64_t flags
, void *data
)
3672 Error
*local_err
= NULL
, **errp
= &local_err
;
3673 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(opaque
);
3675 RDMAControlHeader head
= { .len
= 0, .repeat
= 1 };
3679 rdma
= atomic_rcu_read(&rioc
->rdmaout
);
3685 CHECK_ERROR_STATE();
3687 if (migrate_get_current()->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
3693 ret
= qemu_rdma_drain_cq(f
, rdma
);
3699 if (flags
== RAM_CONTROL_SETUP
) {
3700 RDMAControlHeader resp
= {.type
= RDMA_CONTROL_RAM_BLOCKS_RESULT
};
3701 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
3702 int reg_result_idx
, i
, nb_dest_blocks
;
3704 head
.type
= RDMA_CONTROL_RAM_BLOCKS_REQUEST
;
3705 trace_qemu_rdma_registration_stop_ram();
3708 * Make sure that we parallelize the pinning on both sides.
3709 * For very large guests, doing this serially takes a really
3710 * long time, so we have to 'interleave' the pinning locally
3711 * with the control messages by performing the pinning on this
3712 * side before we receive the control response from the other
3713 * side that the pinning has completed.
3715 ret
= qemu_rdma_exchange_send(rdma
, &head
, NULL
, &resp
,
3716 ®_result_idx
, rdma
->pin_all
?
3717 qemu_rdma_reg_whole_ram_blocks
: NULL
);
3719 ERROR(errp
, "receiving remote info!");
3724 nb_dest_blocks
= resp
.len
/ sizeof(RDMADestBlock
);
3727 * The protocol uses two different sets of rkeys (mutually exclusive):
3728 * 1. One key to represent the virtual address of the entire ram block.
3729 * (dynamic chunk registration disabled - pin everything with one rkey.)
3730 * 2. One to represent individual chunks within a ram block.
3731 * (dynamic chunk registration enabled - pin individual chunks.)
3733 * Once the capability is successfully negotiated, the destination transmits
3734 * the keys to use (or sends them later) including the virtual addresses
3735 * and then propagates the remote ram block descriptions to his local copy.
3738 if (local
->nb_blocks
!= nb_dest_blocks
) {
3739 ERROR(errp
, "ram blocks mismatch (Number of blocks %d vs %d) "
3740 "Your QEMU command line parameters are probably "
3741 "not identical on both the source and destination.",
3742 local
->nb_blocks
, nb_dest_blocks
);
3743 rdma
->error_state
= -EINVAL
;
3748 qemu_rdma_move_header(rdma
, reg_result_idx
, &resp
);
3749 memcpy(rdma
->dest_blocks
,
3750 rdma
->wr_data
[reg_result_idx
].control_curr
, resp
.len
);
3751 for (i
= 0; i
< nb_dest_blocks
; i
++) {
3752 network_to_dest_block(&rdma
->dest_blocks
[i
]);
3754 /* We require that the blocks are in the same order */
3755 if (rdma
->dest_blocks
[i
].length
!= local
->block
[i
].length
) {
3756 ERROR(errp
, "Block %s/%d has a different length %" PRIu64
3757 "vs %" PRIu64
, local
->block
[i
].block_name
, i
,
3758 local
->block
[i
].length
,
3759 rdma
->dest_blocks
[i
].length
);
3760 rdma
->error_state
= -EINVAL
;
3764 local
->block
[i
].remote_host_addr
=
3765 rdma
->dest_blocks
[i
].remote_host_addr
;
3766 local
->block
[i
].remote_rkey
= rdma
->dest_blocks
[i
].remote_rkey
;
3770 trace_qemu_rdma_registration_stop(flags
);
3772 head
.type
= RDMA_CONTROL_REGISTER_FINISHED
;
3773 ret
= qemu_rdma_exchange_send(rdma
, &head
, NULL
, NULL
, NULL
, NULL
);
3782 rdma
->error_state
= ret
;
3787 static const QEMUFileHooks rdma_read_hooks
= {
3788 .hook_ram_load
= rdma_load_hook
,
3791 static const QEMUFileHooks rdma_write_hooks
= {
3792 .before_ram_iterate
= qemu_rdma_registration_start
,
3793 .after_ram_iterate
= qemu_rdma_registration_stop
,
3794 .save_page
= qemu_rdma_save_page
,
3798 static void qio_channel_rdma_finalize(Object
*obj
)
3800 QIOChannelRDMA
*rioc
= QIO_CHANNEL_RDMA(obj
);
3802 qemu_rdma_cleanup(rioc
->rdmain
);
3803 g_free(rioc
->rdmain
);
3804 rioc
->rdmain
= NULL
;
3806 if (rioc
->rdmaout
) {
3807 qemu_rdma_cleanup(rioc
->rdmaout
);
3808 g_free(rioc
->rdmaout
);
3809 rioc
->rdmaout
= NULL
;
3813 static void qio_channel_rdma_class_init(ObjectClass
*klass
,
3814 void *class_data G_GNUC_UNUSED
)
3816 QIOChannelClass
*ioc_klass
= QIO_CHANNEL_CLASS(klass
);
3818 ioc_klass
->io_writev
= qio_channel_rdma_writev
;
3819 ioc_klass
->io_readv
= qio_channel_rdma_readv
;
3820 ioc_klass
->io_set_blocking
= qio_channel_rdma_set_blocking
;
3821 ioc_klass
->io_close
= qio_channel_rdma_close
;
3822 ioc_klass
->io_create_watch
= qio_channel_rdma_create_watch
;
3825 static const TypeInfo qio_channel_rdma_info
= {
3826 .parent
= TYPE_QIO_CHANNEL
,
3827 .name
= TYPE_QIO_CHANNEL_RDMA
,
3828 .instance_size
= sizeof(QIOChannelRDMA
),
3829 .instance_finalize
= qio_channel_rdma_finalize
,
3830 .class_init
= qio_channel_rdma_class_init
,
3833 static void qio_channel_rdma_register_types(void)
3835 type_register_static(&qio_channel_rdma_info
);
3838 type_init(qio_channel_rdma_register_types
);
3840 static QEMUFile
*qemu_fopen_rdma(RDMAContext
*rdma
, const char *mode
)
3842 QIOChannelRDMA
*rioc
;
3844 if (qemu_file_mode_is_not_valid(mode
)) {
3848 rioc
= QIO_CHANNEL_RDMA(object_new(TYPE_QIO_CHANNEL_RDMA
));
3850 if (mode
[0] == 'w') {
3851 rioc
->file
= qemu_fopen_channel_output(QIO_CHANNEL(rioc
));
3852 rioc
->rdmaout
= rdma
;
3853 rioc
->rdmain
= rdma
->return_path
;
3854 qemu_file_set_hooks(rioc
->file
, &rdma_write_hooks
);
3856 rioc
->file
= qemu_fopen_channel_input(QIO_CHANNEL(rioc
));
3857 rioc
->rdmain
= rdma
;
3858 rioc
->rdmaout
= rdma
->return_path
;
3859 qemu_file_set_hooks(rioc
->file
, &rdma_read_hooks
);
3865 static void rdma_accept_incoming_migration(void *opaque
)
3867 RDMAContext
*rdma
= opaque
;
3870 Error
*local_err
= NULL
, **errp
= &local_err
;
3872 trace_qemu_rdma_accept_incoming_migration();
3873 ret
= qemu_rdma_accept(rdma
);
3876 ERROR(errp
, "RDMA Migration initialization failed!");
3880 trace_qemu_rdma_accept_incoming_migration_accepted();
3882 if (rdma
->is_return_path
) {
3886 f
= qemu_fopen_rdma(rdma
, "rb");
3888 ERROR(errp
, "could not qemu_fopen_rdma!");
3889 qemu_rdma_cleanup(rdma
);
3893 rdma
->migration_started_on_destination
= 1;
3894 migration_fd_process_incoming(f
);
3897 void rdma_start_incoming_migration(const char *host_port
, Error
**errp
)
3900 RDMAContext
*rdma
, *rdma_return_path
;
3901 Error
*local_err
= NULL
;
3903 trace_rdma_start_incoming_migration();
3904 rdma
= qemu_rdma_data_init(host_port
, &local_err
);
3910 ret
= qemu_rdma_dest_init(rdma
, &local_err
);
3916 trace_rdma_start_incoming_migration_after_dest_init();
3918 ret
= rdma_listen(rdma
->listen_id
, 5);
3921 ERROR(errp
, "listening on socket!");
3925 trace_rdma_start_incoming_migration_after_rdma_listen();
3927 /* initialize the RDMAContext for return path */
3928 if (migrate_postcopy()) {
3929 rdma_return_path
= qemu_rdma_data_init(host_port
, &local_err
);
3931 if (rdma_return_path
== NULL
) {
3935 qemu_rdma_return_path_dest_init(rdma_return_path
, rdma
);
3938 qemu_set_fd_handler(rdma
->channel
->fd
, rdma_accept_incoming_migration
,
3939 NULL
, (void *)(intptr_t)rdma
);
3942 error_propagate(errp
, local_err
);
3944 g_free(rdma_return_path
);
3947 void rdma_start_outgoing_migration(void *opaque
,
3948 const char *host_port
, Error
**errp
)
3950 MigrationState
*s
= opaque
;
3951 RDMAContext
*rdma
= qemu_rdma_data_init(host_port
, errp
);
3952 RDMAContext
*rdma_return_path
= NULL
;
3959 ret
= qemu_rdma_source_init(rdma
,
3960 s
->enabled_capabilities
[MIGRATION_CAPABILITY_RDMA_PIN_ALL
], errp
);
3966 trace_rdma_start_outgoing_migration_after_rdma_source_init();
3967 ret
= qemu_rdma_connect(rdma
, errp
);
3973 /* RDMA postcopy need a seprate queue pair for return path */
3974 if (migrate_postcopy()) {
3975 rdma_return_path
= qemu_rdma_data_init(host_port
, errp
);
3977 if (rdma_return_path
== NULL
) {
3981 ret
= qemu_rdma_source_init(rdma_return_path
,
3982 s
->enabled_capabilities
[MIGRATION_CAPABILITY_RDMA_PIN_ALL
], errp
);
3988 ret
= qemu_rdma_connect(rdma_return_path
, errp
);
3994 rdma
->return_path
= rdma_return_path
;
3995 rdma_return_path
->return_path
= rdma
;
3996 rdma_return_path
->is_return_path
= true;
3999 trace_rdma_start_outgoing_migration_after_rdma_connect();
4001 s
->to_dst_file
= qemu_fopen_rdma(rdma
, "wb");
4002 migrate_fd_connect(s
, NULL
);
4006 g_free(rdma_return_path
);