rdma.c 115.3 KB
Newer Older
M
Michael R. Hines 已提交
1 2 3 4
/*
 * RDMA protocol and interfaces
 *
 * Copyright IBM, Corp. 2010-2013
5
 * Copyright Red Hat, Inc. 2015-2016
M
Michael R. Hines 已提交
6 7 8 9
 *
 * Authors:
 *  Michael R. Hines <mrhines@us.ibm.com>
 *  Jiuxing Liu <jl@us.ibm.com>
10
 *  Daniel P. Berrange <berrange@redhat.com>
M
Michael R. Hines 已提交
11 12 13 14 15
 *
 * This work is licensed under the terms of the GNU GPL, version 2 or
 * later.  See the COPYING file in the top-level directory.
 *
 */
P
Peter Maydell 已提交
16
#include "qemu/osdep.h"
17
#include "qapi/error.h"
M
Michael R. Hines 已提交
18
#include "qemu-common.h"
19
#include "qemu/cutils.h"
20
#include "rdma.h"
21
#include "migration.h"
J
Juan Quintela 已提交
22
#include "qemu-file.h"
23
#include "ram.h"
24
#include "qemu-file-channel.h"
25
#include "qemu/error-report.h"
M
Michael R. Hines 已提交
26 27 28
#include "qemu/main-loop.h"
#include "qemu/sockets.h"
#include "qemu/bitmap.h"
29
#include "qemu/coroutine.h"
M
Michael R. Hines 已提交
30 31 32 33
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <rdma/rdma_cma.h>
34
#include "trace.h"
M
Michael R. Hines 已提交
35 36 37 38 39 40

/*
 * Print and error on both the Monitor and the Log file.
 */
