2 * RDMA protocol and interfaces
4 * Copyright IBM, Corp. 2010-2013
7 * Michael R. Hines <mrhines@us.ibm.com>
8 * Jiuxing Liu <jl@us.ibm.com>
10 * This work is licensed under the terms of the GNU GPL, version 2 or
11 * later. See the COPYING file in the top-level directory.
14 #include "qemu/osdep.h"
15 #include "qemu-common.h"
16 #include "migration/migration.h"
17 #include "migration/qemu-file.h"
18 #include "exec/cpu-common.h"
19 #include "qemu/error-report.h"
20 #include "qemu/main-loop.h"
21 #include "qemu/sockets.h"
22 #include "qemu/bitmap.h"
23 #include "qemu/coroutine.h"
24 #include <sys/socket.h>
26 #include <arpa/inet.h>
27 #include <rdma/rdma_cma.h>
31 * Print and error on both the Monitor and the Log file.
33 #define ERROR(errp, fmt, ...) \
35 fprintf(stderr, "RDMA ERROR: " fmt "\n", ## __VA_ARGS__); \
36 if (errp && (*(errp) == NULL)) { \
37 error_setg(errp, "RDMA ERROR: " fmt, ## __VA_ARGS__); \
41 #define RDMA_RESOLVE_TIMEOUT_MS 10000
43 /* Do not merge data if larger than this. */
44 #define RDMA_MERGE_MAX (2 * 1024 * 1024)
45 #define RDMA_SIGNALED_SEND_MAX (RDMA_MERGE_MAX / 4096)
47 #define RDMA_REG_CHUNK_SHIFT 20 /* 1 MB */
50 * This is only for non-live state being migrated.
51 * Instead of RDMA_WRITE messages, we use RDMA_SEND
52 * messages for that state, which requires a different
53 * delivery design than main memory.
55 #define RDMA_SEND_INCREMENT 32768
58 * Maximum size infiniband SEND message
60 #define RDMA_CONTROL_MAX_BUFFER (512 * 1024)
61 #define RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE 4096
63 #define RDMA_CONTROL_VERSION_CURRENT 1
65 * Capabilities for negotiation.
67 #define RDMA_CAPABILITY_PIN_ALL 0x01
70 * Add the other flags above to this list of known capabilities
71 * as they are introduced.
73 static uint32_t known_capabilities
= RDMA_CAPABILITY_PIN_ALL
;
75 #define CHECK_ERROR_STATE() \
77 if (rdma->error_state) { \
78 if (!rdma->error_reported) { \
79 error_report("RDMA is in an error state waiting migration" \
81 rdma->error_reported = 1; \
83 return rdma->error_state; \
88 * A work request ID is 64-bits and we split up these bits
91 * bits 0-15 : type of control message, 2^16
92 * bits 16-29: ram block index, 2^14
93 * bits 30-63: ram block chunk number, 2^34
95 * The last two bit ranges are only used for RDMA writes,
96 * in order to track their completion and potentially
97 * also track unregistration status of the message.
99 #define RDMA_WRID_TYPE_SHIFT 0UL
100 #define RDMA_WRID_BLOCK_SHIFT 16UL
101 #define RDMA_WRID_CHUNK_SHIFT 30UL
103 #define RDMA_WRID_TYPE_MASK \
104 ((1UL << RDMA_WRID_BLOCK_SHIFT) - 1UL)
106 #define RDMA_WRID_BLOCK_MASK \
107 (~RDMA_WRID_TYPE_MASK & ((1UL << RDMA_WRID_CHUNK_SHIFT) - 1UL))
109 #define RDMA_WRID_CHUNK_MASK (~RDMA_WRID_BLOCK_MASK & ~RDMA_WRID_TYPE_MASK)
112 * RDMA migration protocol:
113 * 1. RDMA Writes (data messages, i.e. RAM)
114 * 2. IB Send/Recv (control channel messages)
118 RDMA_WRID_RDMA_WRITE
= 1,
119 RDMA_WRID_SEND_CONTROL
= 2000,
120 RDMA_WRID_RECV_CONTROL
= 4000,
123 static const char *wrid_desc
[] = {
124 [RDMA_WRID_NONE
] = "NONE",
125 [RDMA_WRID_RDMA_WRITE
] = "WRITE RDMA",
126 [RDMA_WRID_SEND_CONTROL
] = "CONTROL SEND",
127 [RDMA_WRID_RECV_CONTROL
] = "CONTROL RECV",
131 * Work request IDs for IB SEND messages only (not RDMA writes).
132 * This is used by the migration protocol to transmit
133 * control messages (such as device state and registration commands)
135 * We could use more WRs, but we have enough for now.
145 * SEND/RECV IB Control Messages.
148 RDMA_CONTROL_NONE
= 0,
150 RDMA_CONTROL_READY
, /* ready to receive */
151 RDMA_CONTROL_QEMU_FILE
, /* QEMUFile-transmitted bytes */
152 RDMA_CONTROL_RAM_BLOCKS_REQUEST
, /* RAMBlock synchronization */
153 RDMA_CONTROL_RAM_BLOCKS_RESULT
, /* RAMBlock synchronization */
154 RDMA_CONTROL_COMPRESS
, /* page contains repeat values */
155 RDMA_CONTROL_REGISTER_REQUEST
, /* dynamic page registration */
156 RDMA_CONTROL_REGISTER_RESULT
, /* key to use after registration */
157 RDMA_CONTROL_REGISTER_FINISHED
, /* current iteration finished */
158 RDMA_CONTROL_UNREGISTER_REQUEST
, /* dynamic UN-registration */
159 RDMA_CONTROL_UNREGISTER_FINISHED
, /* unpinning finished */
162 static const char *control_desc
[] = {
163 [RDMA_CONTROL_NONE
] = "NONE",
164 [RDMA_CONTROL_ERROR
] = "ERROR",
165 [RDMA_CONTROL_READY
] = "READY",
166 [RDMA_CONTROL_QEMU_FILE
] = "QEMU FILE",
167 [RDMA_CONTROL_RAM_BLOCKS_REQUEST
] = "RAM BLOCKS REQUEST",
168 [RDMA_CONTROL_RAM_BLOCKS_RESULT
] = "RAM BLOCKS RESULT",
169 [RDMA_CONTROL_COMPRESS
] = "COMPRESS",
170 [RDMA_CONTROL_REGISTER_REQUEST
] = "REGISTER REQUEST",
171 [RDMA_CONTROL_REGISTER_RESULT
] = "REGISTER RESULT",
172 [RDMA_CONTROL_REGISTER_FINISHED
] = "REGISTER FINISHED",
173 [RDMA_CONTROL_UNREGISTER_REQUEST
] = "UNREGISTER REQUEST",
174 [RDMA_CONTROL_UNREGISTER_FINISHED
] = "UNREGISTER FINISHED",
178 * Memory and MR structures used to represent an IB Send/Recv work request.
179 * This is *not* used for RDMA writes, only IB Send/Recv.
182 uint8_t control
[RDMA_CONTROL_MAX_BUFFER
]; /* actual buffer to register */
183 struct ibv_mr
*control_mr
; /* registration metadata */
184 size_t control_len
; /* length of the message */
185 uint8_t *control_curr
; /* start of unconsumed bytes */
186 } RDMAWorkRequestData
;
189 * Negotiate RDMA capabilities during connection-setup time.
196 static void caps_to_network(RDMACapabilities
*cap
)
198 cap
->version
= htonl(cap
->version
);
199 cap
->flags
= htonl(cap
->flags
);
202 static void network_to_caps(RDMACapabilities
*cap
)
204 cap
->version
= ntohl(cap
->version
);
205 cap
->flags
= ntohl(cap
->flags
);
209 * Representation of a RAMBlock from an RDMA perspective.
210 * This is not transmitted, only local.
211 * This and subsequent structures cannot be linked lists
212 * because we're using a single IB message to transmit
213 * the information. It's small anyway, so a list is overkill.
215 typedef struct RDMALocalBlock
{
217 uint8_t *local_host_addr
; /* local virtual address */
218 uint64_t remote_host_addr
; /* remote virtual address */
221 struct ibv_mr
**pmr
; /* MRs for chunk-level registration */
222 struct ibv_mr
*mr
; /* MR for non-chunk-level registration */
223 uint32_t *remote_keys
; /* rkeys for chunk-level registration */
224 uint32_t remote_rkey
; /* rkeys for non-chunk-level registration */
225 int index
; /* which block are we */
226 unsigned int src_index
; /* (Only used on dest) */
229 unsigned long *transit_bitmap
;
230 unsigned long *unregister_bitmap
;
234 * Also represents a RAMblock, but only on the dest.
235 * This gets transmitted by the dest during connection-time
236 * to the source VM and then is used to populate the
237 * corresponding RDMALocalBlock with
238 * the information needed to perform the actual RDMA.
240 typedef struct QEMU_PACKED RDMADestBlock
{
241 uint64_t remote_host_addr
;
244 uint32_t remote_rkey
;
248 static uint64_t htonll(uint64_t v
)
250 union { uint32_t lv
[2]; uint64_t llv
; } u
;
251 u
.lv
[0] = htonl(v
>> 32);
252 u
.lv
[1] = htonl(v
& 0xFFFFFFFFULL
);
256 static uint64_t ntohll(uint64_t v
) {
257 union { uint32_t lv
[2]; uint64_t llv
; } u
;
259 return ((uint64_t)ntohl(u
.lv
[0]) << 32) | (uint64_t) ntohl(u
.lv
[1]);
262 static void dest_block_to_network(RDMADestBlock
*db
)
264 db
->remote_host_addr
= htonll(db
->remote_host_addr
);
265 db
->offset
= htonll(db
->offset
);
266 db
->length
= htonll(db
->length
);
267 db
->remote_rkey
= htonl(db
->remote_rkey
);
270 static void network_to_dest_block(RDMADestBlock
*db
)
272 db
->remote_host_addr
= ntohll(db
->remote_host_addr
);
273 db
->offset
= ntohll(db
->offset
);
274 db
->length
= ntohll(db
->length
);
275 db
->remote_rkey
= ntohl(db
->remote_rkey
);
279 * Virtual address of the above structures used for transmitting
280 * the RAMBlock descriptions at connection-time.
281 * This structure is *not* transmitted.
283 typedef struct RDMALocalBlocks
{
285 bool init
; /* main memory init complete */
286 RDMALocalBlock
*block
;
290 * Main data structure for RDMA state.
291 * While there is only one copy of this structure being allocated right now,
292 * this is the place where one would start if you wanted to consider
293 * having more than one RDMA connection open at the same time.
295 typedef struct RDMAContext
{
299 RDMAWorkRequestData wr_data
[RDMA_WRID_MAX
];
302 * This is used by *_exchange_send() to figure out whether or not
303 * the initial "READY" message has already been received or not.
304 * This is because other functions may potentially poll() and detect
305 * the READY message before send() does, in which case we need to
306 * know if it completed.
308 int control_ready_expected
;
310 /* number of outstanding writes */
313 /* store info about current buffer so that we can
314 merge it with future sends */
315 uint64_t current_addr
;
316 uint64_t current_length
;
317 /* index of ram block the current buffer belongs to */
319 /* index of the chunk in the current ram block */
325 * infiniband-specific variables for opening the device
326 * and maintaining connection state and so forth.
328 * cm_id also has ibv_context, rdma_event_channel, and ibv_qp in
329 * cm_id->verbs, cm_id->channel, and cm_id->qp.
331 struct rdma_cm_id
*cm_id
; /* connection manager ID */
332 struct rdma_cm_id
*listen_id
;
335 struct ibv_context
*verbs
;
336 struct rdma_event_channel
*channel
;
337 struct ibv_qp
*qp
; /* queue pair */
338 struct ibv_comp_channel
*comp_channel
; /* completion channel */
339 struct ibv_pd
*pd
; /* protection domain */
340 struct ibv_cq
*cq
; /* completion queue */
343 * If a previous write failed (perhaps because of a failed
344 * memory registration, then do not attempt any future work
345 * and remember the error state.
351 * Description of ram blocks used throughout the code.
353 RDMALocalBlocks local_ram_blocks
;
354 RDMADestBlock
*dest_blocks
;
356 /* Index of the next RAMBlock received during block registration */
357 unsigned int next_src_index
;
360 * Migration on *destination* started.
361 * Then use coroutine yield function.
362 * Source runs in a thread, so we don't care.
364 int migration_started_on_destination
;
366 int total_registrations
;
369 int unregister_current
, unregister_next
;
370 uint64_t unregistrations
[RDMA_SIGNALED_SEND_MAX
];
372 GHashTable
*blockmap
;
376 * Interface to the rest of the migration call stack.
378 typedef struct QEMUFileRDMA
{
385 * Main structure for IB Send/Recv control messages.
386 * This gets prepended at the beginning of every Send/Recv.
388 typedef struct QEMU_PACKED
{
389 uint32_t len
; /* Total length of data portion */
390 uint32_t type
; /* which control command to perform */
391 uint32_t repeat
; /* number of commands in data portion of same type */
395 static void control_to_network(RDMAControlHeader
*control
)
397 control
->type
= htonl(control
->type
);
398 control
->len
= htonl(control
->len
);
399 control
->repeat
= htonl(control
->repeat
);
402 static void network_to_control(RDMAControlHeader
*control
)
404 control
->type
= ntohl(control
->type
);
405 control
->len
= ntohl(control
->len
);
406 control
->repeat
= ntohl(control
->repeat
);
410 * Register a single Chunk.
411 * Information sent by the source VM to inform the dest
412 * to register an single chunk of memory before we can perform
413 * the actual RDMA operation.
415 typedef struct QEMU_PACKED
{
417 uint64_t current_addr
; /* offset into the ram_addr_t space */
418 uint64_t chunk
; /* chunk to lookup if unregistering */
420 uint32_t current_index
; /* which ramblock the chunk belongs to */
422 uint64_t chunks
; /* how many sequential chunks to register */
425 static void register_to_network(RDMAContext
*rdma
, RDMARegister
*reg
)
427 RDMALocalBlock
*local_block
;
428 local_block
= &rdma
->local_ram_blocks
.block
[reg
->current_index
];
430 if (local_block
->is_ram_block
) {
432 * current_addr as passed in is an address in the local ram_addr_t
433 * space, we need to translate this for the destination
435 reg
->key
.current_addr
-= local_block
->offset
;
436 reg
->key
.current_addr
+= rdma
->dest_blocks
[reg
->current_index
].offset
;
438 reg
->key
.current_addr
= htonll(reg
->key
.current_addr
);
439 reg
->current_index
= htonl(reg
->current_index
);
440 reg
->chunks
= htonll(reg
->chunks
);
443 static void network_to_register(RDMARegister
*reg
)
445 reg
->key
.current_addr
= ntohll(reg
->key
.current_addr
);
446 reg
->current_index
= ntohl(reg
->current_index
);
447 reg
->chunks
= ntohll(reg
->chunks
);
450 typedef struct QEMU_PACKED
{
451 uint32_t value
; /* if zero, we will madvise() */
452 uint32_t block_idx
; /* which ram block index */
453 uint64_t offset
; /* Address in remote ram_addr_t space */
454 uint64_t length
; /* length of the chunk */
457 static void compress_to_network(RDMAContext
*rdma
, RDMACompress
*comp
)
459 comp
->value
= htonl(comp
->value
);
461 * comp->offset as passed in is an address in the local ram_addr_t
462 * space, we need to translate this for the destination
464 comp
->offset
-= rdma
->local_ram_blocks
.block
[comp
->block_idx
].offset
;
465 comp
->offset
+= rdma
->dest_blocks
[comp
->block_idx
].offset
;
466 comp
->block_idx
= htonl(comp
->block_idx
);
467 comp
->offset
= htonll(comp
->offset
);
468 comp
->length
= htonll(comp
->length
);
471 static void network_to_compress(RDMACompress
*comp
)
473 comp
->value
= ntohl(comp
->value
);
474 comp
->block_idx
= ntohl(comp
->block_idx
);
475 comp
->offset
= ntohll(comp
->offset
);
476 comp
->length
= ntohll(comp
->length
);
480 * The result of the dest's memory registration produces an "rkey"
481 * which the source VM must reference in order to perform
482 * the RDMA operation.
484 typedef struct QEMU_PACKED
{
488 } RDMARegisterResult
;
490 static void result_to_network(RDMARegisterResult
*result
)
492 result
->rkey
= htonl(result
->rkey
);
493 result
->host_addr
= htonll(result
->host_addr
);
496 static void network_to_result(RDMARegisterResult
*result
)
498 result
->rkey
= ntohl(result
->rkey
);
499 result
->host_addr
= ntohll(result
->host_addr
);
502 const char *print_wrid(int wrid
);
503 static int qemu_rdma_exchange_send(RDMAContext
*rdma
, RDMAControlHeader
*head
,
504 uint8_t *data
, RDMAControlHeader
*resp
,
506 int (*callback
)(RDMAContext
*rdma
));
508 static inline uint64_t ram_chunk_index(const uint8_t *start
,
511 return ((uintptr_t) host
- (uintptr_t) start
) >> RDMA_REG_CHUNK_SHIFT
;
514 static inline uint8_t *ram_chunk_start(const RDMALocalBlock
*rdma_ram_block
,
517 return (uint8_t *)(uintptr_t)(rdma_ram_block
->local_host_addr
+
518 (i
<< RDMA_REG_CHUNK_SHIFT
));
521 static inline uint8_t *ram_chunk_end(const RDMALocalBlock
*rdma_ram_block
,
524 uint8_t *result
= ram_chunk_start(rdma_ram_block
, i
) +
525 (1UL << RDMA_REG_CHUNK_SHIFT
);
527 if (result
> (rdma_ram_block
->local_host_addr
+ rdma_ram_block
->length
)) {
528 result
= rdma_ram_block
->local_host_addr
+ rdma_ram_block
->length
;
534 static int rdma_add_block(RDMAContext
*rdma
, const char *block_name
,
536 ram_addr_t block_offset
, uint64_t length
)
538 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
539 RDMALocalBlock
*block
;
540 RDMALocalBlock
*old
= local
->block
;
542 local
->block
= g_new0(RDMALocalBlock
, local
->nb_blocks
+ 1);
544 if (local
->nb_blocks
) {
547 if (rdma
->blockmap
) {
548 for (x
= 0; x
< local
->nb_blocks
; x
++) {
549 g_hash_table_remove(rdma
->blockmap
,
550 (void *)(uintptr_t)old
[x
].offset
);
551 g_hash_table_insert(rdma
->blockmap
,
552 (void *)(uintptr_t)old
[x
].offset
,
556 memcpy(local
->block
, old
, sizeof(RDMALocalBlock
) * local
->nb_blocks
);
560 block
= &local
->block
[local
->nb_blocks
];
562 block
->block_name
= g_strdup(block_name
);
563 block
->local_host_addr
= host_addr
;
564 block
->offset
= block_offset
;
565 block
->length
= length
;
566 block
->index
= local
->nb_blocks
;
567 block
->src_index
= ~0U; /* Filled in by the receipt of the block list */
568 block
->nb_chunks
= ram_chunk_index(host_addr
, host_addr
+ length
) + 1UL;
569 block
->transit_bitmap
= bitmap_new(block
->nb_chunks
);
570 bitmap_clear(block
->transit_bitmap
, 0, block
->nb_chunks
);
571 block
->unregister_bitmap
= bitmap_new(block
->nb_chunks
);
572 bitmap_clear(block
->unregister_bitmap
, 0, block
->nb_chunks
);
573 block
->remote_keys
= g_new0(uint32_t, block
->nb_chunks
);
575 block
->is_ram_block
= local
->init
? false : true;
577 if (rdma
->blockmap
) {
578 g_hash_table_insert(rdma
->blockmap
, (void *)(uintptr_t)block_offset
, block
);
581 trace_rdma_add_block(block_name
, local
->nb_blocks
,
582 (uintptr_t) block
->local_host_addr
,
583 block
->offset
, block
->length
,
584 (uintptr_t) (block
->local_host_addr
+ block
->length
),
585 BITS_TO_LONGS(block
->nb_chunks
) *
586 sizeof(unsigned long) * 8,
595 * Memory regions need to be registered with the device and queue pairs setup
596 * in advanced before the migration starts. This tells us where the RAM blocks
597 * are so that we can register them individually.
599 static int qemu_rdma_init_one_block(const char *block_name
, void *host_addr
,
600 ram_addr_t block_offset
, ram_addr_t length
, void *opaque
)
602 return rdma_add_block(opaque
, block_name
, host_addr
, block_offset
, length
);
606 * Identify the RAMBlocks and their quantity. They will be references to
607 * identify chunk boundaries inside each RAMBlock and also be referenced
608 * during dynamic page registration.
610 static int qemu_rdma_init_ram_blocks(RDMAContext
*rdma
)
612 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
614 assert(rdma
->blockmap
== NULL
);
615 memset(local
, 0, sizeof *local
);
616 qemu_ram_foreach_block(qemu_rdma_init_one_block
, rdma
);
617 trace_qemu_rdma_init_ram_blocks(local
->nb_blocks
);
618 rdma
->dest_blocks
= g_new0(RDMADestBlock
,
619 rdma
->local_ram_blocks
.nb_blocks
);
625 * Note: If used outside of cleanup, the caller must ensure that the destination
626 * block structures are also updated
628 static int rdma_delete_block(RDMAContext
*rdma
, RDMALocalBlock
*block
)
630 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
631 RDMALocalBlock
*old
= local
->block
;
634 if (rdma
->blockmap
) {
635 g_hash_table_remove(rdma
->blockmap
, (void *)(uintptr_t)block
->offset
);
640 for (j
= 0; j
< block
->nb_chunks
; j
++) {
641 if (!block
->pmr
[j
]) {
644 ibv_dereg_mr(block
->pmr
[j
]);
645 rdma
->total_registrations
--;
652 ibv_dereg_mr(block
->mr
);
653 rdma
->total_registrations
--;
657 g_free(block
->transit_bitmap
);
658 block
->transit_bitmap
= NULL
;
660 g_free(block
->unregister_bitmap
);
661 block
->unregister_bitmap
= NULL
;
663 g_free(block
->remote_keys
);
664 block
->remote_keys
= NULL
;
666 g_free(block
->block_name
);
667 block
->block_name
= NULL
;
669 if (rdma
->blockmap
) {
670 for (x
= 0; x
< local
->nb_blocks
; x
++) {
671 g_hash_table_remove(rdma
->blockmap
,
672 (void *)(uintptr_t)old
[x
].offset
);
676 if (local
->nb_blocks
> 1) {
678 local
->block
= g_new0(RDMALocalBlock
, local
->nb_blocks
- 1);
681 memcpy(local
->block
, old
, sizeof(RDMALocalBlock
) * block
->index
);
684 if (block
->index
< (local
->nb_blocks
- 1)) {
685 memcpy(local
->block
+ block
->index
, old
+ (block
->index
+ 1),
686 sizeof(RDMALocalBlock
) *
687 (local
->nb_blocks
- (block
->index
+ 1)));
690 assert(block
== local
->block
);
694 trace_rdma_delete_block(block
, (uintptr_t)block
->local_host_addr
,
695 block
->offset
, block
->length
,
696 (uintptr_t)(block
->local_host_addr
+ block
->length
),
697 BITS_TO_LONGS(block
->nb_chunks
) *
698 sizeof(unsigned long) * 8, block
->nb_chunks
);
704 if (local
->nb_blocks
&& rdma
->blockmap
) {
705 for (x
= 0; x
< local
->nb_blocks
; x
++) {
706 g_hash_table_insert(rdma
->blockmap
,
707 (void *)(uintptr_t)local
->block
[x
].offset
,
716 * Put in the log file which RDMA device was opened and the details
717 * associated with that device.
719 static void qemu_rdma_dump_id(const char *who
, struct ibv_context
*verbs
)
721 struct ibv_port_attr port
;
723 if (ibv_query_port(verbs
, 1, &port
)) {
724 error_report("Failed to query port information");
728 printf("%s RDMA Device opened: kernel name %s "
729 "uverbs device name %s, "
730 "infiniband_verbs class device path %s, "
731 "infiniband class device path %s, "
732 "transport: (%d) %s\n",
735 verbs
->device
->dev_name
,
736 verbs
->device
->dev_path
,
737 verbs
->device
->ibdev_path
,
739 (port
.link_layer
== IBV_LINK_LAYER_INFINIBAND
) ? "Infiniband" :
740 ((port
.link_layer
== IBV_LINK_LAYER_ETHERNET
)
741 ? "Ethernet" : "Unknown"));
745 * Put in the log file the RDMA gid addressing information,
746 * useful for folks who have trouble understanding the
747 * RDMA device hierarchy in the kernel.
749 static void qemu_rdma_dump_gid(const char *who
, struct rdma_cm_id
*id
)
753 inet_ntop(AF_INET6
, &id
->route
.addr
.addr
.ibaddr
.sgid
, sgid
, sizeof sgid
);
754 inet_ntop(AF_INET6
, &id
->route
.addr
.addr
.ibaddr
.dgid
, dgid
, sizeof dgid
);
755 trace_qemu_rdma_dump_gid(who
, sgid
, dgid
);
759 * As of now, IPv6 over RoCE / iWARP is not supported by linux.
760 * We will try the next addrinfo struct, and fail if there are
761 * no other valid addresses to bind against.
763 * If user is listening on '[::]', then we will not have a opened a device
764 * yet and have no way of verifying if the device is RoCE or not.
766 * In this case, the source VM will throw an error for ALL types of
767 * connections (both IPv4 and IPv6) if the destination machine does not have
768 * a regular infiniband network available for use.
770 * The only way to guarantee that an error is thrown for broken kernels is
771 * for the management software to choose a *specific* interface at bind time
772 * and validate what time of hardware it is.
774 * Unfortunately, this puts the user in a fix:
776 * If the source VM connects with an IPv4 address without knowing that the
777 * destination has bound to '[::]' the migration will unconditionally fail
778 * unless the management software is explicitly listening on the IPv4
779 * address while using a RoCE-based device.
781 * If the source VM connects with an IPv6 address, then we're OK because we can
782 * throw an error on the source (and similarly on the destination).
784 * But in mixed environments, this will be broken for a while until it is fixed
787 * We do provide a *tiny* bit of help in this function: We can list all of the
788 * devices in the system and check to see if all the devices are RoCE or
791 * If we detect that we have a *pure* RoCE environment, then we can safely
792 * thrown an error even if the management software has specified '[::]' as the
795 * However, if there is are multiple hetergeneous devices, then we cannot make
796 * this assumption and the user just has to be sure they know what they are
799 * Patches are being reviewed on linux-rdma.
801 static int qemu_rdma_broken_ipv6_kernel(Error
**errp
, struct ibv_context
*verbs
)
803 struct ibv_port_attr port_attr
;
805 /* This bug only exists in linux, to our knowledge. */
809 * Verbs are only NULL if management has bound to '[::]'.
811 * Let's iterate through all the devices and see if there any pure IB
812 * devices (non-ethernet).
814 * If not, then we can safely proceed with the migration.
815 * Otherwise, there are no guarantees until the bug is fixed in linux.
819 struct ibv_device
** dev_list
= ibv_get_device_list(&num_devices
);
820 bool roce_found
= false;
821 bool ib_found
= false;
823 for (x
= 0; x
< num_devices
; x
++) {
824 verbs
= ibv_open_device(dev_list
[x
]);
826 if (errno
== EPERM
) {
833 if (ibv_query_port(verbs
, 1, &port_attr
)) {
834 ibv_close_device(verbs
);
835 ERROR(errp
, "Could not query initial IB port");
839 if (port_attr
.link_layer
== IBV_LINK_LAYER_INFINIBAND
) {
841 } else if (port_attr
.link_layer
== IBV_LINK_LAYER_ETHERNET
) {
845 ibv_close_device(verbs
);
851 fprintf(stderr
, "WARN: migrations may fail:"
852 " IPv6 over RoCE / iWARP in linux"
853 " is broken. But since you appear to have a"
854 " mixed RoCE / IB environment, be sure to only"
855 " migrate over the IB fabric until the kernel "
856 " fixes the bug.\n");
858 ERROR(errp
, "You only have RoCE / iWARP devices in your systems"
859 " and your management software has specified '[::]'"
860 ", but IPv6 over RoCE / iWARP is not supported in Linux.");
869 * If we have a verbs context, that means that some other than '[::]' was
870 * used by the management software for binding. In which case we can
871 * actually warn the user about a potentially broken kernel.
874 /* IB ports start with 1, not 0 */
875 if (ibv_query_port(verbs
, 1, &port_attr
)) {
876 ERROR(errp
, "Could not query initial IB port");
880 if (port_attr
.link_layer
== IBV_LINK_LAYER_ETHERNET
) {
881 ERROR(errp
, "Linux kernel's RoCE / iWARP does not support IPv6 "
882 "(but patches on linux-rdma in progress)");
892 * Figure out which RDMA device corresponds to the requested IP hostname
893 * Also create the initial connection manager identifiers for opening
896 static int qemu_rdma_resolve_host(RDMAContext
*rdma
, Error
**errp
)
899 struct rdma_addrinfo
*res
;
901 struct rdma_cm_event
*cm_event
;
902 char ip
[40] = "unknown";
903 struct rdma_addrinfo
*e
;
905 if (rdma
->host
== NULL
|| !strcmp(rdma
->host
, "")) {
906 ERROR(errp
, "RDMA hostname has not been set");
910 /* create CM channel */
911 rdma
->channel
= rdma_create_event_channel();
912 if (!rdma
->channel
) {
913 ERROR(errp
, "could not create CM channel");
918 ret
= rdma_create_id(rdma
->channel
, &rdma
->cm_id
, NULL
, RDMA_PS_TCP
);
920 ERROR(errp
, "could not create channel id");
921 goto err_resolve_create_id
;
924 snprintf(port_str
, 16, "%d", rdma
->port
);
927 ret
= rdma_getaddrinfo(rdma
->host
, port_str
, NULL
, &res
);
929 ERROR(errp
, "could not rdma_getaddrinfo address %s", rdma
->host
);
930 goto err_resolve_get_addr
;
933 for (e
= res
; e
!= NULL
; e
= e
->ai_next
) {
934 inet_ntop(e
->ai_family
,
935 &((struct sockaddr_in
*) e
->ai_dst_addr
)->sin_addr
, ip
, sizeof ip
);
936 trace_qemu_rdma_resolve_host_trying(rdma
->host
, ip
);
938 ret
= rdma_resolve_addr(rdma
->cm_id
, NULL
, e
->ai_dst_addr
,
939 RDMA_RESOLVE_TIMEOUT_MS
);
941 if (e
->ai_family
== AF_INET6
) {
942 ret
= qemu_rdma_broken_ipv6_kernel(errp
, rdma
->cm_id
->verbs
);
951 ERROR(errp
, "could not resolve address %s", rdma
->host
);
952 goto err_resolve_get_addr
;
955 qemu_rdma_dump_gid("source_resolve_addr", rdma
->cm_id
);
957 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
959 ERROR(errp
, "could not perform event_addr_resolved");
960 goto err_resolve_get_addr
;
963 if (cm_event
->event
!= RDMA_CM_EVENT_ADDR_RESOLVED
) {
964 ERROR(errp
, "result not equal to event_addr_resolved %s",
965 rdma_event_str(cm_event
->event
));
966 perror("rdma_resolve_addr");
967 rdma_ack_cm_event(cm_event
);
969 goto err_resolve_get_addr
;
971 rdma_ack_cm_event(cm_event
);
974 ret
= rdma_resolve_route(rdma
->cm_id
, RDMA_RESOLVE_TIMEOUT_MS
);
976 ERROR(errp
, "could not resolve rdma route");
977 goto err_resolve_get_addr
;
980 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
982 ERROR(errp
, "could not perform event_route_resolved");
983 goto err_resolve_get_addr
;
985 if (cm_event
->event
!= RDMA_CM_EVENT_ROUTE_RESOLVED
) {
986 ERROR(errp
, "result not equal to event_route_resolved: %s",
987 rdma_event_str(cm_event
->event
));
988 rdma_ack_cm_event(cm_event
);
990 goto err_resolve_get_addr
;
992 rdma_ack_cm_event(cm_event
);
993 rdma
->verbs
= rdma
->cm_id
->verbs
;
994 qemu_rdma_dump_id("source_resolve_host", rdma
->cm_id
->verbs
);
995 qemu_rdma_dump_gid("source_resolve_host", rdma
->cm_id
);
998 err_resolve_get_addr
:
999 rdma_destroy_id(rdma
->cm_id
);
1001 err_resolve_create_id
:
1002 rdma_destroy_event_channel(rdma
->channel
);
1003 rdma
->channel
= NULL
;
1008 * Create protection domain and completion queues
1010 static int qemu_rdma_alloc_pd_cq(RDMAContext
*rdma
)
1013 rdma
->pd
= ibv_alloc_pd(rdma
->verbs
);
1015 error_report("failed to allocate protection domain");
1019 /* create completion channel */
1020 rdma
->comp_channel
= ibv_create_comp_channel(rdma
->verbs
);
1021 if (!rdma
->comp_channel
) {
1022 error_report("failed to allocate completion channel");
1023 goto err_alloc_pd_cq
;
1027 * Completion queue can be filled by both read and write work requests,
1028 * so must reflect the sum of both possible queue sizes.
1030 rdma
->cq
= ibv_create_cq(rdma
->verbs
, (RDMA_SIGNALED_SEND_MAX
* 3),
1031 NULL
, rdma
->comp_channel
, 0);
1033 error_report("failed to allocate completion queue");
1034 goto err_alloc_pd_cq
;
1041 ibv_dealloc_pd(rdma
->pd
);
1043 if (rdma
->comp_channel
) {
1044 ibv_destroy_comp_channel(rdma
->comp_channel
);
1047 rdma
->comp_channel
= NULL
;
1053 * Create queue pairs.
1055 static int qemu_rdma_alloc_qp(RDMAContext
*rdma
)
1057 struct ibv_qp_init_attr attr
= { 0 };
1060 attr
.cap
.max_send_wr
= RDMA_SIGNALED_SEND_MAX
;
1061 attr
.cap
.max_recv_wr
= 3;
1062 attr
.cap
.max_send_sge
= 1;
1063 attr
.cap
.max_recv_sge
= 1;
1064 attr
.send_cq
= rdma
->cq
;
1065 attr
.recv_cq
= rdma
->cq
;
1066 attr
.qp_type
= IBV_QPT_RC
;
1068 ret
= rdma_create_qp(rdma
->cm_id
, rdma
->pd
, &attr
);
1073 rdma
->qp
= rdma
->cm_id
->qp
;
1077 static int qemu_rdma_reg_whole_ram_blocks(RDMAContext
*rdma
)
1080 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
1082 for (i
= 0; i
< local
->nb_blocks
; i
++) {
1083 local
->block
[i
].mr
=
1084 ibv_reg_mr(rdma
->pd
,
1085 local
->block
[i
].local_host_addr
,
1086 local
->block
[i
].length
,
1087 IBV_ACCESS_LOCAL_WRITE
|
1088 IBV_ACCESS_REMOTE_WRITE
1090 if (!local
->block
[i
].mr
) {
1091 perror("Failed to register local dest ram block!\n");
1094 rdma
->total_registrations
++;
1097 if (i
>= local
->nb_blocks
) {
1101 for (i
--; i
>= 0; i
--) {
1102 ibv_dereg_mr(local
->block
[i
].mr
);
1103 rdma
->total_registrations
--;
1111 * Find the ram block that corresponds to the page requested to be
1112 * transmitted by QEMU.
1114 * Once the block is found, also identify which 'chunk' within that
1115 * block that the page belongs to.
1117 * This search cannot fail or the migration will fail.
1119 static int qemu_rdma_search_ram_block(RDMAContext
*rdma
,
1120 uintptr_t block_offset
,
1123 uint64_t *block_index
,
1124 uint64_t *chunk_index
)
1126 uint64_t current_addr
= block_offset
+ offset
;
1127 RDMALocalBlock
*block
= g_hash_table_lookup(rdma
->blockmap
,
1128 (void *) block_offset
);
1130 assert(current_addr
>= block
->offset
);
1131 assert((current_addr
+ length
) <= (block
->offset
+ block
->length
));
1133 *block_index
= block
->index
;
1134 *chunk_index
= ram_chunk_index(block
->local_host_addr
,
1135 block
->local_host_addr
+ (current_addr
- block
->offset
));
1141 * Register a chunk with IB. If the chunk was already registered
1142 * previously, then skip.
1144 * Also return the keys associated with the registration needed
1145 * to perform the actual RDMA operation.
1147 static int qemu_rdma_register_and_get_keys(RDMAContext
*rdma
,
1148 RDMALocalBlock
*block
, uintptr_t host_addr
,
1149 uint32_t *lkey
, uint32_t *rkey
, int chunk
,
1150 uint8_t *chunk_start
, uint8_t *chunk_end
)
1154 *lkey
= block
->mr
->lkey
;
1157 *rkey
= block
->mr
->rkey
;
1162 /* allocate memory to store chunk MRs */
1164 block
->pmr
= g_new0(struct ibv_mr
*, block
->nb_chunks
);
1168 * If 'rkey', then we're the destination, so grant access to the source.
1170 * If 'lkey', then we're the source VM, so grant access only to ourselves.
1172 if (!block
->pmr
[chunk
]) {
1173 uint64_t len
= chunk_end
- chunk_start
;
1175 trace_qemu_rdma_register_and_get_keys(len
, chunk_start
);
1177 block
->pmr
[chunk
] = ibv_reg_mr(rdma
->pd
,
1179 (rkey
? (IBV_ACCESS_LOCAL_WRITE
|
1180 IBV_ACCESS_REMOTE_WRITE
) : 0));
1182 if (!block
->pmr
[chunk
]) {
1183 perror("Failed to register chunk!");
1184 fprintf(stderr
, "Chunk details: block: %d chunk index %d"
1185 " start %" PRIuPTR
" end %" PRIuPTR
1187 " local %" PRIuPTR
" registrations: %d\n",
1188 block
->index
, chunk
, (uintptr_t)chunk_start
,
1189 (uintptr_t)chunk_end
, host_addr
,
1190 (uintptr_t)block
->local_host_addr
,
1191 rdma
->total_registrations
);
1194 rdma
->total_registrations
++;
1198 *lkey
= block
->pmr
[chunk
]->lkey
;
1201 *rkey
= block
->pmr
[chunk
]->rkey
;
1207 * Register (at connection time) the memory used for control
1210 static int qemu_rdma_reg_control(RDMAContext
*rdma
, int idx
)
1212 rdma
->wr_data
[idx
].control_mr
= ibv_reg_mr(rdma
->pd
,
1213 rdma
->wr_data
[idx
].control
, RDMA_CONTROL_MAX_BUFFER
,
1214 IBV_ACCESS_LOCAL_WRITE
| IBV_ACCESS_REMOTE_WRITE
);
1215 if (rdma
->wr_data
[idx
].control_mr
) {
1216 rdma
->total_registrations
++;
1219 error_report("qemu_rdma_reg_control failed");
1223 const char *print_wrid(int wrid
)
1225 if (wrid
>= RDMA_WRID_RECV_CONTROL
) {
1226 return wrid_desc
[RDMA_WRID_RECV_CONTROL
];
1228 return wrid_desc
[wrid
];
1232 * RDMA requires memory registration (mlock/pinning), but this is not good for
1235 * In preparation for the future where LRU information or workload-specific
1236 * writable writable working set memory access behavior is available to QEMU
1237 * it would be nice to have in place the ability to UN-register/UN-pin
1238 * particular memory regions from the RDMA hardware when it is determine that
1239 * those regions of memory will likely not be accessed again in the near future.
1241 * While we do not yet have such information right now, the following
1242 * compile-time option allows us to perform a non-optimized version of this
1245 * By uncommenting this option, you will cause *all* RDMA transfers to be
1246 * unregistered immediately after the transfer completes on both sides of the
1247 * connection. This has no effect in 'rdma-pin-all' mode, only regular mode.
1249 * This will have a terrible impact on migration performance, so until future
1250 * workload information or LRU information is available, do not attempt to use
1251 * this feature except for basic testing.
1253 //#define RDMA_UNREGISTRATION_EXAMPLE
1256 * Perform a non-optimized memory unregistration after every transfer
1257 * for demonstration purposes, only if pin-all is not requested.
1259 * Potential optimizations:
1260 * 1. Start a new thread to run this function continuously
1262 - and for receipt of unregister messages
1264 * 3. Use workload hints.
1266 static int qemu_rdma_unregister_waiting(RDMAContext
*rdma
)
1268 while (rdma
->unregistrations
[rdma
->unregister_current
]) {
1270 uint64_t wr_id
= rdma
->unregistrations
[rdma
->unregister_current
];
1272 (wr_id
& RDMA_WRID_CHUNK_MASK
) >> RDMA_WRID_CHUNK_SHIFT
;
1274 (wr_id
& RDMA_WRID_BLOCK_MASK
) >> RDMA_WRID_BLOCK_SHIFT
;
1275 RDMALocalBlock
*block
=
1276 &(rdma
->local_ram_blocks
.block
[index
]);
1277 RDMARegister reg
= { .current_index
= index
};
1278 RDMAControlHeader resp
= { .type
= RDMA_CONTROL_UNREGISTER_FINISHED
,
1280 RDMAControlHeader head
= { .len
= sizeof(RDMARegister
),
1281 .type
= RDMA_CONTROL_UNREGISTER_REQUEST
,
1285 trace_qemu_rdma_unregister_waiting_proc(chunk
,
1286 rdma
->unregister_current
);
1288 rdma
->unregistrations
[rdma
->unregister_current
] = 0;
1289 rdma
->unregister_current
++;
1291 if (rdma
->unregister_current
== RDMA_SIGNALED_SEND_MAX
) {
1292 rdma
->unregister_current
= 0;
1297 * Unregistration is speculative (because migration is single-threaded
1298 * and we cannot break the protocol's inifinband message ordering).
1299 * Thus, if the memory is currently being used for transmission,
1300 * then abort the attempt to unregister and try again
1301 * later the next time a completion is received for this memory.
1303 clear_bit(chunk
, block
->unregister_bitmap
);
1305 if (test_bit(chunk
, block
->transit_bitmap
)) {
1306 trace_qemu_rdma_unregister_waiting_inflight(chunk
);
1310 trace_qemu_rdma_unregister_waiting_send(chunk
);
1312 ret
= ibv_dereg_mr(block
->pmr
[chunk
]);
1313 block
->pmr
[chunk
] = NULL
;
1314 block
->remote_keys
[chunk
] = 0;
1317 perror("unregistration chunk failed");
1320 rdma
->total_registrations
--;
1322 reg
.key
.chunk
= chunk
;
1323 register_to_network(rdma
, ®
);
1324 ret
= qemu_rdma_exchange_send(rdma
, &head
, (uint8_t *) ®
,
1330 trace_qemu_rdma_unregister_waiting_complete(chunk
);
1336 static uint64_t qemu_rdma_make_wrid(uint64_t wr_id
, uint64_t index
,
1339 uint64_t result
= wr_id
& RDMA_WRID_TYPE_MASK
;
1341 result
|= (index
<< RDMA_WRID_BLOCK_SHIFT
);
1342 result
|= (chunk
<< RDMA_WRID_CHUNK_SHIFT
);
1348 * Set bit for unregistration in the next iteration.
1349 * We cannot transmit right here, but will unpin later.
1351 static void qemu_rdma_signal_unregister(RDMAContext
*rdma
, uint64_t index
,
1352 uint64_t chunk
, uint64_t wr_id
)
1354 if (rdma
->unregistrations
[rdma
->unregister_next
] != 0) {
1355 error_report("rdma migration: queue is full");
1357 RDMALocalBlock
*block
= &(rdma
->local_ram_blocks
.block
[index
]);
1359 if (!test_and_set_bit(chunk
, block
->unregister_bitmap
)) {
1360 trace_qemu_rdma_signal_unregister_append(chunk
,
1361 rdma
->unregister_next
);
1363 rdma
->unregistrations
[rdma
->unregister_next
++] =
1364 qemu_rdma_make_wrid(wr_id
, index
, chunk
);
1366 if (rdma
->unregister_next
== RDMA_SIGNALED_SEND_MAX
) {
1367 rdma
->unregister_next
= 0;
1370 trace_qemu_rdma_signal_unregister_already(chunk
);
1376 * Consult the connection manager to see a work request
1377 * (of any kind) has completed.
1378 * Return the work request ID that completed.
1380 static uint64_t qemu_rdma_poll(RDMAContext
*rdma
, uint64_t *wr_id_out
,
1387 ret
= ibv_poll_cq(rdma
->cq
, 1, &wc
);
1390 *wr_id_out
= RDMA_WRID_NONE
;
1395 error_report("ibv_poll_cq return %d", ret
);
1399 wr_id
= wc
.wr_id
& RDMA_WRID_TYPE_MASK
;
1401 if (wc
.status
!= IBV_WC_SUCCESS
) {
1402 fprintf(stderr
, "ibv_poll_cq wc.status=%d %s!\n",
1403 wc
.status
, ibv_wc_status_str(wc
.status
));
1404 fprintf(stderr
, "ibv_poll_cq wrid=%s!\n", wrid_desc
[wr_id
]);
1409 if (rdma
->control_ready_expected
&&
1410 (wr_id
>= RDMA_WRID_RECV_CONTROL
)) {
1411 trace_qemu_rdma_poll_recv(wrid_desc
[RDMA_WRID_RECV_CONTROL
],
1412 wr_id
- RDMA_WRID_RECV_CONTROL
, wr_id
, rdma
->nb_sent
);
1413 rdma
->control_ready_expected
= 0;
1416 if (wr_id
== RDMA_WRID_RDMA_WRITE
) {
1418 (wc
.wr_id
& RDMA_WRID_CHUNK_MASK
) >> RDMA_WRID_CHUNK_SHIFT
;
1420 (wc
.wr_id
& RDMA_WRID_BLOCK_MASK
) >> RDMA_WRID_BLOCK_SHIFT
;
1421 RDMALocalBlock
*block
= &(rdma
->local_ram_blocks
.block
[index
]);
1423 trace_qemu_rdma_poll_write(print_wrid(wr_id
), wr_id
, rdma
->nb_sent
,
1424 index
, chunk
, block
->local_host_addr
,
1425 (void *)(uintptr_t)block
->remote_host_addr
);
1427 clear_bit(chunk
, block
->transit_bitmap
);
1429 if (rdma
->nb_sent
> 0) {
1433 if (!rdma
->pin_all
) {
1435 * FYI: If one wanted to signal a specific chunk to be unregistered
1436 * using LRU or workload-specific information, this is the function
1437 * you would call to do so. That chunk would then get asynchronously
1438 * unregistered later.
1440 #ifdef RDMA_UNREGISTRATION_EXAMPLE
1441 qemu_rdma_signal_unregister(rdma
, index
, chunk
, wc
.wr_id
);
1445 trace_qemu_rdma_poll_other(print_wrid(wr_id
), wr_id
, rdma
->nb_sent
);
1448 *wr_id_out
= wc
.wr_id
;
1450 *byte_len
= wc
.byte_len
;
1457 * Block until the next work request has completed.
1459 * First poll to see if a work request has already completed,
1462 * If we encounter completed work requests for IDs other than
1463 * the one we're interested in, then that's generally an error.
1465 * The only exception is actual RDMA Write completions. These
1466 * completions only need to be recorded, but do not actually
1467 * need further processing.
1469 static int qemu_rdma_block_for_wrid(RDMAContext
*rdma
, int wrid_requested
,
1472 int num_cq_events
= 0, ret
= 0;
1475 uint64_t wr_id
= RDMA_WRID_NONE
, wr_id_in
;
1477 if (ibv_req_notify_cq(rdma
->cq
, 0)) {
1481 while (wr_id
!= wrid_requested
) {
1482 ret
= qemu_rdma_poll(rdma
, &wr_id_in
, byte_len
);
1487 wr_id
= wr_id_in
& RDMA_WRID_TYPE_MASK
;
1489 if (wr_id
== RDMA_WRID_NONE
) {
1492 if (wr_id
!= wrid_requested
) {
1493 trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested
),
1494 wrid_requested
, print_wrid(wr_id
), wr_id
);
1498 if (wr_id
== wrid_requested
) {
1504 * Coroutine doesn't start until process_incoming_migration()
1505 * so don't yield unless we know we're running inside of a coroutine.
1507 if (rdma
->migration_started_on_destination
) {
1508 yield_until_fd_readable(rdma
->comp_channel
->fd
);
1511 if (ibv_get_cq_event(rdma
->comp_channel
, &cq
, &cq_ctx
)) {
1512 perror("ibv_get_cq_event");
1513 goto err_block_for_wrid
;
1518 if (ibv_req_notify_cq(cq
, 0)) {
1519 goto err_block_for_wrid
;
1522 while (wr_id
!= wrid_requested
) {
1523 ret
= qemu_rdma_poll(rdma
, &wr_id_in
, byte_len
);
1525 goto err_block_for_wrid
;
1528 wr_id
= wr_id_in
& RDMA_WRID_TYPE_MASK
;
1530 if (wr_id
== RDMA_WRID_NONE
) {
1533 if (wr_id
!= wrid_requested
) {
1534 trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested
),
1535 wrid_requested
, print_wrid(wr_id
), wr_id
);
1539 if (wr_id
== wrid_requested
) {
1540 goto success_block_for_wrid
;
1544 success_block_for_wrid
:
1545 if (num_cq_events
) {
1546 ibv_ack_cq_events(cq
, num_cq_events
);
1551 if (num_cq_events
) {
1552 ibv_ack_cq_events(cq
, num_cq_events
);
1558 * Post a SEND message work request for the control channel
1559 * containing some data and block until the post completes.
1561 static int qemu_rdma_post_send_control(RDMAContext
*rdma
, uint8_t *buf
,
1562 RDMAControlHeader
*head
)
1565 RDMAWorkRequestData
*wr
= &rdma
->wr_data
[RDMA_WRID_CONTROL
];
1566 struct ibv_send_wr
*bad_wr
;
1567 struct ibv_sge sge
= {
1568 .addr
= (uintptr_t)(wr
->control
),
1569 .length
= head
->len
+ sizeof(RDMAControlHeader
),
1570 .lkey
= wr
->control_mr
->lkey
,
1572 struct ibv_send_wr send_wr
= {
1573 .wr_id
= RDMA_WRID_SEND_CONTROL
,
1574 .opcode
= IBV_WR_SEND
,
1575 .send_flags
= IBV_SEND_SIGNALED
,
1580 trace_qemu_rdma_post_send_control(control_desc
[head
->type
]);
1583 * We don't actually need to do a memcpy() in here if we used
1584 * the "sge" properly, but since we're only sending control messages
1585 * (not RAM in a performance-critical path), then its OK for now.
1587 * The copy makes the RDMAControlHeader simpler to manipulate
1588 * for the time being.
1590 assert(head
->len
<= RDMA_CONTROL_MAX_BUFFER
- sizeof(*head
));
1591 memcpy(wr
->control
, head
, sizeof(RDMAControlHeader
));
1592 control_to_network((void *) wr
->control
);
1595 memcpy(wr
->control
+ sizeof(RDMAControlHeader
), buf
, head
->len
);
1599 ret
= ibv_post_send(rdma
->qp
, &send_wr
, &bad_wr
);
1602 error_report("Failed to use post IB SEND for control");
1606 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_SEND_CONTROL
, NULL
);
1608 error_report("rdma migration: send polling control error");
1615 * Post a RECV work request in anticipation of some future receipt
1616 * of data on the control channel.
1618 static int qemu_rdma_post_recv_control(RDMAContext
*rdma
, int idx
)
1620 struct ibv_recv_wr
*bad_wr
;
1621 struct ibv_sge sge
= {
1622 .addr
= (uintptr_t)(rdma
->wr_data
[idx
].control
),
1623 .length
= RDMA_CONTROL_MAX_BUFFER
,
1624 .lkey
= rdma
->wr_data
[idx
].control_mr
->lkey
,
1627 struct ibv_recv_wr recv_wr
= {
1628 .wr_id
= RDMA_WRID_RECV_CONTROL
+ idx
,
1634 if (ibv_post_recv(rdma
->qp
, &recv_wr
, &bad_wr
)) {
1642 * Block and wait for a RECV control channel message to arrive.
1644 static int qemu_rdma_exchange_get_response(RDMAContext
*rdma
,
1645 RDMAControlHeader
*head
, int expecting
, int idx
)
1648 int ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RECV_CONTROL
+ idx
,
1652 error_report("rdma migration: recv polling control error!");
1656 network_to_control((void *) rdma
->wr_data
[idx
].control
);
1657 memcpy(head
, rdma
->wr_data
[idx
].control
, sizeof(RDMAControlHeader
));
1659 trace_qemu_rdma_exchange_get_response_start(control_desc
[expecting
]);
1661 if (expecting
== RDMA_CONTROL_NONE
) {
1662 trace_qemu_rdma_exchange_get_response_none(control_desc
[head
->type
],
1664 } else if (head
->type
!= expecting
|| head
->type
== RDMA_CONTROL_ERROR
) {
1665 error_report("Was expecting a %s (%d) control message"
1666 ", but got: %s (%d), length: %d",
1667 control_desc
[expecting
], expecting
,
1668 control_desc
[head
->type
], head
->type
, head
->len
);
1671 if (head
->len
> RDMA_CONTROL_MAX_BUFFER
- sizeof(*head
)) {
1672 error_report("too long length: %d", head
->len
);
1675 if (sizeof(*head
) + head
->len
!= byte_len
) {
1676 error_report("Malformed length: %d byte_len %d", head
->len
, byte_len
);
1684 * When a RECV work request has completed, the work request's
1685 * buffer is pointed at the header.
1687 * This will advance the pointer to the data portion
1688 * of the control message of the work request's buffer that
1689 * was populated after the work request finished.
1691 static void qemu_rdma_move_header(RDMAContext
*rdma
, int idx
,
1692 RDMAControlHeader
*head
)
1694 rdma
->wr_data
[idx
].control_len
= head
->len
;
1695 rdma
->wr_data
[idx
].control_curr
=
1696 rdma
->wr_data
[idx
].control
+ sizeof(RDMAControlHeader
);
1700 * This is an 'atomic' high-level operation to deliver a single, unified
1701 * control-channel message.
1703 * Additionally, if the user is expecting some kind of reply to this message,
1704 * they can request a 'resp' response message be filled in by posting an
1705 * additional work request on behalf of the user and waiting for an additional
1708 * The extra (optional) response is used during registration to us from having
1709 * to perform an *additional* exchange of message just to provide a response by
1710 * instead piggy-backing on the acknowledgement.
1712 static int qemu_rdma_exchange_send(RDMAContext
*rdma
, RDMAControlHeader
*head
,
1713 uint8_t *data
, RDMAControlHeader
*resp
,
1715 int (*callback
)(RDMAContext
*rdma
))
1720 * Wait until the dest is ready before attempting to deliver the message
1721 * by waiting for a READY message.
1723 if (rdma
->control_ready_expected
) {
1724 RDMAControlHeader resp
;
1725 ret
= qemu_rdma_exchange_get_response(rdma
,
1726 &resp
, RDMA_CONTROL_READY
, RDMA_WRID_READY
);
1733 * If the user is expecting a response, post a WR in anticipation of it.
1736 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_DATA
);
1738 error_report("rdma migration: error posting"
1739 " extra control recv for anticipated result!");
1745 * Post a WR to replace the one we just consumed for the READY message.
1747 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
1749 error_report("rdma migration: error posting first control recv!");
1754 * Deliver the control message that was requested.
1756 ret
= qemu_rdma_post_send_control(rdma
, data
, head
);
1759 error_report("Failed to send control buffer!");
1764 * If we're expecting a response, block and wait for it.
1768 trace_qemu_rdma_exchange_send_issue_callback();
1769 ret
= callback(rdma
);
1775 trace_qemu_rdma_exchange_send_waiting(control_desc
[resp
->type
]);
1776 ret
= qemu_rdma_exchange_get_response(rdma
, resp
,
1777 resp
->type
, RDMA_WRID_DATA
);
1783 qemu_rdma_move_header(rdma
, RDMA_WRID_DATA
, resp
);
1785 *resp_idx
= RDMA_WRID_DATA
;
1787 trace_qemu_rdma_exchange_send_received(control_desc
[resp
->type
]);
1790 rdma
->control_ready_expected
= 1;
1796 * This is an 'atomic' high-level operation to receive a single, unified
1797 * control-channel message.
1799 static int qemu_rdma_exchange_recv(RDMAContext
*rdma
, RDMAControlHeader
*head
,
1802 RDMAControlHeader ready
= {
1804 .type
= RDMA_CONTROL_READY
,
1810 * Inform the source that we're ready to receive a message.
1812 ret
= qemu_rdma_post_send_control(rdma
, NULL
, &ready
);
1815 error_report("Failed to send control buffer!");
1820 * Block and wait for the message.
1822 ret
= qemu_rdma_exchange_get_response(rdma
, head
,
1823 expecting
, RDMA_WRID_READY
);
1829 qemu_rdma_move_header(rdma
, RDMA_WRID_READY
, head
);
1832 * Post a new RECV work request to replace the one we just consumed.
1834 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
1836 error_report("rdma migration: error posting second control recv!");
1844 * Write an actual chunk of memory using RDMA.
1846 * If we're using dynamic registration on the dest-side, we have to
1847 * send a registration command first.
1849 static int qemu_rdma_write_one(QEMUFile
*f
, RDMAContext
*rdma
,
1850 int current_index
, uint64_t current_addr
,
1854 struct ibv_send_wr send_wr
= { 0 };
1855 struct ibv_send_wr
*bad_wr
;
1856 int reg_result_idx
, ret
, count
= 0;
1857 uint64_t chunk
, chunks
;
1858 uint8_t *chunk_start
, *chunk_end
;
1859 RDMALocalBlock
*block
= &(rdma
->local_ram_blocks
.block
[current_index
]);
1861 RDMARegisterResult
*reg_result
;
1862 RDMAControlHeader resp
= { .type
= RDMA_CONTROL_REGISTER_RESULT
};
1863 RDMAControlHeader head
= { .len
= sizeof(RDMARegister
),
1864 .type
= RDMA_CONTROL_REGISTER_REQUEST
,
1869 sge
.addr
= (uintptr_t)(block
->local_host_addr
+
1870 (current_addr
- block
->offset
));
1871 sge
.length
= length
;
1873 chunk
= ram_chunk_index(block
->local_host_addr
,
1874 (uint8_t *)(uintptr_t)sge
.addr
);
1875 chunk_start
= ram_chunk_start(block
, chunk
);
1877 if (block
->is_ram_block
) {
1878 chunks
= length
/ (1UL << RDMA_REG_CHUNK_SHIFT
);
1880 if (chunks
&& ((length
% (1UL << RDMA_REG_CHUNK_SHIFT
)) == 0)) {
1884 chunks
= block
->length
/ (1UL << RDMA_REG_CHUNK_SHIFT
);
1886 if (chunks
&& ((block
->length
% (1UL << RDMA_REG_CHUNK_SHIFT
)) == 0)) {
1891 trace_qemu_rdma_write_one_top(chunks
+ 1,
1893 (1UL << RDMA_REG_CHUNK_SHIFT
) / 1024 / 1024);
1895 chunk_end
= ram_chunk_end(block
, chunk
+ chunks
);
1897 if (!rdma
->pin_all
) {
1898 #ifdef RDMA_UNREGISTRATION_EXAMPLE
1899 qemu_rdma_unregister_waiting(rdma
);
1903 while (test_bit(chunk
, block
->transit_bitmap
)) {
1905 trace_qemu_rdma_write_one_block(count
++, current_index
, chunk
,
1906 sge
.addr
, length
, rdma
->nb_sent
, block
->nb_chunks
);
1908 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RDMA_WRITE
, NULL
);
1911 error_report("Failed to Wait for previous write to complete "
1912 "block %d chunk %" PRIu64
1913 " current %" PRIu64
" len %" PRIu64
" %d",
1914 current_index
, chunk
, sge
.addr
, length
, rdma
->nb_sent
);
1919 if (!rdma
->pin_all
|| !block
->is_ram_block
) {
1920 if (!block
->remote_keys
[chunk
]) {
1922 * This chunk has not yet been registered, so first check to see
1923 * if the entire chunk is zero. If so, tell the other size to
1924 * memset() + madvise() the entire chunk without RDMA.
1927 if (can_use_buffer_find_nonzero_offset((void *)(uintptr_t)sge
.addr
,
1929 && buffer_find_nonzero_offset((void *)(uintptr_t)sge
.addr
,
1930 length
) == length
) {
1931 RDMACompress comp
= {
1932 .offset
= current_addr
,
1934 .block_idx
= current_index
,
1938 head
.len
= sizeof(comp
);
1939 head
.type
= RDMA_CONTROL_COMPRESS
;
1941 trace_qemu_rdma_write_one_zero(chunk
, sge
.length
,
1942 current_index
, current_addr
);
1944 compress_to_network(rdma
, &comp
);
1945 ret
= qemu_rdma_exchange_send(rdma
, &head
,
1946 (uint8_t *) &comp
, NULL
, NULL
, NULL
);
1952 acct_update_position(f
, sge
.length
, true);
1958 * Otherwise, tell other side to register.
1960 reg
.current_index
= current_index
;
1961 if (block
->is_ram_block
) {
1962 reg
.key
.current_addr
= current_addr
;
1964 reg
.key
.chunk
= chunk
;
1966 reg
.chunks
= chunks
;
1968 trace_qemu_rdma_write_one_sendreg(chunk
, sge
.length
, current_index
,
1971 register_to_network(rdma
, ®
);
1972 ret
= qemu_rdma_exchange_send(rdma
, &head
, (uint8_t *) ®
,
1973 &resp
, ®_result_idx
, NULL
);
1978 /* try to overlap this single registration with the one we sent. */
1979 if (qemu_rdma_register_and_get_keys(rdma
, block
, sge
.addr
,
1980 &sge
.lkey
, NULL
, chunk
,
1981 chunk_start
, chunk_end
)) {
1982 error_report("cannot get lkey");
1986 reg_result
= (RDMARegisterResult
*)
1987 rdma
->wr_data
[reg_result_idx
].control_curr
;
1989 network_to_result(reg_result
);
1991 trace_qemu_rdma_write_one_recvregres(block
->remote_keys
[chunk
],
1992 reg_result
->rkey
, chunk
);
1994 block
->remote_keys
[chunk
] = reg_result
->rkey
;
1995 block
->remote_host_addr
= reg_result
->host_addr
;
1997 /* already registered before */
1998 if (qemu_rdma_register_and_get_keys(rdma
, block
, sge
.addr
,
1999 &sge
.lkey
, NULL
, chunk
,
2000 chunk_start
, chunk_end
)) {
2001 error_report("cannot get lkey!");
2006 send_wr
.wr
.rdma
.rkey
= block
->remote_keys
[chunk
];
2008 send_wr
.wr
.rdma
.rkey
= block
->remote_rkey
;
2010 if (qemu_rdma_register_and_get_keys(rdma
, block
, sge
.addr
,
2011 &sge
.lkey
, NULL
, chunk
,
2012 chunk_start
, chunk_end
)) {
2013 error_report("cannot get lkey!");
2019 * Encode the ram block index and chunk within this wrid.
2020 * We will use this information at the time of completion
2021 * to figure out which bitmap to check against and then which
2022 * chunk in the bitmap to look for.
2024 send_wr
.wr_id
= qemu_rdma_make_wrid(RDMA_WRID_RDMA_WRITE
,
2025 current_index
, chunk
);
2027 send_wr
.opcode
= IBV_WR_RDMA_WRITE
;
2028 send_wr
.send_flags
= IBV_SEND_SIGNALED
;
2029 send_wr
.sg_list
= &sge
;
2030 send_wr
.num_sge
= 1;
2031 send_wr
.wr
.rdma
.remote_addr
= block
->remote_host_addr
+
2032 (current_addr
- block
->offset
);
2034 trace_qemu_rdma_write_one_post(chunk
, sge
.addr
, send_wr
.wr
.rdma
.remote_addr
,
2038 * ibv_post_send() does not return negative error numbers,
2039 * per the specification they are positive - no idea why.
2041 ret
= ibv_post_send(rdma
->qp
, &send_wr
, &bad_wr
);
2043 if (ret
== ENOMEM
) {
2044 trace_qemu_rdma_write_one_queue_full();
2045 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RDMA_WRITE
, NULL
);
2047 error_report("rdma migration: failed to make "
2048 "room in full send queue! %d", ret
);
2054 } else if (ret
> 0) {
2055 perror("rdma migration: post rdma write failed");
2059 set_bit(chunk
, block
->transit_bitmap
);
2060 acct_update_position(f
, sge
.length
, false);
2061 rdma
->total_writes
++;
2067 * Push out any unwritten RDMA operations.
2069 * We support sending out multiple chunks at the same time.
2070 * Not all of them need to get signaled in the completion queue.
2072 static int qemu_rdma_write_flush(QEMUFile
*f
, RDMAContext
*rdma
)
2076 if (!rdma
->current_length
) {
2080 ret
= qemu_rdma_write_one(f
, rdma
,
2081 rdma
->current_index
, rdma
->current_addr
, rdma
->current_length
);
2089 trace_qemu_rdma_write_flush(rdma
->nb_sent
);
2092 rdma
->current_length
= 0;
2093 rdma
->current_addr
= 0;
2098 static inline int qemu_rdma_buffer_mergable(RDMAContext
*rdma
,
2099 uint64_t offset
, uint64_t len
)
2101 RDMALocalBlock
*block
;
2105 if (rdma
->current_index
< 0) {
2109 if (rdma
->current_chunk
< 0) {
2113 block
= &(rdma
->local_ram_blocks
.block
[rdma
->current_index
]);
2114 host_addr
= block
->local_host_addr
+ (offset
- block
->offset
);
2115 chunk_end
= ram_chunk_end(block
, rdma
->current_chunk
);
2117 if (rdma
->current_length
== 0) {
2122 * Only merge into chunk sequentially.
2124 if (offset
!= (rdma
->current_addr
+ rdma
->current_length
)) {
2128 if (offset
< block
->offset
) {
2132 if ((offset
+ len
) > (block
->offset
+ block
->length
)) {
2136 if ((host_addr
+ len
) > chunk_end
) {
2144 * We're not actually writing here, but doing three things:
2146 * 1. Identify the chunk the buffer belongs to.
2147 * 2. If the chunk is full or the buffer doesn't belong to the current
2148 * chunk, then start a new chunk and flush() the old chunk.
2149 * 3. To keep the hardware busy, we also group chunks into batches
2150 * and only require that a batch gets acknowledged in the completion
2151 * qeueue instead of each individual chunk.
2153 static int qemu_rdma_write(QEMUFile
*f
, RDMAContext
*rdma
,
2154 uint64_t block_offset
, uint64_t offset
,
2157 uint64_t current_addr
= block_offset
+ offset
;
2158 uint64_t index
= rdma
->current_index
;
2159 uint64_t chunk
= rdma
->current_chunk
;
2162 /* If we cannot merge it, we flush the current buffer first. */
2163 if (!qemu_rdma_buffer_mergable(rdma
, current_addr
, len
)) {
2164 ret
= qemu_rdma_write_flush(f
, rdma
);
2168 rdma
->current_length
= 0;
2169 rdma
->current_addr
= current_addr
;
2171 ret
= qemu_rdma_search_ram_block(rdma
, block_offset
,
2172 offset
, len
, &index
, &chunk
);
2174 error_report("ram block search failed");
2177 rdma
->current_index
= index
;
2178 rdma
->current_chunk
= chunk
;
2182 rdma
->current_length
+= len
;
2184 /* flush it if buffer is too large */
2185 if (rdma
->current_length
>= RDMA_MERGE_MAX
) {
2186 return qemu_rdma_write_flush(f
, rdma
);
2192 static void qemu_rdma_cleanup(RDMAContext
*rdma
)
2194 struct rdma_cm_event
*cm_event
;
2197 if (rdma
->cm_id
&& rdma
->connected
) {
2198 if (rdma
->error_state
) {
2199 RDMAControlHeader head
= { .len
= 0,
2200 .type
= RDMA_CONTROL_ERROR
,
2203 error_report("Early error. Sending error.");
2204 qemu_rdma_post_send_control(rdma
, NULL
, &head
);
2207 ret
= rdma_disconnect(rdma
->cm_id
);
2209 trace_qemu_rdma_cleanup_waiting_for_disconnect();
2210 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
2212 rdma_ack_cm_event(cm_event
);
2215 trace_qemu_rdma_cleanup_disconnect();
2216 rdma
->connected
= false;
2219 g_free(rdma
->dest_blocks
);
2220 rdma
->dest_blocks
= NULL
;
2222 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2223 if (rdma
->wr_data
[idx
].control_mr
) {
2224 rdma
->total_registrations
--;
2225 ibv_dereg_mr(rdma
->wr_data
[idx
].control_mr
);
2227 rdma
->wr_data
[idx
].control_mr
= NULL
;
2230 if (rdma
->local_ram_blocks
.block
) {
2231 while (rdma
->local_ram_blocks
.nb_blocks
) {
2232 rdma_delete_block(rdma
, &rdma
->local_ram_blocks
.block
[0]);
2237 rdma_destroy_qp(rdma
->cm_id
);
2241 ibv_destroy_cq(rdma
->cq
);
2244 if (rdma
->comp_channel
) {
2245 ibv_destroy_comp_channel(rdma
->comp_channel
);
2246 rdma
->comp_channel
= NULL
;
2249 ibv_dealloc_pd(rdma
->pd
);
2253 rdma_destroy_id(rdma
->cm_id
);
2256 if (rdma
->listen_id
) {
2257 rdma_destroy_id(rdma
->listen_id
);
2258 rdma
->listen_id
= NULL
;
2260 if (rdma
->channel
) {
2261 rdma_destroy_event_channel(rdma
->channel
);
2262 rdma
->channel
= NULL
;
2269 static int qemu_rdma_source_init(RDMAContext
*rdma
, Error
**errp
, bool pin_all
)
2272 Error
*local_err
= NULL
, **temp
= &local_err
;
2275 * Will be validated against destination's actual capabilities
2276 * after the connect() completes.
2278 rdma
->pin_all
= pin_all
;
2280 ret
= qemu_rdma_resolve_host(rdma
, temp
);
2282 goto err_rdma_source_init
;
2285 ret
= qemu_rdma_alloc_pd_cq(rdma
);
2287 ERROR(temp
, "rdma migration: error allocating pd and cq! Your mlock()"
2288 " limits may be too low. Please check $ ulimit -a # and "
2289 "search for 'ulimit -l' in the output");
2290 goto err_rdma_source_init
;
2293 ret
= qemu_rdma_alloc_qp(rdma
);
2295 ERROR(temp
, "rdma migration: error allocating qp!");
2296 goto err_rdma_source_init
;
2299 ret
= qemu_rdma_init_ram_blocks(rdma
);
2301 ERROR(temp
, "rdma migration: error initializing ram blocks!");
2302 goto err_rdma_source_init
;
2305 /* Build the hash that maps from offset to RAMBlock */
2306 rdma
->blockmap
= g_hash_table_new(g_direct_hash
, g_direct_equal
);
2307 for (idx
= 0; idx
< rdma
->local_ram_blocks
.nb_blocks
; idx
++) {
2308 g_hash_table_insert(rdma
->blockmap
,
2309 (void *)(uintptr_t)rdma
->local_ram_blocks
.block
[idx
].offset
,
2310 &rdma
->local_ram_blocks
.block
[idx
]);
2313 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2314 ret
= qemu_rdma_reg_control(rdma
, idx
);
2316 ERROR(temp
, "rdma migration: error registering %d control!",
2318 goto err_rdma_source_init
;
2324 err_rdma_source_init
:
2325 error_propagate(errp
, local_err
);
2326 qemu_rdma_cleanup(rdma
);
2330 static int qemu_rdma_connect(RDMAContext
*rdma
, Error
**errp
)
2332 RDMACapabilities cap
= {
2333 .version
= RDMA_CONTROL_VERSION_CURRENT
,
2336 struct rdma_conn_param conn_param
= { .initiator_depth
= 2,
2338 .private_data
= &cap
,
2339 .private_data_len
= sizeof(cap
),
2341 struct rdma_cm_event
*cm_event
;
2345 * Only negotiate the capability with destination if the user
2346 * on the source first requested the capability.
2348 if (rdma
->pin_all
) {
2349 trace_qemu_rdma_connect_pin_all_requested();
2350 cap
.flags
|= RDMA_CAPABILITY_PIN_ALL
;
2353 caps_to_network(&cap
);
2355 ret
= rdma_connect(rdma
->cm_id
, &conn_param
);
2357 perror("rdma_connect");
2358 ERROR(errp
, "connecting to destination!");
2359 goto err_rdma_source_connect
;
2362 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
2364 perror("rdma_get_cm_event after rdma_connect");
2365 ERROR(errp
, "connecting to destination!");
2366 rdma_ack_cm_event(cm_event
);
2367 goto err_rdma_source_connect
;
2370 if (cm_event
->event
!= RDMA_CM_EVENT_ESTABLISHED
) {
2371 perror("rdma_get_cm_event != EVENT_ESTABLISHED after rdma_connect");
2372 ERROR(errp
, "connecting to destination!");
2373 rdma_ack_cm_event(cm_event
);
2374 goto err_rdma_source_connect
;
2376 rdma
->connected
= true;
2378 memcpy(&cap
, cm_event
->param
.conn
.private_data
, sizeof(cap
));
2379 network_to_caps(&cap
);
2382 * Verify that the *requested* capabilities are supported by the destination
2383 * and disable them otherwise.
2385 if (rdma
->pin_all
&& !(cap
.flags
& RDMA_CAPABILITY_PIN_ALL
)) {
2386 ERROR(errp
, "Server cannot support pinning all memory. "
2387 "Will register memory dynamically.");
2388 rdma
->pin_all
= false;
2391 trace_qemu_rdma_connect_pin_all_outcome(rdma
->pin_all
);
2393 rdma_ack_cm_event(cm_event
);
2395 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
2397 ERROR(errp
, "posting second control recv!");
2398 goto err_rdma_source_connect
;
2401 rdma
->control_ready_expected
= 1;
2405 err_rdma_source_connect
:
2406 qemu_rdma_cleanup(rdma
);
2410 static int qemu_rdma_dest_init(RDMAContext
*rdma
, Error
**errp
)
2413 struct rdma_cm_id
*listen_id
;
2414 char ip
[40] = "unknown";
2415 struct rdma_addrinfo
*res
, *e
;
2418 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2419 rdma
->wr_data
[idx
].control_len
= 0;
2420 rdma
->wr_data
[idx
].control_curr
= NULL
;
2423 if (!rdma
->host
|| !rdma
->host
[0]) {
2424 ERROR(errp
, "RDMA host is not set!");
2425 rdma
->error_state
= -EINVAL
;
2428 /* create CM channel */
2429 rdma
->channel
= rdma_create_event_channel();
2430 if (!rdma
->channel
) {
2431 ERROR(errp
, "could not create rdma event channel");
2432 rdma
->error_state
= -EINVAL
;
2437 ret
= rdma_create_id(rdma
->channel
, &listen_id
, NULL
, RDMA_PS_TCP
);
2439 ERROR(errp
, "could not create cm_id!");
2440 goto err_dest_init_create_listen_id
;
2443 snprintf(port_str
, 16, "%d", rdma
->port
);
2444 port_str
[15] = '\0';
2446 ret
= rdma_getaddrinfo(rdma
->host
, port_str
, NULL
, &res
);
2448 ERROR(errp
, "could not rdma_getaddrinfo address %s", rdma
->host
);
2449 goto err_dest_init_bind_addr
;
2452 for (e
= res
; e
!= NULL
; e
= e
->ai_next
) {
2453 inet_ntop(e
->ai_family
,
2454 &((struct sockaddr_in
*) e
->ai_dst_addr
)->sin_addr
, ip
, sizeof ip
);
2455 trace_qemu_rdma_dest_init_trying(rdma
->host
, ip
);
2456 ret
= rdma_bind_addr(listen_id
, e
->ai_dst_addr
);
2460 if (e
->ai_family
== AF_INET6
) {
2461 ret
= qemu_rdma_broken_ipv6_kernel(errp
, listen_id
->verbs
);
2470 ERROR(errp
, "Error: could not rdma_bind_addr!");
2471 goto err_dest_init_bind_addr
;
2474 rdma
->listen_id
= listen_id
;
2475 qemu_rdma_dump_gid("dest_init", listen_id
);
2478 err_dest_init_bind_addr
:
2479 rdma_destroy_id(listen_id
);
2480 err_dest_init_create_listen_id
:
2481 rdma_destroy_event_channel(rdma
->channel
);
2482 rdma
->channel
= NULL
;
2483 rdma
->error_state
= ret
;
2488 static void *qemu_rdma_data_init(const char *host_port
, Error
**errp
)
2490 RDMAContext
*rdma
= NULL
;
2491 InetSocketAddress
*addr
;
2494 rdma
= g_new0(RDMAContext
, 1);
2495 rdma
->current_index
= -1;
2496 rdma
->current_chunk
= -1;
2498 addr
= inet_parse(host_port
, NULL
);
2500 rdma
->port
= atoi(addr
->port
);
2501 rdma
->host
= g_strdup(addr
->host
);
2503 ERROR(errp
, "bad RDMA migration address '%s'", host_port
);
2508 qapi_free_InetSocketAddress(addr
);
2515 * QEMUFile interface to the control channel.
2516 * SEND messages for control only.
2517 * VM's ram is handled with regular RDMA messages.
2519 static ssize_t
qemu_rdma_put_buffer(void *opaque
, const uint8_t *buf
,
2520 int64_t pos
, size_t size
)
2522 QEMUFileRDMA
*r
= opaque
;
2523 QEMUFile
*f
= r
->file
;
2524 RDMAContext
*rdma
= r
->rdma
;
2525 size_t remaining
= size
;
2526 uint8_t * data
= (void *) buf
;
2529 CHECK_ERROR_STATE();
2532 * Push out any writes that
2533 * we're queued up for VM's ram.
2535 ret
= qemu_rdma_write_flush(f
, rdma
);
2537 rdma
->error_state
= ret
;
2542 RDMAControlHeader head
;
2544 r
->len
= MIN(remaining
, RDMA_SEND_INCREMENT
);
2545 remaining
-= r
->len
;
2547 /* Guaranteed to fit due to RDMA_SEND_INCREMENT MIN above */
2548 head
.len
= (uint32_t)r
->len
;
2549 head
.type
= RDMA_CONTROL_QEMU_FILE
;
2551 ret
= qemu_rdma_exchange_send(rdma
, &head
, data
, NULL
, NULL
, NULL
);
2554 rdma
->error_state
= ret
;
2564 static size_t qemu_rdma_fill(RDMAContext
*rdma
, uint8_t *buf
,
2565 size_t size
, int idx
)
2569 if (rdma
->wr_data
[idx
].control_len
) {
2570 trace_qemu_rdma_fill(rdma
->wr_data
[idx
].control_len
, size
);
2572 len
= MIN(size
, rdma
->wr_data
[idx
].control_len
);
2573 memcpy(buf
, rdma
->wr_data
[idx
].control_curr
, len
);
2574 rdma
->wr_data
[idx
].control_curr
+= len
;
2575 rdma
->wr_data
[idx
].control_len
-= len
;
2582 * QEMUFile interface to the control channel.
2583 * RDMA links don't use bytestreams, so we have to
2584 * return bytes to QEMUFile opportunistically.
2586 static ssize_t
qemu_rdma_get_buffer(void *opaque
, uint8_t *buf
,
2587 int64_t pos
, size_t size
)
2589 QEMUFileRDMA
*r
= opaque
;
2590 RDMAContext
*rdma
= r
->rdma
;
2591 RDMAControlHeader head
;
2594 CHECK_ERROR_STATE();
2597 * First, we hold on to the last SEND message we
2598 * were given and dish out the bytes until we run
2601 r
->len
= qemu_rdma_fill(r
->rdma
, buf
, size
, 0);
2607 * Once we run out, we block and wait for another
2608 * SEND message to arrive.
2610 ret
= qemu_rdma_exchange_recv(rdma
, &head
, RDMA_CONTROL_QEMU_FILE
);
2613 rdma
->error_state
= ret
;
2618 * SEND was received with new bytes, now try again.
2620 return qemu_rdma_fill(r
->rdma
, buf
, size
, 0);
2624 * Block until all the outstanding chunks have been delivered by the hardware.
2626 static int qemu_rdma_drain_cq(QEMUFile
*f
, RDMAContext
*rdma
)
2630 if (qemu_rdma_write_flush(f
, rdma
) < 0) {
2634 while (rdma
->nb_sent
) {
2635 ret
= qemu_rdma_block_for_wrid(rdma
, RDMA_WRID_RDMA_WRITE
, NULL
);
2637 error_report("rdma migration: complete polling error!");
2642 qemu_rdma_unregister_waiting(rdma
);
2647 static int qemu_rdma_close(void *opaque
)
2649 trace_qemu_rdma_close();
2650 QEMUFileRDMA
*r
= opaque
;
2652 qemu_rdma_cleanup(r
->rdma
);
2662 * This means that 'block_offset' is a full virtual address that does not
2663 * belong to a RAMBlock of the virtual machine and instead
2664 * represents a private malloc'd memory area that the caller wishes to
2668 * Offset is an offset to be added to block_offset and used
2669 * to also lookup the corresponding RAMBlock.
2672 * Initiate an transfer this size.
2675 * A 'hint' or 'advice' that means that we wish to speculatively
2676 * and asynchronously unregister this memory. In this case, there is no
2677 * guarantee that the unregister will actually happen, for example,
2678 * if the memory is being actively transmitted. Additionally, the memory
2679 * may be re-registered at any future time if a write within the same
2680 * chunk was requested again, even if you attempted to unregister it
2683 * @size < 0 : TODO, not yet supported
2684 * Unregister the memory NOW. This means that the caller does not
2685 * expect there to be any future RDMA transfers and we just want to clean
2686 * things up. This is used in case the upper layer owns the memory and
2687 * cannot wait for qemu_fclose() to occur.
2689 * @bytes_sent : User-specificed pointer to indicate how many bytes were
2690 * sent. Usually, this will not be more than a few bytes of
2691 * the protocol because most transfers are sent asynchronously.
2693 static size_t qemu_rdma_save_page(QEMUFile
*f
, void *opaque
,
2694 ram_addr_t block_offset
, ram_addr_t offset
,
2695 size_t size
, uint64_t *bytes_sent
)
2697 QEMUFileRDMA
*rfile
= opaque
;
2698 RDMAContext
*rdma
= rfile
->rdma
;
2701 CHECK_ERROR_STATE();
2707 * Add this page to the current 'chunk'. If the chunk
2708 * is full, or the page doen't belong to the current chunk,
2709 * an actual RDMA write will occur and a new chunk will be formed.
2711 ret
= qemu_rdma_write(f
, rdma
, block_offset
, offset
, size
);
2713 error_report("rdma migration: write error! %d", ret
);
2718 * We always return 1 bytes because the RDMA
2719 * protocol is completely asynchronous. We do not yet know
2720 * whether an identified chunk is zero or not because we're
2721 * waiting for other pages to potentially be merged with
2722 * the current chunk. So, we have to call qemu_update_position()
2723 * later on when the actual write occurs.
2729 uint64_t index
, chunk
;
2731 /* TODO: Change QEMUFileOps prototype to be signed: size_t => long
2733 ret = qemu_rdma_drain_cq(f, rdma);
2735 fprintf(stderr, "rdma: failed to synchronously drain"
2736 " completion queue before unregistration.\n");
2742 ret
= qemu_rdma_search_ram_block(rdma
, block_offset
,
2743 offset
, size
, &index
, &chunk
);
2746 error_report("ram block search failed");
2750 qemu_rdma_signal_unregister(rdma
, index
, chunk
, 0);
2753 * TODO: Synchronous, guaranteed unregistration (should not occur during
2754 * fast-path). Otherwise, unregisters will process on the next call to
2755 * qemu_rdma_drain_cq()
2757 qemu_rdma_unregister_waiting(rdma);
2763 * Drain the Completion Queue if possible, but do not block,
2766 * If nothing to poll, the end of the iteration will do this
2767 * again to make sure we don't overflow the request queue.
2770 uint64_t wr_id
, wr_id_in
;
2771 int ret
= qemu_rdma_poll(rdma
, &wr_id_in
, NULL
);
2773 error_report("rdma migration: polling error! %d", ret
);
2777 wr_id
= wr_id_in
& RDMA_WRID_TYPE_MASK
;
2779 if (wr_id
== RDMA_WRID_NONE
) {
2784 return RAM_SAVE_CONTROL_DELAYED
;
2786 rdma
->error_state
= ret
;
2790 static int qemu_rdma_accept(RDMAContext
*rdma
)
2792 RDMACapabilities cap
;
2793 struct rdma_conn_param conn_param
= {
2794 .responder_resources
= 2,
2795 .private_data
= &cap
,
2796 .private_data_len
= sizeof(cap
),
2798 struct rdma_cm_event
*cm_event
;
2799 struct ibv_context
*verbs
;
2803 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
2805 goto err_rdma_dest_wait
;
2808 if (cm_event
->event
!= RDMA_CM_EVENT_CONNECT_REQUEST
) {
2809 rdma_ack_cm_event(cm_event
);
2810 goto err_rdma_dest_wait
;
2813 memcpy(&cap
, cm_event
->param
.conn
.private_data
, sizeof(cap
));
2815 network_to_caps(&cap
);
2817 if (cap
.version
< 1 || cap
.version
> RDMA_CONTROL_VERSION_CURRENT
) {
2818 error_report("Unknown source RDMA version: %d, bailing...",
2820 rdma_ack_cm_event(cm_event
);
2821 goto err_rdma_dest_wait
;
2825 * Respond with only the capabilities this version of QEMU knows about.
2827 cap
.flags
&= known_capabilities
;
2830 * Enable the ones that we do know about.
2831 * Add other checks here as new ones are introduced.
2833 if (cap
.flags
& RDMA_CAPABILITY_PIN_ALL
) {
2834 rdma
->pin_all
= true;
2837 rdma
->cm_id
= cm_event
->id
;
2838 verbs
= cm_event
->id
->verbs
;
2840 rdma_ack_cm_event(cm_event
);
2842 trace_qemu_rdma_accept_pin_state(rdma
->pin_all
);
2844 caps_to_network(&cap
);
2846 trace_qemu_rdma_accept_pin_verbsc(verbs
);
2849 rdma
->verbs
= verbs
;
2850 } else if (rdma
->verbs
!= verbs
) {
2851 error_report("ibv context not matching %p, %p!", rdma
->verbs
,
2853 goto err_rdma_dest_wait
;
2856 qemu_rdma_dump_id("dest_init", verbs
);
2858 ret
= qemu_rdma_alloc_pd_cq(rdma
);
2860 error_report("rdma migration: error allocating pd and cq!");
2861 goto err_rdma_dest_wait
;
2864 ret
= qemu_rdma_alloc_qp(rdma
);
2866 error_report("rdma migration: error allocating qp!");
2867 goto err_rdma_dest_wait
;
2870 ret
= qemu_rdma_init_ram_blocks(rdma
);
2872 error_report("rdma migration: error initializing ram blocks!");
2873 goto err_rdma_dest_wait
;
2876 for (idx
= 0; idx
< RDMA_WRID_MAX
; idx
++) {
2877 ret
= qemu_rdma_reg_control(rdma
, idx
);
2879 error_report("rdma: error registering %d control", idx
);
2880 goto err_rdma_dest_wait
;
2884 qemu_set_fd_handler(rdma
->channel
->fd
, NULL
, NULL
, NULL
);
2886 ret
= rdma_accept(rdma
->cm_id
, &conn_param
);
2888 error_report("rdma_accept returns %d", ret
);
2889 goto err_rdma_dest_wait
;
2892 ret
= rdma_get_cm_event(rdma
->channel
, &cm_event
);
2894 error_report("rdma_accept get_cm_event failed %d", ret
);
2895 goto err_rdma_dest_wait
;
2898 if (cm_event
->event
!= RDMA_CM_EVENT_ESTABLISHED
) {
2899 error_report("rdma_accept not event established");
2900 rdma_ack_cm_event(cm_event
);
2901 goto err_rdma_dest_wait
;
2904 rdma_ack_cm_event(cm_event
);
2905 rdma
->connected
= true;
2907 ret
= qemu_rdma_post_recv_control(rdma
, RDMA_WRID_READY
);
2909 error_report("rdma migration: error posting second control recv");
2910 goto err_rdma_dest_wait
;
2913 qemu_rdma_dump_gid("dest_connect", rdma
->cm_id
);
2918 rdma
->error_state
= ret
;
2919 qemu_rdma_cleanup(rdma
);
2923 static int dest_ram_sort_func(const void *a
, const void *b
)
2925 unsigned int a_index
= ((const RDMALocalBlock
*)a
)->src_index
;
2926 unsigned int b_index
= ((const RDMALocalBlock
*)b
)->src_index
;
2928 return (a_index
< b_index
) ? -1 : (a_index
!= b_index
);
2932 * During each iteration of the migration, we listen for instructions
2933 * by the source VM to perform dynamic page registrations before they
2934 * can perform RDMA operations.
2936 * We respond with the 'rkey'.
2938 * Keep doing this until the source tells us to stop.
2940 static int qemu_rdma_registration_handle(QEMUFile
*f
, void *opaque
)
2942 RDMAControlHeader reg_resp
= { .len
= sizeof(RDMARegisterResult
),
2943 .type
= RDMA_CONTROL_REGISTER_RESULT
,
2946 RDMAControlHeader unreg_resp
= { .len
= 0,
2947 .type
= RDMA_CONTROL_UNREGISTER_FINISHED
,
2950 RDMAControlHeader blocks
= { .type
= RDMA_CONTROL_RAM_BLOCKS_RESULT
,
2952 QEMUFileRDMA
*rfile
= opaque
;
2953 RDMAContext
*rdma
= rfile
->rdma
;
2954 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
2955 RDMAControlHeader head
;
2956 RDMARegister
*reg
, *registers
;
2958 RDMARegisterResult
*reg_result
;
2959 static RDMARegisterResult results
[RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE
];
2960 RDMALocalBlock
*block
;
2967 CHECK_ERROR_STATE();
2970 trace_qemu_rdma_registration_handle_wait();
2972 ret
= qemu_rdma_exchange_recv(rdma
, &head
, RDMA_CONTROL_NONE
);
2978 if (head
.repeat
> RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE
) {
2979 error_report("rdma: Too many requests in this message (%d)."
2980 "Bailing.", head
.repeat
);
2985 switch (head
.type
) {
2986 case RDMA_CONTROL_COMPRESS
:
2987 comp
= (RDMACompress
*) rdma
->wr_data
[idx
].control_curr
;
2988 network_to_compress(comp
);
2990 trace_qemu_rdma_registration_handle_compress(comp
->length
,
2993 if (comp
->block_idx
>= rdma
->local_ram_blocks
.nb_blocks
) {
2994 error_report("rdma: 'compress' bad block index %u (vs %d)",
2995 (unsigned int)comp
->block_idx
,
2996 rdma
->local_ram_blocks
.nb_blocks
);
3000 block
= &(rdma
->local_ram_blocks
.block
[comp
->block_idx
]);
3002 host_addr
= block
->local_host_addr
+
3003 (comp
->offset
- block
->offset
);
3005 ram_handle_compressed(host_addr
, comp
->value
, comp
->length
);
3008 case RDMA_CONTROL_REGISTER_FINISHED
:
3009 trace_qemu_rdma_registration_handle_finished();
3012 case RDMA_CONTROL_RAM_BLOCKS_REQUEST
:
3013 trace_qemu_rdma_registration_handle_ram_blocks();
3015 /* Sort our local RAM Block list so it's the same as the source,
3016 * we can do this since we've filled in a src_index in the list
3017 * as we received the RAMBlock list earlier.
3019 qsort(rdma
->local_ram_blocks
.block
,
3020 rdma
->local_ram_blocks
.nb_blocks
,
3021 sizeof(RDMALocalBlock
), dest_ram_sort_func
);
3022 if (rdma
->pin_all
) {
3023 ret
= qemu_rdma_reg_whole_ram_blocks(rdma
);
3025 error_report("rdma migration: error dest "
3026 "registering ram blocks");
3032 * Dest uses this to prepare to transmit the RAMBlock descriptions
3033 * to the source VM after connection setup.
3034 * Both sides use the "remote" structure to communicate and update
3035 * their "local" descriptions with what was sent.
3037 for (i
= 0; i
< local
->nb_blocks
; i
++) {
3038 rdma
->dest_blocks
[i
].remote_host_addr
=
3039 (uintptr_t)(local
->block
[i
].local_host_addr
);
3041 if (rdma
->pin_all
) {
3042 rdma
->dest_blocks
[i
].remote_rkey
= local
->block
[i
].mr
->rkey
;
3045 rdma
->dest_blocks
[i
].offset
= local
->block
[i
].offset
;
3046 rdma
->dest_blocks
[i
].length
= local
->block
[i
].length
;
3048 dest_block_to_network(&rdma
->dest_blocks
[i
]);
3049 trace_qemu_rdma_registration_handle_ram_blocks_loop(
3050 local
->block
[i
].block_name
,
3051 local
->block
[i
].offset
,
3052 local
->block
[i
].length
,
3053 local
->block
[i
].local_host_addr
,
3054 local
->block
[i
].src_index
);
3057 blocks
.len
= rdma
->local_ram_blocks
.nb_blocks
3058 * sizeof(RDMADestBlock
);
3061 ret
= qemu_rdma_post_send_control(rdma
,
3062 (uint8_t *) rdma
->dest_blocks
, &blocks
);
3065 error_report("rdma migration: error sending remote info");
3070 case RDMA_CONTROL_REGISTER_REQUEST
:
3071 trace_qemu_rdma_registration_handle_register(head
.repeat
);
3073 reg_resp
.repeat
= head
.repeat
;
3074 registers
= (RDMARegister
*) rdma
->wr_data
[idx
].control_curr
;
3076 for (count
= 0; count
< head
.repeat
; count
++) {
3078 uint8_t *chunk_start
, *chunk_end
;
3080 reg
= ®isters
[count
];
3081 network_to_register(reg
);
3083 reg_result
= &results
[count
];
3085 trace_qemu_rdma_registration_handle_register_loop(count
,
3086 reg
->current_index
, reg
->key
.current_addr
, reg
->chunks
);
3088 if (reg
->current_index
>= rdma
->local_ram_blocks
.nb_blocks
) {
3089 error_report("rdma: 'register' bad block index %u (vs %d)",
3090 (unsigned int)reg
->current_index
,
3091 rdma
->local_ram_blocks
.nb_blocks
);
3095 block
= &(rdma
->local_ram_blocks
.block
[reg
->current_index
]);
3096 if (block
->is_ram_block
) {
3097 if (block
->offset
> reg
->key
.current_addr
) {
3098 error_report("rdma: bad register address for block %s"
3099 " offset: %" PRIx64
" current_addr: %" PRIx64
,
3100 block
->block_name
, block
->offset
,
3101 reg
->key
.current_addr
);
3105 host_addr
= (block
->local_host_addr
+
3106 (reg
->key
.current_addr
- block
->offset
));
3107 chunk
= ram_chunk_index(block
->local_host_addr
,
3108 (uint8_t *) host_addr
);
3110 chunk
= reg
->key
.chunk
;
3111 host_addr
= block
->local_host_addr
+
3112 (reg
->key
.chunk
* (1UL << RDMA_REG_CHUNK_SHIFT
));
3113 /* Check for particularly bad chunk value */
3114 if (host_addr
< (void *)block
->local_host_addr
) {
3115 error_report("rdma: bad chunk for block %s"
3117 block
->block_name
, reg
->key
.chunk
);
3122 chunk_start
= ram_chunk_start(block
, chunk
);
3123 chunk_end
= ram_chunk_end(block
, chunk
+ reg
->chunks
);
3124 if (qemu_rdma_register_and_get_keys(rdma
, block
,
3125 (uintptr_t)host_addr
, NULL
, ®_result
->rkey
,
3126 chunk
, chunk_start
, chunk_end
)) {
3127 error_report("cannot get rkey");
3132 reg_result
->host_addr
= (uintptr_t)block
->local_host_addr
;
3134 trace_qemu_rdma_registration_handle_register_rkey(
3137 result_to_network(reg_result
);
3140 ret
= qemu_rdma_post_send_control(rdma
,
3141 (uint8_t *) results
, ®_resp
);
3144 error_report("Failed to send control buffer");
3148 case RDMA_CONTROL_UNREGISTER_REQUEST
:
3149 trace_qemu_rdma_registration_handle_unregister(head
.repeat
);
3150 unreg_resp
.repeat
= head
.repeat
;
3151 registers
= (RDMARegister
*) rdma
->wr_data
[idx
].control_curr
;
3153 for (count
= 0; count
< head
.repeat
; count
++) {
3154 reg
= ®isters
[count
];
3155 network_to_register(reg
);
3157 trace_qemu_rdma_registration_handle_unregister_loop(count
,
3158 reg
->current_index
, reg
->key
.chunk
);
3160 block
= &(rdma
->local_ram_blocks
.block
[reg
->current_index
]);
3162 ret
= ibv_dereg_mr(block
->pmr
[reg
->key
.chunk
]);
3163 block
->pmr
[reg
->key
.chunk
] = NULL
;
3166 perror("rdma unregistration chunk failed");
3171 rdma
->total_registrations
--;
3173 trace_qemu_rdma_registration_handle_unregister_success(
3177 ret
= qemu_rdma_post_send_control(rdma
, NULL
, &unreg_resp
);
3180 error_report("Failed to send control buffer");
3184 case RDMA_CONTROL_REGISTER_RESULT
:
3185 error_report("Invalid RESULT message at dest.");
3189 error_report("Unknown control message %s", control_desc
[head
.type
]);
3196 rdma
->error_state
= ret
;
3202 * Called via a ram_control_load_hook during the initial RAM load section which
3203 * lists the RAMBlocks by name. This lets us know the order of the RAMBlocks
3205 * We've already built our local RAMBlock list, but not yet sent the list to
3208 static int rdma_block_notification_handle(QEMUFileRDMA
*rfile
, const char *name
)
3210 RDMAContext
*rdma
= rfile
->rdma
;
3214 /* Find the matching RAMBlock in our local list */
3215 for (curr
= 0; curr
< rdma
->local_ram_blocks
.nb_blocks
; curr
++) {
3216 if (!strcmp(rdma
->local_ram_blocks
.block
[curr
].block_name
, name
)) {
3223 error_report("RAMBlock '%s' not found on destination", name
);
3227 rdma
->local_ram_blocks
.block
[curr
].src_index
= rdma
->next_src_index
;
3228 trace_rdma_block_notification_handle(name
, rdma
->next_src_index
);
3229 rdma
->next_src_index
++;
3234 static int rdma_load_hook(QEMUFile
*f
, void *opaque
, uint64_t flags
, void *data
)
3237 case RAM_CONTROL_BLOCK_REG
:
3238 return rdma_block_notification_handle(opaque
, data
);
3240 case RAM_CONTROL_HOOK
:
3241 return qemu_rdma_registration_handle(f
, opaque
);
3244 /* Shouldn't be called with any other values */
3249 static int qemu_rdma_registration_start(QEMUFile
*f
, void *opaque
,
3250 uint64_t flags
, void *data
)
3252 QEMUFileRDMA
*rfile
= opaque
;
3253 RDMAContext
*rdma
= rfile
->rdma
;
3255 CHECK_ERROR_STATE();
3257 trace_qemu_rdma_registration_start(flags
);
3258 qemu_put_be64(f
, RAM_SAVE_FLAG_HOOK
);
3265 * Inform dest that dynamic registrations are done for now.
3266 * First, flush writes, if any.
3268 static int qemu_rdma_registration_stop(QEMUFile
*f
, void *opaque
,
3269 uint64_t flags
, void *data
)
3271 Error
*local_err
= NULL
, **errp
= &local_err
;
3272 QEMUFileRDMA
*rfile
= opaque
;
3273 RDMAContext
*rdma
= rfile
->rdma
;
3274 RDMAControlHeader head
= { .len
= 0, .repeat
= 1 };
3277 CHECK_ERROR_STATE();
3280 ret
= qemu_rdma_drain_cq(f
, rdma
);
3286 if (flags
== RAM_CONTROL_SETUP
) {
3287 RDMAControlHeader resp
= {.type
= RDMA_CONTROL_RAM_BLOCKS_RESULT
};
3288 RDMALocalBlocks
*local
= &rdma
->local_ram_blocks
;
3289 int reg_result_idx
, i
, nb_dest_blocks
;
3291 head
.type
= RDMA_CONTROL_RAM_BLOCKS_REQUEST
;
3292 trace_qemu_rdma_registration_stop_ram();
3295 * Make sure that we parallelize the pinning on both sides.
3296 * For very large guests, doing this serially takes a really
3297 * long time, so we have to 'interleave' the pinning locally
3298 * with the control messages by performing the pinning on this
3299 * side before we receive the control response from the other
3300 * side that the pinning has completed.
3302 ret
= qemu_rdma_exchange_send(rdma
, &head
, NULL
, &resp
,
3303 ®_result_idx
, rdma
->pin_all
?
3304 qemu_rdma_reg_whole_ram_blocks
: NULL
);
3306 ERROR(errp
, "receiving remote info!");
3310 nb_dest_blocks
= resp
.len
/ sizeof(RDMADestBlock
);
3313 * The protocol uses two different sets of rkeys (mutually exclusive):
3314 * 1. One key to represent the virtual address of the entire ram block.
3315 * (dynamic chunk registration disabled - pin everything with one rkey.)
3316 * 2. One to represent individual chunks within a ram block.
3317 * (dynamic chunk registration enabled - pin individual chunks.)
3319 * Once the capability is successfully negotiated, the destination transmits
3320 * the keys to use (or sends them later) including the virtual addresses
3321 * and then propagates the remote ram block descriptions to his local copy.
3324 if (local
->nb_blocks
!= nb_dest_blocks
) {
3325 ERROR(errp
, "ram blocks mismatch (Number of blocks %d vs %d) "
3326 "Your QEMU command line parameters are probably "
3327 "not identical on both the source and destination.",
3328 local
->nb_blocks
, nb_dest_blocks
);
3329 rdma
->error_state
= -EINVAL
;
3333 qemu_rdma_move_header(rdma
, reg_result_idx
, &resp
);
3334 memcpy(rdma
->dest_blocks
,
3335 rdma
->wr_data
[reg_result_idx
].control_curr
, resp
.len
);
3336 for (i
= 0; i
< nb_dest_blocks
; i
++) {
3337 network_to_dest_block(&rdma
->dest_blocks
[i
]);
3339 /* We require that the blocks are in the same order */
3340 if (rdma
->dest_blocks
[i
].length
!= local
->block
[i
].length
) {
3341 ERROR(errp
, "Block %s/%d has a different length %" PRIu64
3342 "vs %" PRIu64
, local
->block
[i
].block_name
, i
,
3343 local
->block
[i
].length
,
3344 rdma
->dest_blocks
[i
].length
);
3345 rdma
->error_state
= -EINVAL
;
3348 local
->block
[i
].remote_host_addr
=
3349 rdma
->dest_blocks
[i
].remote_host_addr
;
3350 local
->block
[i
].remote_rkey
= rdma
->dest_blocks
[i
].remote_rkey
;
3354 trace_qemu_rdma_registration_stop(flags
);
3356 head
.type
= RDMA_CONTROL_REGISTER_FINISHED
;
3357 ret
= qemu_rdma_exchange_send(rdma
, &head
, NULL
, NULL
, NULL
, NULL
);
3365 rdma
->error_state
= ret
;
3369 static int qemu_rdma_get_fd(void *opaque
)
3371 QEMUFileRDMA
*rfile
= opaque
;
3372 RDMAContext
*rdma
= rfile
->rdma
;
3374 return rdma
->comp_channel
->fd
;
3377 static const QEMUFileOps rdma_read_ops
= {
3378 .get_buffer
= qemu_rdma_get_buffer
,
3379 .get_fd
= qemu_rdma_get_fd
,
3380 .close
= qemu_rdma_close
,
3381 .hook_ram_load
= rdma_load_hook
,
3384 static const QEMUFileOps rdma_write_ops
= {
3385 .put_buffer
= qemu_rdma_put_buffer
,
3386 .close
= qemu_rdma_close
,
3387 .before_ram_iterate
= qemu_rdma_registration_start
,
3388 .after_ram_iterate
= qemu_rdma_registration_stop
,
3389 .save_page
= qemu_rdma_save_page
,
3392 static void *qemu_fopen_rdma(RDMAContext
*rdma
, const char *mode
)
3396 if (qemu_file_mode_is_not_valid(mode
)) {
3400 r
= g_new0(QEMUFileRDMA
, 1);
3403 if (mode
[0] == 'w') {
3404 r
->file
= qemu_fopen_ops(r
, &rdma_write_ops
);
3406 r
->file
= qemu_fopen_ops(r
, &rdma_read_ops
);
3412 static void rdma_accept_incoming_migration(void *opaque
)
3414 RDMAContext
*rdma
= opaque
;
3417 Error
*local_err
= NULL
, **errp
= &local_err
;
3419 trace_qemu_rdma_accept_incoming_migration();
3420 ret
= qemu_rdma_accept(rdma
);
3423 ERROR(errp
, "RDMA Migration initialization failed!");
3427 trace_qemu_rdma_accept_incoming_migration_accepted();
3429 f
= qemu_fopen_rdma(rdma
, "rb");
3431 ERROR(errp
, "could not qemu_fopen_rdma!");
3432 qemu_rdma_cleanup(rdma
);
3436 rdma
->migration_started_on_destination
= 1;
3437 process_incoming_migration(f
);
3440 void rdma_start_incoming_migration(const char *host_port
, Error
**errp
)
3444 Error
*local_err
= NULL
;
3446 trace_rdma_start_incoming_migration();
3447 rdma
= qemu_rdma_data_init(host_port
, &local_err
);
3453 ret
= qemu_rdma_dest_init(rdma
, &local_err
);
3459 trace_rdma_start_incoming_migration_after_dest_init();
3461 ret
= rdma_listen(rdma
->listen_id
, 5);
3464 ERROR(errp
, "listening on socket!");
3468 trace_rdma_start_incoming_migration_after_rdma_listen();
3470 qemu_set_fd_handler(rdma
->channel
->fd
, rdma_accept_incoming_migration
,
3471 NULL
, (void *)(intptr_t)rdma
);
3474 error_propagate(errp
, local_err
);
3478 void rdma_start_outgoing_migration(void *opaque
,
3479 const char *host_port
, Error
**errp
)
3481 MigrationState
*s
= opaque
;
3482 Error
*local_err
= NULL
, **temp
= &local_err
;
3483 RDMAContext
*rdma
= qemu_rdma_data_init(host_port
, &local_err
);
3487 ERROR(temp
, "Failed to initialize RDMA data structures! %d", ret
);
3491 ret
= qemu_rdma_source_init(rdma
, &local_err
,
3492 s
->enabled_capabilities
[MIGRATION_CAPABILITY_RDMA_PIN_ALL
]);
3498 trace_rdma_start_outgoing_migration_after_rdma_source_init();
3499 ret
= qemu_rdma_connect(rdma
, &local_err
);
3505 trace_rdma_start_outgoing_migration_after_rdma_connect();
3507 s
->file
= qemu_fopen_rdma(rdma
, "wb");
3508 migrate_fd_connect(s
);
3511 error_propagate(errp
, local_err
);
3513 migrate_fd_error(s
);