qemu/block/nbd.c
<<
>>
Prefs
   1/*
   2 * QEMU Block driver for  NBD
   3 *
   4 * Copyright (C) 2016 Red Hat, Inc.
   5 * Copyright (C) 2008 Bull S.A.S.
   6 *     Author: Laurent Vivier <Laurent.Vivier@bull.net>
   7 *
   8 * Some parts:
   9 *    Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
  10 *
  11 * Permission is hereby granted, free of charge, to any person obtaining a copy
  12 * of this software and associated documentation files (the "Software"), to deal
  13 * in the Software without restriction, including without limitation the rights
  14 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15 * copies of the Software, and to permit persons to whom the Software is
  16 * furnished to do so, subject to the following conditions:
  17 *
  18 * The above copyright notice and this permission notice shall be included in
  19 * all copies or substantial portions of the Software.
  20 *
  21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  24 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27 * THE SOFTWARE.
  28 */
  29
  30#include "qemu/osdep.h"
  31
  32#include "trace.h"
  33#include "qemu/uri.h"
  34#include "qemu/option.h"
  35#include "qemu/cutils.h"
  36
  37#include "qapi/qapi-visit-sockets.h"
  38#include "qapi/qmp/qstring.h"
  39
  40#include "block/qdict.h"
  41#include "block/nbd.h"
  42#include "block/block_int.h"
  43
  44#define EN_OPTSTR ":exportname="
  45#define MAX_NBD_REQUESTS    16
  46
  47#define HANDLE_TO_INDEX(bs, handle) ((handle) ^ (uint64_t)(intptr_t)(bs))
  48#define INDEX_TO_HANDLE(bs, index)  ((index)  ^ (uint64_t)(intptr_t)(bs))
  49
  50typedef struct {
  51    Coroutine *coroutine;
  52    uint64_t offset;        /* original offset of the request */
  53    bool receiving;         /* waiting for connection_co? */
  54} NBDClientRequest;
  55
  56typedef struct BDRVNBDState {
  57    QIOChannelSocket *sioc; /* The master data channel */
  58    QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
  59    NBDExportInfo info;
  60
  61    CoMutex send_mutex;
  62    CoQueue free_sema;
  63    Coroutine *connection_co;
  64    int in_flight;
  65
  66    NBDClientRequest requests[MAX_NBD_REQUESTS];
  67    NBDReply reply;
  68    BlockDriverState *bs;
  69    bool quit;
  70
  71    /* For nbd_refresh_filename() */
  72    SocketAddress *saddr;
  73    char *export, *tlscredsid;
  74} BDRVNBDState;
  75
  76static void nbd_recv_coroutines_wake_all(BDRVNBDState *s)
  77{
  78    int i;
  79
  80    for (i = 0; i < MAX_NBD_REQUESTS; i++) {
  81        NBDClientRequest *req = &s->requests[i];
  82
  83        if (req->coroutine && req->receiving) {
  84            aio_co_wake(req->coroutine);
  85        }
  86    }
  87}
  88
  89static void nbd_client_detach_aio_context(BlockDriverState *bs)
  90{
  91    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
  92
  93    qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
  94}
  95
  96static void nbd_client_attach_aio_context_bh(void *opaque)
  97{
  98    BlockDriverState *bs = opaque;
  99    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
 100
 101    /*
 102     * The node is still drained, so we know the coroutine has yielded in
 103     * nbd_read_eof(), the only place where bs->in_flight can reach 0, or it is
 104     * entered for the first time. Both places are safe for entering the
 105     * coroutine.
 106     */
 107    qemu_aio_coroutine_enter(bs->aio_context, s->connection_co);
 108    bdrv_dec_in_flight(bs);
 109}
 110
 111static void nbd_client_attach_aio_context(BlockDriverState *bs,
 112                                          AioContext *new_context)
 113{
 114    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
 115
 116    qio_channel_attach_aio_context(QIO_CHANNEL(s->ioc), new_context);
 117
 118    bdrv_inc_in_flight(bs);
 119
 120    /*
 121     * Need to wait here for the BH to run because the BH must run while the
 122     * node is still drained.
 123     */
 124    aio_wait_bh_oneshot(new_context, nbd_client_attach_aio_context_bh, bs);
 125}
 126
 127
 128static void nbd_teardown_connection(BlockDriverState *bs)
 129{
 130    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
 131
 132    assert(s->ioc);
 133
 134    /* finish any pending coroutines */
 135    qio_channel_shutdown(s->ioc,
 136                         QIO_CHANNEL_SHUTDOWN_BOTH,
 137                         NULL);
 138    BDRV_POLL_WHILE(bs, s->connection_co);
 139
 140    nbd_client_detach_aio_context(bs);
 141    object_unref(OBJECT(s->sioc));
 142    s->sioc = NULL;
 143    object_unref(OBJECT(s->ioc));
 144    s->ioc = NULL;
 145}
 146
 147static coroutine_fn void nbd_connection_entry(void *opaque)
 148{
 149    BDRVNBDState *s = opaque;
 150    uint64_t i;
 151    int ret = 0;
 152    Error *local_err = NULL;
 153
 154    while (!s->quit) {
 155        /*
 156         * The NBD client can only really be considered idle when it has
 157         * yielded from qio_channel_readv_all_eof(), waiting for data. This is
 158         * the point where the additional scheduled coroutine entry happens
 159         * after nbd_client_attach_aio_context().
 160         *
 161         * Therefore we keep an additional in_flight reference all the time and
 162         * only drop it temporarily here.
 163         */
 164        assert(s->reply.handle == 0);
 165        ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, &local_err);
 166
 167        if (local_err) {
 168            trace_nbd_read_reply_entry_fail(ret, error_get_pretty(local_err));
 169            error_free(local_err);
 170        }
 171        if (ret <= 0) {
 172            break;
 173        }
 174
 175        /*
 176         * There's no need for a mutex on the receive side, because the
 177         * handler acts as a synchronization point and ensures that only
 178         * one coroutine is called until the reply finishes.
 179         */
 180        i = HANDLE_TO_INDEX(s, s->reply.handle);
 181        if (i >= MAX_NBD_REQUESTS ||
 182            !s->requests[i].coroutine ||
 183            !s->requests[i].receiving ||
 184            (nbd_reply_is_structured(&s->reply) && !s->info.structured_reply))
 185        {
 186            break;
 187        }
 188
 189        /*
 190         * We're woken up again by the request itself.  Note that there
 191         * is no race between yielding and reentering connection_co.  This
 192         * is because:
 193         *
 194         * - if the request runs on the same AioContext, it is only
 195         *   entered after we yield
 196         *
 197         * - if the request runs on a different AioContext, reentering
 198         *   connection_co happens through a bottom half, which can only
 199         *   run after we yield.
 200         */
 201        aio_co_wake(s->requests[i].coroutine);
 202        qemu_coroutine_yield();
 203    }
 204
 205    s->quit = true;
 206    nbd_recv_coroutines_wake_all(s);
 207    bdrv_dec_in_flight(s->bs);
 208
 209    s->connection_co = NULL;
 210    aio_wait_kick();
 211}
 212
 213static int nbd_co_send_request(BlockDriverState *bs,
 214                               NBDRequest *request,
 215                               QEMUIOVector *qiov)
 216{
 217    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
 218    int rc, i;
 219
 220    qemu_co_mutex_lock(&s->send_mutex);
 221    while (s->in_flight == MAX_NBD_REQUESTS) {
 222        qemu_co_queue_wait(&s->free_sema, &s->send_mutex);
 223    }
 224    s->in_flight++;
 225
 226    for (i = 0; i < MAX_NBD_REQUESTS; i++) {
 227        if (s->requests[i].coroutine == NULL) {
 228            break;
 229        }
 230    }
 231
 232    g_assert(qemu_in_coroutine());
 233    assert(i < MAX_NBD_REQUESTS);
 234
 235    s->requests[i].coroutine = qemu_coroutine_self();
 236    s->requests[i].offset = request->from;
 237    s->requests[i].receiving = false;
 238
 239    request->handle = INDEX_TO_HANDLE(s, i);
 240
 241    if (s->quit) {
 242        rc = -EIO;
 243        goto err;
 244    }
 245    assert(s->ioc);
 246
 247    if (qiov) {
 248        qio_channel_set_cork(s->ioc, true);
 249        rc = nbd_send_request(s->ioc, request);
 250        if (rc >= 0 && !s->quit) {
 251            if (qio_channel_writev_all(s->ioc, qiov->iov, qiov->niov,
 252                                       NULL) < 0) {
 253                rc = -EIO;
 254            }
 255        } else if (rc >= 0) {
 256            rc = -EIO;
 257        }
 258        qio_channel_set_cork(s->ioc, false);
 259    } else {
 260        rc = nbd_send_request(s->ioc, request);
 261    }
 262
 263err:
 264    if (rc < 0) {
 265        s->quit = true;
 266        s->requests[i].coroutine = NULL;
 267        s->in_flight--;
 268        qemu_co_queue_next(&s->free_sema);
 269    }
 270    qemu_co_mutex_unlock(&s->send_mutex);
 271    return rc;
 272}
 273
 274static inline uint16_t payload_advance16(uint8_t **payload)
 275{
 276    *payload += 2;
 277    return lduw_be_p(*payload - 2);
 278}
 279
 280static inline uint32_t payload_advance32(uint8_t **payload)
 281{
 282    *payload += 4;
 283    return ldl_be_p(*payload - 4);
 284}
 285
 286static inline uint64_t payload_advance64(uint8_t **payload)
 287{
 288    *payload += 8;
 289    return ldq_be_p(*payload - 8);
 290}
 291
 292static int nbd_parse_offset_hole_payload(BDRVNBDState *s,
 293                                         NBDStructuredReplyChunk *chunk,
 294                                         uint8_t *payload, uint64_t orig_offset,
 295                                         QEMUIOVector *qiov, Error **errp)
 296{
 297    uint64_t offset;
 298    uint32_t hole_size;
 299
 300    if (chunk->length != sizeof(offset) + sizeof(hole_size)) {
 301        error_setg(errp, "Protocol error: invalid payload for "
 302                         "NBD_REPLY_TYPE_OFFSET_HOLE");
 303        return -EINVAL;
 304    }
 305
 306    offset = payload_advance64(&payload);
 307    hole_size = payload_advance32(&payload);
 308
 309    if (!hole_size || offset < orig_offset || hole_size > qiov->size ||
 310        offset > orig_offset + qiov->size - hole_size) {
 311        error_setg(errp, "Protocol error: server sent chunk exceeding requested"
 312                         " region");
 313        return -EINVAL;
 314    }
 315    if (s->info.min_block &&
 316        !QEMU_IS_ALIGNED(hole_size, s->info.min_block)) {
 317        trace_nbd_structured_read_compliance("hole");
 318    }
 319
 320    qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size);
 321
 322    return 0;
 323}
 324
 325/*
 326 * nbd_parse_blockstatus_payload
 327 * Based on our request, we expect only one extent in reply, for the
 328 * base:allocation context.
 329 */
 330static int nbd_parse_blockstatus_payload(BDRVNBDState *s,
 331                                         NBDStructuredReplyChunk *chunk,
 332                                         uint8_t *payload, uint64_t orig_length,
 333                                         NBDExtent *extent, Error **errp)
 334{
 335    uint32_t context_id;
 336
 337    /* The server succeeded, so it must have sent [at least] one extent */
 338    if (chunk->length < sizeof(context_id) + sizeof(*extent)) {
 339        error_setg(errp, "Protocol error: invalid payload for "
 340                         "NBD_REPLY_TYPE_BLOCK_STATUS");
 341        return -EINVAL;
 342    }
 343
 344    context_id = payload_advance32(&payload);
 345    if (s->info.context_id != context_id) {
 346        error_setg(errp, "Protocol error: unexpected context id %d for "
 347                         "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
 348                         "id is %d", context_id,
 349                         s->info.context_id);
 350        return -EINVAL;
 351    }
 352
 353    extent->length = payload_advance32(&payload);
 354    extent->flags = payload_advance32(&payload);
 355
 356    if (extent->length == 0) {
 357        error_setg(errp, "Protocol error: server sent status chunk with "
 358                   "zero length");
 359        return -EINVAL;
 360    }
 361
 362    /*
 363     * A server sending unaligned block status is in violation of the
 364     * protocol, but as qemu-nbd 3.1 is such a server (at least for
 365     * POSIX files that are not a multiple of 512 bytes, since qemu
 366     * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
 367     * still sees an implicit hole beyond the real EOF), it's nicer to
 368     * work around the misbehaving server. If the request included
 369     * more than the final unaligned block, truncate it back to an
 370     * aligned result; if the request was only the final block, round
 371     * up to the full block and change the status to fully-allocated
 372     * (always a safe status, even if it loses information).
 373     */
 374    if (s->info.min_block && !QEMU_IS_ALIGNED(extent->length,
 375                                                   s->info.min_block)) {
 376        trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
 377        if (extent->length > s->info.min_block) {
 378            extent->length = QEMU_ALIGN_DOWN(extent->length,
 379                                             s->info.min_block);
 380        } else {
 381            extent->length = s->info.min_block;
 382            extent->flags = 0;
 383        }
 384    }
 385
 386    /*
 387     * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
 388     * sent us any more than one extent, nor should it have included
 389     * status beyond our request in that extent. However, it's easy
 390     * enough to ignore the server's noncompliance without killing the
 391     * connection; just ignore trailing extents, and clamp things to
 392     * the length of our request.
 393     */
 394    if (chunk->length > sizeof(context_id) + sizeof(*extent)) {
 395        trace_nbd_parse_blockstatus_compliance("more than one extent");
 396    }
 397    if (extent->length > orig_length) {
 398        extent->length = orig_length;
 399        trace_nbd_parse_blockstatus_compliance("extent length too large");
 400    }
 401
 402    return 0;
 403}
 404
 405/*
 406 * nbd_parse_error_payload
 407 * on success @errp contains message describing nbd error reply
 408 */
 409static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
 410                                   uint8_t *payload, int *request_ret,
 411                                   Error **errp)
 412{
 413    uint32_t error;
 414    uint16_t message_size;
 415
 416    assert(chunk->type & (1 << 15));
 417
 418    if (chunk->length < sizeof(error) + sizeof(message_size)) {
 419        error_setg(errp,
 420                   "Protocol error: invalid payload for structured error");
 421        return -EINVAL;
 422    }
 423
 424    error = nbd_errno_to_system_errno(payload_advance32(&payload));
 425    if (error == 0) {
 426        error_setg(errp, "Protocol error: server sent structured error chunk "
 427                         "with error = 0");
 428        return -EINVAL;
 429    }
 430
 431    *request_ret = -error;
 432    message_size = payload_advance16(&payload);
 433
 434    if (message_size > chunk->length - sizeof(error) - sizeof(message_size)) {
 435        error_setg(errp, "Protocol error: server sent structured error chunk "
 436                         "with incorrect message size");
 437        return -EINVAL;
 438    }
 439
 440    /* TODO: Add a trace point to mention the server complaint */
 441
 442    /* TODO handle ERROR_OFFSET */
 443
 444    return 0;
 445}
 446
 447static int nbd_co_receive_offset_data_payload(BDRVNBDState *s,
 448                                              uint64_t orig_offset,
 449                                              QEMUIOVector *qiov, Error **errp)
 450{
 451    QEMUIOVector sub_qiov;
 452    uint64_t offset;
 453    size_t data_size;
 454    int ret;
 455    NBDStructuredReplyChunk *chunk = &s->reply.structured;
 456
 457    assert(nbd_reply_is_structured(&s->reply));
 458
 459    /* The NBD spec requires at least one byte of payload */
 460    if (chunk->length <= sizeof(offset)) {
 461        error_setg(errp, "Protocol error: invalid payload for "
 462                         "NBD_REPLY_TYPE_OFFSET_DATA");
 463        return -EINVAL;
 464    }
 465
 466    if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) {
 467        return -EIO;
 468    }
 469
 470    data_size = chunk->length - sizeof(offset);
 471    assert(data_size);
 472    if (offset < orig_offset || data_size > qiov->size ||
 473        offset > orig_offset + qiov->size - data_size) {
 474        error_setg(errp, "Protocol error: server sent chunk exceeding requested"
 475                         " region");
 476        return -EINVAL;
 477    }
 478    if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) {
 479        trace_nbd_structured_read_compliance("data");
 480    }
 481
 482    qemu_iovec_init(&sub_qiov, qiov->niov);
 483    qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size);
 484    ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);
 485    qemu_iovec_destroy(&sub_qiov);
 486
 487    return ret < 0 ? -EIO : 0;
 488}
 489
 490#define NBD_MAX_MALLOC_PAYLOAD 1000
 491static coroutine_fn int nbd_co_receive_structured_payload(
 492        BDRVNBDState *s, void **payload, Error **errp)
 493{
 494    int ret;
 495    uint32_t len;
 496
 497    assert(nbd_reply_is_structured(&s->reply));
 498
 499    len = s->reply.structured.length;
 500
 501    if (len == 0) {
 502        return 0;
 503    }
 504
 505    if (payload == NULL) {
 506        error_setg(errp, "Unexpected structured payload");
 507        return -EINVAL;
 508    }
 509
 510    if (len > NBD_MAX_MALLOC_PAYLOAD) {
 511        error_setg(errp, "Payload too large");
 512        return -EINVAL;
 513    }
 514
 515    *payload = g_new(char, len);
 516    ret = nbd_read(s->ioc, *payload, len, "structured payload", errp);
 517    if (ret < 0) {
 518        g_free(*payload);
 519        *payload = NULL;
 520        return ret;
 521    }
 522
 523    return 0;
 524}
 525
 526/*
 527 * nbd_co_do_receive_one_chunk
 528 * for simple reply:
 529 *   set request_ret to received reply error
 530 *   if qiov is not NULL: read payload to @qiov
 531 * for structured reply chunk:
 532 *   if error chunk: read payload, set @request_ret, do not set @payload
 533 *   else if offset_data chunk: read payload data to @qiov, do not set @payload
 534 *   else: read payload to @payload
 535 *
 536 * If function fails, @errp contains corresponding error message, and the
 537 * connection with the server is suspect.  If it returns 0, then the
 538 * transaction succeeded (although @request_ret may be a negative errno
 539 * corresponding to the server's error reply), and errp is unchanged.
 540 */
 541static coroutine_fn int nbd_co_do_receive_one_chunk(
 542        BDRVNBDState *s, uint64_t handle, bool only_structured,
 543        int *request_ret, QEMUIOVector *qiov, void **payload, Error **errp)
 544{
 545    int ret;
 546    int i = HANDLE_TO_INDEX(s, handle);
 547    void *local_payload = NULL;
 548    NBDStructuredReplyChunk *chunk;
 549
 550    if (payload) {
 551        *payload = NULL;
 552    }
 553    *request_ret = 0;
 554
 555    /* Wait until we're woken up by nbd_connection_entry.  */
 556    s->requests[i].receiving = true;
 557    qemu_coroutine_yield();
 558    s->requests[i].receiving = false;
 559    if (s->quit) {
 560        error_setg(errp, "Connection closed");
 561        return -EIO;
 562    }
 563    assert(s->ioc);
 564
 565    assert(s->reply.handle == handle);
 566
 567    if (nbd_reply_is_simple(&s->reply)) {
 568        if (only_structured) {
 569            error_setg(errp, "Protocol error: simple reply when structured "
 570                             "reply chunk was expected");
 571            return -EINVAL;
 572        }
 573
 574        *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error);
 575        if (*request_ret < 0 || !qiov) {
 576            return 0;
 577        }
 578
 579        return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov,
 580                                     errp) < 0 ? -EIO : 0;
 581    }
 582
 583    /* handle structured reply chunk */
 584    assert(s->info.structured_reply);
 585    chunk = &s->reply.structured;
 586
 587    if (chunk->type == NBD_REPLY_TYPE_NONE) {
 588        if (!(chunk->flags & NBD_REPLY_FLAG_DONE)) {
 589            error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
 590                       " NBD_REPLY_FLAG_DONE flag set");
 591            return -EINVAL;
 592        }
 593        if (chunk->length) {
 594            error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
 595                       " nonzero length");
 596            return -EINVAL;
 597        }
 598        return 0;
 599    }
 600
 601    if (chunk->type == NBD_REPLY_TYPE_OFFSET_DATA) {
 602        if (!qiov) {
 603            error_setg(errp, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
 604            return -EINVAL;
 605        }
 606
 607        return nbd_co_receive_offset_data_payload(s, s->requests[i].offset,
 608                                                  qiov, errp);
 609    }
 610
 611    if (nbd_reply_type_is_error(chunk->type)) {
 612        payload = &local_payload;
 613    }
 614
 615    ret = nbd_co_receive_structured_payload(s, payload, errp);
 616    if (ret < 0) {
 617        return ret;
 618    }
 619
 620    if (nbd_reply_type_is_error(chunk->type)) {
 621        ret = nbd_parse_error_payload(chunk, local_payload, request_ret, errp);
 622        g_free(local_payload);
 623        return ret;
 624    }
 625
 626    return 0;
 627}
 628
 629/*
 630 * nbd_co_receive_one_chunk
 631 * Read reply, wake up connection_co and set s->quit if needed.
 632 * Return value is a fatal error code or normal nbd reply error code
 633 */
 634static coroutine_fn int nbd_co_receive_one_chunk(
 635        BDRVNBDState *s, uint64_t handle, bool only_structured,
 636        int *request_ret, QEMUIOVector *qiov, NBDReply *reply, void **payload,
 637        Error **errp)
 638{
 639    int ret = nbd_co_do_receive_one_chunk(s, handle, only_structured,
 640                                          request_ret, qiov, payload, errp);
 641
 642    if (ret < 0) {
 643        memset(reply, 0, sizeof(*reply));
 644        s->quit = true;
 645    } else {
 646        /* For assert at loop start in nbd_connection_entry */
 647        *reply = s->reply;
 648        s->reply.handle = 0;
 649    }
 650
 651    if (s->connection_co) {
 652        aio_co_wake(s->connection_co);
 653    }
 654
 655    return ret;
 656}
 657
 658typedef struct NBDReplyChunkIter {
 659    int ret;
 660    int request_ret;
 661    Error *err;
 662    bool done, only_structured;
 663} NBDReplyChunkIter;
 664
 665static void nbd_iter_channel_error(NBDReplyChunkIter *iter,
 666                                   int ret, Error **local_err)
 667{
 668    assert(ret < 0);
 669
 670    if (!iter->ret) {
 671        iter->ret = ret;
 672        error_propagate(&iter->err, *local_err);
 673    } else {
 674        error_free(*local_err);
 675    }
 676
 677    *local_err = NULL;
 678}
 679
 680static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret)
 681{
 682    assert(ret < 0);
 683
 684    if (!iter->request_ret) {
 685        iter->request_ret = ret;
 686    }
 687}
 688
 689/*
 690 * NBD_FOREACH_REPLY_CHUNK
 691 * The pointer stored in @payload requires g_free() to free it.
 692 */
 693#define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
 694                                qiov, reply, payload) \
 695    for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
 696         nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
 697
 698/*
 699 * nbd_reply_chunk_iter_receive
 700 * The pointer stored in @payload requires g_free() to free it.
 701 */
 702static bool nbd_reply_chunk_iter_receive(BDRVNBDState *s,
 703                                         NBDReplyChunkIter *iter,
 704                                         uint64_t handle,
 705                                         QEMUIOVector *qiov, NBDReply *reply,
 706                                         void **payload)
 707{
 708    int ret, request_ret;
 709    NBDReply local_reply;
 710    NBDStructuredReplyChunk *chunk;
 711    Error *local_err = NULL;
 712    if (s->quit) {
 713        error_setg(&local_err, "Connection closed");
 714        nbd_iter_channel_error(iter, -EIO, &local_err);
 715        goto break_loop;
 716    }
 717
 718    if (iter->done) {
 719        /* Previous iteration was last. */
 720        goto break_loop;
 721    }
 722
 723    if (reply == NULL) {
 724        reply = &local_reply;
 725    }
 726
 727    ret = nbd_co_receive_one_chunk(s, handle, iter->only_structured,
 728                                   &request_ret, qiov, reply, payload,
 729                                   &local_err);
 730    if (ret < 0) {
 731        nbd_iter_channel_error(iter, ret, &local_err);
 732    } else if (request_ret < 0) {
 733        nbd_iter_request_error(iter, request_ret);
 734    }
 735
 736    /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
 737    if (nbd_reply_is_simple(reply) || s->quit) {
 738        goto break_loop;
 739    }
 740
 741    chunk = &reply->structured;
 742    iter->only_structured = true;
 743
 744    if (chunk->type == NBD_REPLY_TYPE_NONE) {
 745        /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
 746        assert(chunk->flags & NBD_REPLY_FLAG_DONE);
 747        goto break_loop;
 748    }
 749
 750    if (chunk->flags & NBD_REPLY_FLAG_DONE) {
 751        /* This iteration is last. */
 752        iter->done = true;
 753    }
 754
 755    /* Execute the loop body */
 756    return true;
 757
 758break_loop:
 759    s->requests[HANDLE_TO_INDEX(s, handle)].coroutine = NULL;
 760
 761    qemu_co_mutex_lock(&s->send_mutex);
 762    s->in_flight--;
 763    qemu_co_queue_next(&s->free_sema);
 764    qemu_co_mutex_unlock(&s->send_mutex);
 765
 766    return false;
 767}
 768
 769static int nbd_co_receive_return_code(BDRVNBDState *s, uint64_t handle,
 770                                      int *request_ret, Error **errp)
 771{
 772    NBDReplyChunkIter iter;
 773
 774    NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, NULL, NULL) {
 775        /* nbd_reply_chunk_iter_receive does all the work */
 776    }
 777
 778    error_propagate(errp, iter.err);
 779    *request_ret = iter.request_ret;
 780    return iter.ret;
 781}
 782
 783static int nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t handle,
 784                                        uint64_t offset, QEMUIOVector *qiov,
 785                                        int *request_ret, Error **errp)
 786{
 787    NBDReplyChunkIter iter;
 788    NBDReply reply;
 789    void *payload = NULL;
 790    Error *local_err = NULL;
 791
 792    NBD_FOREACH_REPLY_CHUNK(s, iter, handle, s->info.structured_reply,
 793                            qiov, &reply, &payload)
 794    {
 795        int ret;
 796        NBDStructuredReplyChunk *chunk = &reply.structured;
 797
 798        assert(nbd_reply_is_structured(&reply));
 799
 800        switch (chunk->type) {
 801        case NBD_REPLY_TYPE_OFFSET_DATA:
 802            /*
 803             * special cased in nbd_co_receive_one_chunk, data is already
 804             * in qiov
 805             */
 806            break;
 807        case NBD_REPLY_TYPE_OFFSET_HOLE:
 808            ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload,
 809                                                offset, qiov, &local_err);
 810            if (ret < 0) {
 811                s->quit = true;
 812                nbd_iter_channel_error(&iter, ret, &local_err);
 813            }
 814            break;
 815        default:
 816            if (!nbd_reply_type_is_error(chunk->type)) {
 817                /* not allowed reply type */
 818                s->quit = true;
 819                error_setg(&local_err,
 820                           "Unexpected reply type: %d (%s) for CMD_READ",
 821                           chunk->type, nbd_reply_type_lookup(chunk->type));
 822                nbd_iter_channel_error(&iter, -EINVAL, &local_err);
 823            }
 824        }
 825
 826        g_free(payload);
 827        payload = NULL;
 828    }
 829
 830    error_propagate(errp, iter.err);
 831    *request_ret = iter.request_ret;
 832    return iter.ret;
 833}
 834
 835static int nbd_co_receive_blockstatus_reply(BDRVNBDState *s,
 836                                            uint64_t handle, uint64_t length,
 837                                            NBDExtent *extent,
 838                                            int *request_ret, Error **errp)
 839{
 840    NBDReplyChunkIter iter;
 841    NBDReply reply;
 842    void *payload = NULL;
 843    Error *local_err = NULL;
 844    bool received = false;
 845
 846    assert(!extent->length);
 847    NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, &reply, &payload) {
 848        int ret;
 849        NBDStructuredReplyChunk *chunk = &reply.structured;
 850
 851        assert(nbd_reply_is_structured(&reply));
 852
 853        switch (chunk->type) {
 854        case NBD_REPLY_TYPE_BLOCK_STATUS:
 855            if (received) {
 856                s->quit = true;
 857                error_setg(&local_err, "Several BLOCK_STATUS chunks in reply");
 858                nbd_iter_channel_error(&iter, -EINVAL, &local_err);
 859            }
 860            received = true;
 861
 862            ret = nbd_parse_blockstatus_payload(s, &reply.structured,
 863                                                payload, length, extent,
 864                                                &local_err);
 865            if (ret < 0) {
 866                s->quit = true;
 867                nbd_iter_channel_error(&iter, ret, &local_err);
 868            }
 869            break;
 870        default:
 871            if (!nbd_reply_type_is_error(chunk->type)) {
 872                s->quit = true;
 873                error_setg(&local_err,
 874                           "Unexpected reply type: %d (%s) "
 875                           "for CMD_BLOCK_STATUS",
 876                           chunk->type, nbd_reply_type_lookup(chunk->type));
 877                nbd_iter_channel_error(&iter, -EINVAL, &local_err);
 878            }
 879        }
 880
 881        g_free(payload);
 882        payload = NULL;
 883    }
 884
 885    if (!extent->length && !iter.request_ret) {
 886        error_setg(&local_err, "Server did not reply with any status extents");
 887        nbd_iter_channel_error(&iter, -EIO, &local_err);
 888    }
 889
 890    error_propagate(errp, iter.err);
 891    *request_ret = iter.request_ret;
 892    return iter.ret;
 893}
 894
 895static int nbd_co_request(BlockDriverState *bs, NBDRequest *request,
 896                          QEMUIOVector *write_qiov)
 897{
 898    int ret, request_ret;
 899    Error *local_err = NULL;
 900    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
 901
 902    assert(request->type != NBD_CMD_READ);
 903    if (write_qiov) {
 904        assert(request->type == NBD_CMD_WRITE);
 905        assert(request->len == iov_size(write_qiov->iov, write_qiov->niov));
 906    } else {
 907        assert(request->type != NBD_CMD_WRITE);
 908    }
 909    ret = nbd_co_send_request(bs, request, write_qiov);
 910    if (ret < 0) {
 911        return ret;
 912    }
 913
 914    ret = nbd_co_receive_return_code(s, request->handle,
 915                                     &request_ret, &local_err);
 916    if (local_err) {
 917        trace_nbd_co_request_fail(request->from, request->len, request->handle,
 918                                  request->flags, request->type,
 919                                  nbd_cmd_lookup(request->type),
 920                                  ret, error_get_pretty(local_err));
 921        error_free(local_err);
 922    }
 923    return ret ? ret : request_ret;
 924}
 925
 926static int nbd_client_co_preadv(BlockDriverState *bs, uint64_t offset,
 927                                uint64_t bytes, QEMUIOVector *qiov, int flags)
 928{
 929    int ret, request_ret;
 930    Error *local_err = NULL;
 931    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
 932    NBDRequest request = {
 933        .type = NBD_CMD_READ,
 934        .from = offset,
 935        .len = bytes,
 936    };
 937
 938    assert(bytes <= NBD_MAX_BUFFER_SIZE);
 939    assert(!flags);
 940
 941    if (!bytes) {
 942        return 0;
 943    }
 944    /*
 945     * Work around the fact that the block layer doesn't do
 946     * byte-accurate sizing yet - if the read exceeds the server's
 947     * advertised size because the block layer rounded size up, then
 948     * truncate the request to the server and tail-pad with zero.
 949     */
 950    if (offset >= s->info.size) {
 951        assert(bytes < BDRV_SECTOR_SIZE);
 952        qemu_iovec_memset(qiov, 0, 0, bytes);
 953        return 0;
 954    }
 955    if (offset + bytes > s->info.size) {
 956        uint64_t slop = offset + bytes - s->info.size;
 957
 958        assert(slop < BDRV_SECTOR_SIZE);
 959        qemu_iovec_memset(qiov, bytes - slop, 0, slop);
 960        request.len -= slop;
 961    }
 962
 963    ret = nbd_co_send_request(bs, &request, NULL);
 964    if (ret < 0) {
 965        return ret;
 966    }
 967
 968    ret = nbd_co_receive_cmdread_reply(s, request.handle, offset, qiov,
 969                                       &request_ret, &local_err);
 970    if (local_err) {
 971        trace_nbd_co_request_fail(request.from, request.len, request.handle,
 972                                  request.flags, request.type,
 973                                  nbd_cmd_lookup(request.type),
 974                                  ret, error_get_pretty(local_err));
 975        error_free(local_err);
 976    }
 977    return ret ? ret : request_ret;
 978}
 979
 980static int nbd_client_co_pwritev(BlockDriverState *bs, uint64_t offset,
 981                                 uint64_t bytes, QEMUIOVector *qiov, int flags)
 982{
 983    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
 984    NBDRequest request = {
 985        .type = NBD_CMD_WRITE,
 986        .from = offset,
 987        .len = bytes,
 988    };
 989
 990    assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
 991    if (flags & BDRV_REQ_FUA) {
 992        assert(s->info.flags & NBD_FLAG_SEND_FUA);
 993        request.flags |= NBD_CMD_FLAG_FUA;
 994    }
 995
 996    assert(bytes <= NBD_MAX_BUFFER_SIZE);
 997
 998    if (!bytes) {
 999        return 0;
1000    }
1001    return nbd_co_request(bs, &request, qiov);
1002}
1003
1004static int nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1005                                       int bytes, BdrvRequestFlags flags)
1006{
1007    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1008    NBDRequest request = {
1009        .type = NBD_CMD_WRITE_ZEROES,
1010        .from = offset,
1011        .len = bytes,
1012    };
1013
1014    assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1015    if (!(s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {
1016        return -ENOTSUP;
1017    }
1018
1019    if (flags & BDRV_REQ_FUA) {
1020        assert(s->info.flags & NBD_FLAG_SEND_FUA);
1021        request.flags |= NBD_CMD_FLAG_FUA;
1022    }
1023    if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1024        request.flags |= NBD_CMD_FLAG_NO_HOLE;
1025    }
1026
1027    if (!bytes) {
1028        return 0;
1029    }
1030    return nbd_co_request(bs, &request, NULL);
1031}
1032
1033static int nbd_client_co_flush(BlockDriverState *bs)
1034{
1035    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1036    NBDRequest request = { .type = NBD_CMD_FLUSH };
1037
1038    if (!(s->info.flags & NBD_FLAG_SEND_FLUSH)) {
1039        return 0;
1040    }
1041
1042    request.from = 0;
1043    request.len = 0;
1044
1045    return nbd_co_request(bs, &request, NULL);
1046}
1047
1048static int nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset,
1049                                  int bytes)
1050{
1051    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1052    NBDRequest request = {
1053        .type = NBD_CMD_TRIM,
1054        .from = offset,
1055        .len = bytes,
1056    };
1057
1058    assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1059    if (!(s->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) {
1060        return 0;
1061    }
1062
1063    return nbd_co_request(bs, &request, NULL);
1064}
1065
1066static int coroutine_fn nbd_client_co_block_status(
1067        BlockDriverState *bs, bool want_zero, int64_t offset, int64_t bytes,
1068        int64_t *pnum, int64_t *map, BlockDriverState **file)
1069{
1070    int ret, request_ret;
1071    NBDExtent extent = { 0 };
1072    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1073    Error *local_err = NULL;
1074
1075    NBDRequest request = {
1076        .type = NBD_CMD_BLOCK_STATUS,
1077        .from = offset,
1078        .len = MIN(MIN_NON_ZERO(QEMU_ALIGN_DOWN(INT_MAX,
1079                                                bs->bl.request_alignment),
1080                                s->info.max_block),
1081                   MIN(bytes, s->info.size - offset)),
1082        .flags = NBD_CMD_FLAG_REQ_ONE,
1083    };
1084
1085    if (!s->info.base_allocation) {
1086        *pnum = bytes;
1087        *map = offset;
1088        *file = bs;
1089        return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
1090    }
1091
1092    /*
1093     * Work around the fact that the block layer doesn't do
1094     * byte-accurate sizing yet - if the status request exceeds the
1095     * server's advertised size because the block layer rounded size
1096     * up, we truncated the request to the server (above), or are
1097     * called on just the hole.
1098     */
1099    if (offset >= s->info.size) {
1100        *pnum = bytes;
1101        assert(bytes < BDRV_SECTOR_SIZE);
1102        /* Intentionally don't report offset_valid for the hole */
1103        return BDRV_BLOCK_ZERO;
1104    }
1105
1106    if (s->info.min_block) {
1107        assert(QEMU_IS_ALIGNED(request.len, s->info.min_block));
1108    }
1109    ret = nbd_co_send_request(bs, &request, NULL);
1110    if (ret < 0) {
1111        return ret;
1112    }
1113
1114    ret = nbd_co_receive_blockstatus_reply(s, request.handle, bytes,
1115                                           &extent, &request_ret, &local_err);
1116    if (local_err) {
1117        trace_nbd_co_request_fail(request.from, request.len, request.handle,
1118                                  request.flags, request.type,
1119                                  nbd_cmd_lookup(request.type),
1120                                  ret, error_get_pretty(local_err));
1121        error_free(local_err);
1122    }
1123    if (ret < 0 || request_ret < 0) {
1124        return ret ? ret : request_ret;
1125    }
1126
1127    assert(extent.length);
1128    *pnum = extent.length;
1129    *map = offset;
1130    *file = bs;
1131    return (extent.flags & NBD_STATE_HOLE ? 0 : BDRV_BLOCK_DATA) |
1132        (extent.flags & NBD_STATE_ZERO ? BDRV_BLOCK_ZERO : 0) |
1133        BDRV_BLOCK_OFFSET_VALID;
1134}
1135
1136static void nbd_client_close(BlockDriverState *bs)
1137{
1138    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1139    NBDRequest request = { .type = NBD_CMD_DISC };
1140
1141    assert(s->ioc);
1142
1143    nbd_send_request(s->ioc, &request);
1144
1145    nbd_teardown_connection(bs);
1146}
1147
1148static QIOChannelSocket *nbd_establish_connection(SocketAddress *saddr,
1149                                                  Error **errp)
1150{
1151    QIOChannelSocket *sioc;
1152    Error *local_err = NULL;
1153
1154    sioc = qio_channel_socket_new();
1155    qio_channel_set_name(QIO_CHANNEL(sioc), "nbd-client");
1156
1157    qio_channel_socket_connect_sync(sioc, saddr, &local_err);
1158    if (local_err) {
1159        object_unref(OBJECT(sioc));
1160        error_propagate(errp, local_err);
1161        return NULL;
1162    }
1163
1164    qio_channel_set_delay(QIO_CHANNEL(sioc), false);
1165
1166    return sioc;
1167}
1168
1169static int nbd_client_connect(BlockDriverState *bs,
1170                              SocketAddress *saddr,
1171                              const char *export,
1172                              QCryptoTLSCreds *tlscreds,
1173                              const char *hostname,
1174                              const char *x_dirty_bitmap,
1175                              Error **errp)
1176{
1177    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1178    int ret;
1179
1180    /*
1181     * establish TCP connection, return error if it fails
1182     * TODO: Configurable retry-until-timeout behaviour.
1183     */
1184    QIOChannelSocket *sioc = nbd_establish_connection(saddr, errp);
1185
1186    if (!sioc) {
1187        return -ECONNREFUSED;
1188    }
1189
1190    /* NBD handshake */
1191    trace_nbd_client_connect(export);
1192    qio_channel_set_blocking(QIO_CHANNEL(sioc), true, NULL);
1193
1194    s->info.request_sizes = true;
1195    s->info.structured_reply = true;
1196    s->info.base_allocation = true;
1197    s->info.x_dirty_bitmap = g_strdup(x_dirty_bitmap);
1198    s->info.name = g_strdup(export ?: "");
1199    ret = nbd_receive_negotiate(QIO_CHANNEL(sioc), tlscreds, hostname,
1200                                &s->ioc, &s->info, errp);
1201    g_free(s->info.x_dirty_bitmap);
1202    g_free(s->info.name);
1203    if (ret < 0) {
1204        object_unref(OBJECT(sioc));
1205        return ret;
1206    }
1207    if (x_dirty_bitmap && !s->info.base_allocation) {
1208        error_setg(errp, "requested x-dirty-bitmap %s not found",
1209                   x_dirty_bitmap);
1210        ret = -EINVAL;
1211        goto fail;
1212    }
1213    if (s->info.flags & NBD_FLAG_READ_ONLY) {
1214        ret = bdrv_apply_auto_read_only(bs, "NBD export is read-only", errp);
1215        if (ret < 0) {
1216            goto fail;
1217        }
1218    }
1219    if (s->info.flags & NBD_FLAG_SEND_FUA) {
1220        bs->supported_write_flags = BDRV_REQ_FUA;
1221        bs->supported_zero_flags |= BDRV_REQ_FUA;
1222    }
1223    if (s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES) {
1224        bs->supported_zero_flags |= BDRV_REQ_MAY_UNMAP;
1225    }
1226
1227    s->sioc = sioc;
1228
1229    if (!s->ioc) {
1230        s->ioc = QIO_CHANNEL(sioc);
1231        object_ref(OBJECT(s->ioc));
1232    }
1233
1234    /*
1235     * Now that we're connected, set the socket to be non-blocking and
1236     * kick the reply mechanism.
1237     */
1238    qio_channel_set_blocking(QIO_CHANNEL(sioc), false, NULL);
1239    s->connection_co = qemu_coroutine_create(nbd_connection_entry, s);
1240    bdrv_inc_in_flight(bs);
1241    nbd_client_attach_aio_context(bs, bdrv_get_aio_context(bs));
1242
1243    trace_nbd_client_connect_success(export);
1244
1245    return 0;
1246
1247 fail:
1248    /*
1249     * We have connected, but must fail for other reasons. The
1250     * connection is still blocking; send NBD_CMD_DISC as a courtesy
1251     * to the server.
1252     */
1253    {
1254        NBDRequest request = { .type = NBD_CMD_DISC };
1255
1256        nbd_send_request(s->ioc ?: QIO_CHANNEL(sioc), &request);
1257
1258        object_unref(OBJECT(sioc));
1259
1260        return ret;
1261    }
1262}
1263
1264static int nbd_client_init(BlockDriverState *bs,
1265                           SocketAddress *saddr,
1266                           const char *export,
1267                           QCryptoTLSCreds *tlscreds,
1268                           const char *hostname,
1269                           const char *x_dirty_bitmap,
1270                           Error **errp)
1271{
1272    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1273
1274    s->bs = bs;
1275    qemu_co_mutex_init(&s->send_mutex);
1276    qemu_co_queue_init(&s->free_sema);
1277
1278    return nbd_client_connect(bs, saddr, export, tlscreds, hostname,
1279                              x_dirty_bitmap, errp);
1280}
1281
1282static int nbd_parse_uri(const char *filename, QDict *options)
1283{
1284    URI *uri;
1285    const char *p;
1286    QueryParams *qp = NULL;
1287    int ret = 0;
1288    bool is_unix;
1289
1290    uri = uri_parse(filename);
1291    if (!uri) {
1292        return -EINVAL;
1293    }
1294
1295    /* transport */
1296    if (!g_strcmp0(uri->scheme, "nbd")) {
1297        is_unix = false;
1298    } else if (!g_strcmp0(uri->scheme, "nbd+tcp")) {
1299        is_unix = false;
1300    } else if (!g_strcmp0(uri->scheme, "nbd+unix")) {
1301        is_unix = true;
1302    } else {
1303        ret = -EINVAL;
1304        goto out;
1305    }
1306
1307    p = uri->path ? uri->path : "/";
1308    p += strspn(p, "/");
1309    if (p[0]) {
1310        qdict_put_str(options, "export", p);
1311    }
1312
1313    qp = query_params_parse(uri->query);
1314    if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
1315        ret = -EINVAL;
1316        goto out;
1317    }
1318
1319    if (is_unix) {
1320        /* nbd+unix:///export?socket=path */
1321        if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
1322            ret = -EINVAL;
1323            goto out;
1324        }
1325        qdict_put_str(options, "server.type", "unix");
1326        qdict_put_str(options, "server.path", qp->p[0].value);
1327    } else {
1328        QString *host;
1329        char *port_str;
1330
1331        /* nbd[+tcp]://host[:port]/export */
1332        if (!uri->server) {
1333            ret = -EINVAL;
1334            goto out;
1335        }
1336
1337        /* strip braces from literal IPv6 address */
1338        if (uri->server[0] == '[') {
1339            host = qstring_from_substr(uri->server, 1,
1340                                       strlen(uri->server) - 1);
1341        } else {
1342            host = qstring_from_str(uri->server);
1343        }
1344
1345        qdict_put_str(options, "server.type", "inet");
1346        qdict_put(options, "server.host", host);
1347
1348        port_str = g_strdup_printf("%d", uri->port ?: NBD_DEFAULT_PORT);
1349        qdict_put_str(options, "server.port", port_str);
1350        g_free(port_str);
1351    }
1352
1353out:
1354    if (qp) {
1355        query_params_free(qp);
1356    }
1357    uri_free(uri);
1358    return ret;
1359}
1360
1361static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
1362{
1363    const QDictEntry *e;
1364
1365    for (e = qdict_first(options); e; e = qdict_next(options, e)) {
1366        if (!strcmp(e->key, "host") ||
1367            !strcmp(e->key, "port") ||
1368            !strcmp(e->key, "path") ||
1369            !strcmp(e->key, "export") ||
1370            strstart(e->key, "server.", NULL))
1371        {
1372            error_setg(errp, "Option '%s' cannot be used with a file name",
1373                       e->key);
1374            return true;
1375        }
1376    }
1377
1378    return false;
1379}
1380
1381static void nbd_parse_filename(const char *filename, QDict *options,
1382                               Error **errp)
1383{
1384    char *file;
1385    char *export_name;
1386    const char *host_spec;
1387    const char *unixpath;
1388
1389    if (nbd_has_filename_options_conflict(options, errp)) {
1390        return;
1391    }
1392
1393    if (strstr(filename, "://")) {
1394        int ret = nbd_parse_uri(filename, options);
1395        if (ret < 0) {
1396            error_setg(errp, "No valid URL specified");
1397        }
1398        return;
1399    }
1400
1401    file = g_strdup(filename);
1402
1403    export_name = strstr(file, EN_OPTSTR);
1404    if (export_name) {
1405        if (export_name[strlen(EN_OPTSTR)] == 0) {
1406            goto out;
1407        }
1408        export_name[0] = 0; /* truncate 'file' */
1409        export_name += strlen(EN_OPTSTR);
1410
1411        qdict_put_str(options, "export", export_name);
1412    }
1413
1414    /* extract the host_spec - fail if it's not nbd:... */
1415    if (!strstart(file, "nbd:", &host_spec)) {
1416        error_setg(errp, "File name string for NBD must start with 'nbd:'");
1417        goto out;
1418    }
1419
1420    if (!*host_spec) {
1421        goto out;
1422    }
1423
1424    /* are we a UNIX or TCP socket? */
1425    if (strstart(host_spec, "unix:", &unixpath)) {
1426        qdict_put_str(options, "server.type", "unix");
1427        qdict_put_str(options, "server.path", unixpath);
1428    } else {
1429        InetSocketAddress *addr = g_new(InetSocketAddress, 1);
1430
1431        if (inet_parse(addr, host_spec, errp)) {
1432            goto out_inet;
1433        }
1434
1435        qdict_put_str(options, "server.type", "inet");
1436        qdict_put_str(options, "server.host", addr->host);
1437        qdict_put_str(options, "server.port", addr->port);
1438    out_inet:
1439        qapi_free_InetSocketAddress(addr);
1440    }
1441
1442out:
1443    g_free(file);
1444}
1445
1446static bool nbd_process_legacy_socket_options(QDict *output_options,
1447                                              QemuOpts *legacy_opts,
1448                                              Error **errp)
1449{
1450    const char *path = qemu_opt_get(legacy_opts, "path");
1451    const char *host = qemu_opt_get(legacy_opts, "host");
1452    const char *port = qemu_opt_get(legacy_opts, "port");
1453    const QDictEntry *e;
1454
1455    if (!path && !host && !port) {
1456        return true;
1457    }
1458
1459    for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
1460    {
1461        if (strstart(e->key, "server.", NULL)) {
1462            error_setg(errp, "Cannot use 'server' and path/host/port at the "
1463                       "same time");
1464            return false;
1465        }
1466    }
1467
1468    if (path && host) {
1469        error_setg(errp, "path and host may not be used at the same time");
1470        return false;
1471    } else if (path) {
1472        if (port) {
1473            error_setg(errp, "port may not be used without host");
1474            return false;
1475        }
1476
1477        qdict_put_str(output_options, "server.type", "unix");
1478        qdict_put_str(output_options, "server.path", path);
1479    } else if (host) {
1480        qdict_put_str(output_options, "server.type", "inet");
1481        qdict_put_str(output_options, "server.host", host);
1482        qdict_put_str(output_options, "server.port",
1483                      port ?: stringify(NBD_DEFAULT_PORT));
1484    }
1485
1486    return true;
1487}
1488
1489static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options,
1490                                 Error **errp)
1491{
1492    SocketAddress *saddr = NULL;
1493    QDict *addr = NULL;
1494    Visitor *iv = NULL;
1495    Error *local_err = NULL;
1496
1497    qdict_extract_subqdict(options, &addr, "server.");
1498    if (!qdict_size(addr)) {
1499        error_setg(errp, "NBD server address missing");
1500        goto done;
1501    }
1502
1503    iv = qobject_input_visitor_new_flat_confused(addr, errp);
1504    if (!iv) {
1505        goto done;
1506    }
1507
1508    visit_type_SocketAddress(iv, NULL, &saddr, &local_err);
1509    if (local_err) {
1510        error_propagate(errp, local_err);
1511        goto done;
1512    }
1513
1514done:
1515    qobject_unref(addr);
1516    visit_free(iv);
1517    return saddr;
1518}
1519
1520static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
1521{
1522    Object *obj;
1523    QCryptoTLSCreds *creds;
1524
1525    obj = object_resolve_path_component(
1526        object_get_objects_root(), id);
1527    if (!obj) {
1528        error_setg(errp, "No TLS credentials with id '%s'",
1529                   id);
1530        return NULL;
1531    }
1532    creds = (QCryptoTLSCreds *)
1533        object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
1534    if (!creds) {
1535        error_setg(errp, "Object with id '%s' is not TLS credentials",
1536                   id);
1537        return NULL;
1538    }
1539
1540    if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
1541        error_setg(errp,
1542                   "Expecting TLS credentials with a client endpoint");
1543        return NULL;
1544    }
1545    object_ref(obj);
1546    return creds;
1547}
1548
1549
1550static QemuOptsList nbd_runtime_opts = {
1551    .name = "nbd",
1552    .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
1553    .desc = {
1554        {
1555            .name = "host",
1556            .type = QEMU_OPT_STRING,
1557            .help = "TCP host to connect to",
1558        },
1559        {
1560            .name = "port",
1561            .type = QEMU_OPT_STRING,
1562            .help = "TCP port to connect to",
1563        },
1564        {
1565            .name = "path",
1566            .type = QEMU_OPT_STRING,
1567            .help = "Unix socket path to connect to",
1568        },
1569        {
1570            .name = "export",
1571            .type = QEMU_OPT_STRING,
1572            .help = "Name of the NBD export to open",
1573        },
1574        {
1575            .name = "tls-creds",
1576            .type = QEMU_OPT_STRING,
1577            .help = "ID of the TLS credentials to use",
1578        },
1579        {
1580            .name = "x-dirty-bitmap",
1581            .type = QEMU_OPT_STRING,
1582            .help = "experimental: expose named dirty bitmap in place of "
1583                    "block status",
1584        },
1585        { /* end of list */ }
1586    },
1587};
1588
1589static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
1590                    Error **errp)
1591{
1592    BDRVNBDState *s = bs->opaque;
1593    QemuOpts *opts = NULL;
1594    Error *local_err = NULL;
1595    QCryptoTLSCreds *tlscreds = NULL;
1596    const char *hostname = NULL;
1597    int ret = -EINVAL;
1598
1599    opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
1600    qemu_opts_absorb_qdict(opts, options, &local_err);
1601    if (local_err) {
1602        error_propagate(errp, local_err);
1603        goto error;
1604    }
1605
1606    /* Translate @host, @port, and @path to a SocketAddress */
1607    if (!nbd_process_legacy_socket_options(options, opts, errp)) {
1608        goto error;
1609    }
1610
1611    /* Pop the config into our state object. Exit if invalid. */
1612    s->saddr = nbd_config(s, options, errp);
1613    if (!s->saddr) {
1614        goto error;
1615    }
1616
1617    s->export = g_strdup(qemu_opt_get(opts, "export"));
1618
1619    s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
1620    if (s->tlscredsid) {
1621        tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
1622        if (!tlscreds) {
1623            goto error;
1624        }
1625
1626        /* TODO SOCKET_ADDRESS_KIND_FD where fd has AF_INET or AF_INET6 */
1627        if (s->saddr->type != SOCKET_ADDRESS_TYPE_INET) {
1628            error_setg(errp, "TLS only supported over IP sockets");
1629            goto error;
1630        }
1631        hostname = s->saddr->u.inet.host;
1632    }
1633
1634    /* NBD handshake */
1635    ret = nbd_client_init(bs, s->saddr, s->export, tlscreds, hostname,
1636                          qemu_opt_get(opts, "x-dirty-bitmap"), errp);
1637
1638 error:
1639    if (tlscreds) {
1640        object_unref(OBJECT(tlscreds));
1641    }
1642    if (ret < 0) {
1643        qapi_free_SocketAddress(s->saddr);
1644        g_free(s->export);
1645        g_free(s->tlscredsid);
1646    }
1647    qemu_opts_del(opts);
1648    return ret;
1649}
1650
1651static int nbd_co_flush(BlockDriverState *bs)
1652{
1653    return nbd_client_co_flush(bs);
1654}
1655
1656static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
1657{
1658    BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1659    uint32_t min = s->info.min_block;
1660    uint32_t max = MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE, s->info.max_block);
1661
1662    /*
1663     * If the server did not advertise an alignment:
1664     * - a size that is not sector-aligned implies that an alignment
1665     *   of 1 can be used to access those tail bytes
1666     * - advertisement of block status requires an alignment of 1, so
1667     *   that we don't violate block layer constraints that block
1668     *   status is always aligned (as we can't control whether the
1669     *   server will report sub-sector extents, such as a hole at EOF
1670     *   on an unaligned POSIX file)
1671     * - otherwise, assume the server is so old that we are safer avoiding
1672     *   sub-sector requests
1673     */
1674    if (!min) {
1675        min = (!QEMU_IS_ALIGNED(s->info.size, BDRV_SECTOR_SIZE) ||
1676               s->info.base_allocation) ? 1 : BDRV_SECTOR_SIZE;
1677    }
1678
1679    bs->bl.request_alignment = min;
1680    bs->bl.max_pdiscard = max;
1681    bs->bl.max_pwrite_zeroes = max;
1682    bs->bl.max_transfer = max;
1683
1684    if (s->info.opt_block &&
1685        s->info.opt_block > bs->bl.opt_transfer) {
1686        bs->bl.opt_transfer = s->info.opt_block;
1687    }
1688}
1689
1690static void nbd_close(BlockDriverState *bs)
1691{
1692    BDRVNBDState *s = bs->opaque;
1693
1694    nbd_client_close(bs);
1695
1696    qapi_free_SocketAddress(s->saddr);
1697    g_free(s->export);
1698    g_free(s->tlscredsid);
1699}
1700
1701static int64_t nbd_getlength(BlockDriverState *bs)
1702{
1703    BDRVNBDState *s = bs->opaque;
1704
1705    return s->info.size;
1706}
1707
1708static void nbd_refresh_filename(BlockDriverState *bs)
1709{
1710    BDRVNBDState *s = bs->opaque;
1711    const char *host = NULL, *port = NULL, *path = NULL;
1712
1713    if (s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
1714        const InetSocketAddress *inet = &s->saddr->u.inet;
1715        if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) {
1716            host = inet->host;
1717            port = inet->port;
1718        }
1719    } else if (s->saddr->type == SOCKET_ADDRESS_TYPE_UNIX) {
1720        path = s->saddr->u.q_unix.path;
1721    } /* else can't represent as pseudo-filename */
1722
1723    if (path && s->export) {
1724        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1725                 "nbd+unix:///%s?socket=%s", s->export, path);
1726    } else if (path && !s->export) {
1727        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1728                 "nbd+unix://?socket=%s", path);
1729    } else if (host && s->export) {
1730        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1731                 "nbd://%s:%s/%s", host, port, s->export);
1732    } else if (host && !s->export) {
1733        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1734                 "nbd://%s:%s", host, port);
1735    }
1736}
1737
1738static char *nbd_dirname(BlockDriverState *bs, Error **errp)
1739{
1740    /* The generic bdrv_dirname() implementation is able to work out some
1741     * directory name for NBD nodes, but that would be wrong. So far there is no
1742     * specification for how "export paths" would work, so NBD does not have
1743     * directory names. */
1744    error_setg(errp, "Cannot generate a base directory for NBD nodes");
1745    return NULL;
1746}
1747
1748static const char *const nbd_strong_runtime_opts[] = {
1749    "path",
1750    "host",
1751    "port",
1752    "export",
1753    "tls-creds",
1754    "server.",
1755
1756    NULL
1757};
1758
1759static BlockDriver bdrv_nbd = {
1760    .format_name                = "nbd",
1761    .protocol_name              = "nbd",
1762    .instance_size              = sizeof(BDRVNBDState),
1763    .bdrv_parse_filename        = nbd_parse_filename,
1764    .bdrv_file_open             = nbd_open,
1765    .bdrv_co_preadv             = nbd_client_co_preadv,
1766    .bdrv_co_pwritev            = nbd_client_co_pwritev,
1767    .bdrv_co_pwrite_zeroes      = nbd_client_co_pwrite_zeroes,
1768    .bdrv_close                 = nbd_close,
1769    .bdrv_co_flush_to_os        = nbd_co_flush,
1770    .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
1771    .bdrv_refresh_limits        = nbd_refresh_limits,
1772    .bdrv_getlength             = nbd_getlength,
1773    .bdrv_detach_aio_context    = nbd_client_detach_aio_context,
1774    .bdrv_attach_aio_context    = nbd_client_attach_aio_context,
1775    .bdrv_refresh_filename      = nbd_refresh_filename,
1776    .bdrv_co_block_status       = nbd_client_co_block_status,
1777    .bdrv_dirname               = nbd_dirname,
1778    .strong_runtime_opts        = nbd_strong_runtime_opts,
1779};
1780
1781static BlockDriver bdrv_nbd_tcp = {
1782    .format_name                = "nbd",
1783    .protocol_name              = "nbd+tcp",
1784    .instance_size              = sizeof(BDRVNBDState),
1785    .bdrv_parse_filename        = nbd_parse_filename,
1786    .bdrv_file_open             = nbd_open,
1787    .bdrv_co_preadv             = nbd_client_co_preadv,
1788    .bdrv_co_pwritev            = nbd_client_co_pwritev,
1789    .bdrv_co_pwrite_zeroes      = nbd_client_co_pwrite_zeroes,
1790    .bdrv_close                 = nbd_close,
1791    .bdrv_co_flush_to_os        = nbd_co_flush,
1792    .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
1793    .bdrv_refresh_limits        = nbd_refresh_limits,
1794    .bdrv_getlength             = nbd_getlength,
1795    .bdrv_detach_aio_context    = nbd_client_detach_aio_context,
1796    .bdrv_attach_aio_context    = nbd_client_attach_aio_context,
1797    .bdrv_refresh_filename      = nbd_refresh_filename,
1798    .bdrv_co_block_status       = nbd_client_co_block_status,
1799    .bdrv_dirname               = nbd_dirname,
1800    .strong_runtime_opts        = nbd_strong_runtime_opts,
1801};
1802
1803static BlockDriver bdrv_nbd_unix = {
1804    .format_name                = "nbd",
1805    .protocol_name              = "nbd+unix",
1806    .instance_size              = sizeof(BDRVNBDState),
1807    .bdrv_parse_filename        = nbd_parse_filename,
1808    .bdrv_file_open             = nbd_open,
1809    .bdrv_co_preadv             = nbd_client_co_preadv,
1810    .bdrv_co_pwritev            = nbd_client_co_pwritev,
1811    .bdrv_co_pwrite_zeroes      = nbd_client_co_pwrite_zeroes,
1812    .bdrv_close                 = nbd_close,
1813    .bdrv_co_flush_to_os        = nbd_co_flush,
1814    .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
1815    .bdrv_refresh_limits        = nbd_refresh_limits,
1816    .bdrv_getlength             = nbd_getlength,
1817    .bdrv_detach_aio_context    = nbd_client_detach_aio_context,
1818    .bdrv_attach_aio_context    = nbd_client_attach_aio_context,
1819    .bdrv_refresh_filename      = nbd_refresh_filename,
1820    .bdrv_co_block_status       = nbd_client_co_block_status,
1821    .bdrv_dirname               = nbd_dirname,
1822    .strong_runtime_opts        = nbd_strong_runtime_opts,
1823};
1824
1825static void bdrv_nbd_init(void)
1826{
1827    bdrv_register(&bdrv_nbd);
1828    bdrv_register(&bdrv_nbd_tcp);
1829    bdrv_register(&bdrv_nbd_unix);
1830}
1831
1832block_init(bdrv_nbd_init);
1833