#define ERROR(errp, fmt, ...) \
    do { \
41
        fprintf(stderr, "RDMA ERROR: " fmt "\n", ## __VA_ARGS__); \
M
Michael R. Hines 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
        if (errp && (*(errp) == NULL)) { \
            error_setg(errp, "RDMA ERROR: " fmt, ## __VA_ARGS__); \
        } \
    } while (0)

#define RDMA_RESOLVE_TIMEOUT_MS 10000

/* Do not merge data if larger than this. */
#define RDMA_MERGE_MAX (2 * 1024 * 1024)
#define RDMA_SIGNALED_SEND_MAX (RDMA_MERGE_MAX / 4096)

#define RDMA_REG_CHUNK_SHIFT 20 /* 1 MB */

/*
 * This is only for non-live state being migrated.
 * Instead of RDMA_WRITE messages, we use RDMA_SEND
 * messages for that state, which requires a different
 * delivery design than main memory.
 */
#define RDMA_SEND_INCREMENT 32768

/*
 * Maximum size infiniband SEND message
 */
#define RDMA_CONTROL_MAX_BUFFER (512 * 1024)
#define RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE 4096

#define RDMA_CONTROL_VERSION_CURRENT 1
/*
 * Capabilities for negotiation.
 */
#define RDMA_CAPABILITY_PIN_ALL 0x01

/*
 * Add the other flags above to this list of known capabilities
 * as they are introduced.
 */
static uint32_t known_capabilities = RDMA_CAPABILITY_PIN_ALL;

#define CHECK_ERROR_STATE() \
    do { \
        if (rdma->error_state) { \
            if (!rdma->error_reported) { \
85 86
                error_report("RDMA is in an error state waiting migration" \
                                " to abort!"); \
M
Michael R. Hines 已提交
87 88 89 90
                rdma->error_reported = 1; \
            } \
            return rdma->error_state; \
        } \
91
    } while (0)
M
Michael R. Hines 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

/*
 * A work request ID is 64-bits and we split up these bits
 * into 3 parts:
 *
 * bits 0-15 : type of control message, 2^16
 * bits 16-29: ram block index, 2^14
 * bits 30-63: ram block chunk number, 2^34
 *
 * The last two bit ranges are only used for RDMA writes,
 * in order to track their completion and potentially
 * also track unregistration status of the message.
 */
#define RDMA_WRID_TYPE_SHIFT  0UL
#define RDMA_WRID_BLOCK_SHIFT 16UL
#define RDMA_WRID_CHUNK_SHIFT 30UL

#define RDMA_WRID_TYPE_MASK \
    ((1UL << RDMA_WRID_BLOCK_SHIFT) - 1UL)

#define RDMA_WRID_BLOCK_MASK \
    (~RDMA_WRID_TYPE_MASK & ((1UL << RDMA_WRID_CHUNK_SHIFT) - 1UL))

#define RDMA_WRID_CHUNK_MASK (~RDMA_WRID_BLOCK_MASK & ~RDMA_WRID_TYPE_MASK)

/*
 * RDMA migration protocol:
 * 1. RDMA Writes (data messages, i.e. RAM)
 * 2. IB Send/Recv (control channel messages)
 */
enum {
    RDMA_WRID_NONE = 0,
    RDMA_WRID_RDMA_WRITE = 1,
    RDMA_WRID_SEND_CONTROL = 2000,
    RDMA_WRID_RECV_CONTROL = 4000,
};

129
static const char *wrid_desc[] = {
M
Michael R. Hines 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
    [RDMA_WRID_NONE] = "NONE",
    [RDMA_WRID_RDMA_WRITE] = "WRITE RDMA",
    [RDMA_WRID_SEND_CONTROL] = "CONTROL SEND",
    [RDMA_WRID_RECV_CONTROL] = "CONTROL RECV",
};

/*
 * Work request IDs for IB SEND messages only (not RDMA writes).
 * This is used by the migration protocol to transmit
 * control messages (such as device state and registration commands)
 *
 * We could use more WRs, but we have enough for now.
 */
enum {
    RDMA_WRID_READY = 0,
    RDMA_WRID_DATA,
    RDMA_WRID_CONTROL,
    RDMA_WRID_MAX,
};

/*
 * SEND/RECV IB Control Messages.
 */
enum {
    RDMA_CONTROL_NONE = 0,
    RDMA_CONTROL_ERROR,
    RDMA_CONTROL_READY,               /* ready to receive */
    RDMA_CONTROL_QEMU_FILE,           /* QEMUFile-transmitted bytes */
    RDMA_CONTROL_RAM_BLOCKS_REQUEST,  /* RAMBlock synchronization */
    RDMA_CONTROL_RAM_BLOCKS_RESULT,   /* RAMBlock synchronization */
    RDMA_CONTROL_COMPRESS,            /* page contains repeat values */
    RDMA_CONTROL_REGISTER_REQUEST,    /* dynamic page registration */
    RDMA_CONTROL_REGISTER_RESULT,     /* key to use after registration */
    RDMA_CONTROL_REGISTER_FINISHED,   /* current iteration finished */
    RDMA_CONTROL_UNREGISTER_REQUEST,  /* dynamic UN-registration */
    RDMA_CONTROL_UNREGISTER_FINISHED, /* unpinning finished */
};


/*
 * Memory and MR structures used to represent an IB Send/Recv work request.
 * This is *not* used for RDMA writes, only IB Send/Recv.
 */
typedef struct {
    uint8_t  control[RDMA_CONTROL_MAX_BUFFER]; /* actual buffer to register */
    struct   ibv_mr *control_mr;               /* registration metadata */
    size_t   control_len;                      /* length of the message */
    uint8_t *control_curr;                     /* start of unconsumed bytes */
} RDMAWorkRequestData;

/*
 * Negotiate RDMA capabilities during connection-setup time.
 */
typedef struct {
    uint32_t version;
    uint32_t flags;
} RDMACapabilities;

static void caps_to_network(RDMACapabilities *cap)
{
    cap->version = htonl(cap->version);
    cap->flags = htonl(cap->flags);
}

static void network_to_caps(RDMACapabilities *cap)
{
    cap->version = ntohl(cap->version);
    cap->flags = ntohl(cap->flags);
}

/*
 * Representation of a RAMBlock from an RDMA perspective.
 * This is not transmitted, only local.
 * This and subsequent structures cannot be linked lists
 * because we're using a single IB message to transmit
 * the information. It's small anyway, so a list is overkill.
 */
typedef struct RDMALocalBlock {
208 209 210 211 212 213 214 215 216 217
    char          *block_name;
    uint8_t       *local_host_addr; /* local virtual address */
    uint64_t       remote_host_addr; /* remote virtual address */
    uint64_t       offset;
    uint64_t       length;
    struct         ibv_mr **pmr;    /* MRs for chunk-level registration */
    struct         ibv_mr *mr;      /* MR for non-chunk-level registration */
    uint32_t      *remote_keys;     /* rkeys for chunk-level registration */
    uint32_t       remote_rkey;     /* rkeys for non-chunk-level registration */
    int            index;           /* which block are we */
218
    unsigned int   src_index;       /* (Only used on dest) */
219 220
    bool           is_ram_block;
    int            nb_chunks;
M
Michael R. Hines 已提交
221 222 223 224 225 226 227 228 229 230 231
    unsigned long *transit_bitmap;
    unsigned long *unregister_bitmap;
} RDMALocalBlock;

/*
 * Also represents a RAMblock, but only on the dest.
 * This gets transmitted by the dest during connection-time
 * to the source VM and then is used to populate the
 * corresponding RDMALocalBlock with
 * the information needed to perform the actual RDMA.
 */
232
typedef struct QEMU_PACKED RDMADestBlock {
M
Michael R. Hines 已提交
233 234 235 236 237
    uint64_t remote_host_addr;
    uint64_t offset;
    uint64_t length;
    uint32_t remote_rkey;
    uint32_t padding;
238
} RDMADestBlock;
M
Michael R. Hines 已提交
239

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
static const char *control_desc(unsigned int rdma_control)
{
    static const char *strs[] = {
        [RDMA_CONTROL_NONE] = "NONE",
        [RDMA_CONTROL_ERROR] = "ERROR",
        [RDMA_CONTROL_READY] = "READY",
        [RDMA_CONTROL_QEMU_FILE] = "QEMU FILE",
        [RDMA_CONTROL_RAM_BLOCKS_REQUEST] = "RAM BLOCKS REQUEST",
        [RDMA_CONTROL_RAM_BLOCKS_RESULT] = "RAM BLOCKS RESULT",
        [RDMA_CONTROL_COMPRESS] = "COMPRESS",
        [RDMA_CONTROL_REGISTER_REQUEST] = "REGISTER REQUEST",
        [RDMA_CONTROL_REGISTER_RESULT] = "REGISTER RESULT",
        [RDMA_CONTROL_REGISTER_FINISHED] = "REGISTER FINISHED",
        [RDMA_CONTROL_UNREGISTER_REQUEST] = "UNREGISTER REQUEST",
        [RDMA_CONTROL_UNREGISTER_FINISHED] = "UNREGISTER FINISHED",
    };

    if (rdma_control > RDMA_CONTROL_UNREGISTER_FINISHED) {
        return "??BAD CONTROL VALUE??";
    }

    return strs[rdma_control];
}

M
Michael R. Hines 已提交
264 265 266 267 268 269 270 271 272 273 274 275 276 277
static uint64_t htonll(uint64_t v)
{
    union { uint32_t lv[2]; uint64_t llv; } u;
    u.lv[0] = htonl(v >> 32);
    u.lv[1] = htonl(v & 0xFFFFFFFFULL);
    return u.llv;
}

static uint64_t ntohll(uint64_t v) {
    union { uint32_t lv[2]; uint64_t llv; } u;
    u.llv = v;
    return ((uint64_t)ntohl(u.lv[0]) << 32) | (uint64_t) ntohl(u.lv[1]);
}

278
static void dest_block_to_network(RDMADestBlock *db)
M
Michael R. Hines 已提交
279
{
280 281 282 283
    db->remote_host_addr = htonll(db->remote_host_addr);
    db->offset = htonll(db->offset);
    db->length = htonll(db->length);
    db->remote_rkey = htonl(db->remote_rkey);
M
Michael R. Hines 已提交
284 285
}

286
static void network_to_dest_block(RDMADestBlock *db)
M
Michael R. Hines 已提交
287
{
288 289 290 291
    db->remote_host_addr = ntohll(db->remote_host_addr);
    db->offset = ntohll(db->offset);
    db->length = ntohll(db->length);
    db->remote_rkey = ntohl(db->remote_rkey);
M
Michael R. Hines 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
}

/*
 * Virtual address of the above structures used for transmitting
 * the RAMBlock descriptions at connection-time.
 * This structure is *not* transmitted.
 */
typedef struct RDMALocalBlocks {
    int nb_blocks;
    bool     init;             /* main memory init complete */
    RDMALocalBlock *block;
} RDMALocalBlocks;

/*
 * Main data structure for RDMA state.
 * While there is only one copy of this structure being allocated right now,
 * this is the place where one would start if you wanted to consider
 * having more than one RDMA connection open at the same time.
 */
typedef struct RDMAContext {
    char *host;
    int port;

315
    RDMAWorkRequestData wr_data[RDMA_WRID_MAX];
M
Michael R. Hines 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348

    /*
     * This is used by *_exchange_send() to figure out whether or not
     * the initial "READY" message has already been received or not.
     * This is because other functions may potentially poll() and detect
     * the READY message before send() does, in which case we need to
     * know if it completed.
     */
    int control_ready_expected;

    /* number of outstanding writes */
    int nb_sent;

    /* store info about current buffer so that we can
       merge it with future sends */
    uint64_t current_addr;
    uint64_t current_length;
    /* index of ram block the current buffer belongs to */
    int current_index;
    /* index of the chunk in the current ram block */
    int current_chunk;

    bool pin_all;

    /*
     * infiniband-specific variables for opening the device
     * and maintaining connection state and so forth.
     *
     * cm_id also has ibv_context, rdma_event_channel, and ibv_qp in
     * cm_id->verbs, cm_id->channel, and cm_id->qp.
     */
    struct rdma_cm_id *cm_id;               /* connection manager ID */
    struct rdma_cm_id *listen_id;
349
    bool connected;
M
Michael R. Hines 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364

    struct ibv_context          *verbs;
    struct rdma_event_channel   *channel;
    struct ibv_qp *qp;                      /* queue pair */
    struct ibv_comp_channel *comp_channel;  /* completion channel */
    struct ibv_pd *pd;                      /* protection domain */
    struct ibv_cq *cq;                      /* completion queue */

    /*
     * If a previous write failed (perhaps because of a failed
     * memory registration, then do not attempt any future work
     * and remember the error state.
     */
    int error_state;
    int error_reported;
365
    int received_error;
M
Michael R. Hines 已提交
366 367 368 369 370

    /*
     * Description of ram blocks used throughout the code.
     */
    RDMALocalBlocks local_ram_blocks;
371
    RDMADestBlock  *dest_blocks;
M
Michael R. Hines 已提交
372

373 374 375
    /* Index of the next RAMBlock received during block registration */
    unsigned int    next_src_index;

M
Michael R. Hines 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
    /*
     * Migration on *destination* started.
     * Then use coroutine yield function.
     * Source runs in a thread, so we don't care.
     */
    int migration_started_on_destination;

    int total_registrations;
    int total_writes;

    int unregister_current, unregister_next;
    uint64_t unregistrations[RDMA_SIGNALED_SEND_MAX];

    GHashTable *blockmap;
} RDMAContext;

392 393 394 395 396 397 398 399 400
#define TYPE_QIO_CHANNEL_RDMA "qio-channel-rdma"
#define QIO_CHANNEL_RDMA(obj)                                     \
    OBJECT_CHECK(QIOChannelRDMA, (obj), TYPE_QIO_CHANNEL_RDMA)

typedef struct QIOChannelRDMA QIOChannelRDMA;


struct QIOChannelRDMA {
    QIOChannel parent;
M
Michael R. Hines 已提交
401
    RDMAContext *rdma;
402
    QEMUFile *file;
M
Michael R. Hines 已提交
403
    size_t len;
404 405
    bool blocking; /* XXX we don't actually honour this yet */
};
M
Michael R. Hines 已提交
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439

/*
 * Main structure for IB Send/Recv control messages.
 * This gets prepended at the beginning of every Send/Recv.
 */
typedef struct QEMU_PACKED {
    uint32_t len;     /* Total length of data portion */
    uint32_t type;    /* which control command to perform */
    uint32_t repeat;  /* number of commands in data portion of same type */
    uint32_t padding;
} RDMAControlHeader;

static void control_to_network(RDMAControlHeader *control)
{
    control->type = htonl(control->type);
    control->len = htonl(control->len);
    control->repeat = htonl(control->repeat);
}

static void network_to_control(RDMAControlHeader *control)
{
    control->type = ntohl(control->type);
    control->len = ntohl(control->len);
    control->repeat = ntohl(control->repeat);
}

/*
 * Register a single Chunk.
 * Information sent by the source VM to inform the dest
 * to register an single chunk of memory before we can perform
 * the actual RDMA operation.
 */
typedef struct QEMU_PACKED {
    union QEMU_PACKED {
440
        uint64_t current_addr;  /* offset into the ram_addr_t space */
M
Michael R. Hines 已提交
441 442 443 444 445 446 447
        uint64_t chunk;         /* chunk to lookup if unregistering */
    } key;
    uint32_t current_index; /* which ramblock the chunk belongs to */
    uint32_t padding;
    uint64_t chunks;            /* how many sequential chunks to register */
} RDMARegister;

448
static void register_to_network(RDMAContext *rdma, RDMARegister *reg)
M
Michael R. Hines 已提交
449
{
450 451 452 453 454 455 456 457 458 459 460
    RDMALocalBlock *local_block;
    local_block  = &rdma->local_ram_blocks.block[reg->current_index];

    if (local_block->is_ram_block) {
        /*
         * current_addr as passed in is an address in the local ram_addr_t
         * space, we need to translate this for the destination
         */
        reg->key.current_addr -= local_block->offset;
        reg->key.current_addr += rdma->dest_blocks[reg->current_index].offset;
    }
M
Michael R. Hines 已提交
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
    reg->key.current_addr = htonll(reg->key.current_addr);
    reg->current_index = htonl(reg->current_index);
    reg->chunks = htonll(reg->chunks);
}

static void network_to_register(RDMARegister *reg)
{
    reg->key.current_addr = ntohll(reg->key.current_addr);
    reg->current_index = ntohl(reg->current_index);
    reg->chunks = ntohll(reg->chunks);
}

typedef struct QEMU_PACKED {
    uint32_t value;     /* if zero, we will madvise() */
    uint32_t block_idx; /* which ram block index */
476
    uint64_t offset;    /* Address in remote ram_addr_t space */
M
Michael R. Hines 已提交
477 478 479
    uint64_t length;    /* length of the chunk */
} RDMACompress;

480
static void compress_to_network(RDMAContext *rdma, RDMACompress *comp)
M
Michael R. Hines 已提交
481 482
{
    comp->value = htonl(comp->value);
483 484 485 486 487 488
    /*
     * comp->offset as passed in is an address in the local ram_addr_t
     * space, we need to translate this for the destination
     */
    comp->offset -= rdma->local_ram_blocks.block[comp->block_idx].offset;
    comp->offset += rdma->dest_blocks[comp->block_idx].offset;
M
Michael R. Hines 已提交
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
    comp->block_idx = htonl(comp->block_idx);
    comp->offset = htonll(comp->offset);
    comp->length = htonll(comp->length);
}

static void network_to_compress(RDMACompress *comp)
{
    comp->value = ntohl(comp->value);
    comp->block_idx = ntohl(comp->block_idx);
    comp->offset = ntohll(comp->offset);
    comp->length = ntohll(comp->length);
}

/*
 * The result of the dest's memory registration produces an "rkey"
 * which the source VM must reference in order to perform
 * the RDMA operation.
 */
typedef struct QEMU_PACKED {
    uint32_t rkey;
    uint32_t padding;
    uint64_t host_addr;
} RDMARegisterResult;

static void result_to_network(RDMARegisterResult *result)
{
    result->rkey = htonl(result->rkey);
    result->host_addr = htonll(result->host_addr);
};

static void network_to_result(RDMARegisterResult *result)
{
    result->rkey = ntohl(result->rkey);
    result->host_addr = ntohll(result->host_addr);
};

const char *print_wrid(int wrid);
static int qemu_rdma_exchange_send(RDMAContext *rdma, RDMAControlHeader *head,
                                   uint8_t *data, RDMAControlHeader *resp,
                                   int *resp_idx,
                                   int (*callback)(RDMAContext *rdma));

531 532
static inline uint64_t ram_chunk_index(const uint8_t *start,
                                       const uint8_t *host)
M
Michael R. Hines 已提交
533 534 535 536
{
    return ((uintptr_t) host - (uintptr_t) start) >> RDMA_REG_CHUNK_SHIFT;
}

537
static inline uint8_t *ram_chunk_start(const RDMALocalBlock *rdma_ram_block,
M
Michael R. Hines 已提交
538 539
                                       uint64_t i)
{
540 541
    return (uint8_t *)(uintptr_t)(rdma_ram_block->local_host_addr +
                                  (i << RDMA_REG_CHUNK_SHIFT));
M
Michael R. Hines 已提交
542 543
}

544 545
static inline uint8_t *ram_chunk_end(const RDMALocalBlock *rdma_ram_block,
                                     uint64_t i)
M
Michael R. Hines 已提交
546 547 548 549 550 551 552 553 554 555 556
{
    uint8_t *result = ram_chunk_start(rdma_ram_block, i) +
                                         (1UL << RDMA_REG_CHUNK_SHIFT);

    if (result > (rdma_ram_block->local_host_addr + rdma_ram_block->length)) {
        result = rdma_ram_block->local_host_addr + rdma_ram_block->length;
    }

    return result;
}

557 558
static int rdma_add_block(RDMAContext *rdma, const char *block_name,
                         void *host_addr,
M
Michael R. Hines 已提交
559 560 561
                         ram_addr_t block_offset, uint64_t length)
{
    RDMALocalBlocks *local = &rdma->local_ram_blocks;
D
Dr. David Alan Gilbert 已提交
562
    RDMALocalBlock *block;
M
Michael R. Hines 已提交
563 564
    RDMALocalBlock *old = local->block;

565
    local->block = g_new0(RDMALocalBlock, local->nb_blocks + 1);
M
Michael R. Hines 已提交
566 567 568 569

    if (local->nb_blocks) {
        int x;

D
Dr. David Alan Gilbert 已提交
570 571 572 573 574 575 576 577
        if (rdma->blockmap) {
            for (x = 0; x < local->nb_blocks; x++) {
                g_hash_table_remove(rdma->blockmap,
                                    (void *)(uintptr_t)old[x].offset);
                g_hash_table_insert(rdma->blockmap,
                                    (void *)(uintptr_t)old[x].offset,
                                    &local->block[x]);
            }
M
Michael R. Hines 已提交
578 579 580 581 582 583 584
        }
        memcpy(local->block, old, sizeof(RDMALocalBlock) * local->nb_blocks);
        g_free(old);
    }

    block = &local->block[local->nb_blocks];

585
    block->block_name = g_strdup(block_name);
M
Michael R. Hines 已提交
586 587 588 589
    block->local_host_addr = host_addr;
    block->offset = block_offset;
    block->length = length;
    block->index = local->nb_blocks;
590
    block->src_index = ~0U; /* Filled in by the receipt of the block list */
M
Michael R. Hines 已提交
591 592 593 594 595
    block->nb_chunks = ram_chunk_index(host_addr, host_addr + length) + 1UL;
    block->transit_bitmap = bitmap_new(block->nb_chunks);
    bitmap_clear(block->transit_bitmap, 0, block->nb_chunks);
    block->unregister_bitmap = bitmap_new(block->nb_chunks);
    bitmap_clear(block->unregister_bitmap, 0, block->nb_chunks);
596
    block->remote_keys = g_new0(uint32_t, block->nb_chunks);
M
Michael R. Hines 已提交
597 598 599

    block->is_ram_block = local->init ? false : true;

D
Dr. David Alan Gilbert 已提交
600
    if (rdma->blockmap) {
601
        g_hash_table_insert(rdma->blockmap, (void *)(uintptr_t)block_offset, block);
D
Dr. David Alan Gilbert 已提交
602
    }
M
Michael R. Hines 已提交
603

604 605
    trace_rdma_add_block(block_name, local->nb_blocks,
                         (uintptr_t) block->local_host_addr,
606
                         block->offset, block->length,
607
                         (uintptr_t) (block->local_host_addr + block->length),
608 609 610
                         BITS_TO_LONGS(block->nb_chunks) *
                             sizeof(unsigned long) * 8,
                         block->nb_chunks);
M
Michael R. Hines 已提交
611 612 613 614 615 616 617 618 619 620 621

    local->nb_blocks++;

    return 0;
}

/*
 * Memory regions need to be registered with the device and queue pairs setup
 * in advanced before the migration starts. This tells us where the RAM blocks
 * are so that we can register them individually.
 */
622
static int qemu_rdma_init_one_block(const char *block_name, void *host_addr,
M
Michael R. Hines 已提交
623 624
    ram_addr_t block_offset, ram_addr_t length, void *opaque)
{
625
    return rdma_add_block(opaque, block_name, host_addr, block_offset, length);
M
Michael R. Hines 已提交
626 627 628 629 630 631 632 633 634 635 636 637 638 639
}

/*
 * Identify the RAMBlocks and their quantity. They will be references to
 * identify chunk boundaries inside each RAMBlock and also be referenced
 * during dynamic page registration.
 */
static int qemu_rdma_init_ram_blocks(RDMAContext *rdma)
{
    RDMALocalBlocks *local = &rdma->local_ram_blocks;

    assert(rdma->blockmap == NULL);
    memset(local, 0, sizeof *local);
    qemu_ram_foreach_block(qemu_rdma_init_one_block, rdma);
640
    trace_qemu_rdma_init_ram_blocks(local->nb_blocks);
641 642
    rdma->dest_blocks = g_new0(RDMADestBlock,
                               rdma->local_ram_blocks.nb_blocks);
M
Michael R. Hines 已提交
643 644 645 646
    local->init = true;
    return 0;
}

647 648 649 650 651
/*
 * Note: If used outside of cleanup, the caller must ensure that the destination
 * block structures are also updated
 */
static int rdma_delete_block(RDMAContext *rdma, RDMALocalBlock *block)
M
Michael R. Hines 已提交
652 653 654 655 656
{
    RDMALocalBlocks *local = &rdma->local_ram_blocks;
    RDMALocalBlock *old = local->block;
    int x;

657 658 659
    if (rdma->blockmap) {
        g_hash_table_remove(rdma->blockmap, (void *)(uintptr_t)block->offset);
    }
M
Michael R. Hines 已提交
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
    if (block->pmr) {
        int j;

        for (j = 0; j < block->nb_chunks; j++) {
            if (!block->pmr[j]) {
                continue;
            }
            ibv_dereg_mr(block->pmr[j]);
            rdma->total_registrations--;
        }
        g_free(block->pmr);
        block->pmr = NULL;
    }

    if (block->mr) {
        ibv_dereg_mr(block->mr);
        rdma->total_registrations--;
        block->mr = NULL;
    }

    g_free(block->transit_bitmap);
    block->transit_bitmap = NULL;

    g_free(block->unregister_bitmap);
    block->unregister_bitmap = NULL;

    g_free(block->remote_keys);
    block->remote_keys = NULL;

689 690 691
    g_free(block->block_name);
    block->block_name = NULL;

692 693 694 695 696
    if (rdma->blockmap) {
        for (x = 0; x < local->nb_blocks; x++) {
            g_hash_table_remove(rdma->blockmap,
                                (void *)(uintptr_t)old[x].offset);
        }
M
Michael R. Hines 已提交
697 698 699 700
    }

    if (local->nb_blocks > 1) {

701
        local->block = g_new0(RDMALocalBlock, local->nb_blocks - 1);
M
Michael R. Hines 已提交
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716

        if (block->index) {
            memcpy(local->block, old, sizeof(RDMALocalBlock) * block->index);
        }

        if (block->index < (local->nb_blocks - 1)) {
            memcpy(local->block + block->index, old + (block->index + 1),
                sizeof(RDMALocalBlock) *
                    (local->nb_blocks - (block->index + 1)));
        }
    } else {
        assert(block == local->block);
        local->block = NULL;
    }

717
    trace_rdma_delete_block(block, (uintptr_t)block->local_host_addr,
718
                           block->offset, block->length,
719
                            (uintptr_t)(block->local_host_addr + block->length),
720 721
                           BITS_TO_LONGS(block->nb_chunks) *
                               sizeof(unsigned long) * 8, block->nb_chunks);
M
Michael R. Hines 已提交
722 723 724 725 726

    g_free(old);

    local->nb_blocks--;

727
    if (local->nb_blocks && rdma->blockmap) {
M
Michael R. Hines 已提交
728
        for (x = 0; x < local->nb_blocks; x++) {
729 730 731
            g_hash_table_insert(rdma->blockmap,
                                (void *)(uintptr_t)local->block[x].offset,
                                &local->block[x]);
M
Michael R. Hines 已提交
732 733 734 735 736 737 738 739 740 741 742 743
        }
    }

    return 0;
}

/*
 * Put in the log file which RDMA device was opened and the details
 * associated with that device.
 */
static void qemu_rdma_dump_id(const char *who, struct ibv_context *verbs)
{
744 745 746
    struct ibv_port_attr port;

    if (ibv_query_port(verbs, 1, &port)) {
747
        error_report("Failed to query port information");
748 749 750
        return;
    }

M
Michael R. Hines 已提交
751 752
    printf("%s RDMA Device opened: kernel name %s "
           "uverbs device name %s, "
753 754 755
           "infiniband_verbs class device path %s, "
           "infiniband class device path %s, "
           "transport: (%d) %s\n",
M
Michael R. Hines 已提交
756 757 758 759
                who,
                verbs->device->name,
                verbs->device->dev_name,
                verbs->device->dev_path,
760 761 762
                verbs->device->ibdev_path,
                port.link_layer,
                (port.link_layer == IBV_LINK_LAYER_INFINIBAND) ? "Infiniband" :
763
                 ((port.link_layer == IBV_LINK_LAYER_ETHERNET)
764
                    ? "Ethernet" : "Unknown"));
M
Michael R. Hines 已提交
765 766 767 768 769 770 771 772 773 774 775 776 777
}

/*
 * Put in the log file the RDMA gid addressing information,
 * useful for folks who have trouble understanding the
 * RDMA device hierarchy in the kernel.
 */
static void qemu_rdma_dump_gid(const char *who, struct rdma_cm_id *id)
{
    char sgid[33];
    char dgid[33];
    inet_ntop(AF_INET6, &id->route.addr.addr.ibaddr.sgid, sgid, sizeof sgid);
    inet_ntop(AF_INET6, &id->route.addr.addr.ibaddr.dgid, dgid, sizeof dgid);
778
    trace_qemu_rdma_dump_gid(who, sgid, dgid);
M
Michael R. Hines 已提交
779 780
}

781 782 783 784 785 786 787 788 789 790 791 792
/*
 * As of now, IPv6 over RoCE / iWARP is not supported by linux.
 * We will try the next addrinfo struct, and fail if there are
 * no other valid addresses to bind against.
 *
 * If user is listening on '[::]', then we will not have a opened a device
 * yet and have no way of verifying if the device is RoCE or not.
 *
 * In this case, the source VM will throw an error for ALL types of
 * connections (both IPv4 and IPv6) if the destination machine does not have
 * a regular infiniband network available for use.
 *
793
 * The only way to guarantee that an error is thrown for broken kernels is
794 795 796 797
 * for the management software to choose a *specific* interface at bind time
 * and validate what time of hardware it is.
 *
 * Unfortunately, this puts the user in a fix:
798
 *
799 800
 *  If the source VM connects with an IPv4 address without knowing that the
 *  destination has bound to '[::]' the migration will unconditionally fail
801
 *  unless the management software is explicitly listening on the IPv4
802 803 804 805
 *  address while using a RoCE-based device.
 *
 *  If the source VM connects with an IPv6 address, then we're OK because we can
 *  throw an error on the source (and similarly on the destination).
806
 *
807 808 809 810 811
 *  But in mixed environments, this will be broken for a while until it is fixed
 *  inside linux.
 *
 * We do provide a *tiny* bit of help in this function: We can list all of the
 * devices in the system and check to see if all the devices are RoCE or
812
 * Infiniband.
813 814
 *
 * If we detect that we have a *pure* RoCE environment, then we can safely
815
 * thrown an error even if the management software has specified '[::]' as the
816 817 818 819 820 821 822 823
 * bind address.
 *
 * However, if there is are multiple hetergeneous devices, then we cannot make
 * this assumption and the user just has to be sure they know what they are
 * doing.
 *
 * Patches are being reviewed on linux-rdma.
 */
824
static int qemu_rdma_broken_ipv6_kernel(struct ibv_context *verbs, Error **errp)
825 826 827 828 829 830
{
    struct ibv_port_attr port_attr;

    /* This bug only exists in linux, to our knowledge. */
#ifdef CONFIG_LINUX

831
    /*
832
     * Verbs are only NULL if management has bound to '[::]'.
833
     *
834 835
     * Let's iterate through all the devices and see if there any pure IB
     * devices (non-ethernet).
836
     *
837
     * If not, then we can safely proceed with the migration.
838
     * Otherwise, there are no guarantees until the bug is fixed in linux.
839 840
     */
    if (!verbs) {
841
        int num_devices, x;
842 843 844 845 846 847
        struct ibv_device ** dev_list = ibv_get_device_list(&num_devices);
        bool roce_found = false;
        bool ib_found = false;

        for (x = 0; x < num_devices; x++) {
            verbs = ibv_open_device(dev_list[x]);
848 849 850 851 852 853 854
            if (!verbs) {
                if (errno == EPERM) {
                    continue;
                } else {
                    return -EINVAL;
                }
            }
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892

            if (ibv_query_port(verbs, 1, &port_attr)) {
                ibv_close_device(verbs);
                ERROR(errp, "Could not query initial IB port");
                return -EINVAL;
            }

            if (port_attr.link_layer == IBV_LINK_LAYER_INFINIBAND) {
                ib_found = true;
            } else if (port_attr.link_layer == IBV_LINK_LAYER_ETHERNET) {
                roce_found = true;
            }

            ibv_close_device(verbs);

        }

        if (roce_found) {
            if (ib_found) {
                fprintf(stderr, "WARN: migrations may fail:"
                                " IPv6 over RoCE / iWARP in linux"
                                " is broken. But since you appear to have a"
                                " mixed RoCE / IB environment, be sure to only"
                                " migrate over the IB fabric until the kernel "
                                " fixes the bug.\n");
            } else {
                ERROR(errp, "You only have RoCE / iWARP devices in your systems"
                            " and your management software has specified '[::]'"
                            ", but IPv6 over RoCE / iWARP is not supported in Linux.");
                return -ENONET;
            }
        }

        return 0;
    }

    /*
     * If we have a verbs context, that means that some other than '[::]' was
893 894
     * used by the management software for binding. In which case we can
     * actually warn the user about a potentially broken kernel.
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
     */

    /* IB ports start with 1, not 0 */
    if (ibv_query_port(verbs, 1, &port_attr)) {
        ERROR(errp, "Could not query initial IB port");
        return -EINVAL;
    }

    if (port_attr.link_layer == IBV_LINK_LAYER_ETHERNET) {
        ERROR(errp, "Linux kernel's RoCE / iWARP does not support IPv6 "
                    "(but patches on linux-rdma in progress)");
        return -ENONET;
    }

#endif

    return 0;
}

M
Michael R. Hines 已提交
914 915 916 917 918 919 920 921
/*
 * Figure out which RDMA device corresponds to the requested IP hostname
 * Also create the initial connection manager identifiers for opening
 * the connection.
 */
static int qemu_rdma_resolve_host(RDMAContext *rdma, Error **errp)
{
    int ret;
922
    struct rdma_addrinfo *res;
M
Michael R. Hines 已提交
923 924 925
    char port_str[16];
    struct rdma_cm_event *cm_event;
    char ip[40] = "unknown";
926
    struct rdma_addrinfo *e;
M
Michael R. Hines 已提交
927 928

    if (rdma->host == NULL || !strcmp(rdma->host, "")) {
929
        ERROR(errp, "RDMA hostname has not been set");
930
        return -EINVAL;
M
Michael R. Hines 已提交
931 932 933 934 935
    }

    /* create CM channel */
    rdma->channel = rdma_create_event_channel();
    if (!rdma->channel) {
936
        ERROR(errp, "could not create CM channel");
937
        return -EINVAL;
M
Michael R. Hines 已提交
938 939 940 941 942
    }

    /* create CM id */
    ret = rdma_create_id(rdma->channel, &rdma->cm_id, NULL, RDMA_PS_TCP);
    if (ret) {
943
        ERROR(errp, "could not create channel id");
M
Michael R. Hines 已提交
944 945 946 947 948 949
        goto err_resolve_create_id;
    }

    snprintf(port_str, 16, "%d", rdma->port);
    port_str[15] = '\0';

950
    ret = rdma_getaddrinfo(rdma->host, port_str, NULL, &res);
M
Michael R. Hines 已提交
951
    if (ret < 0) {
952
        ERROR(errp, "could not rdma_getaddrinfo address %s", rdma->host);
M
Michael R. Hines 已提交
953 954 955
        goto err_resolve_get_addr;
    }

956 957
    for (e = res; e != NULL; e = e->ai_next) {
        inet_ntop(e->ai_family,
958
            &((struct sockaddr_in *) e->ai_dst_addr)->sin_addr, ip, sizeof ip);
959
        trace_qemu_rdma_resolve_host_trying(rdma->host, ip);
M
Michael R. Hines 已提交
960

961
        ret = rdma_resolve_addr(rdma->cm_id, NULL, e->ai_dst_addr,
962 963
                RDMA_RESOLVE_TIMEOUT_MS);
        if (!ret) {
M
Michael R. Hines 已提交
964
            if (e->ai_family == AF_INET6) {
965
                ret = qemu_rdma_broken_ipv6_kernel(rdma->cm_id->verbs, errp);
M
Michael R. Hines 已提交
966 967 968
                if (ret) {
                    continue;
                }
969
            }
970 971
            goto route;
        }
M
Michael R. Hines 已提交
972 973
    }

974 975 976 977
    ERROR(errp, "could not resolve address %s", rdma->host);
    goto err_resolve_get_addr;

route:
M
Michael R. Hines 已提交
978 979 980 981
    qemu_rdma_dump_gid("source_resolve_addr", rdma->cm_id);

    ret = rdma_get_cm_event(rdma->channel, &cm_event);
    if (ret) {
982
        ERROR(errp, "could not perform event_addr_resolved");
M
Michael R. Hines 已提交
983 984 985 986
        goto err_resolve_get_addr;
    }

    if (cm_event->event != RDMA_CM_EVENT_ADDR_RESOLVED) {
987
        ERROR(errp, "result not equal to event_addr_resolved %s",
M
Michael R. Hines 已提交
988 989
                rdma_event_str(cm_event->event));
        perror("rdma_resolve_addr");
G
Gonglei 已提交
990
        rdma_ack_cm_event(cm_event);
991
        ret = -EINVAL;
M
Michael R. Hines 已提交
992 993 994 995 996 997 998
        goto err_resolve_get_addr;
    }
    rdma_ack_cm_event(cm_event);

    /* resolve route */
    ret = rdma_resolve_route(rdma->cm_id, RDMA_RESOLVE_TIMEOUT_MS);
    if (ret) {
999
        ERROR(errp, "could not resolve rdma route");
M
Michael R. Hines 已提交
1000 1001 1002 1003 1004
        goto err_resolve_get_addr;
    }

    ret = rdma_get_cm_event(rdma->channel, &cm_event);
    if (ret) {
1005
        ERROR(errp, "could not perform event_route_resolved");
M
Michael R. Hines 已提交
1006 1007 1008
        goto err_resolve_get_addr;
    }
    if (cm_event->event != RDMA_CM_EVENT_ROUTE_RESOLVED) {
1009
        ERROR(errp, "result not equal to event_route_resolved: %s",
M
Michael R. Hines 已提交
1010 1011
                        rdma_event_str(cm_event->event));
        rdma_ack_cm_event(cm_event);
1012
        ret = -EINVAL;
M
Michael R. Hines 已提交
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
        goto err_resolve_get_addr;
    }
    rdma_ack_cm_event(cm_event);
    rdma->verbs = rdma->cm_id->verbs;
    qemu_rdma_dump_id("source_resolve_host", rdma->cm_id->verbs);
    qemu_rdma_dump_gid("source_resolve_host", rdma->cm_id);
    return 0;

err_resolve_get_addr:
    rdma_destroy_id(rdma->cm_id);
    rdma->cm_id = NULL;
err_resolve_create_id:
    rdma_destroy_event_channel(rdma->channel);
    rdma->channel = NULL;
1027
    return ret;
M
Michael R. Hines 已提交
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
}

/*
 * Create protection domain and completion queues
 */
static int qemu_rdma_alloc_pd_cq(RDMAContext *rdma)
{
    /* allocate pd */
    rdma->pd = ibv_alloc_pd(rdma->verbs);
    if (!rdma->pd) {
1038
        error_report("failed to allocate protection domain");
M
Michael R. Hines 已提交
1039 1040 1041 1042 1043 1044
        return -1;
    }

    /* create completion channel */
    rdma->comp_channel = ibv_create_comp_channel(rdma->verbs);
    if (!rdma->comp_channel) {
1045
        error_report("failed to allocate completion channel");
M
Michael R. Hines 已提交
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
        goto err_alloc_pd_cq;
    }

    /*
     * Completion queue can be filled by both read and write work requests,
     * so must reflect the sum of both possible queue sizes.
     */
    rdma->cq = ibv_create_cq(rdma->verbs, (RDMA_SIGNALED_SEND_MAX * 3),
            NULL, rdma->comp_channel, 0);
    if (!rdma->cq) {
1056
        error_report("failed to allocate completion queue");
M
Michael R. Hines 已提交
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
        goto err_alloc_pd_cq;
    }

    return 0;

err_alloc_pd_cq:
    if (rdma->pd) {
        ibv_dealloc_pd(rdma->pd);
    }
    if (rdma->comp_channel) {
        ibv_destroy_comp_channel(rdma->comp_channel);
    }
    rdma->pd = NULL;
    rdma->comp_channel = NULL;
    return -1;

}

/*
 * Create queue pairs.
 */
static int qemu_rdma_alloc_qp(RDMAContext *rdma)
{
    struct ibv_qp_init_attr attr = { 0 };
    int ret;

    attr.cap.max_send_wr = RDMA_SIGNALED_SEND_MAX;
    attr.cap.max_recv_wr = 3;
    attr.cap.max_send_sge = 1;
    attr.cap.max_recv_sge = 1;
    attr.send_cq = rdma->cq;
    attr.recv_cq = rdma->cq;
    attr.qp_type = IBV_QPT_RC;

    ret = rdma_create_qp(rdma->cm_id, rdma->pd, &attr);
    if (ret) {
        return -1;
    }

    rdma->qp = rdma->cm_id->qp;
    return 0;
}

static int qemu_rdma_reg_whole_ram_blocks(RDMAContext *rdma)
{
    int i;
    RDMALocalBlocks *local = &rdma->local_ram_blocks;

    for (i = 0; i < local->nb_blocks; i++) {
        local->block[i].mr =
            ibv_reg_mr(rdma->pd,
                    local->block[i].local_host_addr,
                    local->block[i].length,
                    IBV_ACCESS_LOCAL_WRITE |
                    IBV_ACCESS_REMOTE_WRITE
                    );
        if (!local->block[i].mr) {
            perror("Failed to register local dest ram block!\n");
            break;
        }
        rdma->total_registrations++;
    }

    if (i >= local->nb_blocks) {
        return 0;
    }

    for (i--; i >= 0; i--) {
        ibv_dereg_mr(local->block[i].mr);
        rdma->total_registrations--;
    }

    return -1;

}

/*
 * Find the ram block that corresponds to the page requested to be
 * transmitted by QEMU.
 *
 * Once the block is found, also identify which 'chunk' within that
 * block that the page belongs to.
 *
 * This search cannot fail or the migration will fail.
 */
static int qemu_rdma_search_ram_block(RDMAContext *rdma,
1143
                                      uintptr_t block_offset,
M
Michael R. Hines 已提交
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
                                      uint64_t offset,
                                      uint64_t length,
                                      uint64_t *block_index,
                                      uint64_t *chunk_index)
{
    uint64_t current_addr = block_offset + offset;
    RDMALocalBlock *block = g_hash_table_lookup(rdma->blockmap,
                                                (void *) block_offset);
    assert(block);
    assert(current_addr >= block->offset);
    assert((current_addr + length) <= (block->offset + block->length));

    *block_index = block->index;
    *chunk_index = ram_chunk_index(block->local_host_addr,
                block->local_host_addr + (current_addr - block->offset));

    return 0;
}

/*
 * Register a chunk with IB. If the chunk was already registered
 * previously, then skip.
 *
 * Also return the keys associated with the registration needed
 * to perform the actual RDMA operation.
 */
static int qemu_rdma_register_and_get_keys(RDMAContext *rdma,
1171
        RDMALocalBlock *block, uintptr_t host_addr,
M
Michael R. Hines 已提交
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
        uint32_t *lkey, uint32_t *rkey, int chunk,
        uint8_t *chunk_start, uint8_t *chunk_end)
{
    if (block->mr) {
        if (lkey) {
            *lkey = block->mr->lkey;
        }
        if (rkey) {
            *rkey = block->mr->rkey;
        }
        return 0;
    }

    /* allocate memory to store chunk MRs */
    if (!block->pmr) {
1187
        block->pmr = g_new0(struct ibv_mr *, block->nb_chunks);
M
Michael R. Hines 已提交
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
    }

    /*
     * If 'rkey', then we're the destination, so grant access to the source.
     *
     * If 'lkey', then we're the source VM, so grant access only to ourselves.
     */
    if (!block->pmr[chunk]) {
        uint64_t len = chunk_end - chunk_start;

1198
        trace_qemu_rdma_register_and_get_keys(len, chunk_start);
M
Michael R. Hines 已提交
1199 1200 1201 1202 1203 1204 1205 1206 1207

        block->pmr[chunk] = ibv_reg_mr(rdma->pd,
                chunk_start, len,
                (rkey ? (IBV_ACCESS_LOCAL_WRITE |
                        IBV_ACCESS_REMOTE_WRITE) : 0));

        if (!block->pmr[chunk]) {
            perror("Failed to register chunk!");
            fprintf(stderr, "Chunk details: block: %d chunk index %d"
1208 1209 1210 1211 1212 1213
                            " start %" PRIuPTR " end %" PRIuPTR
                            " host %" PRIuPTR
                            " local %" PRIuPTR " registrations: %d\n",
                            block->index, chunk, (uintptr_t)chunk_start,
                            (uintptr_t)chunk_end, host_addr,
                            (uintptr_t)block->local_host_addr,
M
Michael R. Hines 已提交
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
                            rdma->total_registrations);
            return -1;
        }
        rdma->total_registrations++;
    }

    if (lkey) {
        *lkey = block->pmr[chunk]->lkey;
    }
    if (rkey) {
        *rkey = block->pmr[chunk]->rkey;
    }
    return 0;
}

/*
 * Register (at connection time) the memory used for control
 * channel messages.
 */
static int qemu_rdma_reg_control(RDMAContext *rdma, int idx)
{
    rdma->wr_data[idx].control_mr = ibv_reg_mr(rdma->pd,
            rdma->wr_data[idx].control, RDMA_CONTROL_MAX_BUFFER,
            IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE);
    if (rdma->wr_data[idx].control_mr) {
        rdma->total_registrations++;
        return 0;
    }
1242
    error_report("qemu_rdma_reg_control failed");
M
Michael R. Hines 已提交
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
    return -1;
}

const char *print_wrid(int wrid)
{
    if (wrid >= RDMA_WRID_RECV_CONTROL) {
        return wrid_desc[RDMA_WRID_RECV_CONTROL];
    }
    return wrid_desc[wrid];
}

/*
 * RDMA requires memory registration (mlock/pinning), but this is not good for
 * overcommitment.
 *
 * In preparation for the future where LRU information or workload-specific
 * writable writable working set memory access behavior is available to QEMU
 * it would be nice to have in place the ability to UN-register/UN-pin
 * particular memory regions from the RDMA hardware when it is determine that
 * those regions of memory will likely not be accessed again in the near future.
 *
 * While we do not yet have such information right now, the following
 * compile-time option allows us to perform a non-optimized version of this
 * behavior.
 *
 * By uncommenting this option, you will cause *all* RDMA transfers to be
 * unregistered immediately after the transfer completes on both sides of the
 * connection. This has no effect in 'rdma-pin-all' mode, only regular mode.
 *
 * This will have a terrible impact on migration performance, so until future
 * workload information or LRU information is available, do not attempt to use
 * this feature except for basic testing.
 */
//#define RDMA_UNREGISTRATION_EXAMPLE

/*
 * Perform a non-optimized memory unregistration after every transfer
D
Dr. David Alan Gilbert 已提交
1280
 * for demonstration purposes, only if pin-all is not requested.
M
Michael R. Hines 已提交
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
 *
 * Potential optimizations:
 * 1. Start a new thread to run this function continuously
        - for bit clearing
        - and for receipt of unregister messages
 * 2. Use an LRU.
 * 3. Use workload hints.
 */
static int qemu_rdma_unregister_waiting(RDMAContext *rdma)
{
    while (rdma->unregistrations[rdma->unregister_current]) {
        int ret;
        uint64_t wr_id = rdma->unregistrations[rdma->unregister_current];
        uint64_t chunk =
            (wr_id & RDMA_WRID_CHUNK_MASK) >> RDMA_WRID_CHUNK_SHIFT;
        uint64_t index =
            (wr_id & RDMA_WRID_BLOCK_MASK) >> RDMA_WRID_BLOCK_SHIFT;
        RDMALocalBlock *block =
            &(rdma->local_ram_blocks.block[index]);
        RDMARegister reg = { .current_index = index };
        RDMAControlHeader resp = { .type = RDMA_CONTROL_UNREGISTER_FINISHED,
                                 };
        RDMAControlHeader head = { .len = sizeof(RDMARegister),
                                   .type = RDMA_CONTROL_UNREGISTER_REQUEST,
                                   .repeat = 1,
                                 };

1308 1309
        trace_qemu_rdma_unregister_waiting_proc(chunk,
                                                rdma->unregister_current);
M
Michael R. Hines 已提交
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328

        rdma->unregistrations[rdma->unregister_current] = 0;
        rdma->unregister_current++;

        if (rdma->unregister_current == RDMA_SIGNALED_SEND_MAX) {
            rdma->unregister_current = 0;
        }


        /*
         * Unregistration is speculative (because migration is single-threaded
         * and we cannot break the protocol's inifinband message ordering).
         * Thus, if the memory is currently being used for transmission,
         * then abort the attempt to unregister and try again
         * later the next time a completion is received for this memory.
         */
        clear_bit(chunk, block->unregister_bitmap);

        if (test_bit(chunk, block->transit_bitmap)) {
1329
            trace_qemu_rdma_unregister_waiting_inflight(chunk);
M
Michael R. Hines 已提交
1330 1331 1332
            continue;
        }

1333
        trace_qemu_rdma_unregister_waiting_send(chunk);
M
Michael R. Hines 已提交
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345

        ret = ibv_dereg_mr(block->pmr[chunk]);
        block->pmr[chunk] = NULL;
        block->remote_keys[chunk] = 0;

        if (ret != 0) {
            perror("unregistration chunk failed");
            return -ret;
        }
        rdma->total_registrations--;

        reg.key.chunk = chunk;
1346
        register_to_network(rdma, &reg);
M
Michael R. Hines 已提交
1347 1348 1349 1350 1351 1352
        ret = qemu_rdma_exchange_send(rdma, &head, (uint8_t *) &reg,
                                &resp, NULL, NULL);
        if (ret < 0) {
            return ret;
        }

1353
        trace_qemu_rdma_unregister_waiting_complete(chunk);
M
Michael R. Hines 已提交
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
    }

    return 0;
}

static uint64_t qemu_rdma_make_wrid(uint64_t wr_id, uint64_t index,
                                         uint64_t chunk)
{
    uint64_t result = wr_id & RDMA_WRID_TYPE_MASK;

    result |= (index << RDMA_WRID_BLOCK_SHIFT);
    result |= (chunk << RDMA_WRID_CHUNK_SHIFT);

    return result;
}

/*
 * Set bit for unregistration in the next iteration.
 * We cannot transmit right here, but will unpin later.
 */
static void qemu_rdma_signal_unregister(RDMAContext *rdma, uint64_t index,
                                        uint64_t chunk, uint64_t wr_id)
{
    if (rdma->unregistrations[rdma->unregister_next] != 0) {
1378
        error_report("rdma migration: queue is full");
M
Michael R. Hines 已提交
1379 1380 1381 1382
    } else {
        RDMALocalBlock *block = &(rdma->local_ram_blocks.block[index]);

        if (!test_and_set_bit(chunk, block->unregister_bitmap)) {
1383 1384
            trace_qemu_rdma_signal_unregister_append(chunk,
                                                     rdma->unregister_next);
M
Michael R. Hines 已提交
1385 1386 1387 1388 1389 1390 1391 1392

            rdma->unregistrations[rdma->unregister_next++] =
                    qemu_rdma_make_wrid(wr_id, index, chunk);

            if (rdma->unregister_next == RDMA_SIGNALED_SEND_MAX) {
                rdma->unregister_next = 0;
            }
        } else {
1393
            trace_qemu_rdma_signal_unregister_already(chunk);
M
Michael R. Hines 已提交
1394 1395 1396 1397 1398 1399 1400 1401 1402
        }
    }
}

/*
 * Consult the connection manager to see a work request
 * (of any kind) has completed.
 * Return the work request ID that completed.
 */
1403 1404
static uint64_t qemu_rdma_poll(RDMAContext *rdma, uint64_t *wr_id_out,
                               uint32_t *byte_len)
M
Michael R. Hines 已提交
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
{
    int ret;
    struct ibv_wc wc;
    uint64_t wr_id;

    ret = ibv_poll_cq(rdma->cq, 1, &wc);

    if (!ret) {
        *wr_id_out = RDMA_WRID_NONE;
        return 0;
    }

    if (ret < 0) {
1418
        error_report("ibv_poll_cq return %d", ret);
M
Michael R. Hines 已提交
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
        return ret;
    }

    wr_id = wc.wr_id & RDMA_WRID_TYPE_MASK;

    if (wc.status != IBV_WC_SUCCESS) {
        fprintf(stderr, "ibv_poll_cq wc.status=%d %s!\n",
                        wc.status, ibv_wc_status_str(wc.status));
        fprintf(stderr, "ibv_poll_cq wrid=%s!\n", wrid_desc[wr_id]);

        return -1;
    }

    if (rdma->control_ready_expected &&
        (wr_id >= RDMA_WRID_RECV_CONTROL)) {
1434
        trace_qemu_rdma_poll_recv(wrid_desc[RDMA_WRID_RECV_CONTROL],
M
Michael R. Hines 已提交
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
                  wr_id - RDMA_WRID_RECV_CONTROL, wr_id, rdma->nb_sent);
        rdma->control_ready_expected = 0;
    }

    if (wr_id == RDMA_WRID_RDMA_WRITE) {
        uint64_t chunk =
            (wc.wr_id & RDMA_WRID_CHUNK_MASK) >> RDMA_WRID_CHUNK_SHIFT;
        uint64_t index =
            (wc.wr_id & RDMA_WRID_BLOCK_MASK) >> RDMA_WRID_BLOCK_SHIFT;
        RDMALocalBlock *block = &(rdma->local_ram_blocks.block[index]);

1446
        trace_qemu_rdma_poll_write(print_wrid(wr_id), wr_id, rdma->nb_sent,
1447 1448
                                   index, chunk, block->local_host_addr,
                                   (void *)(uintptr_t)block->remote_host_addr);
M
Michael R. Hines 已提交
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467

        clear_bit(chunk, block->transit_bitmap);

        if (rdma->nb_sent > 0) {
            rdma->nb_sent--;
        }

        if (!rdma->pin_all) {
            /*
             * FYI: If one wanted to signal a specific chunk to be unregistered
             * using LRU or workload-specific information, this is the function
             * you would call to do so. That chunk would then get asynchronously
             * unregistered later.
             */
#ifdef RDMA_UNREGISTRATION_EXAMPLE
            qemu_rdma_signal_unregister(rdma, index, chunk, wc.wr_id);
#endif
        }
    } else {
1468
        trace_qemu_rdma_poll_other(print_wrid(wr_id), wr_id, rdma->nb_sent);
M
Michael R. Hines 已提交
1469 1470 1471
    }

    *wr_id_out = wc.wr_id;
1472 1473 1474
    if (byte_len) {
        *byte_len = wc.byte_len;
    }
M
Michael R. Hines 已提交
1475 1476 1477 1478

    return  0;
}

1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
/* Wait for activity on the completion channel.
 * Returns 0 on success, none-0 on error.
 */
static int qemu_rdma_wait_comp_channel(RDMAContext *rdma)
{
    /*
     * Coroutine doesn't start until migration_fd_process_incoming()
     * so don't yield unless we know we're running inside of a coroutine.
     */
    if (rdma->migration_started_on_destination) {
        yield_until_fd_readable(rdma->comp_channel->fd);
    } else {
        /* This is the source side, we're in a separate thread
         * or destination prior to migration_fd_process_incoming()
         * we can't yield; so we have to poll the fd.
         * But we need to be able to handle 'cancel' or an error
         * without hanging forever.
         */
        while (!rdma->error_state  && !rdma->received_error) {
            GPollFD pfds[1];
            pfds[0].fd = rdma->comp_channel->fd;
            pfds[0].events = G_IO_IN | G_IO_HUP | G_IO_ERR;
            /* 0.1s timeout, should be fine for a 'cancel' */
            switch (qemu_poll_ns(pfds, 1, 100 * 1000 * 1000)) {
            case 1: /* fd active */
                return 0;

            case 0: /* Timeout, go around again */
                break;

            default: /* Error of some type -
                      * I don't trust errno from qemu_poll_ns
                     */
                error_report("%s: poll failed", __func__);
                return -EPIPE;
            }

            if (migrate_get_current()->state == MIGRATION_STATUS_CANCELLING) {
                /* Bail out and let the cancellation happen */
                return -EPIPE;
            }
        }
    }

    if (rdma->received_error) {
        return -EPIPE;
    }
    return rdma->error_state;
}

M
Michael R. Hines 已提交
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
/*
 * Block until the next work request has completed.
 *
 * First poll to see if a work request has already completed,
 * otherwise block.
 *
 * If we encounter completed work requests for IDs other than
 * the one we're interested in, then that's generally an error.
 *
 * The only exception is actual RDMA Write completions. These
 * completions only need to be recorded, but do not actually
 * need further processing.
 */
1542 1543
static int qemu_rdma_block_for_wrid(RDMAContext *rdma, int wrid_requested,
                                    uint32_t *byte_len)
M
Michael R. Hines 已提交
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
{
    int num_cq_events = 0, ret = 0;
    struct ibv_cq *cq;
    void *cq_ctx;
    uint64_t wr_id = RDMA_WRID_NONE, wr_id_in;

    if (ibv_req_notify_cq(rdma->cq, 0)) {
        return -1;
    }
    /* poll cq first */
    while (wr_id != wrid_requested) {
1555
        ret = qemu_rdma_poll(rdma, &wr_id_in, byte_len);
M
Michael R. Hines 已提交
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
        if (ret < 0) {
            return ret;
        }

        wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;

        if (wr_id == RDMA_WRID_NONE) {
            break;
        }
        if (wr_id != wrid_requested) {
1566 1567
            trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested),
                       wrid_requested, print_wrid(wr_id), wr_id);
M
Michael R. Hines 已提交
1568 1569 1570 1571 1572 1573 1574 1575
        }
    }

    if (wr_id == wrid_requested) {
        return 0;
    }

    while (1) {
1576 1577 1578
        ret = qemu_rdma_wait_comp_channel(rdma);
        if (ret) {
            goto err_block_for_wrid;
M
Michael R. Hines 已提交
1579 1580
        }

1581 1582
        ret = ibv_get_cq_event(rdma->comp_channel, &cq, &cq_ctx);
        if (ret) {
M
Michael R. Hines 已提交
1583 1584 1585 1586 1587 1588
            perror("ibv_get_cq_event");
            goto err_block_for_wrid;
        }

        num_cq_events++;

1589 1590
        ret = -ibv_req_notify_cq(cq, 0);
        if (ret) {
M
Michael R. Hines 已提交
1591 1592 1593 1594
            goto err_block_for_wrid;
        }

        while (wr_id != wrid_requested) {
1595
            ret = qemu_rdma_poll(rdma, &wr_id_in, byte_len);
M
Michael R. Hines 已提交
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
            if (ret < 0) {
                goto err_block_for_wrid;
            }

            wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;

            if (wr_id == RDMA_WRID_NONE) {
                break;
            }
            if (wr_id != wrid_requested) {
1606 1607
                trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested),
                                   wrid_requested, print_wrid(wr_id), wr_id);
M
Michael R. Hines 已提交
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
            }
        }

        if (wr_id == wrid_requested) {
            goto success_block_for_wrid;
        }
    }

