1 /* 2 * RDMA protocol and interfaces 3 * 4 * Copyright IBM, Corp. 2010-2013 5 * 6 * Authors: 7 * Michael R. Hines <mrhines@us.ibm.com> 8 * Jiuxing Liu <jl@us.ibm.com> 9 * 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. 12 * 13 */ 14 #include "qemu-common.h" 15 #include "migration/migration.h" 16 #include "migration/qemu-file.h" 17 #include "exec/cpu-common.h" 18 #include "qemu/main-loop.h" 19 #include "qemu/sockets.h" 20 #include "qemu/bitmap.h" 21 #include "block/coroutine.h" 22 #include <stdio.h> 23 #include <sys/types.h> 24 #include <sys/socket.h> 25 #include <netdb.h> 26 #include <arpa/inet.h> 27 #include <string.h> 28 #include <rdma/rdma_cma.h> 29 #include "trace.h" 30 31 /* 32 * Print and error on both the Monitor and the Log file. 33 */ 34 #define ERROR(errp, fmt, ...) \ 35 do { \ 36 fprintf(stderr, "RDMA ERROR: " fmt "\n", ## __VA_ARGS__); \ 37 if (errp && (*(errp) == NULL)) { \ 38 error_setg(errp, "RDMA ERROR: " fmt, ## __VA_ARGS__); \ 39 } \ 40 } while (0) 41 42 #define RDMA_RESOLVE_TIMEOUT_MS 10000 43 44 /* Do not merge data if larger than this. */ 45 #define RDMA_MERGE_MAX (2 * 1024 * 1024) 46 #define RDMA_SIGNALED_SEND_MAX (RDMA_MERGE_MAX / 4096) 47 48 #define RDMA_REG_CHUNK_SHIFT 20 /* 1 MB */ 49 50 /* 51 * This is only for non-live state being migrated. 52 * Instead of RDMA_WRITE messages, we use RDMA_SEND 53 * messages for that state, which requires a different 54 * delivery design than main memory. 55 */ 56 #define RDMA_SEND_INCREMENT 32768 57 58 /* 59 * Maximum size infiniband SEND message 60 */ 61 #define RDMA_CONTROL_MAX_BUFFER (512 * 1024) 62 #define RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE 4096 63 64 #define RDMA_CONTROL_VERSION_CURRENT 1 65 /* 66 * Capabilities for negotiation. 67 */ 68 #define RDMA_CAPABILITY_PIN_ALL 0x01 69 70 /* 71 * Add the other flags above to this list of known capabilities 72 * as they are introduced. 73 */ 74 static uint32_t known_capabilities = RDMA_CAPABILITY_PIN_ALL; 75 76 #define CHECK_ERROR_STATE() \ 77 do { \ 78 if (rdma->error_state) { \ 79 if (!rdma->error_reported) { \ 80 error_report("RDMA is in an error state waiting migration" \ 81 " to abort!"); \ 82 rdma->error_reported = 1; \ 83 } \ 84 return rdma->error_state; \ 85 } \ 86 } while (0); 87 88 /* 89 * A work request ID is 64-bits and we split up these bits 90 * into 3 parts: 91 * 92 * bits 0-15 : type of control message, 2^16 93 * bits 16-29: ram block index, 2^14 94 * bits 30-63: ram block chunk number, 2^34 95 * 96 * The last two bit ranges are only used for RDMA writes, 97 * in order to track their completion and potentially 98 * also track unregistration status of the message. 99 */ 100 #define RDMA_WRID_TYPE_SHIFT 0UL 101 #define RDMA_WRID_BLOCK_SHIFT 16UL 102 #define RDMA_WRID_CHUNK_SHIFT 30UL 103 104 #define RDMA_WRID_TYPE_MASK \ 105 ((1UL << RDMA_WRID_BLOCK_SHIFT) - 1UL) 106 107 #define RDMA_WRID_BLOCK_MASK \ 108 (~RDMA_WRID_TYPE_MASK & ((1UL << RDMA_WRID_CHUNK_SHIFT) - 1UL)) 109 110 #define RDMA_WRID_CHUNK_MASK (~RDMA_WRID_BLOCK_MASK & ~RDMA_WRID_TYPE_MASK) 111 112 /* 113 * RDMA migration protocol: 114 * 1. RDMA Writes (data messages, i.e. RAM) 115 * 2. IB Send/Recv (control channel messages) 116 */ 117 enum { 118 RDMA_WRID_NONE = 0, 119 RDMA_WRID_RDMA_WRITE = 1, 120 RDMA_WRID_SEND_CONTROL = 2000, 121 RDMA_WRID_RECV_CONTROL = 4000, 122 }; 123 124 static const char *wrid_desc[] = { 125 [RDMA_WRID_NONE] = "NONE", 126 [RDMA_WRID_RDMA_WRITE] = "WRITE RDMA", 127 [RDMA_WRID_SEND_CONTROL] = "CONTROL SEND", 128 [RDMA_WRID_RECV_CONTROL] = "CONTROL RECV", 129 }; 130 131 /* 132 * Work request IDs for IB SEND messages only (not RDMA writes). 133 * This is used by the migration protocol to transmit 134 * control messages (such as device state and registration commands) 135 * 136 * We could use more WRs, but we have enough for now. 137 */ 138 enum { 139 RDMA_WRID_READY = 0, 140 RDMA_WRID_DATA, 141 RDMA_WRID_CONTROL, 142 RDMA_WRID_MAX, 143 }; 144 145 /* 146 * SEND/RECV IB Control Messages. 147 */ 148 enum { 149 RDMA_CONTROL_NONE = 0, 150 RDMA_CONTROL_ERROR, 151 RDMA_CONTROL_READY, /* ready to receive */ 152 RDMA_CONTROL_QEMU_FILE, /* QEMUFile-transmitted bytes */ 153 RDMA_CONTROL_RAM_BLOCKS_REQUEST, /* RAMBlock synchronization */ 154 RDMA_CONTROL_RAM_BLOCKS_RESULT, /* RAMBlock synchronization */ 155 RDMA_CONTROL_COMPRESS, /* page contains repeat values */ 156 RDMA_CONTROL_REGISTER_REQUEST, /* dynamic page registration */ 157 RDMA_CONTROL_REGISTER_RESULT, /* key to use after registration */ 158 RDMA_CONTROL_REGISTER_FINISHED, /* current iteration finished */ 159 RDMA_CONTROL_UNREGISTER_REQUEST, /* dynamic UN-registration */ 160 RDMA_CONTROL_UNREGISTER_FINISHED, /* unpinning finished */ 161 }; 162 163 static const char *control_desc[] = { 164 [RDMA_CONTROL_NONE] = "NONE", 165 [RDMA_CONTROL_ERROR] = "ERROR", 166 [RDMA_CONTROL_READY] = "READY", 167 [RDMA_CONTROL_QEMU_FILE] = "QEMU FILE", 168 [RDMA_CONTROL_RAM_BLOCKS_REQUEST] = "RAM BLOCKS REQUEST", 169 [RDMA_CONTROL_RAM_BLOCKS_RESULT] = "RAM BLOCKS RESULT", 170 [RDMA_CONTROL_COMPRESS] = "COMPRESS", 171 [RDMA_CONTROL_REGISTER_REQUEST] = "REGISTER REQUEST", 172 [RDMA_CONTROL_REGISTER_RESULT] = "REGISTER RESULT", 173 [RDMA_CONTROL_REGISTER_FINISHED] = "REGISTER FINISHED", 174 [RDMA_CONTROL_UNREGISTER_REQUEST] = "UNREGISTER REQUEST", 175 [RDMA_CONTROL_UNREGISTER_FINISHED] = "UNREGISTER FINISHED", 176 }; 177 178 /* 179 * Memory and MR structures used to represent an IB Send/Recv work request. 180 * This is *not* used for RDMA writes, only IB Send/Recv. 181 */ 182 typedef struct { 183 uint8_t control[RDMA_CONTROL_MAX_BUFFER]; /* actual buffer to register */ 184 struct ibv_mr *control_mr; /* registration metadata */ 185 size_t control_len; /* length of the message */ 186 uint8_t *control_curr; /* start of unconsumed bytes */ 187 } RDMAWorkRequestData; 188 189 /* 190 * Negotiate RDMA capabilities during connection-setup time. 191 */ 192 typedef struct { 193 uint32_t version; 194 uint32_t flags; 195 } RDMACapabilities; 196 197 static void caps_to_network(RDMACapabilities *cap) 198 { 199 cap->version = htonl(cap->version); 200 cap->flags = htonl(cap->flags); 201 } 202 203 static void network_to_caps(RDMACapabilities *cap) 204 { 205 cap->version = ntohl(cap->version); 206 cap->flags = ntohl(cap->flags); 207 } 208 209 /* 210 * Representation of a RAMBlock from an RDMA perspective. 211 * This is not transmitted, only local. 212 * This and subsequent structures cannot be linked lists 213 * because we're using a single IB message to transmit 214 * the information. It's small anyway, so a list is overkill. 215 */ 216 typedef struct RDMALocalBlock { 217 uint8_t *local_host_addr; /* local virtual address */ 218 uint64_t remote_host_addr; /* remote virtual address */ 219 uint64_t offset; 220 uint64_t length; 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 bool is_ram_block; 227 int nb_chunks; 228 unsigned long *transit_bitmap; 229 unsigned long *unregister_bitmap; 230 } RDMALocalBlock; 231 232 /* 233 * Also represents a RAMblock, but only on the dest. 234 * This gets transmitted by the dest during connection-time 235 * to the source VM and then is used to populate the 236 * corresponding RDMALocalBlock with 237 * the information needed to perform the actual RDMA. 238 */ 239 typedef struct QEMU_PACKED RDMARemoteBlock { 240 uint64_t remote_host_addr; 241 uint64_t offset; 242 uint64_t length; 243 uint32_t remote_rkey; 244 uint32_t padding; 245 } RDMARemoteBlock; 246 247 static uint64_t htonll(uint64_t v) 248 { 249 union { uint32_t lv[2]; uint64_t llv; } u; 250 u.lv[0] = htonl(v >> 32); 251 u.lv[1] = htonl(v & 0xFFFFFFFFULL); 252 return u.llv; 253 } 254 255 static uint64_t ntohll(uint64_t v) { 256 union { uint32_t lv[2]; uint64_t llv; } u; 257 u.llv = v; 258 return ((uint64_t)ntohl(u.lv[0]) << 32) | (uint64_t) ntohl(u.lv[1]); 259 } 260 261 static void remote_block_to_network(RDMARemoteBlock *rb) 262 { 263 rb->remote_host_addr = htonll(rb->remote_host_addr); 264 rb->offset = htonll(rb->offset); 265 rb->length = htonll(rb->length); 266 rb->remote_rkey = htonl(rb->remote_rkey); 267 } 268 269 static void network_to_remote_block(RDMARemoteBlock *rb) 270 { 271 rb->remote_host_addr = ntohll(rb->remote_host_addr); 272 rb->offset = ntohll(rb->offset); 273 rb->length = ntohll(rb->length); 274 rb->remote_rkey = ntohl(rb->remote_rkey); 275 } 276 277 /* 278 * Virtual address of the above structures used for transmitting 279 * the RAMBlock descriptions at connection-time. 280 * This structure is *not* transmitted. 281 */ 282 typedef struct RDMALocalBlocks { 283 int nb_blocks; 284 bool init; /* main memory init complete */ 285 RDMALocalBlock *block; 286 } RDMALocalBlocks; 287 288 /* 289 * Main data structure for RDMA state. 290 * While there is only one copy of this structure being allocated right now, 291 * this is the place where one would start if you wanted to consider 292 * having more than one RDMA connection open at the same time. 293 */ 294 typedef struct RDMAContext { 295 char *host; 296 int port; 297 298 RDMAWorkRequestData wr_data[RDMA_WRID_MAX]; 299 300 /* 301 * This is used by *_exchange_send() to figure out whether or not 302 * the initial "READY" message has already been received or not. 303 * This is because other functions may potentially poll() and detect 304 * the READY message before send() does, in which case we need to 305 * know if it completed. 306 */ 307 int control_ready_expected; 308 309 /* number of outstanding writes */ 310 int nb_sent; 311 312 /* store info about current buffer so that we can 313 merge it with future sends */ 314 uint64_t current_addr; 315 uint64_t current_length; 316 /* index of ram block the current buffer belongs to */ 317 int current_index; 318 /* index of the chunk in the current ram block */ 319 int current_chunk; 320 321 bool pin_all; 322 323 /* 324 * infiniband-specific variables for opening the device 325 * and maintaining connection state and so forth. 326 * 327 * cm_id also has ibv_context, rdma_event_channel, and ibv_qp in 328 * cm_id->verbs, cm_id->channel, and cm_id->qp. 329 */ 330 struct rdma_cm_id *cm_id; /* connection manager ID */ 331 struct rdma_cm_id *listen_id; 332 bool connected; 333 334 struct ibv_context *verbs; 335 struct rdma_event_channel *channel; 336 struct ibv_qp *qp; /* queue pair */ 337 struct ibv_comp_channel *comp_channel; /* completion channel */ 338 struct ibv_pd *pd; /* protection domain */ 339 struct ibv_cq *cq; /* completion queue */ 340 341 /* 342 * If a previous write failed (perhaps because of a failed 343 * memory registration, then do not attempt any future work 344 * and remember the error state. 345 */ 346 int error_state; 347 int error_reported; 348 349 /* 350 * Description of ram blocks used throughout the code. 351 */ 352 RDMALocalBlocks local_ram_blocks; 353 RDMARemoteBlock *block; 354 355 /* 356 * Migration on *destination* started. 357 * Then use coroutine yield function. 358 * Source runs in a thread, so we don't care. 359 */ 360 int migration_started_on_destination; 361 362 int total_registrations; 363 int total_writes; 364 365 int unregister_current, unregister_next; 366 uint64_t unregistrations[RDMA_SIGNALED_SEND_MAX]; 367 368 GHashTable *blockmap; 369 } RDMAContext; 370 371 /* 372 * Interface to the rest of the migration call stack. 373 */ 374 typedef struct QEMUFileRDMA { 375 RDMAContext *rdma; 376 size_t len; 377 void *file; 378 } QEMUFileRDMA; 379 380 /* 381 * Main structure for IB Send/Recv control messages. 382 * This gets prepended at the beginning of every Send/Recv. 383 */ 384 typedef struct QEMU_PACKED { 385 uint32_t len; /* Total length of data portion */ 386 uint32_t type; /* which control command to perform */ 387 uint32_t repeat; /* number of commands in data portion of same type */ 388 uint32_t padding; 389 } RDMAControlHeader; 390 391 static void control_to_network(RDMAControlHeader *control) 392 { 393 control->type = htonl(control->type); 394 control->len = htonl(control->len); 395 control->repeat = htonl(control->repeat); 396 } 397 398 static void network_to_control(RDMAControlHeader *control) 399 { 400 control->type = ntohl(control->type); 401 control->len = ntohl(control->len); 402 control->repeat = ntohl(control->repeat); 403 } 404 405 /* 406 * Register a single Chunk. 407 * Information sent by the source VM to inform the dest 408 * to register an single chunk of memory before we can perform 409 * the actual RDMA operation. 410 */ 411 typedef struct QEMU_PACKED { 412 union QEMU_PACKED { 413 uint64_t current_addr; /* offset into the ramblock of the chunk */ 414 uint64_t chunk; /* chunk to lookup if unregistering */ 415 } key; 416 uint32_t current_index; /* which ramblock the chunk belongs to */ 417 uint32_t padding; 418 uint64_t chunks; /* how many sequential chunks to register */ 419 } RDMARegister; 420 421 static void register_to_network(RDMARegister *reg) 422 { 423 reg->key.current_addr = htonll(reg->key.current_addr); 424 reg->current_index = htonl(reg->current_index); 425 reg->chunks = htonll(reg->chunks); 426 } 427 428 static void network_to_register(RDMARegister *reg) 429 { 430 reg->key.current_addr = ntohll(reg->key.current_addr); 431 reg->current_index = ntohl(reg->current_index); 432 reg->chunks = ntohll(reg->chunks); 433 } 434 435 typedef struct QEMU_PACKED { 436 uint32_t value; /* if zero, we will madvise() */ 437 uint32_t block_idx; /* which ram block index */ 438 uint64_t offset; /* where in the remote ramblock this chunk */ 439 uint64_t length; /* length of the chunk */ 440 } RDMACompress; 441 442 static void compress_to_network(RDMACompress *comp) 443 { 444 comp->value = htonl(comp->value); 445 comp->block_idx = htonl(comp->block_idx); 446 comp->offset = htonll(comp->offset); 447 comp->length = htonll(comp->length); 448 } 449 450 static void network_to_compress(RDMACompress *comp) 451 { 452 comp->value = ntohl(comp->value); 453 comp->block_idx = ntohl(comp->block_idx); 454 comp->offset = ntohll(comp->offset); 455 comp->length = ntohll(comp->length); 456 } 457 458 /* 459 * The result of the dest's memory registration produces an "rkey" 460 * which the source VM must reference in order to perform 461 * the RDMA operation. 462 */ 463 typedef struct QEMU_PACKED { 464 uint32_t rkey; 465 uint32_t padding; 466 uint64_t host_addr; 467 } RDMARegisterResult; 468 469 static void result_to_network(RDMARegisterResult *result) 470 { 471 result->rkey = htonl(result->rkey); 472 result->host_addr = htonll(result->host_addr); 473 }; 474 475 static void network_to_result(RDMARegisterResult *result) 476 { 477 result->rkey = ntohl(result->rkey); 478 result->host_addr = ntohll(result->host_addr); 479 }; 480 481 const char *print_wrid(int wrid); 482 static int qemu_rdma_exchange_send(RDMAContext *rdma, RDMAControlHeader *head, 483 uint8_t *data, RDMAControlHeader *resp, 484 int *resp_idx, 485 int (*callback)(RDMAContext *rdma)); 486 487 static inline uint64_t ram_chunk_index(const uint8_t *start, 488 const uint8_t *host) 489 { 490 return ((uintptr_t) host - (uintptr_t) start) >> RDMA_REG_CHUNK_SHIFT; 491 } 492 493 static inline uint8_t *ram_chunk_start(const RDMALocalBlock *rdma_ram_block, 494 uint64_t i) 495 { 496 return (uint8_t *)(uintptr_t)(rdma_ram_block->local_host_addr + 497 (i << RDMA_REG_CHUNK_SHIFT)); 498 } 499 500 static inline uint8_t *ram_chunk_end(const RDMALocalBlock *rdma_ram_block, 501 uint64_t i) 502 { 503 uint8_t *result = ram_chunk_start(rdma_ram_block, i) + 504 (1UL << RDMA_REG_CHUNK_SHIFT); 505 506 if (result > (rdma_ram_block->local_host_addr + rdma_ram_block->length)) { 507 result = rdma_ram_block->local_host_addr + rdma_ram_block->length; 508 } 509 510 return result; 511 } 512 513 static int rdma_add_block(RDMAContext *rdma, void *host_addr, 514 ram_addr_t block_offset, uint64_t length) 515 { 516 RDMALocalBlocks *local = &rdma->local_ram_blocks; 517 RDMALocalBlock *block = g_hash_table_lookup(rdma->blockmap, 518 (void *)(uintptr_t)block_offset); 519 RDMALocalBlock *old = local->block; 520 521 assert(block == NULL); 522 523 local->block = g_malloc0(sizeof(RDMALocalBlock) * (local->nb_blocks + 1)); 524 525 if (local->nb_blocks) { 526 int x; 527 528 for (x = 0; x < local->nb_blocks; x++) { 529 g_hash_table_remove(rdma->blockmap, 530 (void *)(uintptr_t)old[x].offset); 531 g_hash_table_insert(rdma->blockmap, 532 (void *)(uintptr_t)old[x].offset, 533 &local->block[x]); 534 } 535 memcpy(local->block, old, sizeof(RDMALocalBlock) * local->nb_blocks); 536 g_free(old); 537 } 538 539 block = &local->block[local->nb_blocks]; 540 541 block->local_host_addr = host_addr; 542 block->offset = block_offset; 543 block->length = length; 544 block->index = local->nb_blocks; 545 block->nb_chunks = ram_chunk_index(host_addr, host_addr + length) + 1UL; 546 block->transit_bitmap = bitmap_new(block->nb_chunks); 547 bitmap_clear(block->transit_bitmap, 0, block->nb_chunks); 548 block->unregister_bitmap = bitmap_new(block->nb_chunks); 549 bitmap_clear(block->unregister_bitmap, 0, block->nb_chunks); 550 block->remote_keys = g_malloc0(block->nb_chunks * sizeof(uint32_t)); 551 552 block->is_ram_block = local->init ? false : true; 553 554 g_hash_table_insert(rdma->blockmap, (void *) block_offset, block); 555 556 trace_rdma_add_block(local->nb_blocks, (uintptr_t) block->local_host_addr, 557 block->offset, block->length, 558 (uintptr_t) (block->local_host_addr + block->length), 559 BITS_TO_LONGS(block->nb_chunks) * 560 sizeof(unsigned long) * 8, 561 block->nb_chunks); 562 563 local->nb_blocks++; 564 565 return 0; 566 } 567 568 /* 569 * Memory regions need to be registered with the device and queue pairs setup 570 * in advanced before the migration starts. This tells us where the RAM blocks 571 * are so that we can register them individually. 572 */ 573 static void qemu_rdma_init_one_block(void *host_addr, 574 ram_addr_t block_offset, ram_addr_t length, void *opaque) 575 { 576 rdma_add_block(opaque, host_addr, block_offset, length); 577 } 578 579 /* 580 * Identify the RAMBlocks and their quantity. They will be references to 581 * identify chunk boundaries inside each RAMBlock and also be referenced 582 * during dynamic page registration. 583 */ 584 static int qemu_rdma_init_ram_blocks(RDMAContext *rdma) 585 { 586 RDMALocalBlocks *local = &rdma->local_ram_blocks; 587 588 assert(rdma->blockmap == NULL); 589 rdma->blockmap = g_hash_table_new(g_direct_hash, g_direct_equal); 590 memset(local, 0, sizeof *local); 591 qemu_ram_foreach_block(qemu_rdma_init_one_block, rdma); 592 trace_qemu_rdma_init_ram_blocks(local->nb_blocks); 593 rdma->block = (RDMARemoteBlock *) g_malloc0(sizeof(RDMARemoteBlock) * 594 rdma->local_ram_blocks.nb_blocks); 595 local->init = true; 596 return 0; 597 } 598 599 static int rdma_delete_block(RDMAContext *rdma, ram_addr_t block_offset) 600 { 601 RDMALocalBlocks *local = &rdma->local_ram_blocks; 602 RDMALocalBlock *block = g_hash_table_lookup(rdma->blockmap, 603 (void *) block_offset); 604 RDMALocalBlock *old = local->block; 605 int x; 606 607 assert(block); 608 609 if (block->pmr) { 610 int j; 611 612 for (j = 0; j < block->nb_chunks; j++) { 613 if (!block->pmr[j]) { 614 continue; 615 } 616 ibv_dereg_mr(block->pmr[j]); 617 rdma->total_registrations--; 618 } 619 g_free(block->pmr); 620 block->pmr = NULL; 621 } 622 623 if (block->mr) { 624 ibv_dereg_mr(block->mr); 625 rdma->total_registrations--; 626 block->mr = NULL; 627 } 628 629 g_free(block->transit_bitmap); 630 block->transit_bitmap = NULL; 631 632 g_free(block->unregister_bitmap); 633 block->unregister_bitmap = NULL; 634 635 g_free(block->remote_keys); 636 block->remote_keys = NULL; 637 638 for (x = 0; x < local->nb_blocks; x++) { 639 g_hash_table_remove(rdma->blockmap, (void *)(uintptr_t)old[x].offset); 640 } 641 642 if (local->nb_blocks > 1) { 643 644 local->block = g_malloc0(sizeof(RDMALocalBlock) * 645 (local->nb_blocks - 1)); 646 647 if (block->index) { 648 memcpy(local->block, old, sizeof(RDMALocalBlock) * block->index); 649 } 650 651 if (block->index < (local->nb_blocks - 1)) { 652 memcpy(local->block + block->index, old + (block->index + 1), 653 sizeof(RDMALocalBlock) * 654 (local->nb_blocks - (block->index + 1))); 655 } 656 } else { 657 assert(block == local->block); 658 local->block = NULL; 659 } 660 661 trace_rdma_delete_block(local->nb_blocks, 662 (uintptr_t)block->local_host_addr, 663 block->offset, block->length, 664 (uintptr_t)(block->local_host_addr + block->length), 665 BITS_TO_LONGS(block->nb_chunks) * 666 sizeof(unsigned long) * 8, block->nb_chunks); 667 668 g_free(old); 669 670 local->nb_blocks--; 671 672 if (local->nb_blocks) { 673 for (x = 0; x < local->nb_blocks; x++) { 674 g_hash_table_insert(rdma->blockmap, 675 (void *)(uintptr_t)local->block[x].offset, 676 &local->block[x]); 677 } 678 } 679 680 return 0; 681 } 682 683 /* 684 * Put in the log file which RDMA device was opened and the details 685 * associated with that device. 686 */ 687 static void qemu_rdma_dump_id(const char *who, struct ibv_context *verbs) 688 { 689 struct ibv_port_attr port; 690 691 if (ibv_query_port(verbs, 1, &port)) { 692 error_report("Failed to query port information"); 693 return; 694 } 695 696 printf("%s RDMA Device opened: kernel name %s " 697 "uverbs device name %s, " 698 "infiniband_verbs class device path %s, " 699 "infiniband class device path %s, " 700 "transport: (%d) %s\n", 701 who, 702 verbs->device->name, 703 verbs->device->dev_name, 704 verbs->device->dev_path, 705 verbs->device->ibdev_path, 706 port.link_layer, 707 (port.link_layer == IBV_LINK_LAYER_INFINIBAND) ? "Infiniband" : 708 ((port.link_layer == IBV_LINK_LAYER_ETHERNET) 709 ? "Ethernet" : "Unknown")); 710 } 711 712 /* 713 * Put in the log file the RDMA gid addressing information, 714 * useful for folks who have trouble understanding the 715 * RDMA device hierarchy in the kernel. 716 */ 717 static void qemu_rdma_dump_gid(const char *who, struct rdma_cm_id *id) 718 { 719 char sgid[33]; 720 char dgid[33]; 721 inet_ntop(AF_INET6, &id->route.addr.addr.ibaddr.sgid, sgid, sizeof sgid); 722 inet_ntop(AF_INET6, &id->route.addr.addr.ibaddr.dgid, dgid, sizeof dgid); 723 trace_qemu_rdma_dump_gid(who, sgid, dgid); 724 } 725 726 /* 727 * As of now, IPv6 over RoCE / iWARP is not supported by linux. 728 * We will try the next addrinfo struct, and fail if there are 729 * no other valid addresses to bind against. 730 * 731 * If user is listening on '[::]', then we will not have a opened a device 732 * yet and have no way of verifying if the device is RoCE or not. 733 * 734 * In this case, the source VM will throw an error for ALL types of 735 * connections (both IPv4 and IPv6) if the destination machine does not have 736 * a regular infiniband network available for use. 737 * 738 * The only way to guarantee that an error is thrown for broken kernels is 739 * for the management software to choose a *specific* interface at bind time 740 * and validate what time of hardware it is. 741 * 742 * Unfortunately, this puts the user in a fix: 743 * 744 * If the source VM connects with an IPv4 address without knowing that the 745 * destination has bound to '[::]' the migration will unconditionally fail 746 * unless the management software is explicitly listening on the the IPv4 747 * address while using a RoCE-based device. 748 * 749 * If the source VM connects with an IPv6 address, then we're OK because we can 750 * throw an error on the source (and similarly on the destination). 751 * 752 * But in mixed environments, this will be broken for a while until it is fixed 753 * inside linux. 754 * 755 * We do provide a *tiny* bit of help in this function: We can list all of the 756 * devices in the system and check to see if all the devices are RoCE or 757 * Infiniband. 758 * 759 * If we detect that we have a *pure* RoCE environment, then we can safely 760 * thrown an error even if the management software has specified '[::]' as the 761 * bind address. 762 * 763 * However, if there is are multiple hetergeneous devices, then we cannot make 764 * this assumption and the user just has to be sure they know what they are 765 * doing. 766 * 767 * Patches are being reviewed on linux-rdma. 768 */ 769 static int qemu_rdma_broken_ipv6_kernel(Error **errp, struct ibv_context *verbs) 770 { 771 struct ibv_port_attr port_attr; 772 773 /* This bug only exists in linux, to our knowledge. */ 774 #ifdef CONFIG_LINUX 775 776 /* 777 * Verbs are only NULL if management has bound to '[::]'. 778 * 779 * Let's iterate through all the devices and see if there any pure IB 780 * devices (non-ethernet). 781 * 782 * If not, then we can safely proceed with the migration. 783 * Otherwise, there are no guarantees until the bug is fixed in linux. 784 */ 785 if (!verbs) { 786 int num_devices, x; 787 struct ibv_device ** dev_list = ibv_get_device_list(&num_devices); 788 bool roce_found = false; 789 bool ib_found = false; 790 791 for (x = 0; x < num_devices; x++) { 792 verbs = ibv_open_device(dev_list[x]); 793 794 if (ibv_query_port(verbs, 1, &port_attr)) { 795 ibv_close_device(verbs); 796 ERROR(errp, "Could not query initial IB port"); 797 return -EINVAL; 798 } 799 800 if (port_attr.link_layer == IBV_LINK_LAYER_INFINIBAND) { 801 ib_found = true; 802 } else if (port_attr.link_layer == IBV_LINK_LAYER_ETHERNET) { 803 roce_found = true; 804 } 805 806 ibv_close_device(verbs); 807 808 } 809 810 if (roce_found) { 811 if (ib_found) { 812 fprintf(stderr, "WARN: migrations may fail:" 813 " IPv6 over RoCE / iWARP in linux" 814 " is broken. But since you appear to have a" 815 " mixed RoCE / IB environment, be sure to only" 816 " migrate over the IB fabric until the kernel " 817 " fixes the bug.\n"); 818 } else { 819 ERROR(errp, "You only have RoCE / iWARP devices in your systems" 820 " and your management software has specified '[::]'" 821 ", but IPv6 over RoCE / iWARP is not supported in Linux."); 822 return -ENONET; 823 } 824 } 825 826 return 0; 827 } 828 829 /* 830 * If we have a verbs context, that means that some other than '[::]' was 831 * used by the management software for binding. In which case we can 832 * actually warn the user about a potentially broken kernel. 833 */ 834 835 /* IB ports start with 1, not 0 */ 836 if (ibv_query_port(verbs, 1, &port_attr)) { 837 ERROR(errp, "Could not query initial IB port"); 838 return -EINVAL; 839 } 840 841 if (port_attr.link_layer == IBV_LINK_LAYER_ETHERNET) { 842 ERROR(errp, "Linux kernel's RoCE / iWARP does not support IPv6 " 843 "(but patches on linux-rdma in progress)"); 844 return -ENONET; 845 } 846 847 #endif 848 849 return 0; 850 } 851 852 /* 853 * Figure out which RDMA device corresponds to the requested IP hostname 854 * Also create the initial connection manager identifiers for opening 855 * the connection. 856 */ 857 static int qemu_rdma_resolve_host(RDMAContext *rdma, Error **errp) 858 { 859 int ret; 860 struct rdma_addrinfo *res; 861 char port_str[16]; 862 struct rdma_cm_event *cm_event; 863 char ip[40] = "unknown"; 864 struct rdma_addrinfo *e; 865 866 if (rdma->host == NULL || !strcmp(rdma->host, "")) { 867 ERROR(errp, "RDMA hostname has not been set"); 868 return -EINVAL; 869 } 870 871 /* create CM channel */ 872 rdma->channel = rdma_create_event_channel(); 873 if (!rdma->channel) { 874 ERROR(errp, "could not create CM channel"); 875 return -EINVAL; 876 } 877 878 /* create CM id */ 879 ret = rdma_create_id(rdma->channel, &rdma->cm_id, NULL, RDMA_PS_TCP); 880 if (ret) { 881 ERROR(errp, "could not create channel id"); 882 goto err_resolve_create_id; 883 } 884 885 snprintf(port_str, 16, "%d", rdma->port); 886 port_str[15] = '\0'; 887 888 ret = rdma_getaddrinfo(rdma->host, port_str, NULL, &res); 889 if (ret < 0) { 890 ERROR(errp, "could not rdma_getaddrinfo address %s", rdma->host); 891 goto err_resolve_get_addr; 892 } 893 894 for (e = res; e != NULL; e = e->ai_next) { 895 inet_ntop(e->ai_family, 896 &((struct sockaddr_in *) e->ai_dst_addr)->sin_addr, ip, sizeof ip); 897 trace_qemu_rdma_resolve_host_trying(rdma->host, ip); 898 899 ret = rdma_resolve_addr(rdma->cm_id, NULL, e->ai_dst_addr, 900 RDMA_RESOLVE_TIMEOUT_MS); 901 if (!ret) { 902 if (e->ai_family == AF_INET6) { 903 ret = qemu_rdma_broken_ipv6_kernel(errp, rdma->cm_id->verbs); 904 if (ret) { 905 continue; 906 } 907 } 908 goto route; 909 } 910 } 911 912 ERROR(errp, "could not resolve address %s", rdma->host); 913 goto err_resolve_get_addr; 914 915 route: 916 qemu_rdma_dump_gid("source_resolve_addr", rdma->cm_id); 917 918 ret = rdma_get_cm_event(rdma->channel, &cm_event); 919 if (ret) { 920 ERROR(errp, "could not perform event_addr_resolved"); 921 goto err_resolve_get_addr; 922 } 923 924 if (cm_event->event != RDMA_CM_EVENT_ADDR_RESOLVED) { 925 ERROR(errp, "result not equal to event_addr_resolved %s", 926 rdma_event_str(cm_event->event)); 927 perror("rdma_resolve_addr"); 928 rdma_ack_cm_event(cm_event); 929 ret = -EINVAL; 930 goto err_resolve_get_addr; 931 } 932 rdma_ack_cm_event(cm_event); 933 934 /* resolve route */ 935 ret = rdma_resolve_route(rdma->cm_id, RDMA_RESOLVE_TIMEOUT_MS); 936 if (ret) { 937 ERROR(errp, "could not resolve rdma route"); 938 goto err_resolve_get_addr; 939 } 940 941 ret = rdma_get_cm_event(rdma->channel, &cm_event); 942 if (ret) { 943 ERROR(errp, "could not perform event_route_resolved"); 944 goto err_resolve_get_addr; 945 } 946 if (cm_event->event != RDMA_CM_EVENT_ROUTE_RESOLVED) { 947 ERROR(errp, "result not equal to event_route_resolved: %s", 948 rdma_event_str(cm_event->event)); 949 rdma_ack_cm_event(cm_event); 950 ret = -EINVAL; 951 goto err_resolve_get_addr; 952 } 953 rdma_ack_cm_event(cm_event); 954 rdma->verbs = rdma->cm_id->verbs; 955 qemu_rdma_dump_id("source_resolve_host", rdma->cm_id->verbs); 956 qemu_rdma_dump_gid("source_resolve_host", rdma->cm_id); 957 return 0; 958 959 err_resolve_get_addr: 960 rdma_destroy_id(rdma->cm_id); 961 rdma->cm_id = NULL; 962 err_resolve_create_id: 963 rdma_destroy_event_channel(rdma->channel); 964 rdma->channel = NULL; 965 return ret; 966 } 967 968 /* 969 * Create protection domain and completion queues 970 */ 971 static int qemu_rdma_alloc_pd_cq(RDMAContext *rdma) 972 { 973 /* allocate pd */ 974 rdma->pd = ibv_alloc_pd(rdma->verbs); 975 if (!rdma->pd) { 976 error_report("failed to allocate protection domain"); 977 return -1; 978 } 979 980 /* create completion channel */ 981 rdma->comp_channel = ibv_create_comp_channel(rdma->verbs); 982 if (!rdma->comp_channel) { 983 error_report("failed to allocate completion channel"); 984 goto err_alloc_pd_cq; 985 } 986 987 /* 988 * Completion queue can be filled by both read and write work requests, 989 * so must reflect the sum of both possible queue sizes. 990 */ 991 rdma->cq = ibv_create_cq(rdma->verbs, (RDMA_SIGNALED_SEND_MAX * 3), 992 NULL, rdma->comp_channel, 0); 993 if (!rdma->cq) { 994 error_report("failed to allocate completion queue"); 995 goto err_alloc_pd_cq; 996 } 997 998 return 0; 999 1000 err_alloc_pd_cq: 1001 if (rdma->pd) { 1002 ibv_dealloc_pd(rdma->pd); 1003 } 1004 if (rdma->comp_channel) { 1005 ibv_destroy_comp_channel(rdma->comp_channel); 1006 } 1007 rdma->pd = NULL; 1008 rdma->comp_channel = NULL; 1009 return -1; 1010 1011 } 1012 1013 /* 1014 * Create queue pairs. 1015 */ 1016 static int qemu_rdma_alloc_qp(RDMAContext *rdma) 1017 { 1018 struct ibv_qp_init_attr attr = { 0 }; 1019 int ret; 1020 1021 attr.cap.max_send_wr = RDMA_SIGNALED_SEND_MAX; 1022 attr.cap.max_recv_wr = 3; 1023 attr.cap.max_send_sge = 1; 1024 attr.cap.max_recv_sge = 1; 1025 attr.send_cq = rdma->cq; 1026 attr.recv_cq = rdma->cq; 1027 attr.qp_type = IBV_QPT_RC; 1028 1029 ret = rdma_create_qp(rdma->cm_id, rdma->pd, &attr); 1030 if (ret) { 1031 return -1; 1032 } 1033 1034 rdma->qp = rdma->cm_id->qp; 1035 return 0; 1036 } 1037 1038 static int qemu_rdma_reg_whole_ram_blocks(RDMAContext *rdma) 1039 { 1040 int i; 1041 RDMALocalBlocks *local = &rdma->local_ram_blocks; 1042 1043 for (i = 0; i < local->nb_blocks; i++) { 1044 local->block[i].mr = 1045 ibv_reg_mr(rdma->pd, 1046 local->block[i].local_host_addr, 1047 local->block[i].length, 1048 IBV_ACCESS_LOCAL_WRITE | 1049 IBV_ACCESS_REMOTE_WRITE 1050 ); 1051 if (!local->block[i].mr) { 1052 perror("Failed to register local dest ram block!\n"); 1053 break; 1054 } 1055 rdma->total_registrations++; 1056 } 1057 1058 if (i >= local->nb_blocks) { 1059 return 0; 1060 } 1061 1062 for (i--; i >= 0; i--) { 1063 ibv_dereg_mr(local->block[i].mr); 1064 rdma->total_registrations--; 1065 } 1066 1067 return -1; 1068 1069 } 1070 1071 /* 1072 * Find the ram block that corresponds to the page requested to be 1073 * transmitted by QEMU. 1074 * 1075 * Once the block is found, also identify which 'chunk' within that 1076 * block that the page belongs to. 1077 * 1078 * This search cannot fail or the migration will fail. 1079 */ 1080 static int qemu_rdma_search_ram_block(RDMAContext *rdma, 1081 uintptr_t block_offset, 1082 uint64_t offset, 1083 uint64_t length, 1084 uint64_t *block_index, 1085 uint64_t *chunk_index) 1086 { 1087 uint64_t current_addr = block_offset + offset; 1088 RDMALocalBlock *block = g_hash_table_lookup(rdma->blockmap, 1089 (void *) block_offset); 1090 assert(block); 1091 assert(current_addr >= block->offset); 1092 assert((current_addr + length) <= (block->offset + block->length)); 1093 1094 *block_index = block->index; 1095 *chunk_index = ram_chunk_index(block->local_host_addr, 1096 block->local_host_addr + (current_addr - block->offset)); 1097 1098 return 0; 1099 } 1100 1101 /* 1102 * Register a chunk with IB. If the chunk was already registered 1103 * previously, then skip. 1104 * 1105 * Also return the keys associated with the registration needed 1106 * to perform the actual RDMA operation. 1107 */ 1108 static int qemu_rdma_register_and_get_keys(RDMAContext *rdma, 1109 RDMALocalBlock *block, uintptr_t host_addr, 1110 uint32_t *lkey, uint32_t *rkey, int chunk, 1111 uint8_t *chunk_start, uint8_t *chunk_end) 1112 { 1113 if (block->mr) { 1114 if (lkey) { 1115 *lkey = block->mr->lkey; 1116 } 1117 if (rkey) { 1118 *rkey = block->mr->rkey; 1119 } 1120 return 0; 1121 } 1122 1123 /* allocate memory to store chunk MRs */ 1124 if (!block->pmr) { 1125 block->pmr = g_malloc0(block->nb_chunks * sizeof(struct ibv_mr *)); 1126 } 1127 1128 /* 1129 * If 'rkey', then we're the destination, so grant access to the source. 1130 * 1131 * If 'lkey', then we're the source VM, so grant access only to ourselves. 1132 */ 1133 if (!block->pmr[chunk]) { 1134 uint64_t len = chunk_end - chunk_start; 1135 1136 trace_qemu_rdma_register_and_get_keys(len, chunk_start); 1137 1138 block->pmr[chunk] = ibv_reg_mr(rdma->pd, 1139 chunk_start, len, 1140 (rkey ? (IBV_ACCESS_LOCAL_WRITE | 1141 IBV_ACCESS_REMOTE_WRITE) : 0)); 1142 1143 if (!block->pmr[chunk]) { 1144 perror("Failed to register chunk!"); 1145 fprintf(stderr, "Chunk details: block: %d chunk index %d" 1146 " start %" PRIuPTR " end %" PRIuPTR 1147 " host %" PRIuPTR 1148 " local %" PRIuPTR " registrations: %d\n", 1149 block->index, chunk, (uintptr_t)chunk_start, 1150 (uintptr_t)chunk_end, host_addr, 1151 (uintptr_t)block->local_host_addr, 1152 rdma->total_registrations); 1153 return -1; 1154 } 1155 rdma->total_registrations++; 1156 } 1157 1158 if (lkey) { 1159 *lkey = block->pmr[chunk]->lkey; 1160 } 1161 if (rkey) { 1162 *rkey = block->pmr[chunk]->rkey; 1163 } 1164 return 0; 1165 } 1166 1167 /* 1168 * Register (at connection time) the memory used for control 1169 * channel messages. 1170 */ 1171 static int qemu_rdma_reg_control(RDMAContext *rdma, int idx) 1172 { 1173 rdma->wr_data[idx].control_mr = ibv_reg_mr(rdma->pd, 1174 rdma->wr_data[idx].control, RDMA_CONTROL_MAX_BUFFER, 1175 IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE); 1176 if (rdma->wr_data[idx].control_mr) { 1177 rdma->total_registrations++; 1178 return 0; 1179 } 1180 error_report("qemu_rdma_reg_control failed"); 1181 return -1; 1182 } 1183 1184 const char *print_wrid(int wrid) 1185 { 1186 if (wrid >= RDMA_WRID_RECV_CONTROL) { 1187 return wrid_desc[RDMA_WRID_RECV_CONTROL]; 1188 } 1189 return wrid_desc[wrid]; 1190 } 1191 1192 /* 1193 * RDMA requires memory registration (mlock/pinning), but this is not good for 1194 * overcommitment. 1195 * 1196 * In preparation for the future where LRU information or workload-specific 1197 * writable writable working set memory access behavior is available to QEMU 1198 * it would be nice to have in place the ability to UN-register/UN-pin 1199 * particular memory regions from the RDMA hardware when it is determine that 1200 * those regions of memory will likely not be accessed again in the near future. 1201 * 1202 * While we do not yet have such information right now, the following 1203 * compile-time option allows us to perform a non-optimized version of this 1204 * behavior. 1205 * 1206 * By uncommenting this option, you will cause *all* RDMA transfers to be 1207 * unregistered immediately after the transfer completes on both sides of the 1208 * connection. This has no effect in 'rdma-pin-all' mode, only regular mode. 1209 * 1210 * This will have a terrible impact on migration performance, so until future 1211 * workload information or LRU information is available, do not attempt to use 1212 * this feature except for basic testing. 1213 */ 1214 //#define RDMA_UNREGISTRATION_EXAMPLE 1215 1216 /* 1217 * Perform a non-optimized memory unregistration after every transfer 1218 * for demonsration purposes, only if pin-all is not requested. 1219 * 1220 * Potential optimizations: 1221 * 1. Start a new thread to run this function continuously 1222 - for bit clearing 1223 - and for receipt of unregister messages 1224 * 2. Use an LRU. 1225 * 3. Use workload hints. 1226 */ 1227 static int qemu_rdma_unregister_waiting(RDMAContext *rdma) 1228 { 1229 while (rdma->unregistrations[rdma->unregister_current]) { 1230 int ret; 1231 uint64_t wr_id = rdma->unregistrations[rdma->unregister_current]; 1232 uint64_t chunk = 1233 (wr_id & RDMA_WRID_CHUNK_MASK) >> RDMA_WRID_CHUNK_SHIFT; 1234 uint64_t index = 1235 (wr_id & RDMA_WRID_BLOCK_MASK) >> RDMA_WRID_BLOCK_SHIFT; 1236 RDMALocalBlock *block = 1237 &(rdma->local_ram_blocks.block[index]); 1238 RDMARegister reg = { .current_index = index }; 1239 RDMAControlHeader resp = { .type = RDMA_CONTROL_UNREGISTER_FINISHED, 1240 }; 1241 RDMAControlHeader head = { .len = sizeof(RDMARegister), 1242 .type = RDMA_CONTROL_UNREGISTER_REQUEST, 1243 .repeat = 1, 1244 }; 1245 1246 trace_qemu_rdma_unregister_waiting_proc(chunk, 1247 rdma->unregister_current); 1248 1249 rdma->unregistrations[rdma->unregister_current] = 0; 1250 rdma->unregister_current++; 1251 1252 if (rdma->unregister_current == RDMA_SIGNALED_SEND_MAX) { 1253 rdma->unregister_current = 0; 1254 } 1255 1256 1257 /* 1258 * Unregistration is speculative (because migration is single-threaded 1259 * and we cannot break the protocol's inifinband message ordering). 1260 * Thus, if the memory is currently being used for transmission, 1261 * then abort the attempt to unregister and try again 1262 * later the next time a completion is received for this memory. 1263 */ 1264 clear_bit(chunk, block->unregister_bitmap); 1265 1266 if (test_bit(chunk, block->transit_bitmap)) { 1267 trace_qemu_rdma_unregister_waiting_inflight(chunk); 1268 continue; 1269 } 1270 1271 trace_qemu_rdma_unregister_waiting_send(chunk); 1272 1273 ret = ibv_dereg_mr(block->pmr[chunk]); 1274 block->pmr[chunk] = NULL; 1275 block->remote_keys[chunk] = 0; 1276 1277 if (ret != 0) { 1278 perror("unregistration chunk failed"); 1279 return -ret; 1280 } 1281 rdma->total_registrations--; 1282 1283 reg.key.chunk = chunk; 1284 register_to_network(®); 1285 ret = qemu_rdma_exchange_send(rdma, &head, (uint8_t *) ®, 1286 &resp, NULL, NULL); 1287 if (ret < 0) { 1288 return ret; 1289 } 1290 1291 trace_qemu_rdma_unregister_waiting_complete(chunk); 1292 } 1293 1294 return 0; 1295 } 1296 1297 static uint64_t qemu_rdma_make_wrid(uint64_t wr_id, uint64_t index, 1298 uint64_t chunk) 1299 { 1300 uint64_t result = wr_id & RDMA_WRID_TYPE_MASK; 1301 1302 result |= (index << RDMA_WRID_BLOCK_SHIFT); 1303 result |= (chunk << RDMA_WRID_CHUNK_SHIFT); 1304 1305 return result; 1306 } 1307 1308 /* 1309 * Set bit for unregistration in the next iteration. 1310 * We cannot transmit right here, but will unpin later. 1311 */ 1312 static void qemu_rdma_signal_unregister(RDMAContext *rdma, uint64_t index, 1313 uint64_t chunk, uint64_t wr_id) 1314 { 1315 if (rdma->unregistrations[rdma->unregister_next] != 0) { 1316 error_report("rdma migration: queue is full"); 1317 } else { 1318 RDMALocalBlock *block = &(rdma->local_ram_blocks.block[index]); 1319 1320 if (!test_and_set_bit(chunk, block->unregister_bitmap)) { 1321 trace_qemu_rdma_signal_unregister_append(chunk, 1322 rdma->unregister_next); 1323 1324 rdma->unregistrations[rdma->unregister_next++] = 1325 qemu_rdma_make_wrid(wr_id, index, chunk); 1326 1327 if (rdma->unregister_next == RDMA_SIGNALED_SEND_MAX) { 1328 rdma->unregister_next = 0; 1329 } 1330 } else { 1331 trace_qemu_rdma_signal_unregister_already(chunk); 1332 } 1333 } 1334 } 1335 1336 /* 1337 * Consult the connection manager to see a work request 1338 * (of any kind) has completed. 1339 * Return the work request ID that completed. 1340 */ 1341 static uint64_t qemu_rdma_poll(RDMAContext *rdma, uint64_t *wr_id_out, 1342 uint32_t *byte_len) 1343 { 1344 int ret; 1345 struct ibv_wc wc; 1346 uint64_t wr_id; 1347 1348 ret = ibv_poll_cq(rdma->cq, 1, &wc); 1349 1350 if (!ret) { 1351 *wr_id_out = RDMA_WRID_NONE; 1352 return 0; 1353 } 1354 1355 if (ret < 0) { 1356 error_report("ibv_poll_cq return %d", ret); 1357 return ret; 1358 } 1359 1360 wr_id = wc.wr_id & RDMA_WRID_TYPE_MASK; 1361 1362 if (wc.status != IBV_WC_SUCCESS) { 1363 fprintf(stderr, "ibv_poll_cq wc.status=%d %s!\n", 1364 wc.status, ibv_wc_status_str(wc.status)); 1365 fprintf(stderr, "ibv_poll_cq wrid=%s!\n", wrid_desc[wr_id]); 1366 1367 return -1; 1368 } 1369 1370 if (rdma->control_ready_expected && 1371 (wr_id >= RDMA_WRID_RECV_CONTROL)) { 1372 trace_qemu_rdma_poll_recv(wrid_desc[RDMA_WRID_RECV_CONTROL], 1373 wr_id - RDMA_WRID_RECV_CONTROL, wr_id, rdma->nb_sent); 1374 rdma->control_ready_expected = 0; 1375 } 1376 1377 if (wr_id == RDMA_WRID_RDMA_WRITE) { 1378 uint64_t chunk = 1379 (wc.wr_id & RDMA_WRID_CHUNK_MASK) >> RDMA_WRID_CHUNK_SHIFT; 1380 uint64_t index = 1381 (wc.wr_id & RDMA_WRID_BLOCK_MASK) >> RDMA_WRID_BLOCK_SHIFT; 1382 RDMALocalBlock *block = &(rdma->local_ram_blocks.block[index]); 1383 1384 trace_qemu_rdma_poll_write(print_wrid(wr_id), wr_id, rdma->nb_sent, 1385 index, chunk, block->local_host_addr, 1386 (void *)(uintptr_t)block->remote_host_addr); 1387 1388 clear_bit(chunk, block->transit_bitmap); 1389 1390 if (rdma->nb_sent > 0) { 1391 rdma->nb_sent--; 1392 } 1393 1394 if (!rdma->pin_all) { 1395 /* 1396 * FYI: If one wanted to signal a specific chunk to be unregistered 1397 * using LRU or workload-specific information, this is the function 1398 * you would call to do so. That chunk would then get asynchronously 1399 * unregistered later. 1400 */ 1401 #ifdef RDMA_UNREGISTRATION_EXAMPLE 1402 qemu_rdma_signal_unregister(rdma, index, chunk, wc.wr_id); 1403 #endif 1404 } 1405 } else { 1406 trace_qemu_rdma_poll_other(print_wrid(wr_id), wr_id, rdma->nb_sent); 1407 } 1408 1409 *wr_id_out = wc.wr_id; 1410 if (byte_len) { 1411 *byte_len = wc.byte_len; 1412 } 1413 1414 return 0; 1415 } 1416 1417 /* 1418 * Block until the next work request has completed. 1419 * 1420 * First poll to see if a work request has already completed, 1421 * otherwise block. 1422 * 1423 * If we encounter completed work requests for IDs other than 1424 * the one we're interested in, then that's generally an error. 1425 * 1426 * The only exception is actual RDMA Write completions. These 1427 * completions only need to be recorded, but do not actually 1428 * need further processing. 1429 */ 1430 static int qemu_rdma_block_for_wrid(RDMAContext *rdma, int wrid_requested, 1431 uint32_t *byte_len) 1432 { 1433 int num_cq_events = 0, ret = 0; 1434 struct ibv_cq *cq; 1435 void *cq_ctx; 1436 uint64_t wr_id = RDMA_WRID_NONE, wr_id_in; 1437 1438 if (ibv_req_notify_cq(rdma->cq, 0)) { 1439 return -1; 1440 } 1441 /* poll cq first */ 1442 while (wr_id != wrid_requested) { 1443 ret = qemu_rdma_poll(rdma, &wr_id_in, byte_len); 1444 if (ret < 0) { 1445 return ret; 1446 } 1447 1448 wr_id = wr_id_in & RDMA_WRID_TYPE_MASK; 1449 1450 if (wr_id == RDMA_WRID_NONE) { 1451 break; 1452 } 1453 if (wr_id != wrid_requested) { 1454 trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested), 1455 wrid_requested, print_wrid(wr_id), wr_id); 1456 } 1457 } 1458 1459 if (wr_id == wrid_requested) { 1460 return 0; 1461 } 1462 1463 while (1) { 1464 /* 1465 * Coroutine doesn't start until process_incoming_migration() 1466 * so don't yield unless we know we're running inside of a coroutine. 1467 */ 1468 if (rdma->migration_started_on_destination) { 1469 yield_until_fd_readable(rdma->comp_channel->fd); 1470 } 1471 1472 if (ibv_get_cq_event(rdma->comp_channel, &cq, &cq_ctx)) { 1473 perror("ibv_get_cq_event"); 1474 goto err_block_for_wrid; 1475 } 1476 1477 num_cq_events++; 1478 1479 if (ibv_req_notify_cq(cq, 0)) { 1480 goto err_block_for_wrid; 1481 } 1482 1483 while (wr_id != wrid_requested) { 1484 ret = qemu_rdma_poll(rdma, &wr_id_in, byte_len); 1485 if (ret < 0) { 1486 goto err_block_for_wrid; 1487 } 1488 1489 wr_id = wr_id_in & RDMA_WRID_TYPE_MASK; 1490 1491 if (wr_id == RDMA_WRID_NONE) { 1492 break; 1493 } 1494 if (wr_id != wrid_requested) { 1495 trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested), 1496 wrid_requested, print_wrid(wr_id), wr_id); 1497 } 1498 } 1499 1500 if (wr_id == wrid_requested) { 1501 goto success_block_for_wrid; 1502 } 1503 } 1504 1505 success_block_for_wrid: 1506 if (num_cq_events) { 1507 ibv_ack_cq_events(cq, num_cq_events); 1508 } 1509 return 0; 1510 1511 err_block_for_wrid: 1512 if (num_cq_events) { 1513 ibv_ack_cq_events(cq, num_cq_events); 1514 } 1515 return ret; 1516 } 1517 1518 /* 1519 * Post a SEND message work request for the control channel 1520 * containing some data and block until the post completes. 1521 */ 1522 static int qemu_rdma_post_send_control(RDMAContext *rdma, uint8_t *buf, 1523 RDMAControlHeader *head) 1524 { 1525 int ret = 0; 1526 RDMAWorkRequestData *wr = &rdma->wr_data[RDMA_WRID_CONTROL]; 1527 struct ibv_send_wr *bad_wr; 1528 struct ibv_sge sge = { 1529 .addr = (uintptr_t)(wr->control), 1530 .length = head->len + sizeof(RDMAControlHeader), 1531 .lkey = wr->control_mr->lkey, 1532 }; 1533 struct ibv_send_wr send_wr = { 1534 .wr_id = RDMA_WRID_SEND_CONTROL, 1535 .opcode = IBV_WR_SEND, 1536 .send_flags = IBV_SEND_SIGNALED, 1537 .sg_list = &sge, 1538 .num_sge = 1, 1539 }; 1540 1541 trace_qemu_rdma_post_send_control(control_desc[head->type]); 1542 1543 /* 1544 * We don't actually need to do a memcpy() in here if we used 1545 * the "sge" properly, but since we're only sending control messages 1546 * (not RAM in a performance-critical path), then its OK for now. 1547 * 1548 * The copy makes the RDMAControlHeader simpler to manipulate 1549 * for the time being. 1550 */ 1551 assert(head->len <= RDMA_CONTROL_MAX_BUFFER - sizeof(*head)); 1552 memcpy(wr->control, head, sizeof(RDMAControlHeader)); 1553 control_to_network((void *) wr->control); 1554 1555 if (buf) { 1556 memcpy(wr->control + sizeof(RDMAControlHeader), buf, head->len); 1557 } 1558 1559 1560 ret = ibv_post_send(rdma->qp, &send_wr, &bad_wr); 1561 1562 if (ret > 0) { 1563 error_report("Failed to use post IB SEND for control"); 1564 return -ret; 1565 } 1566 1567 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_SEND_CONTROL, NULL); 1568 if (ret < 0) { 1569 error_report("rdma migration: send polling control error"); 1570 } 1571 1572 return ret; 1573 } 1574 1575 /* 1576 * Post a RECV work request in anticipation of some future receipt 1577 * of data on the control channel. 1578 */ 1579 static int qemu_rdma_post_recv_control(RDMAContext *rdma, int idx) 1580 { 1581 struct ibv_recv_wr *bad_wr; 1582 struct ibv_sge sge = { 1583 .addr = (uintptr_t)(rdma->wr_data[idx].control), 1584 .length = RDMA_CONTROL_MAX_BUFFER, 1585 .lkey = rdma->wr_data[idx].control_mr->lkey, 1586 }; 1587 1588 struct ibv_recv_wr recv_wr = { 1589 .wr_id = RDMA_WRID_RECV_CONTROL + idx, 1590 .sg_list = &sge, 1591 .num_sge = 1, 1592 }; 1593 1594 1595 if (ibv_post_recv(rdma->qp, &recv_wr, &bad_wr)) { 1596 return -1; 1597 } 1598 1599 return 0; 1600 } 1601 1602 /* 1603 * Block and wait for a RECV control channel message to arrive. 1604 */ 1605 static int qemu_rdma_exchange_get_response(RDMAContext *rdma, 1606 RDMAControlHeader *head, int expecting, int idx) 1607 { 1608 uint32_t byte_len; 1609 int ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RECV_CONTROL + idx, 1610 &byte_len); 1611 1612 if (ret < 0) { 1613 error_report("rdma migration: recv polling control error!"); 1614 return ret; 1615 } 1616 1617 network_to_control((void *) rdma->wr_data[idx].control); 1618 memcpy(head, rdma->wr_data[idx].control, sizeof(RDMAControlHeader)); 1619 1620 trace_qemu_rdma_exchange_get_response_start(control_desc[expecting]); 1621 1622 if (expecting == RDMA_CONTROL_NONE) { 1623 trace_qemu_rdma_exchange_get_response_none(control_desc[head->type], 1624 head->type); 1625 } else if (head->type != expecting || head->type == RDMA_CONTROL_ERROR) { 1626 error_report("Was expecting a %s (%d) control message" 1627 ", but got: %s (%d), length: %d", 1628 control_desc[expecting], expecting, 1629 control_desc[head->type], head->type, head->len); 1630 return -EIO; 1631 } 1632 if (head->len > RDMA_CONTROL_MAX_BUFFER - sizeof(*head)) { 1633 error_report("too long length: %d", head->len); 1634 return -EINVAL; 1635 } 1636 if (sizeof(*head) + head->len != byte_len) { 1637 error_report("Malformed length: %d byte_len %d", head->len, byte_len); 1638 return -EINVAL; 1639 } 1640 1641 return 0; 1642 } 1643 1644 /* 1645 * When a RECV work request has completed, the work request's 1646 * buffer is pointed at the header. 1647 * 1648 * This will advance the pointer to the data portion 1649 * of the control message of the work request's buffer that 1650 * was populated after the work request finished. 1651 */ 1652 static void qemu_rdma_move_header(RDMAContext *rdma, int idx, 1653 RDMAControlHeader *head) 1654 { 1655 rdma->wr_data[idx].control_len = head->len; 1656 rdma->wr_data[idx].control_curr = 1657 rdma->wr_data[idx].control + sizeof(RDMAControlHeader); 1658 } 1659 1660 /* 1661 * This is an 'atomic' high-level operation to deliver a single, unified 1662 * control-channel message. 1663 * 1664 * Additionally, if the user is expecting some kind of reply to this message, 1665 * they can request a 'resp' response message be filled in by posting an 1666 * additional work request on behalf of the user and waiting for an additional 1667 * completion. 1668 * 1669 * The extra (optional) response is used during registration to us from having 1670 * to perform an *additional* exchange of message just to provide a response by 1671 * instead piggy-backing on the acknowledgement. 1672 */ 1673 static int qemu_rdma_exchange_send(RDMAContext *rdma, RDMAControlHeader *head, 1674 uint8_t *data, RDMAControlHeader *resp, 1675 int *resp_idx, 1676 int (*callback)(RDMAContext *rdma)) 1677 { 1678 int ret = 0; 1679 1680 /* 1681 * Wait until the dest is ready before attempting to deliver the message 1682 * by waiting for a READY message. 1683 */ 1684 if (rdma->control_ready_expected) { 1685 RDMAControlHeader resp; 1686 ret = qemu_rdma_exchange_get_response(rdma, 1687 &resp, RDMA_CONTROL_READY, RDMA_WRID_READY); 1688 if (ret < 0) { 1689 return ret; 1690 } 1691 } 1692 1693 /* 1694 * If the user is expecting a response, post a WR in anticipation of it. 1695 */ 1696 if (resp) { 1697 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_DATA); 1698 if (ret) { 1699 error_report("rdma migration: error posting" 1700 " extra control recv for anticipated result!"); 1701 return ret; 1702 } 1703 } 1704 1705 /* 1706 * Post a WR to replace the one we just consumed for the READY message. 1707 */ 1708 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY); 1709 if (ret) { 1710 error_report("rdma migration: error posting first control recv!"); 1711 return ret; 1712 } 1713 1714 /* 1715 * Deliver the control message that was requested. 1716 */ 1717 ret = qemu_rdma_post_send_control(rdma, data, head); 1718 1719 if (ret < 0) { 1720 error_report("Failed to send control buffer!"); 1721 return ret; 1722 } 1723 1724 /* 1725 * If we're expecting a response, block and wait for it. 1726 */ 1727 if (resp) { 1728 if (callback) { 1729 trace_qemu_rdma_exchange_send_issue_callback(); 1730 ret = callback(rdma); 1731 if (ret < 0) { 1732 return ret; 1733 } 1734 } 1735 1736 trace_qemu_rdma_exchange_send_waiting(control_desc[resp->type]); 1737 ret = qemu_rdma_exchange_get_response(rdma, resp, 1738 resp->type, RDMA_WRID_DATA); 1739 1740 if (ret < 0) { 1741 return ret; 1742 } 1743 1744 qemu_rdma_move_header(rdma, RDMA_WRID_DATA, resp); 1745 if (resp_idx) { 1746 *resp_idx = RDMA_WRID_DATA; 1747 } 1748 trace_qemu_rdma_exchange_send_received(control_desc[resp->type]); 1749 } 1750 1751 rdma->control_ready_expected = 1; 1752 1753 return 0; 1754 } 1755 1756 /* 1757 * This is an 'atomic' high-level operation to receive a single, unified 1758 * control-channel message. 1759 */ 1760 static int qemu_rdma_exchange_recv(RDMAContext *rdma, RDMAControlHeader *head, 1761 int expecting) 1762 { 1763 RDMAControlHeader ready = { 1764 .len = 0, 1765 .type = RDMA_CONTROL_READY, 1766 .repeat = 1, 1767 }; 1768 int ret; 1769 1770 /* 1771 * Inform the source that we're ready to receive a message. 1772 */ 1773 ret = qemu_rdma_post_send_control(rdma, NULL, &ready); 1774 1775 if (ret < 0) { 1776 error_report("Failed to send control buffer!"); 1777 return ret; 1778 } 1779 1780 /* 1781 * Block and wait for the message. 1782 */ 1783 ret = qemu_rdma_exchange_get_response(rdma, head, 1784 expecting, RDMA_WRID_READY); 1785 1786 if (ret < 0) { 1787 return ret; 1788 } 1789 1790 qemu_rdma_move_header(rdma, RDMA_WRID_READY, head); 1791 1792 /* 1793 * Post a new RECV work request to replace the one we just consumed. 1794 */ 1795 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY); 1796 if (ret) { 1797 error_report("rdma migration: error posting second control recv!"); 1798 return ret; 1799 } 1800 1801 return 0; 1802 } 1803 1804 /* 1805 * Write an actual chunk of memory using RDMA. 1806 * 1807 * If we're using dynamic registration on the dest-side, we have to 1808 * send a registration command first. 1809 */ 1810 static int qemu_rdma_write_one(QEMUFile *f, RDMAContext *rdma, 1811 int current_index, uint64_t current_addr, 1812 uint64_t length) 1813 { 1814 struct ibv_sge sge; 1815 struct ibv_send_wr send_wr = { 0 }; 1816 struct ibv_send_wr *bad_wr; 1817 int reg_result_idx, ret, count = 0; 1818 uint64_t chunk, chunks; 1819 uint8_t *chunk_start, *chunk_end; 1820 RDMALocalBlock *block = &(rdma->local_ram_blocks.block[current_index]); 1821 RDMARegister reg; 1822 RDMARegisterResult *reg_result; 1823 RDMAControlHeader resp = { .type = RDMA_CONTROL_REGISTER_RESULT }; 1824 RDMAControlHeader head = { .len = sizeof(RDMARegister), 1825 .type = RDMA_CONTROL_REGISTER_REQUEST, 1826 .repeat = 1, 1827 }; 1828 1829 retry: 1830 sge.addr = (uintptr_t)(block->local_host_addr + 1831 (current_addr - block->offset)); 1832 sge.length = length; 1833 1834 chunk = ram_chunk_index(block->local_host_addr, 1835 (uint8_t *)(uintptr_t)sge.addr); 1836 chunk_start = ram_chunk_start(block, chunk); 1837 1838 if (block->is_ram_block) { 1839 chunks = length / (1UL << RDMA_REG_CHUNK_SHIFT); 1840 1841 if (chunks && ((length % (1UL << RDMA_REG_CHUNK_SHIFT)) == 0)) { 1842 chunks--; 1843 } 1844 } else { 1845 chunks = block->length / (1UL << RDMA_REG_CHUNK_SHIFT); 1846 1847 if (chunks && ((block->length % (1UL << RDMA_REG_CHUNK_SHIFT)) == 0)) { 1848 chunks--; 1849 } 1850 } 1851 1852 trace_qemu_rdma_write_one_top(chunks + 1, 1853 (chunks + 1) * 1854 (1UL << RDMA_REG_CHUNK_SHIFT) / 1024 / 1024); 1855 1856 chunk_end = ram_chunk_end(block, chunk + chunks); 1857 1858 if (!rdma->pin_all) { 1859 #ifdef RDMA_UNREGISTRATION_EXAMPLE 1860 qemu_rdma_unregister_waiting(rdma); 1861 #endif 1862 } 1863 1864 while (test_bit(chunk, block->transit_bitmap)) { 1865 (void)count; 1866 trace_qemu_rdma_write_one_block(count++, current_index, chunk, 1867 sge.addr, length, rdma->nb_sent, block->nb_chunks); 1868 1869 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL); 1870 1871 if (ret < 0) { 1872 error_report("Failed to Wait for previous write to complete " 1873 "block %d chunk %" PRIu64 1874 " current %" PRIu64 " len %" PRIu64 " %d", 1875 current_index, chunk, sge.addr, length, rdma->nb_sent); 1876 return ret; 1877 } 1878 } 1879 1880 if (!rdma->pin_all || !block->is_ram_block) { 1881 if (!block->remote_keys[chunk]) { 1882 /* 1883 * This chunk has not yet been registered, so first check to see 1884 * if the entire chunk is zero. If so, tell the other size to 1885 * memset() + madvise() the entire chunk without RDMA. 1886 */ 1887 1888 if (can_use_buffer_find_nonzero_offset((void *)(uintptr_t)sge.addr, 1889 length) 1890 && buffer_find_nonzero_offset((void *)(uintptr_t)sge.addr, 1891 length) == length) { 1892 RDMACompress comp = { 1893 .offset = current_addr, 1894 .value = 0, 1895 .block_idx = current_index, 1896 .length = length, 1897 }; 1898 1899 head.len = sizeof(comp); 1900 head.type = RDMA_CONTROL_COMPRESS; 1901 1902 trace_qemu_rdma_write_one_zero(chunk, sge.length, 1903 current_index, current_addr); 1904 1905 compress_to_network(&comp); 1906 ret = qemu_rdma_exchange_send(rdma, &head, 1907 (uint8_t *) &comp, NULL, NULL, NULL); 1908 1909 if (ret < 0) { 1910 return -EIO; 1911 } 1912 1913 acct_update_position(f, sge.length, true); 1914 1915 return 1; 1916 } 1917 1918 /* 1919 * Otherwise, tell other side to register. 1920 */ 1921 reg.current_index = current_index; 1922 if (block->is_ram_block) { 1923 reg.key.current_addr = current_addr; 1924 } else { 1925 reg.key.chunk = chunk; 1926 } 1927 reg.chunks = chunks; 1928 1929 trace_qemu_rdma_write_one_sendreg(chunk, sge.length, current_index, 1930 current_addr); 1931 1932 register_to_network(®); 1933 ret = qemu_rdma_exchange_send(rdma, &head, (uint8_t *) ®, 1934 &resp, ®_result_idx, NULL); 1935 if (ret < 0) { 1936 return ret; 1937 } 1938 1939 /* try to overlap this single registration with the one we sent. */ 1940 if (qemu_rdma_register_and_get_keys(rdma, block, sge.addr, 1941 &sge.lkey, NULL, chunk, 1942 chunk_start, chunk_end)) { 1943 error_report("cannot get lkey"); 1944 return -EINVAL; 1945 } 1946 1947 reg_result = (RDMARegisterResult *) 1948 rdma->wr_data[reg_result_idx].control_curr; 1949 1950 network_to_result(reg_result); 1951 1952 trace_qemu_rdma_write_one_recvregres(block->remote_keys[chunk], 1953 reg_result->rkey, chunk); 1954 1955 block->remote_keys[chunk] = reg_result->rkey; 1956 block->remote_host_addr = reg_result->host_addr; 1957 } else { 1958 /* already registered before */ 1959 if (qemu_rdma_register_and_get_keys(rdma, block, sge.addr, 1960 &sge.lkey, NULL, chunk, 1961 chunk_start, chunk_end)) { 1962 error_report("cannot get lkey!"); 1963 return -EINVAL; 1964 } 1965 } 1966 1967 send_wr.wr.rdma.rkey = block->remote_keys[chunk]; 1968 } else { 1969 send_wr.wr.rdma.rkey = block->remote_rkey; 1970 1971 if (qemu_rdma_register_and_get_keys(rdma, block, sge.addr, 1972 &sge.lkey, NULL, chunk, 1973 chunk_start, chunk_end)) { 1974 error_report("cannot get lkey!"); 1975 return -EINVAL; 1976 } 1977 } 1978 1979 /* 1980 * Encode the ram block index and chunk within this wrid. 1981 * We will use this information at the time of completion 1982 * to figure out which bitmap to check against and then which 1983 * chunk in the bitmap to look for. 1984 */ 1985 send_wr.wr_id = qemu_rdma_make_wrid(RDMA_WRID_RDMA_WRITE, 1986 current_index, chunk); 1987 1988 send_wr.opcode = IBV_WR_RDMA_WRITE; 1989 send_wr.send_flags = IBV_SEND_SIGNALED; 1990 send_wr.sg_list = &sge; 1991 send_wr.num_sge = 1; 1992 send_wr.wr.rdma.remote_addr = block->remote_host_addr + 1993 (current_addr - block->offset); 1994 1995 trace_qemu_rdma_write_one_post(chunk, sge.addr, send_wr.wr.rdma.remote_addr, 1996 sge.length); 1997 1998 /* 1999 * ibv_post_send() does not return negative error numbers, 2000 * per the specification they are positive - no idea why. 2001 */ 2002 ret = ibv_post_send(rdma->qp, &send_wr, &bad_wr); 2003 2004 if (ret == ENOMEM) { 2005 trace_qemu_rdma_write_one_queue_full(); 2006 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL); 2007 if (ret < 0) { 2008 error_report("rdma migration: failed to make " 2009 "room in full send queue! %d", ret); 2010 return ret; 2011 } 2012 2013 goto retry; 2014 2015 } else if (ret > 0) { 2016 perror("rdma migration: post rdma write failed"); 2017 return -ret; 2018 } 2019 2020 set_bit(chunk, block->transit_bitmap); 2021 acct_update_position(f, sge.length, false); 2022 rdma->total_writes++; 2023 2024 return 0; 2025 } 2026 2027 /* 2028 * Push out any unwritten RDMA operations. 2029 * 2030 * We support sending out multiple chunks at the same time. 2031 * Not all of them need to get signaled in the completion queue. 2032 */ 2033 static int qemu_rdma_write_flush(QEMUFile *f, RDMAContext *rdma) 2034 { 2035 int ret; 2036 2037 if (!rdma->current_length) { 2038 return 0; 2039 } 2040 2041 ret = qemu_rdma_write_one(f, rdma, 2042 rdma->current_index, rdma->current_addr, rdma->current_length); 2043 2044 if (ret < 0) { 2045 return ret; 2046 } 2047 2048 if (ret == 0) { 2049 rdma->nb_sent++; 2050 trace_qemu_rdma_write_flush(rdma->nb_sent); 2051 } 2052 2053 rdma->current_length = 0; 2054 rdma->current_addr = 0; 2055 2056 return 0; 2057 } 2058 2059 static inline int qemu_rdma_buffer_mergable(RDMAContext *rdma, 2060 uint64_t offset, uint64_t len) 2061 { 2062 RDMALocalBlock *block; 2063 uint8_t *host_addr; 2064 uint8_t *chunk_end; 2065 2066 if (rdma->current_index < 0) { 2067 return 0; 2068 } 2069 2070 if (rdma->current_chunk < 0) { 2071 return 0; 2072 } 2073 2074 block = &(rdma->local_ram_blocks.block[rdma->current_index]); 2075 host_addr = block->local_host_addr + (offset - block->offset); 2076 chunk_end = ram_chunk_end(block, rdma->current_chunk); 2077 2078 if (rdma->current_length == 0) { 2079 return 0; 2080 } 2081 2082 /* 2083 * Only merge into chunk sequentially. 2084 */ 2085 if (offset != (rdma->current_addr + rdma->current_length)) { 2086 return 0; 2087 } 2088 2089 if (offset < block->offset) { 2090 return 0; 2091 } 2092 2093 if ((offset + len) > (block->offset + block->length)) { 2094 return 0; 2095 } 2096 2097 if ((host_addr + len) > chunk_end) { 2098 return 0; 2099 } 2100 2101 return 1; 2102 } 2103 2104 /* 2105 * We're not actually writing here, but doing three things: 2106 * 2107 * 1. Identify the chunk the buffer belongs to. 2108 * 2. If the chunk is full or the buffer doesn't belong to the current 2109 * chunk, then start a new chunk and flush() the old chunk. 2110 * 3. To keep the hardware busy, we also group chunks into batches 2111 * and only require that a batch gets acknowledged in the completion 2112 * qeueue instead of each individual chunk. 2113 */ 2114 static int qemu_rdma_write(QEMUFile *f, RDMAContext *rdma, 2115 uint64_t block_offset, uint64_t offset, 2116 uint64_t len) 2117 { 2118 uint64_t current_addr = block_offset + offset; 2119 uint64_t index = rdma->current_index; 2120 uint64_t chunk = rdma->current_chunk; 2121 int ret; 2122 2123 /* If we cannot merge it, we flush the current buffer first. */ 2124 if (!qemu_rdma_buffer_mergable(rdma, current_addr, len)) { 2125 ret = qemu_rdma_write_flush(f, rdma); 2126 if (ret) { 2127 return ret; 2128 } 2129 rdma->current_length = 0; 2130 rdma->current_addr = current_addr; 2131 2132 ret = qemu_rdma_search_ram_block(rdma, block_offset, 2133 offset, len, &index, &chunk); 2134 if (ret) { 2135 error_report("ram block search failed"); 2136 return ret; 2137 } 2138 rdma->current_index = index; 2139 rdma->current_chunk = chunk; 2140 } 2141 2142 /* merge it */ 2143 rdma->current_length += len; 2144 2145 /* flush it if buffer is too large */ 2146 if (rdma->current_length >= RDMA_MERGE_MAX) { 2147 return qemu_rdma_write_flush(f, rdma); 2148 } 2149 2150 return 0; 2151 } 2152 2153 static void qemu_rdma_cleanup(RDMAContext *rdma) 2154 { 2155 struct rdma_cm_event *cm_event; 2156 int ret, idx; 2157 2158 if (rdma->cm_id && rdma->connected) { 2159 if (rdma->error_state) { 2160 RDMAControlHeader head = { .len = 0, 2161 .type = RDMA_CONTROL_ERROR, 2162 .repeat = 1, 2163 }; 2164 error_report("Early error. Sending error."); 2165 qemu_rdma_post_send_control(rdma, NULL, &head); 2166 } 2167 2168 ret = rdma_disconnect(rdma->cm_id); 2169 if (!ret) { 2170 trace_qemu_rdma_cleanup_waiting_for_disconnect(); 2171 ret = rdma_get_cm_event(rdma->channel, &cm_event); 2172 if (!ret) { 2173 rdma_ack_cm_event(cm_event); 2174 } 2175 } 2176 trace_qemu_rdma_cleanup_disconnect(); 2177 rdma->connected = false; 2178 } 2179 2180 g_free(rdma->block); 2181 rdma->block = NULL; 2182 2183 for (idx = 0; idx < RDMA_WRID_MAX; idx++) { 2184 if (rdma->wr_data[idx].control_mr) { 2185 rdma->total_registrations--; 2186 ibv_dereg_mr(rdma->wr_data[idx].control_mr); 2187 } 2188 rdma->wr_data[idx].control_mr = NULL; 2189 } 2190 2191 if (rdma->local_ram_blocks.block) { 2192 while (rdma->local_ram_blocks.nb_blocks) { 2193 rdma_delete_block(rdma, rdma->local_ram_blocks.block->offset); 2194 } 2195 } 2196 2197 if (rdma->qp) { 2198 rdma_destroy_qp(rdma->cm_id); 2199 rdma->qp = NULL; 2200 } 2201 if (rdma->cq) { 2202 ibv_destroy_cq(rdma->cq); 2203 rdma->cq = NULL; 2204 } 2205 if (rdma->comp_channel) { 2206 ibv_destroy_comp_channel(rdma->comp_channel); 2207 rdma->comp_channel = NULL; 2208 } 2209 if (rdma->pd) { 2210 ibv_dealloc_pd(rdma->pd); 2211 rdma->pd = NULL; 2212 } 2213 if (rdma->cm_id) { 2214 rdma_destroy_id(rdma->cm_id); 2215 rdma->cm_id = NULL; 2216 } 2217 if (rdma->listen_id) { 2218 rdma_destroy_id(rdma->listen_id); 2219 rdma->listen_id = NULL; 2220 } 2221 if (rdma->channel) { 2222 rdma_destroy_event_channel(rdma->channel); 2223 rdma->channel = NULL; 2224 } 2225 g_free(rdma->host); 2226 rdma->host = NULL; 2227 } 2228 2229 2230 static int qemu_rdma_source_init(RDMAContext *rdma, Error **errp, bool pin_all) 2231 { 2232 int ret, idx; 2233 Error *local_err = NULL, **temp = &local_err; 2234 2235 /* 2236 * Will be validated against destination's actual capabilities 2237 * after the connect() completes. 2238 */ 2239 rdma->pin_all = pin_all; 2240 2241 ret = qemu_rdma_resolve_host(rdma, temp); 2242 if (ret) { 2243 goto err_rdma_source_init; 2244 } 2245 2246 ret = qemu_rdma_alloc_pd_cq(rdma); 2247 if (ret) { 2248 ERROR(temp, "rdma migration: error allocating pd and cq! Your mlock()" 2249 " limits may be too low. Please check $ ulimit -a # and " 2250 "search for 'ulimit -l' in the output"); 2251 goto err_rdma_source_init; 2252 } 2253 2254 ret = qemu_rdma_alloc_qp(rdma); 2255 if (ret) { 2256 ERROR(temp, "rdma migration: error allocating qp!"); 2257 goto err_rdma_source_init; 2258 } 2259 2260 ret = qemu_rdma_init_ram_blocks(rdma); 2261 if (ret) { 2262 ERROR(temp, "rdma migration: error initializing ram blocks!"); 2263 goto err_rdma_source_init; 2264 } 2265 2266 for (idx = 0; idx < RDMA_WRID_MAX; idx++) { 2267 ret = qemu_rdma_reg_control(rdma, idx); 2268 if (ret) { 2269 ERROR(temp, "rdma migration: error registering %d control!", 2270 idx); 2271 goto err_rdma_source_init; 2272 } 2273 } 2274 2275 return 0; 2276 2277 err_rdma_source_init: 2278 error_propagate(errp, local_err); 2279 qemu_rdma_cleanup(rdma); 2280 return -1; 2281 } 2282 2283 static int qemu_rdma_connect(RDMAContext *rdma, Error **errp) 2284 { 2285 RDMACapabilities cap = { 2286 .version = RDMA_CONTROL_VERSION_CURRENT, 2287 .flags = 0, 2288 }; 2289 struct rdma_conn_param conn_param = { .initiator_depth = 2, 2290 .retry_count = 5, 2291 .private_data = &cap, 2292 .private_data_len = sizeof(cap), 2293 }; 2294 struct rdma_cm_event *cm_event; 2295 int ret; 2296 2297 /* 2298 * Only negotiate the capability with destination if the user 2299 * on the source first requested the capability. 2300 */ 2301 if (rdma->pin_all) { 2302 trace_qemu_rdma_connect_pin_all_requested(); 2303 cap.flags |= RDMA_CAPABILITY_PIN_ALL; 2304 } 2305 2306 caps_to_network(&cap); 2307 2308 ret = rdma_connect(rdma->cm_id, &conn_param); 2309 if (ret) { 2310 perror("rdma_connect"); 2311 ERROR(errp, "connecting to destination!"); 2312 goto err_rdma_source_connect; 2313 } 2314 2315 ret = rdma_get_cm_event(rdma->channel, &cm_event); 2316 if (ret) { 2317 perror("rdma_get_cm_event after rdma_connect"); 2318 ERROR(errp, "connecting to destination!"); 2319 rdma_ack_cm_event(cm_event); 2320 goto err_rdma_source_connect; 2321 } 2322 2323 if (cm_event->event != RDMA_CM_EVENT_ESTABLISHED) { 2324 perror("rdma_get_cm_event != EVENT_ESTABLISHED after rdma_connect"); 2325 ERROR(errp, "connecting to destination!"); 2326 rdma_ack_cm_event(cm_event); 2327 goto err_rdma_source_connect; 2328 } 2329 rdma->connected = true; 2330 2331 memcpy(&cap, cm_event->param.conn.private_data, sizeof(cap)); 2332 network_to_caps(&cap); 2333 2334 /* 2335 * Verify that the *requested* capabilities are supported by the destination 2336 * and disable them otherwise. 2337 */ 2338 if (rdma->pin_all && !(cap.flags & RDMA_CAPABILITY_PIN_ALL)) { 2339 ERROR(errp, "Server cannot support pinning all memory. " 2340 "Will register memory dynamically."); 2341 rdma->pin_all = false; 2342 } 2343 2344 trace_qemu_rdma_connect_pin_all_outcome(rdma->pin_all); 2345 2346 rdma_ack_cm_event(cm_event); 2347 2348 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY); 2349 if (ret) { 2350 ERROR(errp, "posting second control recv!"); 2351 goto err_rdma_source_connect; 2352 } 2353 2354 rdma->control_ready_expected = 1; 2355 rdma->nb_sent = 0; 2356 return 0; 2357 2358 err_rdma_source_connect: 2359 qemu_rdma_cleanup(rdma); 2360 return -1; 2361 } 2362 2363 static int qemu_rdma_dest_init(RDMAContext *rdma, Error **errp) 2364 { 2365 int ret, idx; 2366 struct rdma_cm_id *listen_id; 2367 char ip[40] = "unknown"; 2368 struct rdma_addrinfo *res, *e; 2369 char port_str[16]; 2370 2371 for (idx = 0; idx < RDMA_WRID_MAX; idx++) { 2372 rdma->wr_data[idx].control_len = 0; 2373 rdma->wr_data[idx].control_curr = NULL; 2374 } 2375 2376 if (!rdma->host || !rdma->host[0]) { 2377 ERROR(errp, "RDMA host is not set!"); 2378 rdma->error_state = -EINVAL; 2379 return -1; 2380 } 2381 /* create CM channel */ 2382 rdma->channel = rdma_create_event_channel(); 2383 if (!rdma->channel) { 2384 ERROR(errp, "could not create rdma event channel"); 2385 rdma->error_state = -EINVAL; 2386 return -1; 2387 } 2388 2389 /* create CM id */ 2390 ret = rdma_create_id(rdma->channel, &listen_id, NULL, RDMA_PS_TCP); 2391 if (ret) { 2392 ERROR(errp, "could not create cm_id!"); 2393 goto err_dest_init_create_listen_id; 2394 } 2395 2396 snprintf(port_str, 16, "%d", rdma->port); 2397 port_str[15] = '\0'; 2398 2399 ret = rdma_getaddrinfo(rdma->host, port_str, NULL, &res); 2400 if (ret < 0) { 2401 ERROR(errp, "could not rdma_getaddrinfo address %s", rdma->host); 2402 goto err_dest_init_bind_addr; 2403 } 2404 2405 for (e = res; e != NULL; e = e->ai_next) { 2406 inet_ntop(e->ai_family, 2407 &((struct sockaddr_in *) e->ai_dst_addr)->sin_addr, ip, sizeof ip); 2408 trace_qemu_rdma_dest_init_trying(rdma->host, ip); 2409 ret = rdma_bind_addr(listen_id, e->ai_dst_addr); 2410 if (ret) { 2411 continue; 2412 } 2413 if (e->ai_family == AF_INET6) { 2414 ret = qemu_rdma_broken_ipv6_kernel(errp, listen_id->verbs); 2415 if (ret) { 2416 continue; 2417 } 2418 } 2419 break; 2420 } 2421 2422 if (!e) { 2423 ERROR(errp, "Error: could not rdma_bind_addr!"); 2424 goto err_dest_init_bind_addr; 2425 } 2426 2427 rdma->listen_id = listen_id; 2428 qemu_rdma_dump_gid("dest_init", listen_id); 2429 return 0; 2430 2431 err_dest_init_bind_addr: 2432 rdma_destroy_id(listen_id); 2433 err_dest_init_create_listen_id: 2434 rdma_destroy_event_channel(rdma->channel); 2435 rdma->channel = NULL; 2436 rdma->error_state = ret; 2437 return ret; 2438 2439 } 2440 2441 static void *qemu_rdma_data_init(const char *host_port, Error **errp) 2442 { 2443 RDMAContext *rdma = NULL; 2444 InetSocketAddress *addr; 2445 2446 if (host_port) { 2447 rdma = g_malloc0(sizeof(RDMAContext)); 2448 memset(rdma, 0, sizeof(RDMAContext)); 2449 rdma->current_index = -1; 2450 rdma->current_chunk = -1; 2451 2452 addr = inet_parse(host_port, NULL); 2453 if (addr != NULL) { 2454 rdma->port = atoi(addr->port); 2455 rdma->host = g_strdup(addr->host); 2456 } else { 2457 ERROR(errp, "bad RDMA migration address '%s'", host_port); 2458 g_free(rdma); 2459 rdma = NULL; 2460 } 2461 2462 qapi_free_InetSocketAddress(addr); 2463 } 2464 2465 return rdma; 2466 } 2467 2468 /* 2469 * QEMUFile interface to the control channel. 2470 * SEND messages for control only. 2471 * VM's ram is handled with regular RDMA messages. 2472 */ 2473 static int qemu_rdma_put_buffer(void *opaque, const uint8_t *buf, 2474 int64_t pos, int size) 2475 { 2476 QEMUFileRDMA *r = opaque; 2477 QEMUFile *f = r->file; 2478 RDMAContext *rdma = r->rdma; 2479 size_t remaining = size; 2480 uint8_t * data = (void *) buf; 2481 int ret; 2482 2483 CHECK_ERROR_STATE(); 2484 2485 /* 2486 * Push out any writes that 2487 * we're queued up for VM's ram. 2488 */ 2489 ret = qemu_rdma_write_flush(f, rdma); 2490 if (ret < 0) { 2491 rdma->error_state = ret; 2492 return ret; 2493 } 2494 2495 while (remaining) { 2496 RDMAControlHeader head; 2497 2498 r->len = MIN(remaining, RDMA_SEND_INCREMENT); 2499 remaining -= r->len; 2500 2501 head.len = r->len; 2502 head.type = RDMA_CONTROL_QEMU_FILE; 2503 2504 ret = qemu_rdma_exchange_send(rdma, &head, data, NULL, NULL, NULL); 2505 2506 if (ret < 0) { 2507 rdma->error_state = ret; 2508 return ret; 2509 } 2510 2511 data += r->len; 2512 } 2513 2514 return size; 2515 } 2516 2517 static size_t qemu_rdma_fill(RDMAContext *rdma, uint8_t *buf, 2518 int size, int idx) 2519 { 2520 size_t len = 0; 2521 2522 if (rdma->wr_data[idx].control_len) { 2523 trace_qemu_rdma_fill(rdma->wr_data[idx].control_len, size); 2524 2525 len = MIN(size, rdma->wr_data[idx].control_len); 2526 memcpy(buf, rdma->wr_data[idx].control_curr, len); 2527 rdma->wr_data[idx].control_curr += len; 2528 rdma->wr_data[idx].control_len -= len; 2529 } 2530 2531 return len; 2532 } 2533 2534 /* 2535 * QEMUFile interface to the control channel. 2536 * RDMA links don't use bytestreams, so we have to 2537 * return bytes to QEMUFile opportunistically. 2538 */ 2539 static int qemu_rdma_get_buffer(void *opaque, uint8_t *buf, 2540 int64_t pos, int size) 2541 { 2542 QEMUFileRDMA *r = opaque; 2543 RDMAContext *rdma = r->rdma; 2544 RDMAControlHeader head; 2545 int ret = 0; 2546 2547 CHECK_ERROR_STATE(); 2548 2549 /* 2550 * First, we hold on to the last SEND message we 2551 * were given and dish out the bytes until we run 2552 * out of bytes. 2553 */ 2554 r->len = qemu_rdma_fill(r->rdma, buf, size, 0); 2555 if (r->len) { 2556 return r->len; 2557 } 2558 2559 /* 2560 * Once we run out, we block and wait for another 2561 * SEND message to arrive. 2562 */ 2563 ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_QEMU_FILE); 2564 2565 if (ret < 0) { 2566 rdma->error_state = ret; 2567 return ret; 2568 } 2569 2570 /* 2571 * SEND was received with new bytes, now try again. 2572 */ 2573 return qemu_rdma_fill(r->rdma, buf, size, 0); 2574 } 2575 2576 /* 2577 * Block until all the outstanding chunks have been delivered by the hardware. 2578 */ 2579 static int qemu_rdma_drain_cq(QEMUFile *f, RDMAContext *rdma) 2580 { 2581 int ret; 2582 2583 if (qemu_rdma_write_flush(f, rdma) < 0) { 2584 return -EIO; 2585 } 2586 2587 while (rdma->nb_sent) { 2588 ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL); 2589 if (ret < 0) { 2590 error_report("rdma migration: complete polling error!"); 2591 return -EIO; 2592 } 2593 } 2594 2595 qemu_rdma_unregister_waiting(rdma); 2596 2597 return 0; 2598 } 2599 2600 static int qemu_rdma_close(void *opaque) 2601 { 2602 trace_qemu_rdma_close(); 2603 QEMUFileRDMA *r = opaque; 2604 if (r->rdma) { 2605 qemu_rdma_cleanup(r->rdma); 2606 g_free(r->rdma); 2607 } 2608 g_free(r); 2609 return 0; 2610 } 2611 2612 /* 2613 * Parameters: 2614 * @offset == 0 : 2615 * This means that 'block_offset' is a full virtual address that does not 2616 * belong to a RAMBlock of the virtual machine and instead 2617 * represents a private malloc'd memory area that the caller wishes to 2618 * transfer. 2619 * 2620 * @offset != 0 : 2621 * Offset is an offset to be added to block_offset and used 2622 * to also lookup the corresponding RAMBlock. 2623 * 2624 * @size > 0 : 2625 * Initiate an transfer this size. 2626 * 2627 * @size == 0 : 2628 * A 'hint' or 'advice' that means that we wish to speculatively 2629 * and asynchronously unregister this memory. In this case, there is no 2630 * guarantee that the unregister will actually happen, for example, 2631 * if the memory is being actively transmitted. Additionally, the memory 2632 * may be re-registered at any future time if a write within the same 2633 * chunk was requested again, even if you attempted to unregister it 2634 * here. 2635 * 2636 * @size < 0 : TODO, not yet supported 2637 * Unregister the memory NOW. This means that the caller does not 2638 * expect there to be any future RDMA transfers and we just want to clean 2639 * things up. This is used in case the upper layer owns the memory and 2640 * cannot wait for qemu_fclose() to occur. 2641 * 2642 * @bytes_sent : User-specificed pointer to indicate how many bytes were 2643 * sent. Usually, this will not be more than a few bytes of 2644 * the protocol because most transfers are sent asynchronously. 2645 */ 2646 static size_t qemu_rdma_save_page(QEMUFile *f, void *opaque, 2647 ram_addr_t block_offset, ram_addr_t offset, 2648 size_t size, uint64_t *bytes_sent) 2649 { 2650 QEMUFileRDMA *rfile = opaque; 2651 RDMAContext *rdma = rfile->rdma; 2652 int ret; 2653 2654 CHECK_ERROR_STATE(); 2655 2656 qemu_fflush(f); 2657 2658 if (size > 0) { 2659 /* 2660 * Add this page to the current 'chunk'. If the chunk 2661 * is full, or the page doen't belong to the current chunk, 2662 * an actual RDMA write will occur and a new chunk will be formed. 2663 */ 2664 ret = qemu_rdma_write(f, rdma, block_offset, offset, size); 2665 if (ret < 0) { 2666 error_report("rdma migration: write error! %d", ret); 2667 goto err; 2668 } 2669 2670 /* 2671 * We always return 1 bytes because the RDMA 2672 * protocol is completely asynchronous. We do not yet know 2673 * whether an identified chunk is zero or not because we're 2674 * waiting for other pages to potentially be merged with 2675 * the current chunk. So, we have to call qemu_update_position() 2676 * later on when the actual write occurs. 2677 */ 2678 if (bytes_sent) { 2679 *bytes_sent = 1; 2680 } 2681 } else { 2682 uint64_t index, chunk; 2683 2684 /* TODO: Change QEMUFileOps prototype to be signed: size_t => long 2685 if (size < 0) { 2686 ret = qemu_rdma_drain_cq(f, rdma); 2687 if (ret < 0) { 2688 fprintf(stderr, "rdma: failed to synchronously drain" 2689 " completion queue before unregistration.\n"); 2690 goto err; 2691 } 2692 } 2693 */ 2694 2695 ret = qemu_rdma_search_ram_block(rdma, block_offset, 2696 offset, size, &index, &chunk); 2697 2698 if (ret) { 2699 error_report("ram block search failed"); 2700 goto err; 2701 } 2702 2703 qemu_rdma_signal_unregister(rdma, index, chunk, 0); 2704 2705 /* 2706 * TODO: Synchronous, guaranteed unregistration (should not occur during 2707 * fast-path). Otherwise, unregisters will process on the next call to 2708 * qemu_rdma_drain_cq() 2709 if (size < 0) { 2710 qemu_rdma_unregister_waiting(rdma); 2711 } 2712 */ 2713 } 2714 2715 /* 2716 * Drain the Completion Queue if possible, but do not block, 2717 * just poll. 2718 * 2719 * If nothing to poll, the end of the iteration will do this 2720 * again to make sure we don't overflow the request queue. 2721 */ 2722 while (1) { 2723 uint64_t wr_id, wr_id_in; 2724 int ret = qemu_rdma_poll(rdma, &wr_id_in, NULL); 2725 if (ret < 0) { 2726 error_report("rdma migration: polling error! %d", ret); 2727 goto err; 2728 } 2729 2730 wr_id = wr_id_in & RDMA_WRID_TYPE_MASK; 2731 2732 if (wr_id == RDMA_WRID_NONE) { 2733 break; 2734 } 2735 } 2736 2737 return RAM_SAVE_CONTROL_DELAYED; 2738 err: 2739 rdma->error_state = ret; 2740 return ret; 2741 } 2742 2743 static int qemu_rdma_accept(RDMAContext *rdma) 2744 { 2745 RDMACapabilities cap; 2746 struct rdma_conn_param conn_param = { 2747 .responder_resources = 2, 2748 .private_data = &cap, 2749 .private_data_len = sizeof(cap), 2750 }; 2751 struct rdma_cm_event *cm_event; 2752 struct ibv_context *verbs; 2753 int ret = -EINVAL; 2754 int idx; 2755 2756 ret = rdma_get_cm_event(rdma->channel, &cm_event); 2757 if (ret) { 2758 goto err_rdma_dest_wait; 2759 } 2760 2761 if (cm_event->event != RDMA_CM_EVENT_CONNECT_REQUEST) { 2762 rdma_ack_cm_event(cm_event); 2763 goto err_rdma_dest_wait; 2764 } 2765 2766 memcpy(&cap, cm_event->param.conn.private_data, sizeof(cap)); 2767 2768 network_to_caps(&cap); 2769 2770 if (cap.version < 1 || cap.version > RDMA_CONTROL_VERSION_CURRENT) { 2771 error_report("Unknown source RDMA version: %d, bailing...", 2772 cap.version); 2773 rdma_ack_cm_event(cm_event); 2774 goto err_rdma_dest_wait; 2775 } 2776 2777 /* 2778 * Respond with only the capabilities this version of QEMU knows about. 2779 */ 2780 cap.flags &= known_capabilities; 2781 2782 /* 2783 * Enable the ones that we do know about. 2784 * Add other checks here as new ones are introduced. 2785 */ 2786 if (cap.flags & RDMA_CAPABILITY_PIN_ALL) { 2787 rdma->pin_all = true; 2788 } 2789 2790 rdma->cm_id = cm_event->id; 2791 verbs = cm_event->id->verbs; 2792 2793 rdma_ack_cm_event(cm_event); 2794 2795 trace_qemu_rdma_accept_pin_state(rdma->pin_all); 2796 2797 caps_to_network(&cap); 2798 2799 trace_qemu_rdma_accept_pin_verbsc(verbs); 2800 2801 if (!rdma->verbs) { 2802 rdma->verbs = verbs; 2803 } else if (rdma->verbs != verbs) { 2804 error_report("ibv context not matching %p, %p!", rdma->verbs, 2805 verbs); 2806 goto err_rdma_dest_wait; 2807 } 2808 2809 qemu_rdma_dump_id("dest_init", verbs); 2810 2811 ret = qemu_rdma_alloc_pd_cq(rdma); 2812 if (ret) { 2813 error_report("rdma migration: error allocating pd and cq!"); 2814 goto err_rdma_dest_wait; 2815 } 2816 2817 ret = qemu_rdma_alloc_qp(rdma); 2818 if (ret) { 2819 error_report("rdma migration: error allocating qp!"); 2820 goto err_rdma_dest_wait; 2821 } 2822 2823 ret = qemu_rdma_init_ram_blocks(rdma); 2824 if (ret) { 2825 error_report("rdma migration: error initializing ram blocks!"); 2826 goto err_rdma_dest_wait; 2827 } 2828 2829 for (idx = 0; idx < RDMA_WRID_MAX; idx++) { 2830 ret = qemu_rdma_reg_control(rdma, idx); 2831 if (ret) { 2832 error_report("rdma: error registering %d control", idx); 2833 goto err_rdma_dest_wait; 2834 } 2835 } 2836 2837 qemu_set_fd_handler2(rdma->channel->fd, NULL, NULL, NULL, NULL); 2838 2839 ret = rdma_accept(rdma->cm_id, &conn_param); 2840 if (ret) { 2841 error_report("rdma_accept returns %d", ret); 2842 goto err_rdma_dest_wait; 2843 } 2844 2845 ret = rdma_get_cm_event(rdma->channel, &cm_event); 2846 if (ret) { 2847 error_report("rdma_accept get_cm_event failed %d", ret); 2848 goto err_rdma_dest_wait; 2849 } 2850 2851 if (cm_event->event != RDMA_CM_EVENT_ESTABLISHED) { 2852 error_report("rdma_accept not event established"); 2853 rdma_ack_cm_event(cm_event); 2854 goto err_rdma_dest_wait; 2855 } 2856 2857 rdma_ack_cm_event(cm_event); 2858 rdma->connected = true; 2859 2860 ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY); 2861 if (ret) { 2862 error_report("rdma migration: error posting second control recv"); 2863 goto err_rdma_dest_wait; 2864 } 2865 2866 qemu_rdma_dump_gid("dest_connect", rdma->cm_id); 2867 2868 return 0; 2869 2870 err_rdma_dest_wait: 2871 rdma->error_state = ret; 2872 qemu_rdma_cleanup(rdma); 2873 return ret; 2874 } 2875 2876 /* 2877 * During each iteration of the migration, we listen for instructions 2878 * by the source VM to perform dynamic page registrations before they 2879 * can perform RDMA operations. 2880 * 2881 * We respond with the 'rkey'. 2882 * 2883 * Keep doing this until the source tells us to stop. 2884 */ 2885 static int qemu_rdma_registration_handle(QEMUFile *f, void *opaque, 2886 uint64_t flags) 2887 { 2888 RDMAControlHeader reg_resp = { .len = sizeof(RDMARegisterResult), 2889 .type = RDMA_CONTROL_REGISTER_RESULT, 2890 .repeat = 0, 2891 }; 2892 RDMAControlHeader unreg_resp = { .len = 0, 2893 .type = RDMA_CONTROL_UNREGISTER_FINISHED, 2894 .repeat = 0, 2895 }; 2896 RDMAControlHeader blocks = { .type = RDMA_CONTROL_RAM_BLOCKS_RESULT, 2897 .repeat = 1 }; 2898 QEMUFileRDMA *rfile = opaque; 2899 RDMAContext *rdma = rfile->rdma; 2900 RDMALocalBlocks *local = &rdma->local_ram_blocks; 2901 RDMAControlHeader head; 2902 RDMARegister *reg, *registers; 2903 RDMACompress *comp; 2904 RDMARegisterResult *reg_result; 2905 static RDMARegisterResult results[RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE]; 2906 RDMALocalBlock *block; 2907 void *host_addr; 2908 int ret = 0; 2909 int idx = 0; 2910 int count = 0; 2911 int i = 0; 2912 2913 CHECK_ERROR_STATE(); 2914 2915 do { 2916 trace_qemu_rdma_registration_handle_wait(flags); 2917 2918 ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_NONE); 2919 2920 if (ret < 0) { 2921 break; 2922 } 2923 2924 if (head.repeat > RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE) { 2925 error_report("rdma: Too many requests in this message (%d)." 2926 "Bailing.", head.repeat); 2927 ret = -EIO; 2928 break; 2929 } 2930 2931 switch (head.type) { 2932 case RDMA_CONTROL_COMPRESS: 2933 comp = (RDMACompress *) rdma->wr_data[idx].control_curr; 2934 network_to_compress(comp); 2935 2936 trace_qemu_rdma_registration_handle_compress(comp->length, 2937 comp->block_idx, 2938 comp->offset); 2939 block = &(rdma->local_ram_blocks.block[comp->block_idx]); 2940 2941 host_addr = block->local_host_addr + 2942 (comp->offset - block->offset); 2943 2944 ram_handle_compressed(host_addr, comp->value, comp->length); 2945 break; 2946 2947 case RDMA_CONTROL_REGISTER_FINISHED: 2948 trace_qemu_rdma_registration_handle_finished(); 2949 goto out; 2950 2951 case RDMA_CONTROL_RAM_BLOCKS_REQUEST: 2952 trace_qemu_rdma_registration_handle_ram_blocks(); 2953 2954 if (rdma->pin_all) { 2955 ret = qemu_rdma_reg_whole_ram_blocks(rdma); 2956 if (ret) { 2957 error_report("rdma migration: error dest " 2958 "registering ram blocks"); 2959 goto out; 2960 } 2961 } 2962 2963 /* 2964 * Dest uses this to prepare to transmit the RAMBlock descriptions 2965 * to the source VM after connection setup. 2966 * Both sides use the "remote" structure to communicate and update 2967 * their "local" descriptions with what was sent. 2968 */ 2969 for (i = 0; i < local->nb_blocks; i++) { 2970 rdma->block[i].remote_host_addr = 2971 (uintptr_t)(local->block[i].local_host_addr); 2972 2973 if (rdma->pin_all) { 2974 rdma->block[i].remote_rkey = local->block[i].mr->rkey; 2975 } 2976 2977 rdma->block[i].offset = local->block[i].offset; 2978 rdma->block[i].length = local->block[i].length; 2979 2980 remote_block_to_network(&rdma->block[i]); 2981 } 2982 2983 blocks.len = rdma->local_ram_blocks.nb_blocks 2984 * sizeof(RDMARemoteBlock); 2985 2986 2987 ret = qemu_rdma_post_send_control(rdma, 2988 (uint8_t *) rdma->block, &blocks); 2989 2990 if (ret < 0) { 2991 error_report("rdma migration: error sending remote info"); 2992 goto out; 2993 } 2994 2995 break; 2996 case RDMA_CONTROL_REGISTER_REQUEST: 2997 trace_qemu_rdma_registration_handle_register(head.repeat); 2998 2999 reg_resp.repeat = head.repeat; 3000 registers = (RDMARegister *) rdma->wr_data[idx].control_curr; 3001 3002 for (count = 0; count < head.repeat; count++) { 3003 uint64_t chunk; 3004 uint8_t *chunk_start, *chunk_end; 3005 3006 reg = ®isters[count]; 3007 network_to_register(reg); 3008 3009 reg_result = &results[count]; 3010 3011 trace_qemu_rdma_registration_handle_register_loop(count, 3012 reg->current_index, reg->key.current_addr, reg->chunks); 3013 3014 block = &(rdma->local_ram_blocks.block[reg->current_index]); 3015 if (block->is_ram_block) { 3016 host_addr = (block->local_host_addr + 3017 (reg->key.current_addr - block->offset)); 3018 chunk = ram_chunk_index(block->local_host_addr, 3019 (uint8_t *) host_addr); 3020 } else { 3021 chunk = reg->key.chunk; 3022 host_addr = block->local_host_addr + 3023 (reg->key.chunk * (1UL << RDMA_REG_CHUNK_SHIFT)); 3024 } 3025 chunk_start = ram_chunk_start(block, chunk); 3026 chunk_end = ram_chunk_end(block, chunk + reg->chunks); 3027 if (qemu_rdma_register_and_get_keys(rdma, block, 3028 (uintptr_t)host_addr, NULL, ®_result->rkey, 3029 chunk, chunk_start, chunk_end)) { 3030 error_report("cannot get rkey"); 3031 ret = -EINVAL; 3032 goto out; 3033 } 3034 3035 reg_result->host_addr = (uintptr_t)block->local_host_addr; 3036 3037 trace_qemu_rdma_registration_handle_register_rkey( 3038 reg_result->rkey); 3039 3040 result_to_network(reg_result); 3041 } 3042 3043 ret = qemu_rdma_post_send_control(rdma, 3044 (uint8_t *) results, ®_resp); 3045 3046 if (ret < 0) { 3047 error_report("Failed to send control buffer"); 3048 goto out; 3049 } 3050 break; 3051 case RDMA_CONTROL_UNREGISTER_REQUEST: 3052 trace_qemu_rdma_registration_handle_unregister(head.repeat); 3053 unreg_resp.repeat = head.repeat; 3054 registers = (RDMARegister *) rdma->wr_data[idx].control_curr; 3055 3056 for (count = 0; count < head.repeat; count++) { 3057 reg = ®isters[count]; 3058 network_to_register(reg); 3059 3060 trace_qemu_rdma_registration_handle_unregister_loop(count, 3061 reg->current_index, reg->key.chunk); 3062 3063 block = &(rdma->local_ram_blocks.block[reg->current_index]); 3064 3065 ret = ibv_dereg_mr(block->pmr[reg->key.chunk]); 3066 block->pmr[reg->key.chunk] = NULL; 3067 3068 if (ret != 0) { 3069 perror("rdma unregistration chunk failed"); 3070 ret = -ret; 3071 goto out; 3072 } 3073 3074 rdma->total_registrations--; 3075 3076 trace_qemu_rdma_registration_handle_unregister_success( 3077 reg->key.chunk); 3078 } 3079 3080 ret = qemu_rdma_post_send_control(rdma, NULL, &unreg_resp); 3081 3082 if (ret < 0) { 3083 error_report("Failed to send control buffer"); 3084 goto out; 3085 } 3086 break; 3087 case RDMA_CONTROL_REGISTER_RESULT: 3088 error_report("Invalid RESULT message at dest."); 3089 ret = -EIO; 3090 goto out; 3091 default: 3092 error_report("Unknown control message %s", control_desc[head.type]); 3093 ret = -EIO; 3094 goto out; 3095 } 3096 } while (1); 3097 out: 3098 if (ret < 0) { 3099 rdma->error_state = ret; 3100 } 3101 return ret; 3102 } 3103 3104 static int qemu_rdma_registration_start(QEMUFile *f, void *opaque, 3105 uint64_t flags) 3106 { 3107 QEMUFileRDMA *rfile = opaque; 3108 RDMAContext *rdma = rfile->rdma; 3109 3110 CHECK_ERROR_STATE(); 3111 3112 trace_qemu_rdma_registration_start(flags); 3113 qemu_put_be64(f, RAM_SAVE_FLAG_HOOK); 3114 qemu_fflush(f); 3115 3116 return 0; 3117 } 3118 3119 /* 3120 * Inform dest that dynamic registrations are done for now. 3121 * First, flush writes, if any. 3122 */ 3123 static int qemu_rdma_registration_stop(QEMUFile *f, void *opaque, 3124 uint64_t flags) 3125 { 3126 Error *local_err = NULL, **errp = &local_err; 3127 QEMUFileRDMA *rfile = opaque; 3128 RDMAContext *rdma = rfile->rdma; 3129 RDMAControlHeader head = { .len = 0, .repeat = 1 }; 3130 int ret = 0; 3131 3132 CHECK_ERROR_STATE(); 3133 3134 qemu_fflush(f); 3135 ret = qemu_rdma_drain_cq(f, rdma); 3136 3137 if (ret < 0) { 3138 goto err; 3139 } 3140 3141 if (flags == RAM_CONTROL_SETUP) { 3142 RDMAControlHeader resp = {.type = RDMA_CONTROL_RAM_BLOCKS_RESULT }; 3143 RDMALocalBlocks *local = &rdma->local_ram_blocks; 3144 int reg_result_idx, i, j, nb_remote_blocks; 3145 3146 head.type = RDMA_CONTROL_RAM_BLOCKS_REQUEST; 3147 trace_qemu_rdma_registration_stop_ram(); 3148 3149 /* 3150 * Make sure that we parallelize the pinning on both sides. 3151 * For very large guests, doing this serially takes a really 3152 * long time, so we have to 'interleave' the pinning locally 3153 * with the control messages by performing the pinning on this 3154 * side before we receive the control response from the other 3155 * side that the pinning has completed. 3156 */ 3157 ret = qemu_rdma_exchange_send(rdma, &head, NULL, &resp, 3158 ®_result_idx, rdma->pin_all ? 3159 qemu_rdma_reg_whole_ram_blocks : NULL); 3160 if (ret < 0) { 3161 ERROR(errp, "receiving remote info!"); 3162 return ret; 3163 } 3164 3165 nb_remote_blocks = resp.len / sizeof(RDMARemoteBlock); 3166 3167 /* 3168 * The protocol uses two different sets of rkeys (mutually exclusive): 3169 * 1. One key to represent the virtual address of the entire ram block. 3170 * (dynamic chunk registration disabled - pin everything with one rkey.) 3171 * 2. One to represent individual chunks within a ram block. 3172 * (dynamic chunk registration enabled - pin individual chunks.) 3173 * 3174 * Once the capability is successfully negotiated, the destination transmits 3175 * the keys to use (or sends them later) including the virtual addresses 3176 * and then propagates the remote ram block descriptions to his local copy. 3177 */ 3178 3179 if (local->nb_blocks != nb_remote_blocks) { 3180 ERROR(errp, "ram blocks mismatch #1! " 3181 "Your QEMU command line parameters are probably " 3182 "not identical on both the source and destination."); 3183 return -EINVAL; 3184 } 3185 3186 qemu_rdma_move_header(rdma, reg_result_idx, &resp); 3187 memcpy(rdma->block, 3188 rdma->wr_data[reg_result_idx].control_curr, resp.len); 3189 for (i = 0; i < nb_remote_blocks; i++) { 3190 network_to_remote_block(&rdma->block[i]); 3191 3192 /* search local ram blocks */ 3193 for (j = 0; j < local->nb_blocks; j++) { 3194 if (rdma->block[i].offset != local->block[j].offset) { 3195 continue; 3196 } 3197 3198 if (rdma->block[i].length != local->block[j].length) { 3199 ERROR(errp, "ram blocks mismatch #2! " 3200 "Your QEMU command line parameters are probably " 3201 "not identical on both the source and destination."); 3202 return -EINVAL; 3203 } 3204 local->block[j].remote_host_addr = 3205 rdma->block[i].remote_host_addr; 3206 local->block[j].remote_rkey = rdma->block[i].remote_rkey; 3207 break; 3208 } 3209 3210 if (j >= local->nb_blocks) { 3211 ERROR(errp, "ram blocks mismatch #3! " 3212 "Your QEMU command line parameters are probably " 3213 "not identical on both the source and destination."); 3214 return -EINVAL; 3215 } 3216 } 3217 } 3218 3219 trace_qemu_rdma_registration_stop(flags); 3220 3221 head.type = RDMA_CONTROL_REGISTER_FINISHED; 3222 ret = qemu_rdma_exchange_send(rdma, &head, NULL, NULL, NULL, NULL); 3223 3224 if (ret < 0) { 3225 goto err; 3226 } 3227 3228 return 0; 3229 err: 3230 rdma->error_state = ret; 3231 return ret; 3232 } 3233 3234 static int qemu_rdma_get_fd(void *opaque) 3235 { 3236 QEMUFileRDMA *rfile = opaque; 3237 RDMAContext *rdma = rfile->rdma; 3238 3239 return rdma->comp_channel->fd; 3240 } 3241 3242 static const QEMUFileOps rdma_read_ops = { 3243 .get_buffer = qemu_rdma_get_buffer, 3244 .get_fd = qemu_rdma_get_fd, 3245 .close = qemu_rdma_close, 3246 .hook_ram_load = qemu_rdma_registration_handle, 3247 }; 3248 3249 static const QEMUFileOps rdma_write_ops = { 3250 .put_buffer = qemu_rdma_put_buffer, 3251 .close = qemu_rdma_close, 3252 .before_ram_iterate = qemu_rdma_registration_start, 3253 .after_ram_iterate = qemu_rdma_registration_stop, 3254 .save_page = qemu_rdma_save_page, 3255 }; 3256 3257 static void *qemu_fopen_rdma(RDMAContext *rdma, const char *mode) 3258 { 3259 QEMUFileRDMA *r = g_malloc0(sizeof(QEMUFileRDMA)); 3260 3261 if (qemu_file_mode_is_not_valid(mode)) { 3262 return NULL; 3263 } 3264 3265 r->rdma = rdma; 3266 3267 if (mode[0] == 'w') { 3268 r->file = qemu_fopen_ops(r, &rdma_write_ops); 3269 } else { 3270 r->file = qemu_fopen_ops(r, &rdma_read_ops); 3271 } 3272 3273 return r->file; 3274 } 3275 3276 static void rdma_accept_incoming_migration(void *opaque) 3277 { 3278 RDMAContext *rdma = opaque; 3279 int ret; 3280 QEMUFile *f; 3281 Error *local_err = NULL, **errp = &local_err; 3282 3283 trace_qemu_dma_accept_incoming_migration(); 3284 ret = qemu_rdma_accept(rdma); 3285 3286 if (ret) { 3287 ERROR(errp, "RDMA Migration initialization failed!"); 3288 return; 3289 } 3290 3291 trace_qemu_dma_accept_incoming_migration_accepted(); 3292 3293 f = qemu_fopen_rdma(rdma, "rb"); 3294 if (f == NULL) { 3295 ERROR(errp, "could not qemu_fopen_rdma!"); 3296 qemu_rdma_cleanup(rdma); 3297 return; 3298 } 3299 3300 rdma->migration_started_on_destination = 1; 3301 process_incoming_migration(f); 3302 } 3303 3304 void rdma_start_incoming_migration(const char *host_port, Error **errp) 3305 { 3306 int ret; 3307 RDMAContext *rdma; 3308 Error *local_err = NULL; 3309 3310 trace_rdma_start_incoming_migration(); 3311 rdma = qemu_rdma_data_init(host_port, &local_err); 3312 3313 if (rdma == NULL) { 3314 goto err; 3315 } 3316 3317 ret = qemu_rdma_dest_init(rdma, &local_err); 3318 3319 if (ret) { 3320 goto err; 3321 } 3322 3323 trace_rdma_start_incoming_migration_after_dest_init(); 3324 3325 ret = rdma_listen(rdma->listen_id, 5); 3326 3327 if (ret) { 3328 ERROR(errp, "listening on socket!"); 3329 goto err; 3330 } 3331 3332 trace_rdma_start_incoming_migration_after_rdma_listen(); 3333 3334 qemu_set_fd_handler2(rdma->channel->fd, NULL, 3335 rdma_accept_incoming_migration, NULL, 3336 (void *)(intptr_t) rdma); 3337 return; 3338 err: 3339 error_propagate(errp, local_err); 3340 g_free(rdma); 3341 } 3342 3343 void rdma_start_outgoing_migration(void *opaque, 3344 const char *host_port, Error **errp) 3345 { 3346 MigrationState *s = opaque; 3347 Error *local_err = NULL, **temp = &local_err; 3348 RDMAContext *rdma = qemu_rdma_data_init(host_port, &local_err); 3349 int ret = 0; 3350 3351 if (rdma == NULL) { 3352 ERROR(temp, "Failed to initialize RDMA data structures! %d", ret); 3353 goto err; 3354 } 3355 3356 ret = qemu_rdma_source_init(rdma, &local_err, 3357 s->enabled_capabilities[MIGRATION_CAPABILITY_RDMA_PIN_ALL]); 3358 3359 if (ret) { 3360 goto err; 3361 } 3362 3363 trace_rdma_start_outgoing_migration_after_rdma_source_init(); 3364 ret = qemu_rdma_connect(rdma, &local_err); 3365 3366 if (ret) { 3367 goto err; 3368 } 3369 3370 trace_rdma_start_outgoing_migration_after_rdma_connect(); 3371 3372 s->file = qemu_fopen_rdma(rdma, "wb"); 3373 migrate_fd_connect(s); 3374 return; 3375 err: 3376 error_propagate(errp, local_err); 3377 g_free(rdma); 3378 migrate_fd_error(s); 3379 } 3380