success_block_for_wrid:
    if (num_cq_events) {
        ibv_ack_cq_events(cq, num_cq_events);
    }
    return 0;

err_block_for_wrid:
    if (num_cq_events) {
        ibv_ack_cq_events(cq, num_cq_events);
    }
1626 1627

    rdma->error_state = ret;
M
Michael R. Hines 已提交
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
    return ret;
}

/*
 * Post a SEND message work request for the control channel
 * containing some data and block until the post completes.
 */
static int qemu_rdma_post_send_control(RDMAContext *rdma, uint8_t *buf,
                                       RDMAControlHeader *head)
{
    int ret = 0;
1639
    RDMAWorkRequestData *wr = &rdma->wr_data[RDMA_WRID_CONTROL];
M
Michael R. Hines 已提交
1640 1641
    struct ibv_send_wr *bad_wr;
    struct ibv_sge sge = {
1642
                           .addr = (uintptr_t)(wr->control),
M
Michael R. Hines 已提交
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
                           .length = head->len + sizeof(RDMAControlHeader),
                           .lkey = wr->control_mr->lkey,
                         };
    struct ibv_send_wr send_wr = {
                                   .wr_id = RDMA_WRID_SEND_CONTROL,
                                   .opcode = IBV_WR_SEND,
                                   .send_flags = IBV_SEND_SIGNALED,
                                   .sg_list = &sge,
                                   .num_sge = 1,
                                };

1654
    trace_qemu_rdma_post_send_control(control_desc(head->type));
M
Michael R. Hines 已提交
1655 1656 1657 1658 1659 1660 1661 1662 1663

    /*
     * We don't actually need to do a memcpy() in here if we used
     * the "sge" properly, but since we're only sending control messages
     * (not RAM in a performance-critical path), then its OK for now.
     *
     * The copy makes the RDMAControlHeader simpler to manipulate
     * for the time being.
     */
1664
    assert(head->len <= RDMA_CONTROL_MAX_BUFFER - sizeof(*head));
M
Michael R. Hines 已提交
1665 1666 1667 1668 1669 1670 1671 1672
    memcpy(wr->control, head, sizeof(RDMAControlHeader));
    control_to_network((void *) wr->control);

    if (buf) {
        memcpy(wr->control + sizeof(RDMAControlHeader), buf, head->len);
    }


M
Michael R. Hines 已提交
1673
    ret = ibv_post_send(rdma->qp, &send_wr, &bad_wr);
M
Michael R. Hines 已提交
1674

M
Michael R. Hines 已提交
1675
    if (ret > 0) {
1676
        error_report("Failed to use post IB SEND for control");
M
Michael R. Hines 已提交
1677
        return -ret;
M
Michael R. Hines 已提交
1678 1679
    }

1680
    ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_SEND_CONTROL, NULL);
M
Michael R. Hines 已提交
1681
    if (ret < 0) {
1682
        error_report("rdma migration: send polling control error");
M
Michael R. Hines 已提交
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
    }

    return ret;
}

/*
 * Post a RECV work request in anticipation of some future receipt
 * of data on the control channel.
 */
static int qemu_rdma_post_recv_control(RDMAContext *rdma, int idx)
{
    struct ibv_recv_wr *bad_wr;
    struct ibv_sge sge = {
1696
                            .addr = (uintptr_t)(rdma->wr_data[idx].control),
M
Michael R. Hines 已提交
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
                            .length = RDMA_CONTROL_MAX_BUFFER,
                            .lkey = rdma->wr_data[idx].control_mr->lkey,
                         };

    struct ibv_recv_wr recv_wr = {
                                    .wr_id = RDMA_WRID_RECV_CONTROL + idx,
                                    .sg_list = &sge,
                                    .num_sge = 1,
                                 };


    if (ibv_post_recv(rdma->qp, &recv_wr, &bad_wr)) {
        return -1;
    }

    return 0;
}

/*
 * Block and wait for a RECV control channel message to arrive.
 */
static int qemu_rdma_exchange_get_response(RDMAContext *rdma,
                RDMAControlHeader *head, int expecting, int idx)
{
1721 1722 1723
    uint32_t byte_len;
    int ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RECV_CONTROL + idx,
                                       &byte_len);
M
Michael R. Hines 已提交
1724 1725

    if (ret < 0) {
1726
        error_report("rdma migration: recv polling control error!");
M
Michael R. Hines 已提交
1727 1728 1729 1730 1731 1732
        return ret;
    }

    network_to_control((void *) rdma->wr_data[idx].control);
    memcpy(head, rdma->wr_data[idx].control, sizeof(RDMAControlHeader));

1733
    trace_qemu_rdma_exchange_get_response_start(control_desc(expecting));
M
Michael R. Hines 已提交
1734 1735

    if (expecting == RDMA_CONTROL_NONE) {
1736
        trace_qemu_rdma_exchange_get_response_none(control_desc(head->type),
1737
                                             head->type);
M
Michael R. Hines 已提交
1738
    } else if (head->type != expecting || head->type == RDMA_CONTROL_ERROR) {
1739 1740
        error_report("Was expecting a %s (%d) control message"
                ", but got: %s (%d), length: %d",
1741 1742
                control_desc(expecting), expecting,
                control_desc(head->type), head->type, head->len);
1743 1744 1745
        if (head->type == RDMA_CONTROL_ERROR) {
            rdma->received_error = true;
        }
M
Michael R. Hines 已提交
1746 1747
        return -EIO;
    }
1748
    if (head->len > RDMA_CONTROL_MAX_BUFFER - sizeof(*head)) {
1749
        error_report("too long length: %d", head->len);
1750 1751
        return -EINVAL;
    }
1752
    if (sizeof(*head) + head->len != byte_len) {
1753
        error_report("Malformed length: %d byte_len %d", head->len, byte_len);
1754 1755
        return -EINVAL;
    }
M
Michael R. Hines 已提交
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814

    return 0;
}

/*
 * When a RECV work request has completed, the work request's
 * buffer is pointed at the header.
 *
 * This will advance the pointer to the data portion
 * of the control message of the work request's buffer that
 * was populated after the work request finished.
 */
static void qemu_rdma_move_header(RDMAContext *rdma, int idx,
                                  RDMAControlHeader *head)
{
    rdma->wr_data[idx].control_len = head->len;
    rdma->wr_data[idx].control_curr =
        rdma->wr_data[idx].control + sizeof(RDMAControlHeader);
}

/*
 * This is an 'atomic' high-level operation to deliver a single, unified
 * control-channel message.
 *
 * Additionally, if the user is expecting some kind of reply to this message,
 * they can request a 'resp' response message be filled in by posting an
 * additional work request on behalf of the user and waiting for an additional
 * completion.
 *
 * The extra (optional) response is used during registration to us from having
 * to perform an *additional* exchange of message just to provide a response by
 * instead piggy-backing on the acknowledgement.
 */
static int qemu_rdma_exchange_send(RDMAContext *rdma, RDMAControlHeader *head,
                                   uint8_t *data, RDMAControlHeader *resp,
                                   int *resp_idx,
                                   int (*callback)(RDMAContext *rdma))
{
    int ret = 0;

    /*
     * Wait until the dest is ready before attempting to deliver the message
     * by waiting for a READY message.
     */
    if (rdma->control_ready_expected) {
        RDMAControlHeader resp;
        ret = qemu_rdma_exchange_get_response(rdma,
                                    &resp, RDMA_CONTROL_READY, RDMA_WRID_READY);
        if (ret < 0) {
            return ret;
        }
    }

    /*
     * If the user is expecting a response, post a WR in anticipation of it.
     */
    if (resp) {
        ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_DATA);
        if (ret) {
1815
            error_report("rdma migration: error posting"
M
Michael R. Hines 已提交
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
                    " extra control recv for anticipated result!");
            return ret;
        }
    }

    /*
     * Post a WR to replace the one we just consumed for the READY message.
     */
    ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
    if (ret) {
1826
        error_report("rdma migration: error posting first control recv!");
M
Michael R. Hines 已提交
1827 1828 1829 1830 1831 1832 1833 1834 1835
        return ret;
    }

    /*
     * Deliver the control message that was requested.
     */
    ret = qemu_rdma_post_send_control(rdma, data, head);

    if (ret < 0) {
1836
        error_report("Failed to send control buffer!");
M
Michael R. Hines 已提交
1837 1838 1839 1840 1841 1842 1843 1844
        return ret;
    }

    /*
     * If we're expecting a response, block and wait for it.
     */
    if (resp) {
        if (callback) {
1845
            trace_qemu_rdma_exchange_send_issue_callback();
M
Michael R. Hines 已提交
1846 1847 1848 1849 1850 1851
            ret = callback(rdma);
            if (ret < 0) {
                return ret;
            }
        }

1852
        trace_qemu_rdma_exchange_send_waiting(control_desc(resp->type));
M
Michael R. Hines 已提交
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
        ret = qemu_rdma_exchange_get_response(rdma, resp,
                                              resp->type, RDMA_WRID_DATA);

        if (ret < 0) {
            return ret;
        }

        qemu_rdma_move_header(rdma, RDMA_WRID_DATA, resp);
        if (resp_idx) {
            *resp_idx = RDMA_WRID_DATA;
        }
1864
        trace_qemu_rdma_exchange_send_received(control_desc(resp->type));
M
Michael R. Hines 已提交
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
    }

    rdma->control_ready_expected = 1;

    return 0;
}

/*
 * This is an 'atomic' high-level operation to receive a single, unified
 * control-channel message.
 */
static int qemu_rdma_exchange_recv(RDMAContext *rdma, RDMAControlHeader *head,
                                int expecting)
{
    RDMAControlHeader ready = {
                                .len = 0,
                                .type = RDMA_CONTROL_READY,
                                .repeat = 1,
                              };
    int ret;

    /*
     * Inform the source that we're ready to receive a message.
     */
    ret = qemu_rdma_post_send_control(rdma, NULL, &ready);

    if (ret < 0) {
1892
        error_report("Failed to send control buffer!");
M
Michael R. Hines 已提交
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
        return ret;
    }

    /*
     * Block and wait for the message.
     */
    ret = qemu_rdma_exchange_get_response(rdma, head,
                                          expecting, RDMA_WRID_READY);

    if (ret < 0) {
        return ret;
    }

    qemu_rdma_move_header(rdma, RDMA_WRID_READY, head);

    /*
     * Post a new RECV work request to replace the one we just consumed.
     */
    ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
    if (ret) {
1913
        error_report("rdma migration: error posting second control recv!");
M
Michael R. Hines 已提交
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
        return ret;
    }

    return 0;
}

/*
 * Write an actual chunk of memory using RDMA.
 *
 * If we're using dynamic registration on the dest-side, we have to
 * send a registration command first.
 */
static int qemu_rdma_write_one(QEMUFile *f, RDMAContext *rdma,
                               int current_index, uint64_t current_addr,
                               uint64_t length)
{
    struct ibv_sge sge;
    struct ibv_send_wr send_wr = { 0 };
    struct ibv_send_wr *bad_wr;
    int reg_result_idx, ret, count = 0;
    uint64_t chunk, chunks;
    uint8_t *chunk_start, *chunk_end;
    RDMALocalBlock *block = &(rdma->local_ram_blocks.block[current_index]);
    RDMARegister reg;
    RDMARegisterResult *reg_result;
    RDMAControlHeader resp = { .type = RDMA_CONTROL_REGISTER_RESULT };
    RDMAControlHeader head = { .len = sizeof(RDMARegister),
                               .type = RDMA_CONTROL_REGISTER_REQUEST,
                               .repeat = 1,
                             };

retry:
1946
    sge.addr = (uintptr_t)(block->local_host_addr +
M
Michael R. Hines 已提交
1947 1948 1949
                            (current_addr - block->offset));
    sge.length = length;

1950 1951
    chunk = ram_chunk_index(block->local_host_addr,
                            (uint8_t *)(uintptr_t)sge.addr);
M
Michael R. Hines 已提交
1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
    chunk_start = ram_chunk_start(block, chunk);

    if (block->is_ram_block) {
        chunks = length / (1UL << RDMA_REG_CHUNK_SHIFT);

        if (chunks && ((length % (1UL << RDMA_REG_CHUNK_SHIFT)) == 0)) {
            chunks--;
        }
    } else {
        chunks = block->length / (1UL << RDMA_REG_CHUNK_SHIFT);

        if (chunks && ((block->length % (1UL << RDMA_REG_CHUNK_SHIFT)) == 0)) {
            chunks--;
        }
    }

1968 1969 1970
    trace_qemu_rdma_write_one_top(chunks + 1,
                                  (chunks + 1) *
                                  (1UL << RDMA_REG_CHUNK_SHIFT) / 1024 / 1024);
M
Michael R. Hines 已提交
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981

    chunk_end = ram_chunk_end(block, chunk + chunks);

    if (!rdma->pin_all) {
#ifdef RDMA_UNREGISTRATION_EXAMPLE
        qemu_rdma_unregister_waiting(rdma);
#endif
    }

    while (test_bit(chunk, block->transit_bitmap)) {
        (void)count;
1982
        trace_qemu_rdma_write_one_block(count++, current_index, chunk,
M
Michael R. Hines 已提交
1983 1984
                sge.addr, length, rdma->nb_sent, block->nb_chunks);

1985
        ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL);
M
Michael R. Hines 已提交
1986 1987

        if (ret < 0) {
1988
            error_report("Failed to Wait for previous write to complete "
M
Michael R. Hines 已提交
1989
                    "block %d chunk %" PRIu64
1990
                    " current %" PRIu64 " len %" PRIu64 " %d",
M
Michael R. Hines 已提交
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
                    current_index, chunk, sge.addr, length, rdma->nb_sent);
            return ret;
        }
    }

    if (!rdma->pin_all || !block->is_ram_block) {
        if (!block->remote_keys[chunk]) {
            /*
             * This chunk has not yet been registered, so first check to see
             * if the entire chunk is zero. If so, tell the other size to
             * memset() + madvise() the entire chunk without RDMA.
             */

2004
            if (buffer_is_zero((void *)(uintptr_t)sge.addr, length)) {
M
Michael R. Hines 已提交
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
                RDMACompress comp = {
                                        .offset = current_addr,
                                        .value = 0,
                                        .block_idx = current_index,
                                        .length = length,
                                    };

                head.len = sizeof(comp);
                head.type = RDMA_CONTROL_COMPRESS;

2015 2016
                trace_qemu_rdma_write_one_zero(chunk, sge.length,
                                               current_index, current_addr);
M
Michael R. Hines 已提交
2017

2018
                compress_to_network(rdma, &comp);
M
Michael R. Hines 已提交
2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
                ret = qemu_rdma_exchange_send(rdma, &head,
                                (uint8_t *) &comp, NULL, NULL, NULL);

                if (ret < 0) {
                    return -EIO;
                }

                acct_update_position(f, sge.length, true);

                return 1;
            }

            /*
             * Otherwise, tell other side to register.
             */
            reg.current_index = current_index;
            if (block->is_ram_block) {
                reg.key.current_addr = current_addr;
            } else {
                reg.key.chunk = chunk;
            }
            reg.chunks = chunks;

2042 2043
            trace_qemu_rdma_write_one_sendreg(chunk, sge.length, current_index,
                                              current_addr);
M
Michael R. Hines 已提交
2044

2045
            register_to_network(rdma, &reg);
M
Michael R. Hines 已提交
2046 2047 2048 2049 2050 2051 2052
            ret = qemu_rdma_exchange_send(rdma, &head, (uint8_t *) &reg,
                                    &resp, &reg_result_idx, NULL);
            if (ret < 0) {
                return ret;
            }

            /* try to overlap this single registration with the one we sent. */
2053
            if (qemu_rdma_register_and_get_keys(rdma, block, sge.addr,
M
Michael R. Hines 已提交
2054 2055
                                                &sge.lkey, NULL, chunk,
                                                chunk_start, chunk_end)) {
2056
                error_report("cannot get lkey");
M
Michael R. Hines 已提交
2057 2058 2059 2060 2061 2062 2063 2064
                return -EINVAL;
            }

            reg_result = (RDMARegisterResult *)
                    rdma->wr_data[reg_result_idx].control_curr;

            network_to_result(reg_result);

2065 2066
            trace_qemu_rdma_write_one_recvregres(block->remote_keys[chunk],
                                                 reg_result->rkey, chunk);
M
Michael R. Hines 已提交
2067 2068 2069 2070 2071

            block->remote_keys[chunk] = reg_result->rkey;
            block->remote_host_addr = reg_result->host_addr;
        } else {
            /* already registered before */
2072
            if (qemu_rdma_register_and_get_keys(rdma, block, sge.addr,
M
Michael R. Hines 已提交
2073 2074
                                                &sge.lkey, NULL, chunk,
                                                chunk_start, chunk_end)) {
2075
                error_report("cannot get lkey!");
M
Michael R. Hines 已提交
2076 2077 2078 2079 2080 2081 2082 2083
                return -EINVAL;
            }
        }

        send_wr.wr.rdma.rkey = block->remote_keys[chunk];
    } else {
        send_wr.wr.rdma.rkey = block->remote_rkey;

2084
        if (qemu_rdma_register_and_get_keys(rdma, block, sge.addr,
M
Michael R. Hines 已提交
2085 2086
                                                     &sge.lkey, NULL, chunk,
                                                     chunk_start, chunk_end)) {
2087
            error_report("cannot get lkey!");
M
Michael R. Hines 已提交
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107
            return -EINVAL;
        }
    }

    /*
     * Encode the ram block index and chunk within this wrid.
     * We will use this information at the time of completion
     * to figure out which bitmap to check against and then which
     * chunk in the bitmap to look for.
     */
    send_wr.wr_id = qemu_rdma_make_wrid(RDMA_WRID_RDMA_WRITE,
                                        current_index, chunk);

    send_wr.opcode = IBV_WR_RDMA_WRITE;
    send_wr.send_flags = IBV_SEND_SIGNALED;
    send_wr.sg_list = &sge;
    send_wr.num_sge = 1;
    send_wr.wr.rdma.remote_addr = block->remote_host_addr +
                                (current_addr - block->offset);

2108 2109
    trace_qemu_rdma_write_one_post(chunk, sge.addr, send_wr.wr.rdma.remote_addr,
                                   sge.length);
M
Michael R. Hines 已提交
2110 2111 2112 2113 2114 2115 2116 2117

    /*
     * ibv_post_send() does not return negative error numbers,
     * per the specification they are positive - no idea why.
     */
    ret = ibv_post_send(rdma->qp, &send_wr, &bad_wr);

    if (ret == ENOMEM) {
2118
        trace_qemu_rdma_write_one_queue_full();
2119
        ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL);
M
Michael R. Hines 已提交
2120
        if (ret < 0) {
2121 2122
            error_report("rdma migration: failed to make "
                         "room in full send queue! %d", ret);
M
Michael R. Hines 已提交
2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
            return ret;
        }

        goto retry;

    } else if (ret > 0) {
        perror("rdma migration: post rdma write failed");
        return -ret;
    }

    set_bit(chunk, block->transit_bitmap);
    acct_update_position(f, sge.length, false);
    rdma->total_writes++;

    return 0;
}

/*
 * Push out any unwritten RDMA operations.
 *
 * We support sending out multiple chunks at the same time.
 * Not all of them need to get signaled in the completion queue.
 */
static int qemu_rdma_write_flush(QEMUFile *f, RDMAContext *rdma)
{
    int ret;

    if (!rdma->current_length) {
        return 0;
    }

    ret = qemu_rdma_write_one(f, rdma,
            rdma->current_index, rdma->current_addr, rdma->current_length);

    if (ret < 0) {
        return ret;
    }

    if (ret == 0) {
        rdma->nb_sent++;
2163
        trace_qemu_rdma_write_flush(rdma->nb_sent);
M
Michael R. Hines 已提交
2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
    }

    rdma->current_length = 0;
    rdma->current_addr = 0;

    return 0;
}

static inline int qemu_rdma_buffer_mergable(RDMAContext *rdma,
                    uint64_t offset, uint64_t len)
{
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
    RDMALocalBlock *block;
    uint8_t *host_addr;
    uint8_t *chunk_end;

    if (rdma->current_index < 0) {
        return 0;
    }

    if (rdma->current_chunk < 0) {
        return 0;
    }

    block = &(rdma->local_ram_blocks.block[rdma->current_index]);
    host_addr = block->local_host_addr + (offset - block->offset);
    chunk_end = ram_chunk_end(block, rdma->current_chunk);
M
Michael R. Hines 已提交
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247

    if (rdma->current_length == 0) {
        return 0;
    }

    /*
     * Only merge into chunk sequentially.
     */
    if (offset != (rdma->current_addr + rdma->current_length)) {
        return 0;
    }

    if (offset < block->offset) {
        return 0;
    }

    if ((offset + len) > (block->offset + block->length)) {
        return 0;
    }

    if ((host_addr + len) > chunk_end) {
        return 0;
    }

    return 1;
}

/*
 * We're not actually writing here, but doing three things:
 *
 * 1. Identify the chunk the buffer belongs to.
 * 2. If the chunk is full or the buffer doesn't belong to the current
 *    chunk, then start a new chunk and flush() the old chunk.
 * 3. To keep the hardware busy, we also group chunks into batches
 *    and only require that a batch gets acknowledged in the completion
 *    qeueue instead of each individual chunk.
 */
static int qemu_rdma_write(QEMUFile *f, RDMAContext *rdma,
                           uint64_t block_offset, uint64_t offset,
                           uint64_t len)
{
    uint64_t current_addr = block_offset + offset;
    uint64_t index = rdma->current_index;
    uint64_t chunk = rdma->current_chunk;
    int ret;

    /* If we cannot merge it, we flush the current buffer first. */
    if (!qemu_rdma_buffer_mergable(rdma, current_addr, len)) {
        ret = qemu_rdma_write_flush(f, rdma);
        if (ret) {
            return ret;
        }
        rdma->current_length = 0;
        rdma->current_addr = current_addr;

        ret = qemu_rdma_search_ram_block(rdma, block_offset,
                                         offset, len, &index, &chunk);
        if (ret) {
2248
            error_report("ram block search failed");
M
Michael R. Hines 已提交
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
            return ret;
        }
        rdma->current_index = index;
        rdma->current_chunk = chunk;
    }

    /* merge it */
    rdma->current_length += len;

    /* flush it if buffer is too large */
    if (rdma->current_length >= RDMA_MERGE_MAX) {
        return qemu_rdma_write_flush(f, rdma);
    }

    return 0;
}

static void qemu_rdma_cleanup(RDMAContext *rdma)
{
    struct rdma_cm_event *cm_event;
    int ret, idx;

2271
    if (rdma->cm_id && rdma->connected) {
2272 2273 2274
        if ((rdma->error_state ||
             migrate_get_current()->state == MIGRATION_STATUS_CANCELLING) &&
            !rdma->received_error) {
M
Michael R. Hines 已提交
2275 2276 2277 2278
            RDMAControlHeader head = { .len = 0,
                                       .type = RDMA_CONTROL_ERROR,
                                       .repeat = 1,
                                     };
2279
            error_report("Early error. Sending error.");
M
Michael R. Hines 已提交
2280 2281 2282 2283 2284
            qemu_rdma_post_send_control(rdma, NULL, &head);
        }

        ret = rdma_disconnect(rdma->cm_id);
        if (!ret) {
2285
            trace_qemu_rdma_cleanup_waiting_for_disconnect();
M
Michael R. Hines 已提交
2286 2287 2288 2289 2290
            ret = rdma_get_cm_event(rdma->channel, &cm_event);
            if (!ret) {
                rdma_ack_cm_event(cm_event);
            }
        }
2291
        trace_qemu_rdma_cleanup_disconnect();
2292
        rdma->connected = false;
M
Michael R. Hines 已提交
2293 2294
    }

2295 2296
    g_free(rdma->dest_blocks);
    rdma->dest_blocks = NULL;
M
Michael R. Hines 已提交
2297

2298
    for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
M
Michael R. Hines 已提交
2299 2300 2301 2302 2303 2304 2305 2306 2307
        if (rdma->wr_data[idx].control_mr) {
            rdma->total_registrations--;
            ibv_dereg_mr(rdma->wr_data[idx].control_mr);
        }
        rdma->wr_data[idx].control_mr = NULL;
    }

    if (rdma->local_ram_blocks.block) {
        while (rdma->local_ram_blocks.nb_blocks) {
2308
            rdma_delete_block(rdma, &rdma->local_ram_blocks.block[0]);
M
Michael R. Hines 已提交
2309 2310 2311
        }
    }

2312 2313 2314 2315
    if (rdma->qp) {
        rdma_destroy_qp(rdma->cm_id);
        rdma->qp = NULL;
    }
M
Michael R. Hines 已提交
2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
    if (rdma->cq) {
        ibv_destroy_cq(rdma->cq);
        rdma->cq = NULL;
    }
    if (rdma->comp_channel) {
        ibv_destroy_comp_channel(rdma->comp_channel);
        rdma->comp_channel = NULL;
    }
    if (rdma->pd) {
        ibv_dealloc_pd(rdma->pd);
        rdma->pd = NULL;
    }
    if (rdma->cm_id) {
        rdma_destroy_id(rdma->cm_id);
        rdma->cm_id = NULL;
    }
2332 2333 2334 2335
    if (rdma->listen_id) {
        rdma_destroy_id(rdma->listen_id);
        rdma->listen_id = NULL;
    }
M
Michael R. Hines 已提交
2336 2337 2338 2339
    if (rdma->channel) {
        rdma_destroy_event_channel(rdma->channel);
        rdma->channel = NULL;
    }
2340 2341
    g_free(rdma->host);
    rdma->host = NULL;
M
Michael R. Hines 已提交
2342 2343 2344
}


2345
static int qemu_rdma_source_init(RDMAContext *rdma, bool pin_all, Error **errp)
M
Michael R. Hines 已提交
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
{
    int ret, idx;
    Error *local_err = NULL, **temp = &local_err;

    /*
     * Will be validated against destination's actual capabilities
     * after the connect() completes.
     */
    rdma->pin_all = pin_all;

    ret = qemu_rdma_resolve_host(rdma, temp);
    if (ret) {
        goto err_rdma_source_init;
    }

    ret = qemu_rdma_alloc_pd_cq(rdma);
    if (ret) {
        ERROR(temp, "rdma migration: error allocating pd and cq! Your mlock()"
                    " limits may be too low. Please check $ ulimit -a # and "
2365
                    "search for 'ulimit -l' in the output");
M
Michael R. Hines 已提交
2366 2367 2368 2369 2370
        goto err_rdma_source_init;
    }

    ret = qemu_rdma_alloc_qp(rdma);
    if (ret) {
2371
        ERROR(temp, "rdma migration: error allocating qp!");
M
Michael R. Hines 已提交
2372 2373 2374 2375 2376
        goto err_rdma_source_init;
    }

    ret = qemu_rdma_init_ram_blocks(rdma);
    if (ret) {
2377
        ERROR(temp, "rdma migration: error initializing ram blocks!");
M
Michael R. Hines 已提交
2378 2379 2380
        goto err_rdma_source_init;
    }

D
Dr. David Alan Gilbert 已提交
2381 2382 2383 2384 2385 2386 2387 2388
    /* Build the hash that maps from offset to RAMBlock */
    rdma->blockmap = g_hash_table_new(g_direct_hash, g_direct_equal);
    for (idx = 0; idx < rdma->local_ram_blocks.nb_blocks; idx++) {
        g_hash_table_insert(rdma->blockmap,
                (void *)(uintptr_t)rdma->local_ram_blocks.block[idx].offset,
                &rdma->local_ram_blocks.block[idx]);
    }

2389
    for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
M
Michael R. Hines 已提交
2390 2391
        ret = qemu_rdma_reg_control(rdma, idx);
        if (ret) {
2392
            ERROR(temp, "rdma migration: error registering %d control!",
M
Michael R. Hines 已提交
2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
                                                            idx);
            goto err_rdma_source_init;
        }
    }

    return 0;

err_rdma_source_init:
    error_propagate(errp, local_err);
    qemu_rdma_cleanup(rdma);
    return -1;
}

static int qemu_rdma_connect(RDMAContext *rdma, Error **errp)
{
    RDMACapabilities cap = {
                                .version = RDMA_CONTROL_VERSION_CURRENT,
                                .flags = 0,
                           };
    struct rdma_conn_param conn_param = { .initiator_depth = 2,
                                          .retry_count = 5,
                                          .private_data = &cap,
                                          .private_data_len = sizeof(cap),
                                        };
    struct rdma_cm_event *cm_event;
    int ret;

    /*
     * Only negotiate the capability with destination if the user
     * on the source first requested the capability.
     */
    if (rdma->pin_all) {
2425
        trace_qemu_rdma_connect_pin_all_requested();
M
Michael R. Hines 已提交
2426 2427 2428 2429 2430
        cap.flags |= RDMA_CAPABILITY_PIN_ALL;
    }

    caps_to_network(&cap);

2431 2432 2433 2434 2435 2436
    ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
    if (ret) {
        ERROR(errp, "posting second control recv");
        goto err_rdma_source_connect;
    }

M
Michael R. Hines 已提交
2437 2438 2439
    ret = rdma_connect(rdma->cm_id, &conn_param);
    if (ret) {
        perror("rdma_connect");
2440
        ERROR(errp, "connecting to destination!");
M
Michael R. Hines 已提交
2441 2442 2443 2444 2445 2446
        goto err_rdma_source_connect;
    }

    ret = rdma_get_cm_event(rdma->channel, &cm_event);
    if (ret) {
        perror("rdma_get_cm_event after rdma_connect");
2447
        ERROR(errp, "connecting to destination!");
M
Michael R. Hines 已提交
2448 2449 2450 2451 2452 2453
        rdma_ack_cm_event(cm_event);
        goto err_rdma_source_connect;
    }

    if (cm_event->event != RDMA_CM_EVENT_ESTABLISHED) {
        perror("rdma_get_cm_event != EVENT_ESTABLISHED after rdma_connect");
2454
        ERROR(errp, "connecting to destination!");
M
Michael R. Hines 已提交
2455 2456 2457
        rdma_ack_cm_event(cm_event);
        goto err_rdma_source_connect;
    }
2458
    rdma->connected = true;
M
Michael R. Hines 已提交
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468

    memcpy(&cap, cm_event->param.conn.private_data, sizeof(cap));
    network_to_caps(&cap);

    /*
     * Verify that the *requested* capabilities are supported by the destination
     * and disable them otherwise.
     */
    if (rdma->pin_all && !(cap.flags & RDMA_CAPABILITY_PIN_ALL)) {
        ERROR(errp, "Server cannot support pinning all memory. "
2469
                        "Will register memory dynamically.");
M
Michael R. Hines 已提交
2470 2471 2472
        rdma->pin_all = false;
    }

2473
    trace_qemu_rdma_connect_pin_all_outcome(rdma->pin_all);
M
Michael R. Hines 已提交
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487

    rdma_ack_cm_event(cm_event);

    rdma->control_ready_expected = 1;
    rdma->nb_sent = 0;
    return 0;

err_rdma_source_connect:
    qemu_rdma_cleanup(rdma);
    return -1;
}

static int qemu_rdma_dest_init(RDMAContext *rdma, Error **errp)
{
2488
    int ret, idx;
M
Michael R. Hines 已提交
2489 2490
    struct rdma_cm_id *listen_id;
    char ip[40] = "unknown";
2491
    struct rdma_addrinfo *res, *e;
2492
    char port_str[16];
M
Michael R. Hines 已提交
2493

2494
    for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
M
Michael R. Hines 已提交
2495 2496 2497 2498
        rdma->wr_data[idx].control_len = 0;
        rdma->wr_data[idx].control_curr = NULL;
    }

2499
    if (!rdma->host || !rdma->host[0]) {
2500
        ERROR(errp, "RDMA host is not set!");
M
Michael R. Hines 已提交
2501 2502 2503 2504 2505 2506
        rdma->error_state = -EINVAL;
        return -1;
    }
    /* create CM channel */
    rdma->channel = rdma_create_event_channel();
    if (!rdma->channel) {
2507
        ERROR(errp, "could not create rdma event channel");
M
Michael R. Hines 已提交
2508 2509 2510 2511 2512 2513 2514
        rdma->error_state = -EINVAL;
        return -1;
    }

    /* create CM id */
    ret = rdma_create_id(rdma->channel, &listen_id, NULL, RDMA_PS_TCP);
    if (ret) {
2515
        ERROR(errp, "could not create cm_id!");
M
Michael R. Hines 已提交
2516 2517 2518
        goto err_dest_init_create_listen_id;
    }

2519 2520
    snprintf(port_str, 16, "%d", rdma->port);
    port_str[15] = '\0';
M
Michael R. Hines 已提交
2521

2522 2523 2524 2525 2526
    ret = rdma_getaddrinfo(rdma->host, port_str, NULL, &res);
    if (ret < 0) {
        ERROR(errp, "could not rdma_getaddrinfo address %s", rdma->host);
        goto err_dest_init_bind_addr;
    }
2527

2528 2529 2530 2531 2532 2533 2534
    for (e = res; e != NULL; e = e->ai_next) {
        inet_ntop(e->ai_family,
            &((struct sockaddr_in *) e->ai_dst_addr)->sin_addr, ip, sizeof ip);
        trace_qemu_rdma_dest_init_trying(rdma->host, ip);
        ret = rdma_bind_addr(listen_id, e->ai_dst_addr);
        if (ret) {
            continue;
M
Michael R. Hines 已提交
2535
        }
2536
        if (e->ai_family == AF_INET6) {
2537
            ret = qemu_rdma_broken_ipv6_kernel(listen_id->verbs, errp);
2538 2539
            if (ret) {
                continue;
2540 2541
            }
        }
2542 2543
        break;
    }
2544

2545
    if (!e) {
2546 2547
        ERROR(errp, "Error: could not rdma_bind_addr!");
        goto err_dest_init_bind_addr;
M
Michael R. Hines 已提交
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569
    }

    rdma->listen_id = listen_id;
    qemu_rdma_dump_gid("dest_init", listen_id);
    return 0;

err_dest_init_bind_addr:
    rdma_destroy_id(listen_id);
err_dest_init_create_listen_id:
    rdma_destroy_event_channel(rdma->channel);
    rdma->channel = NULL;
    rdma->error_state = ret;
    return ret;

}

static void *qemu_rdma_data_init(const char *host_port, Error **errp)
{
    RDMAContext *rdma = NULL;
    InetSocketAddress *addr;

    if (host_port) {
2570
        rdma = g_new0(RDMAContext, 1);
M
Michael R. Hines 已提交
2571 2572 2573
        rdma->current_index = -1;
        rdma->current_chunk = -1;

2574 2575
        addr = g_new(InetSocketAddress, 1);
        if (!inet_parse(addr, host_port, NULL)) {
M
Michael R. Hines 已提交
2576 2577 2578 2579 2580
            rdma->port = atoi(addr->port);
            rdma->host = g_strdup(addr->host);
        } else {
            ERROR(errp, "bad RDMA migration address '%s'", host_port);
            g_free(rdma);
M
Michael R. Hines 已提交
2581
            rdma = NULL;
M
Michael R. Hines 已提交
2582
        }
M
Michael R. Hines 已提交
2583 2584

        qapi_free_InetSocketAddress(addr);
M
Michael R. Hines 已提交
2585 2586 2587 2588 2589 2590 2591 2592
    }

    return rdma;
}

/*
 * QEMUFile interface to the control channel.
 * SEND messages for control only.
2593
 * VM's ram is handled with regular RDMA messages.
M
Michael R. Hines 已提交
2594
 */
2595 2596 2597 2598 2599 2600 2601 2602 2603 2604
static ssize_t qio_channel_rdma_writev(QIOChannel *ioc,
                                       const struct iovec *iov,
                                       size_t niov,
                                       int *fds,
                                       size_t nfds,
                                       Error **errp)
{
    QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
    QEMUFile *f = rioc->file;
    RDMAContext *rdma = rioc->rdma;
M
Michael R. Hines 已提交
2605
    int ret;
2606 2607
    ssize_t done = 0;
    size_t i;
M
Michael R. Hines 已提交
2608 2609 2610 2611 2612

    CHECK_ERROR_STATE();

    /*
     * Push out any writes that
2613
     * we're queued up for VM's ram.
M
Michael R. Hines 已提交
2614 2615 2616 2617 2618 2619 2620
     */
    ret = qemu_rdma_write_flush(f, rdma);
    if (ret < 0) {
        rdma->error_state = ret;
        return ret;
    }

2621 2622 2623 2624 2625
    for (i = 0; i < niov; i++) {
        size_t remaining = iov[i].iov_len;
        uint8_t * data = (void *)iov[i].iov_base;
        while (remaining) {
            RDMAControlHeader head;
M
Michael R. Hines 已提交
2626

2627 2628
            rioc->len = MIN(remaining, RDMA_SEND_INCREMENT);
            remaining -= rioc->len;
M
Michael R. Hines 已提交
2629

2630 2631
            head.len = rioc->len;
            head.type = RDMA_CONTROL_QEMU_FILE;
M
Michael R. Hines 已提交
2632

2633
            ret = qemu_rdma_exchange_send(rdma, &head, data, NULL, NULL, NULL);
M
Michael R. Hines 已提交
2634

2635 2636 2637 2638
            if (ret < 0) {
                rdma->error_state = ret;
                return ret;
            }
M
Michael R. Hines 已提交
2639

2640 2641 2642
            data += rioc->len;
            done += rioc->len;
        }
M
Michael R. Hines 已提交
2643 2644
    }

2645
    return done;
M
Michael R. Hines 已提交
2646 2647 2648
}

static size_t qemu_rdma_fill(RDMAContext *rdma, uint8_t *buf,
2649
                             size_t size, int idx)
M
Michael R. Hines 已提交
2650 2651 2652 2653
{
    size_t len = 0;

    if (rdma->wr_data[idx].control_len) {
2654
        trace_qemu_rdma_fill(rdma->wr_data[idx].control_len, size);
M
Michael R. Hines 已提交
2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669

        len = MIN(size, rdma->wr_data[idx].control_len);
        memcpy(buf, rdma->wr_data[idx].control_curr, len);
        rdma->wr_data[idx].control_curr += len;
        rdma->wr_data[idx].control_len -= len;
    }

    return len;
}

/*
 * QEMUFile interface to the control channel.
 * RDMA links don't use bytestreams, so we have to
 * return bytes to QEMUFile opportunistically.
 */
2670 2671 2672 2673 2674 2675 2676 2677 2678
static ssize_t qio_channel_rdma_readv(QIOChannel *ioc,
                                      const struct iovec *iov,
                                      size_t niov,
                                      int **fds,
                                      size_t *nfds,
                                      Error **errp)
{
    QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
    RDMAContext *rdma = rioc->rdma;
M
Michael R. Hines 已提交
2679 2680
    RDMAControlHeader head;
    int ret = 0;
2681 2682
    ssize_t i;
    size_t done = 0;
M
Michael R. Hines 已提交
2683 2684 2685

    CHECK_ERROR_STATE();

2686 2687 2688
    for (i = 0; i < niov; i++) {
        size_t want = iov[i].iov_len;
        uint8_t *data = (void *)iov[i].iov_base;
M
Michael R. Hines 已提交
2689

2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
        /*
         * First, we hold on to the last SEND message we
         * were given and dish out the bytes until we run
         * out of bytes.
         */
        ret = qemu_rdma_fill(rioc->rdma, data, want, 0);
        done += ret;
        want -= ret;
        /* Got what we needed, so go to next iovec */
        if (want == 0) {
            continue;
        }
M
Michael R. Hines 已提交
2702

2703 2704 2705 2706 2707
        /* If we got any data so far, then don't wait
         * for more, just return what we have */
        if (done > 0) {
            break;
        }
M
Michael R. Hines 已提交
2708

2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737

        /* We've got nothing at all, so lets wait for
         * more to arrive
         */
        ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_QEMU_FILE);

        if (ret < 0) {
            rdma->error_state = ret;
            return ret;
        }

        /*
         * SEND was received with new bytes, now try again.
         */
        ret = qemu_rdma_fill(rioc->rdma, data, want, 0);
        done += ret;
        want -= ret;

        /* Still didn't get enough, so lets just return */
        if (want) {
            if (done == 0) {
                return QIO_CHANNEL_ERR_BLOCK;
            } else {
                break;
            }
        }
    }
    rioc->len = done;
    return rioc->len;
M
Michael R. Hines 已提交
2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751
}

/*
 * Block until all the outstanding chunks have been delivered by the hardware.
 */
static int qemu_rdma_drain_cq(QEMUFile *f, RDMAContext *rdma)
{
    int ret;

    if (qemu_rdma_write_flush(f, rdma) < 0) {
        return -EIO;
    }

    while (rdma->nb_sent) {
2752
        ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL);
M
Michael R. Hines 已提交
2753
        if (ret < 0) {
2754
            error_report("rdma migration: complete polling error!");
M
Michael R. Hines 已提交
2755 2756 2757 2758 2759 2760 2761 2762 2763
            return -EIO;
        }
    }

    qemu_rdma_unregister_waiting(rdma);

    return 0;
}

2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851

static int qio_channel_rdma_set_blocking(QIOChannel *ioc,
                                         bool blocking,
                                         Error **errp)
{
    QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
    /* XXX we should make readv/writev actually honour this :-) */
    rioc->blocking = blocking;
    return 0;
}


typedef struct QIOChannelRDMASource QIOChannelRDMASource;
struct QIOChannelRDMASource {
    GSource parent;
    QIOChannelRDMA *rioc;
    GIOCondition condition;
};

static gboolean
qio_channel_rdma_source_prepare(GSource *source,
                                gint *timeout)
{
    QIOChannelRDMASource *rsource = (QIOChannelRDMASource *)source;
    RDMAContext *rdma = rsource->rioc->rdma;
    GIOCondition cond = 0;
    *timeout = -1;

    if (rdma->wr_data[0].control_len) {
        cond |= G_IO_IN;
    }
    cond |= G_IO_OUT;

    return cond & rsource->condition;
}

static gboolean
qio_channel_rdma_source_check(GSource *source)
{
    QIOChannelRDMASource *rsource = (QIOChannelRDMASource *)source;
    RDMAContext *rdma = rsource->rioc->rdma;
    GIOCondition cond = 0;

    if (rdma->wr_data[0].control_len) {
        cond |= G_IO_IN;
    }
    cond |= G_IO_OUT;

    return cond & rsource->condition;
}

static gboolean
qio_channel_rdma_source_dispatch(GSource *source,
                                 GSourceFunc callback,
                                 gpointer user_data)
{
    QIOChannelFunc func = (QIOChannelFunc)callback;
    QIOChannelRDMASource *rsource = (QIOChannelRDMASource *)source;
    RDMAContext *rdma = rsource->rioc->rdma;
    GIOCondition cond = 0;

    if (rdma->wr_data[0].control_len) {
        cond |= G_IO_IN;
    }
    cond |= G_IO_OUT;

    return (*func)(QIO_CHANNEL(rsource->rioc),
                   (cond & rsource->condition),
                   user_data);
}

static void
qio_channel_rdma_source_finalize(GSource *source)
{
    QIOChannelRDMASource *ssource = (QIOChannelRDMASource *)source;

    object_unref(OBJECT(ssource->rioc));
}

GSourceFuncs qio_channel_rdma_source_funcs = {
    qio_channel_rdma_source_prepare,
    qio_channel_rdma_source_check,
    qio_channel_rdma_source_dispatch,
    qio_channel_rdma_source_finalize
};

static GSource *qio_channel_rdma_create_watch(QIOChannel *ioc,
                                              GIOCondition condition)
M
Michael R. Hines 已提交
2852
{
2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873
    QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
    QIOChannelRDMASource *ssource;
    GSource *source;

    source = g_source_new(&qio_channel_rdma_source_funcs,
                          sizeof(QIOChannelRDMASource));
    ssource = (QIOChannelRDMASource *)source;

    ssource->rioc = rioc;
    object_ref(OBJECT(rioc));

    ssource->condition = condition;

    return source;
}


static int qio_channel_rdma_close(QIOChannel *ioc,
                                  Error **errp)
{
    QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(ioc);
2874
    trace_qemu_rdma_close();
2875
    if (rioc->rdma) {
2876 2877 2878
        if (!rioc->rdma->error_state) {
            rioc->rdma->error_state = qemu_file_get_error(rioc->file);
        }
2879 2880 2881
        qemu_rdma_cleanup(rioc->rdma);
        g_free(rioc->rdma);
        rioc->rdma = NULL;
M
Michael R. Hines 已提交
2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903
    }
    return 0;
}

/*
 * Parameters:
 *    @offset == 0 :
 *        This means that 'block_offset' is a full virtual address that does not
 *        belong to a RAMBlock of the virtual machine and instead
 *        represents a private malloc'd memory area that the caller wishes to
 *        transfer.
 *
 *    @offset != 0 :
 *        Offset is an offset to be added to block_offset and used
 *        to also lookup the corresponding RAMBlock.
 *
 *    @size > 0 :
 *        Initiate an transfer this size.
 *
 *    @size == 0 :
 *        A 'hint' or 'advice' that means that we wish to speculatively
 *        and asynchronously unregister this memory. In this case, there is no
2904
 *        guarantee that the unregister will actually happen, for example,
M
Michael R. Hines 已提交
2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921
 *        if the memory is being actively transmitted. Additionally, the memory
 *        may be re-registered at any future time if a write within the same
 *        chunk was requested again, even if you attempted to unregister it
 *        here.
 *
 *    @size < 0 : TODO, not yet supported
 *        Unregister the memory NOW. This means that the caller does not
 *        expect there to be any future RDMA transfers and we just want to clean
 *        things up. This is used in case the upper layer owns the memory and
 *        cannot wait for qemu_fclose() to occur.
 *
 *    @bytes_sent : User-specificed pointer to indicate how many bytes were
 *                  sent. Usually, this will not be more than a few bytes of
 *                  the protocol because most transfers are sent asynchronously.
 */
static size_t qemu_rdma_save_page(QEMUFile *f, void *opaque,
                                  ram_addr_t block_offset, ram_addr_t offset,
2922
                                  size_t size, uint64_t *bytes_sent)
M
Michael R. Hines 已提交
2923
{
2924 2925
    QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(opaque);
    RDMAContext *rdma = rioc->rdma;
M
Michael R. Hines 已提交
2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939
    int ret;

    CHECK_ERROR_STATE();

    qemu_fflush(f);

    if (size > 0) {
        /*
         * Add this page to the current 'chunk'. If the chunk
         * is full, or the page doen't belong to the current chunk,
         * an actual RDMA write will occur and a new chunk will be formed.
         */
        ret = qemu_rdma_write(f, rdma, block_offset, offset, size);
        if (ret < 0) {
2940
            error_report("rdma migration: write error! %d", ret);
M
Michael R. Hines 已提交
2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972
            goto err;
        }

        /*
         * We always return 1 bytes because the RDMA
         * protocol is completely asynchronous. We do not yet know
         * whether an  identified chunk is zero or not because we're
         * waiting for other pages to potentially be merged with
         * the current chunk. So, we have to call qemu_update_position()
         * later on when the actual write occurs.
         */
        if (bytes_sent) {
            *bytes_sent = 1;
        }
    } else {
        uint64_t index, chunk;

        /* TODO: Change QEMUFileOps prototype to be signed: size_t => long
        if (size < 0) {
            ret = qemu_rdma_drain_cq(f, rdma);
            if (ret < 0) {
                fprintf(stderr, "rdma: failed to synchronously drain"
                                " completion queue before unregistration.\n");
                goto err;
            }
        }
        */

        ret = qemu_rdma_search_ram_block(rdma, block_offset,
                                         offset, size, &index, &chunk);

        if (ret) {
2973
            error_report("ram block search failed");
M
Michael R. Hines 已提交
2974 2975 2976 2977 2978 2979
            goto err;
        }

        qemu_rdma_signal_unregister(rdma, index, chunk, 0);

        /*
2980
         * TODO: Synchronous, guaranteed unregistration (should not occur during
M
Michael R. Hines 已提交
2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997
         * fast-path). Otherwise, unregisters will process on the next call to
         * qemu_rdma_drain_cq()
        if (size < 0) {
            qemu_rdma_unregister_waiting(rdma);
        }
        */
    }

    /*
     * Drain the Completion Queue if possible, but do not block,
     * just poll.
     *
     * If nothing to poll, the end of the iteration will do this
     * again to make sure we don't overflow the request queue.
     */
    while (1) {
        uint64_t wr_id, wr_id_in;
2998
        int ret = qemu_rdma_poll(rdma, &wr_id_in, NULL);
M
Michael R. Hines 已提交
2999
        if (ret < 0) {
3000
            error_report("rdma migration: polling error! %d", ret);
M
Michael R. Hines 已提交
3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044
            goto err;
        }

        wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;

        if (wr_id == RDMA_WRID_NONE) {
            break;
        }
    }

    return RAM_SAVE_CONTROL_DELAYED;
err:
    rdma->error_state = ret;
    return ret;
}

static int qemu_rdma_accept(RDMAContext *rdma)
{
    RDMACapabilities cap;
    struct rdma_conn_param conn_param = {
                                            .responder_resources = 2,
                                            .private_data = &cap,
                                            .private_data_len = sizeof(cap),
                                         };
    struct rdma_cm_event *cm_event;
    struct ibv_context *verbs;
    int ret = -EINVAL;
    int idx;

    ret = rdma_get_cm_event(rdma->channel, &cm_event);
    if (ret) {
        goto err_rdma_dest_wait;
    }

    if (cm_event->event != RDMA_CM_EVENT_CONNECT_REQUEST) {
        rdma_ack_cm_event(cm_event);
        goto err_rdma_dest_wait;
    }

    memcpy(&cap, cm_event->param.conn.private_data, sizeof(cap));

    network_to_caps(&cap);

    if (cap.version < 1 || cap.version > RDMA_CONTROL_VERSION_CURRENT) {
3045
            error_report("Unknown source RDMA version: %d, bailing...",
M
Michael R. Hines 已提交
3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068
                            cap.version);
            rdma_ack_cm_event(cm_event);
            goto err_rdma_dest_wait;
    }

    /*
     * Respond with only the capabilities this version of QEMU knows about.
     */
    cap.flags &= known_capabilities;

    /*
     * Enable the ones that we do know about.
     * Add other checks here as new ones are introduced.
     */
    if (cap.flags & RDMA_CAPABILITY_PIN_ALL) {
        rdma->pin_all = true;
    }

    rdma->cm_id = cm_event->id;
    verbs = cm_event->id->verbs;

    rdma_ack_cm_event(cm_event);

3069
    trace_qemu_rdma_accept_pin_state(rdma->pin_all);
M
Michael R. Hines 已提交
3070 3071 3072

    caps_to_network(&cap);

3073
    trace_qemu_rdma_accept_pin_verbsc(verbs);
M
Michael R. Hines 已提交
3074 3075 3076 3077

    if (!rdma->verbs) {
        rdma->verbs = verbs;
    } else if (rdma->verbs != verbs) {
3078 3079
            error_report("ibv context not matching %p, %p!", rdma->verbs,
                         verbs);
M
Michael R. Hines 已提交
3080 3081 3082 3083 3084 3085 3086
            goto err_rdma_dest_wait;
    }

    qemu_rdma_dump_id("dest_init", verbs);

    ret = qemu_rdma_alloc_pd_cq(rdma);
    if (ret) {
3087
        error_report("rdma migration: error allocating pd and cq!");
M
Michael R. Hines 已提交
3088 3089 3090 3091 3092
        goto err_rdma_dest_wait;
    }

    ret = qemu_rdma_alloc_qp(rdma);
    if (ret) {
3093
        error_report("rdma migration: error allocating qp!");
M
Michael R. Hines 已提交
3094 3095 3096 3097 3098
        goto err_rdma_dest_wait;
    }

    ret = qemu_rdma_init_ram_blocks(rdma);
    if (ret) {
3099
        error_report("rdma migration: error initializing ram blocks!");
M
Michael R. Hines 已提交
3100 3101 3102
        goto err_rdma_dest_wait;
    }

3103
    for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
M
Michael R. Hines 已提交
3104 3105
        ret = qemu_rdma_reg_control(rdma, idx);
        if (ret) {
3106
            error_report("rdma: error registering %d control", idx);
M
Michael R. Hines 已提交
3107 3108 3109 3110
            goto err_rdma_dest_wait;
        }
    }

3111
    qemu_set_fd_handler(rdma->channel->fd, NULL, NULL, NULL);
M
Michael R. Hines 已提交
3112 3113 3114

    ret = rdma_accept(rdma->cm_id, &conn_param);
    if (ret) {
3115
        error_report("rdma_accept returns %d", ret);
M
Michael R. Hines 已提交
3116 3117 3118 3119 3120
        goto err_rdma_dest_wait;
    }

    ret = rdma_get_cm_event(rdma->channel, &cm_event);
    if (ret) {
3121
        error_report("rdma_accept get_cm_event failed %d", ret);
M
Michael R. Hines 已提交
3122 3123 3124 3125
        goto err_rdma_dest_wait;
    }

    if (cm_event->event != RDMA_CM_EVENT_ESTABLISHED) {
3126
        error_report("rdma_accept not event established");
M
Michael R. Hines 已提交
3127 3128 3129 3130 3131
        rdma_ack_cm_event(cm_event);
        goto err_rdma_dest_wait;
    }

    rdma_ack_cm_event(cm_event);
3132
    rdma->connected = true;
M
Michael R. Hines 已提交
3133

I
Isaku Yamahata 已提交
3134
    ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
M
Michael R. Hines 已提交
3135
    if (ret) {
3136
        error_report("rdma migration: error posting second control recv");
M
Michael R. Hines 已提交
3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149
        goto err_rdma_dest_wait;
    }

    qemu_rdma_dump_gid("dest_connect", rdma->cm_id);

    return 0;

err_rdma_dest_wait:
    rdma->error_state = ret;
    qemu_rdma_cleanup(rdma);
    return ret;
}

3150 3151 3152 3153 3154 3155 3156 3157
static int dest_ram_sort_func(const void *a, const void *b)
{
    unsigned int a_index = ((const RDMALocalBlock *)a)->src_index;
    unsigned int b_index = ((const RDMALocalBlock *)b)->src_index;

    return (a_index < b_index) ? -1 : (a_index != b_index);
}

M
Michael R. Hines 已提交
3158 3159 3160 3161 3162 3163 3164 3165 3166
/*
 * During each iteration of the migration, we listen for instructions
 * by the source VM to perform dynamic page registrations before they
 * can perform RDMA operations.
 *
 * We respond with the 'rkey'.
 *
 * Keep doing this until the source tells us to stop.
 */
3167
static int qemu_rdma_registration_handle(QEMUFile *f, void *opaque)
M
Michael R. Hines 已提交
3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178
{
    RDMAControlHeader reg_resp = { .len = sizeof(RDMARegisterResult),
                               .type = RDMA_CONTROL_REGISTER_RESULT,
                               .repeat = 0,
                             };
    RDMAControlHeader unreg_resp = { .len = 0,
                               .type = RDMA_CONTROL_UNREGISTER_FINISHED,
                               .repeat = 0,
                             };
    RDMAControlHeader blocks = { .type = RDMA_CONTROL_RAM_BLOCKS_RESULT,
                                 .repeat = 1 };
3179 3180
    QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(opaque);
    RDMAContext *rdma = rioc->rdma;
M
Michael R. Hines 已提交
3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196
    RDMALocalBlocks *local = &rdma->local_ram_blocks;
    RDMAControlHeader head;
    RDMARegister *reg, *registers;
    RDMACompress *comp;
    RDMARegisterResult *reg_result;
    static RDMARegisterResult results[RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE];
    RDMALocalBlock *block;
    void *host_addr;
    int ret = 0;
    int idx = 0;
    int count = 0;
    int i = 0;

    CHECK_ERROR_STATE();

    do {
3197
        trace_qemu_rdma_registration_handle_wait();
M
Michael R. Hines 已提交
3198 3199 3200 3201 3202 3203 3204 3205

        ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_NONE);

        if (ret < 0) {
            break;
        }

        if (head.repeat > RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE) {
3206 3207
            error_report("rdma: Too many requests in this message (%d)."
                            "Bailing.", head.repeat);
M
Michael R. Hines 已提交
3208 3209 3210 3211 3212 3213 3214 3215 3216
            ret = -EIO;
            break;
        }

        switch (head.type) {
        case RDMA_CONTROL_COMPRESS:
            comp = (RDMACompress *) rdma->wr_data[idx].control_curr;
            network_to_compress(comp);

3217 3218 3219
            trace_qemu_rdma_registration_handle_compress(comp->length,
                                                         comp->block_idx,
                                                         comp->offset);
3220 3221 3222 3223 3224
            if (comp->block_idx >= rdma->local_ram_blocks.nb_blocks) {
                error_report("rdma: 'compress' bad block index %u (vs %d)",
                             (unsigned int)comp->block_idx,
                             rdma->local_ram_blocks.nb_blocks);
                ret = -EIO;
D
Dr. David Alan Gilbert 已提交
3225
                goto out;
3226
            }
M
Michael R. Hines 已提交
3227 3228 3229 3230 3231 3232 3233 3234 3235
            block = &(rdma->local_ram_blocks.block[comp->block_idx]);

            host_addr = block->local_host_addr +
                            (comp->offset - block->offset);

            ram_handle_compressed(host_addr, comp->value, comp->length);
            break;

        case RDMA_CONTROL_REGISTER_FINISHED:
3236
            trace_qemu_rdma_registration_handle_finished();
M
Michael R. Hines 已提交
3237 3238 3239
            goto out;

        case RDMA_CONTROL_RAM_BLOCKS_REQUEST:
3240
            trace_qemu_rdma_registration_handle_ram_blocks();
M
Michael R. Hines 已提交
3241

3242 3243 3244 3245 3246 3247 3248
            /* Sort our local RAM Block list so it's the same as the source,
             * we can do this since we've filled in a src_index in the list
             * as we received the RAMBlock list earlier.
             */
            qsort(rdma->local_ram_blocks.block,
                  rdma->local_ram_blocks.nb_blocks,
                  sizeof(RDMALocalBlock), dest_ram_sort_func);
M
Michael R. Hines 已提交
3249 3250 3251
            if (rdma->pin_all) {
                ret = qemu_rdma_reg_whole_ram_blocks(rdma);
                if (ret) {
3252 3253
                    error_report("rdma migration: error dest "
                                    "registering ram blocks");
M
Michael R. Hines 已提交
3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264
                    goto out;
                }
            }

            /*
             * Dest uses this to prepare to transmit the RAMBlock descriptions
             * to the source VM after connection setup.
             * Both sides use the "remote" structure to communicate and update
             * their "local" descriptions with what was sent.
             */
            for (i = 0; i < local->nb_blocks; i++) {
3265
                rdma->dest_blocks[i].remote_host_addr =
3266
                    (uintptr_t)(local->block[i].local_host_addr);
M
Michael R. Hines 已提交
3267 3268

                if (rdma->pin_all) {
3269
                    rdma->dest_blocks[i].remote_rkey = local->block[i].mr->rkey;
M
Michael R. Hines 已提交
3270 3271
                }

3272 3273
                rdma->dest_blocks[i].offset = local->block[i].offset;
                rdma->dest_blocks[i].length = local->block[i].length;
M
Michael R. Hines 已提交
3274

3275
                dest_block_to_network(&rdma->dest_blocks[i]);
3276 3277 3278 3279 3280 3281
                trace_qemu_rdma_registration_handle_ram_blocks_loop(
                    local->block[i].block_name,
                    local->block[i].offset,
                    local->block[i].length,
                    local->block[i].local_host_addr,
                    local->block[i].src_index);
M
Michael R. Hines 已提交
3282 3283 3284
            }

            blocks.len = rdma->local_ram_blocks.nb_blocks
3285
                                                * sizeof(RDMADestBlock);
M
Michael R. Hines 已提交
3286 3287 3288


            ret = qemu_rdma_post_send_control(rdma,
3289
                                        (uint8_t *) rdma->dest_blocks, &blocks);
M
Michael R. Hines 已提交
3290 3291

            if (ret < 0) {
3292
                error_report("rdma migration: error sending remote info");
M
Michael R. Hines 已提交
3293 3294 3295 3296 3297
                goto out;
            }

            break;
        case RDMA_CONTROL_REGISTER_REQUEST:
3298
            trace_qemu_rdma_registration_handle_register(head.repeat);
M
Michael R. Hines 已提交
3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311

            reg_resp.repeat = head.repeat;
            registers = (RDMARegister *) rdma->wr_data[idx].control_curr;

            for (count = 0; count < head.repeat; count++) {
                uint64_t chunk;
                uint8_t *chunk_start, *chunk_end;

                reg = &registers[count];
                network_to_register(reg);

                reg_result = &results[count];

3312
                trace_qemu_rdma_registration_handle_register_loop(count,
M
Michael R. Hines 已提交
3313 3314
                         reg->current_index, reg->key.current_addr, reg->chunks);

3315 3316 3317 3318 3319
                if (reg->current_index >= rdma->local_ram_blocks.nb_blocks) {
                    error_report("rdma: 'register' bad block index %u (vs %d)",
                                 (unsigned int)reg->current_index,
                                 rdma->local_ram_blocks.nb_blocks);
                    ret = -ENOENT;
D
Dr. David Alan Gilbert 已提交
3320
                    goto out;
3321
                }
M
Michael R. Hines 已提交
3322 3323
                block = &(rdma->local_ram_blocks.block[reg->current_index]);
                if (block->is_ram_block) {
3324 3325 3326 3327 3328 3329
                    if (block->offset > reg->key.current_addr) {
                        error_report("rdma: bad register address for block %s"
                            " offset: %" PRIx64 " current_addr: %" PRIx64,
                            block->block_name, block->offset,
                            reg->key.current_addr);
                        ret = -ERANGE;
D
Dr. David Alan Gilbert 已提交
3330
                        goto out;
3331
                    }
M
Michael R. Hines 已提交
3332 3333 3334 3335 3336 3337 3338 3339
                    host_addr = (block->local_host_addr +
                                (reg->key.current_addr - block->offset));
                    chunk = ram_chunk_index(block->local_host_addr,
                                            (uint8_t *) host_addr);
                } else {
                    chunk = reg->key.chunk;
                    host_addr = block->local_host_addr +
                        (reg->key.chunk * (1UL << RDMA_REG_CHUNK_SHIFT));
3340 3341 3342 3343 3344 3345
                    /* Check for particularly bad chunk value */
                    if (host_addr < (void *)block->local_host_addr) {
                        error_report("rdma: bad chunk for block %s"
                            " chunk: %" PRIx64,
                            block->block_name, reg->key.chunk);
                        ret = -ERANGE;
D
Dr. David Alan Gilbert 已提交
3346
                        goto out;
3347
                    }
M
Michael R. Hines 已提交
3348 3349 3350 3351
                }
                chunk_start = ram_chunk_start(block, chunk);
                chunk_end = ram_chunk_end(block, chunk + reg->chunks);
                if (qemu_rdma_register_and_get_keys(rdma, block,
3352
                            (uintptr_t)host_addr, NULL, &reg_result->rkey,
M
Michael R. Hines 已提交
3353
                            chunk, chunk_start, chunk_end)) {
3354
                    error_report("cannot get rkey");
M
Michael R. Hines 已提交
3355 3356 3357 3358
                    ret = -EINVAL;
                    goto out;
                }

3359
                reg_result->host_addr = (uintptr_t)block->local_host_addr;
M
Michael R. Hines 已提交
3360

3361 3362
                trace_qemu_rdma_registration_handle_register_rkey(
                                                           reg_result->rkey);
M
Michael R. Hines 已提交
3363 3364 3365 3366 3367 3368 3369 3370

                result_to_network(reg_result);
            }

            ret = qemu_rdma_post_send_control(rdma,
                            (uint8_t *) results, &reg_resp);

            if (ret < 0) {
3371
                error_report("Failed to send control buffer");
M
Michael R. Hines 已提交
3372 3373 3374 3375
                goto out;
            }
            break;
        case RDMA_CONTROL_UNREGISTER_REQUEST:
3376
            trace_qemu_rdma_registration_handle_unregister(head.repeat);
M
Michael R. Hines 已提交
3377 3378 3379 3380 3381 3382 3383
            unreg_resp.repeat = head.repeat;
            registers = (RDMARegister *) rdma->wr_data[idx].control_curr;

            for (count = 0; count < head.repeat; count++) {
                reg = &registers[count];
                network_to_register(reg);

3384 3385
                trace_qemu_rdma_registration_handle_unregister_loop(count,
                           reg->current_index, reg->key.chunk);
M
Michael R. Hines 已提交
3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399

                block = &(rdma->local_ram_blocks.block[reg->current_index]);

                ret = ibv_dereg_mr(block->pmr[reg->key.chunk]);
                block->pmr[reg->key.chunk] = NULL;

                if (ret != 0) {
                    perror("rdma unregistration chunk failed");
                    ret = -ret;
                    goto out;
                }

                rdma->total_registrations--;

3400 3401
                trace_qemu_rdma_registration_handle_unregister_success(
                                                       reg->key.chunk);
M
Michael R. Hines 已提交
3402 3403 3404 3405 3406
            }

            ret = qemu_rdma_post_send_control(rdma, NULL, &unreg_resp);

            if (ret < 0) {
3407
                error_report("Failed to send control buffer");
M
Michael R. Hines 已提交
3408 3409 3410 3411
                goto out;
            }
            break;
        case RDMA_CONTROL_REGISTER_RESULT:
3412
            error_report("Invalid RESULT message at dest.");
M
Michael R. Hines 已提交
3413 3414 3415
            ret = -EIO;
            goto out;
        default:
3416
            error_report("Unknown control message %s", control_desc(head.type));
M
Michael R. Hines 已提交
3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427
            ret = -EIO;
            goto out;
        }
    } while (1);
out:
    if (ret < 0) {
        rdma->error_state = ret;
    }
    return ret;
}

3428 3429 3430 3431 3432 3433 3434
/* Destination:
 * Called via a ram_control_load_hook during the initial RAM load section which
 * lists the RAMBlocks by name.  This lets us know the order of the RAMBlocks
 * on the source.
 * We've already built our local RAMBlock list, but not yet sent the list to
 * the source.
 */
3435 3436
static int
rdma_block_notification_handle(QIOChannelRDMA *rioc, const char *name)
3437
{
3438
    RDMAContext *rdma = rioc->rdma;
3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461
    int curr;
    int found = -1;

    /* Find the matching RAMBlock in our local list */
    for (curr = 0; curr < rdma->local_ram_blocks.nb_blocks; curr++) {
        if (!strcmp(rdma->local_ram_blocks.block[curr].block_name, name)) {
            found = curr;
            break;
        }
    }

    if (found == -1) {
        error_report("RAMBlock '%s' not found on destination", name);
        return -ENOENT;
    }

    rdma->local_ram_blocks.block[curr].src_index = rdma->next_src_index;
    trace_rdma_block_notification_handle(name, rdma->next_src_index);
    rdma->next_src_index++;

    return 0;
}

3462 3463 3464 3465
static int rdma_load_hook(QEMUFile *f, void *opaque, uint64_t flags, void *data)
{
    switch (flags) {
    case RAM_CONTROL_BLOCK_REG:
3466
        return rdma_block_notification_handle(opaque, data);
3467 3468 3469 3470 3471 3472 3473 3474 3475 3476

    case RAM_CONTROL_HOOK:
        return qemu_rdma_registration_handle(f, opaque);

    default:
        /* Shouldn't be called with any other values */
        abort();
    }
}

M
Michael R. Hines 已提交
3477
static int qemu_rdma_registration_start(QEMUFile *f, void *opaque,
3478
                                        uint64_t flags, void *data)
M
Michael R. Hines 已提交
3479
{
3480 3481
    QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(opaque);
    RDMAContext *rdma = rioc->rdma;
M
Michael R. Hines 已提交
3482 3483 3484

    CHECK_ERROR_STATE();

3485
    trace_qemu_rdma_registration_start(flags);
M
Michael R. Hines 已提交
3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496
    qemu_put_be64(f, RAM_SAVE_FLAG_HOOK);
    qemu_fflush(f);

    return 0;
}

/*
 * Inform dest that dynamic registrations are done for now.
 * First, flush writes, if any.
 */
static int qemu_rdma_registration_stop(QEMUFile *f, void *opaque,
3497
                                       uint64_t flags, void *data)
M
Michael R. Hines 已提交
3498 3499
{
    Error *local_err = NULL, **errp = &local_err;
3500 3501
    QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(opaque);
    RDMAContext *rdma = rioc->rdma;
M
Michael R. Hines 已提交
3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516
    RDMAControlHeader head = { .len = 0, .repeat = 1 };
    int ret = 0;

    CHECK_ERROR_STATE();

    qemu_fflush(f);
    ret = qemu_rdma_drain_cq(f, rdma);

    if (ret < 0) {
        goto err;
    }

    if (flags == RAM_CONTROL_SETUP) {
        RDMAControlHeader resp = {.type = RDMA_CONTROL_RAM_BLOCKS_RESULT };
        RDMALocalBlocks *local = &rdma->local_ram_blocks;
3517
        int reg_result_idx, i, nb_dest_blocks;
M
Michael R. Hines 已提交
3518 3519

        head.type = RDMA_CONTROL_RAM_BLOCKS_REQUEST;
3520
        trace_qemu_rdma_registration_stop_ram();
M
Michael R. Hines 已提交
3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533

        /*
         * Make sure that we parallelize the pinning on both sides.
         * For very large guests, doing this serially takes a really
         * long time, so we have to 'interleave' the pinning locally
         * with the control messages by performing the pinning on this
         * side before we receive the control response from the other
         * side that the pinning has completed.
         */
        ret = qemu_rdma_exchange_send(rdma, &head, NULL, &resp,
                    &reg_result_idx, rdma->pin_all ?
                    qemu_rdma_reg_whole_ram_blocks : NULL);
        if (ret < 0) {
3534
            ERROR(errp, "receiving remote info!");
M
Michael R. Hines 已提交
3535 3536 3537
            return ret;
        }

3538
        nb_dest_blocks = resp.len / sizeof(RDMADestBlock);
M
Michael R. Hines 已提交
3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551

        /*
         * The protocol uses two different sets of rkeys (mutually exclusive):
         * 1. One key to represent the virtual address of the entire ram block.
         *    (dynamic chunk registration disabled - pin everything with one rkey.)
         * 2. One to represent individual chunks within a ram block.
         *    (dynamic chunk registration enabled - pin individual chunks.)
         *
         * Once the capability is successfully negotiated, the destination transmits
         * the keys to use (or sends them later) including the virtual addresses
         * and then propagates the remote ram block descriptions to his local copy.
         */

3552
        if (local->nb_blocks != nb_dest_blocks) {
3553
            ERROR(errp, "ram blocks mismatch (Number of blocks %d vs %d) "
M
Michael R. Hines 已提交
3554
                        "Your QEMU command line parameters are probably "
3555 3556
                        "not identical on both the source and destination.",
                        local->nb_blocks, nb_dest_blocks);
3557
            rdma->error_state = -EINVAL;
M
Michael R. Hines 已提交
3558 3559 3560
            return -EINVAL;
        }

3561
        qemu_rdma_move_header(rdma, reg_result_idx, &resp);
3562
        memcpy(rdma->dest_blocks,
3563
            rdma->wr_data[reg_result_idx].control_curr, resp.len);
3564 3565
        for (i = 0; i < nb_dest_blocks; i++) {
            network_to_dest_block(&rdma->dest_blocks[i]);
M
Michael R. Hines 已提交
3566

3567 3568 3569 3570 3571 3572
            /* We require that the blocks are in the same order */
            if (rdma->dest_blocks[i].length != local->block[i].length) {
                ERROR(errp, "Block %s/%d has a different length %" PRIu64
                            "vs %" PRIu64, local->block[i].block_name, i,
                            local->block[i].length,
                            rdma->dest_blocks[i].length);
3573
                rdma->error_state = -EINVAL;
M
Michael R. Hines 已提交
3574 3575
                return -EINVAL;
            }
3576 3577 3578
            local->block[i].remote_host_addr =
                    rdma->dest_blocks[i].remote_host_addr;
            local->block[i].remote_rkey = rdma->dest_blocks[i].remote_rkey;
M
Michael R. Hines 已提交
3579 3580 3581
        }
    }

3582
    trace_qemu_rdma_registration_stop(flags);
M
Michael R. Hines 已提交
3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596

    head.type = RDMA_CONTROL_REGISTER_FINISHED;
    ret = qemu_rdma_exchange_send(rdma, &head, NULL, NULL, NULL, NULL);

    if (ret < 0) {
        goto err;
    }

    return 0;
err:
    rdma->error_state = ret;
    return ret;
}

3597
static const QEMUFileHooks rdma_read_hooks = {
3598
    .hook_ram_load = rdma_load_hook,
M
Michael R. Hines 已提交
3599 3600
};

3601
static const QEMUFileHooks rdma_write_hooks = {
M
Michael R. Hines 已提交
3602 3603 3604 3605 3606
    .before_ram_iterate = qemu_rdma_registration_start,
    .after_ram_iterate  = qemu_rdma_registration_stop,
    .save_page          = qemu_rdma_save_page,
};

3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645

static void qio_channel_rdma_finalize(Object *obj)
{
    QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(obj);
    if (rioc->rdma) {
        qemu_rdma_cleanup(rioc->rdma);
        g_free(rioc->rdma);
        rioc->rdma = NULL;
    }
}

static void qio_channel_rdma_class_init(ObjectClass *klass,
                                        void *class_data G_GNUC_UNUSED)
{
    QIOChannelClass *ioc_klass = QIO_CHANNEL_CLASS(klass);

    ioc_klass->io_writev = qio_channel_rdma_writev;
    ioc_klass->io_readv = qio_channel_rdma_readv;
    ioc_klass->io_set_blocking = qio_channel_rdma_set_blocking;
    ioc_klass->io_close = qio_channel_rdma_close;
    ioc_klass->io_create_watch = qio_channel_rdma_create_watch;
}

static const TypeInfo qio_channel_rdma_info = {
    .parent = TYPE_QIO_CHANNEL,
    .name = TYPE_QIO_CHANNEL_RDMA,
    .instance_size = sizeof(QIOChannelRDMA),
    .instance_finalize = qio_channel_rdma_finalize,
    .class_init = qio_channel_rdma_class_init,
};

static void qio_channel_rdma_register_types(void)
{
    type_register_static(&qio_channel_rdma_info);
}

type_init(qio_channel_rdma_register_types);

static QEMUFile *qemu_fopen_rdma(RDMAContext *rdma, const char *mode)
M
Michael R. Hines 已提交
3646
{
3647
    QIOChannelRDMA *rioc;
M
Michael R. Hines 已提交
3648 3649 3650 3651 3652

    if (qemu_file_mode_is_not_valid(mode)) {
        return NULL;
    }

3653 3654
    rioc = QIO_CHANNEL_RDMA(object_new(TYPE_QIO_CHANNEL_RDMA));
    rioc->rdma = rdma;
M
Michael R. Hines 已提交
3655 3656

    if (mode[0] == 'w') {
3657 3658
        rioc->file = qemu_fopen_channel_output(QIO_CHANNEL(rioc));
        qemu_file_set_hooks(rioc->file, &rdma_write_hooks);
M
Michael R. Hines 已提交
3659
    } else {
3660 3661
        rioc->file = qemu_fopen_channel_input(QIO_CHANNEL(rioc));
        qemu_file_set_hooks(rioc->file, &rdma_read_hooks);
M
Michael R. Hines 已提交
3662 3663
    }

3664
    return rioc->file;
M
Michael R. Hines 已提交
3665 3666 3667 3668 3669 3670 3671 3672 3673
}

static void rdma_accept_incoming_migration(void *opaque)
{
    RDMAContext *rdma = opaque;
    int ret;
    QEMUFile *f;
    Error *local_err = NULL, **errp = &local_err;

D
Dr. David Alan Gilbert 已提交
3674
    trace_qemu_rdma_accept_incoming_migration();
M
Michael R. Hines 已提交
3675 3676 3677
    ret = qemu_rdma_accept(rdma);

    if (ret) {
3678
        ERROR(errp, "RDMA Migration initialization failed!");
M
Michael R. Hines 已提交
3679 3680 3681
        return;
    }

D
Dr. David Alan Gilbert 已提交
3682
    trace_qemu_rdma_accept_incoming_migration_accepted();
M
Michael R. Hines 已提交
3683 3684 3685

    f = qemu_fopen_rdma(rdma, "rb");
    if (f == NULL) {
3686
        ERROR(errp, "could not qemu_fopen_rdma!");
M
Michael R. Hines 已提交
3687 3688 3689 3690 3691
        qemu_rdma_cleanup(rdma);
        return;
    }

    rdma->migration_started_on_destination = 1;
3692
    migration_fd_process_incoming(f);
M
Michael R. Hines 已提交
3693 3694 3695 3696 3697 3698 3699 3700
}

void rdma_start_incoming_migration(const char *host_port, Error **errp)
{
    int ret;
    RDMAContext *rdma;
    Error *local_err = NULL;

3701
    trace_rdma_start_incoming_migration();
M
Michael R. Hines 已提交
3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713
    rdma = qemu_rdma_data_init(host_port, &local_err);

    if (rdma == NULL) {
        goto err;
    }

    ret = qemu_rdma_dest_init(rdma, &local_err);

    if (ret) {
        goto err;
    }

3714
    trace_rdma_start_incoming_migration_after_dest_init();
M
Michael R. Hines 已提交
3715 3716 3717 3718

    ret = rdma_listen(rdma->listen_id, 5);

    if (ret) {
3719
        ERROR(errp, "listening on socket!");
M
Michael R. Hines 已提交
3720 3721 3722
        goto err;
    }

3723
    trace_rdma_start_incoming_migration_after_rdma_listen();
M
Michael R. Hines 已提交
3724

3725 3726
    qemu_set_fd_handler(rdma->channel->fd, rdma_accept_incoming_migration,
                        NULL, (void *)(intptr_t)rdma);
M
Michael R. Hines 已提交
3727 3728 3729 3730 3731 3732 3733 3734 3735 3736
    return;
err:
    error_propagate(errp, local_err);
    g_free(rdma);
}

void rdma_start_outgoing_migration(void *opaque,
                            const char *host_port, Error **errp)
{
    MigrationState *s = opaque;
3737
    RDMAContext *rdma = qemu_rdma_data_init(host_port, errp);
M
Michael R. Hines 已提交
3738 3739 3740 3741 3742 3743
    int ret = 0;

    if (rdma == NULL) {
        goto err;
    }

3744 3745
    ret = qemu_rdma_source_init(rdma,
        s->enabled_capabilities[MIGRATION_CAPABILITY_RDMA_PIN_ALL], errp);
M
Michael R. Hines 已提交
3746 3747 3748 3749 3750

    if (ret) {
        goto err;
    }

3751
    trace_rdma_start_outgoing_migration_after_rdma_source_init();
3752
    ret = qemu_rdma_connect(rdma, errp);
M
Michael R. Hines 已提交
3753 3754 3755 3756 3757

    if (ret) {
        goto err;
    }

3758
    trace_rdma_start_outgoing_migration_after_rdma_connect();
M
Michael R. Hines 已提交
3759

3760
    s->to_dst_file = qemu_fopen_rdma(rdma, "wb");
M
Michael R. Hines 已提交
3761 3762 3763 3764 3765
    migrate_fd_connect(s);
    return;
err:
    g_free(rdma);
}