1 /* 2 * QEMU Block driver for NBD 3 * 4 * Copyright (c) 2019 Virtuozzo International GmbH. 5 * Copyright (C) 2016 Red Hat, Inc. 6 * Copyright (C) 2008 Bull S.A.S. 7 * Author: Laurent Vivier <Laurent.Vivier@bull.net> 8 * 9 * Some parts: 10 * Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws> 11 * 12 * Permission is hereby granted, free of charge, to any person obtaining a copy 13 * of this software and associated documentation files (the "Software"), to deal 14 * in the Software without restriction, including without limitation the rights 15 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 16 * copies of the Software, and to permit persons to whom the Software is 17 * furnished to do so, subject to the following conditions: 18 * 19 * The above copyright notice and this permission notice shall be included in 20 * all copies or substantial portions of the Software. 21 * 22 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 23 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 24 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 25 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 26 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 27 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 28 * THE SOFTWARE. 29 */ 30 31 #include "qemu/osdep.h" 32 33 #include "trace.h" 34 #include "qemu/uri.h" 35 #include "qemu/option.h" 36 #include "qemu/cutils.h" 37 #include "qemu/main-loop.h" 38 #include "qemu/atomic.h" 39 40 #include "qapi/qapi-visit-sockets.h" 41 #include "qapi/qmp/qstring.h" 42 #include "qapi/clone-visitor.h" 43 44 #include "block/qdict.h" 45 #include "block/nbd.h" 46 #include "block/block_int.h" 47 48 #include "qemu/yank.h" 49 50 #define EN_OPTSTR ":exportname=" 51 #define MAX_NBD_REQUESTS 16 52 53 #define HANDLE_TO_INDEX(bs, handle) ((handle) ^ (uint64_t)(intptr_t)(bs)) 54 #define INDEX_TO_HANDLE(bs, index) ((index) ^ (uint64_t)(intptr_t)(bs)) 55 56 typedef struct { 57 Coroutine *coroutine; 58 uint64_t offset; /* original offset of the request */ 59 bool receiving; /* waiting for connection_co? */ 60 } NBDClientRequest; 61 62 typedef enum NBDClientState { 63 NBD_CLIENT_CONNECTING_WAIT, 64 NBD_CLIENT_CONNECTING_NOWAIT, 65 NBD_CLIENT_CONNECTED, 66 NBD_CLIENT_QUIT 67 } NBDClientState; 68 69 typedef enum NBDConnectThreadState { 70 /* No thread, no pending results */ 71 CONNECT_THREAD_NONE, 72 73 /* Thread is running, no results for now */ 74 CONNECT_THREAD_RUNNING, 75 76 /* 77 * Thread is running, but requestor exited. Thread should close 78 * the new socket and free the connect state on exit. 79 */ 80 CONNECT_THREAD_RUNNING_DETACHED, 81 82 /* Thread finished, results are stored in a state */ 83 CONNECT_THREAD_FAIL, 84 CONNECT_THREAD_SUCCESS 85 } NBDConnectThreadState; 86 87 typedef struct NBDConnectThread { 88 /* Initialization constants */ 89 SocketAddress *saddr; /* address to connect to */ 90 /* 91 * Bottom half to schedule on completion. Scheduled only if bh_ctx is not 92 * NULL 93 */ 94 QEMUBHFunc *bh_func; 95 void *bh_opaque; 96 97 /* 98 * Result of last attempt. Valid in FAIL and SUCCESS states. 99 * If you want to steal error, don't forget to set pointer to NULL. 100 */ 101 QIOChannelSocket *sioc; 102 Error *err; 103 104 /* state and bh_ctx are protected by mutex */ 105 QemuMutex mutex; 106 NBDConnectThreadState state; /* current state of the thread */ 107 AioContext *bh_ctx; /* where to schedule bh (NULL means don't schedule) */ 108 } NBDConnectThread; 109 110 typedef struct BDRVNBDState { 111 QIOChannelSocket *sioc; /* The master data channel */ 112 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */ 113 NBDExportInfo info; 114 115 CoMutex send_mutex; 116 CoQueue free_sema; 117 Coroutine *connection_co; 118 Coroutine *teardown_co; 119 QemuCoSleep reconnect_sleep; 120 bool drained; 121 bool wait_drained_end; 122 int in_flight; 123 NBDClientState state; 124 int connect_status; 125 Error *connect_err; 126 bool wait_in_flight; 127 128 QEMUTimer *reconnect_delay_timer; 129 130 NBDClientRequest requests[MAX_NBD_REQUESTS]; 131 NBDReply reply; 132 BlockDriverState *bs; 133 134 /* Connection parameters */ 135 uint32_t reconnect_delay; 136 SocketAddress *saddr; 137 char *export, *tlscredsid; 138 QCryptoTLSCreds *tlscreds; 139 const char *hostname; 140 char *x_dirty_bitmap; 141 bool alloc_depth; 142 143 bool wait_connect; 144 NBDConnectThread *connect_thread; 145 } BDRVNBDState; 146 147 static int nbd_establish_connection(BlockDriverState *bs, SocketAddress *saddr, 148 Error **errp); 149 static int nbd_co_establish_connection(BlockDriverState *bs, Error **errp); 150 static void nbd_co_establish_connection_cancel(BlockDriverState *bs, 151 bool detach); 152 static int nbd_client_handshake(BlockDriverState *bs, Error **errp); 153 static void nbd_yank(void *opaque); 154 155 static void nbd_clear_bdrvstate(BDRVNBDState *s) 156 { 157 object_unref(OBJECT(s->tlscreds)); 158 qapi_free_SocketAddress(s->saddr); 159 s->saddr = NULL; 160 g_free(s->export); 161 s->export = NULL; 162 g_free(s->tlscredsid); 163 s->tlscredsid = NULL; 164 g_free(s->x_dirty_bitmap); 165 s->x_dirty_bitmap = NULL; 166 } 167 168 static void nbd_channel_error(BDRVNBDState *s, int ret) 169 { 170 if (ret == -EIO) { 171 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTED) { 172 s->state = s->reconnect_delay ? NBD_CLIENT_CONNECTING_WAIT : 173 NBD_CLIENT_CONNECTING_NOWAIT; 174 } 175 } else { 176 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTED) { 177 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL); 178 } 179 s->state = NBD_CLIENT_QUIT; 180 } 181 } 182 183 static void nbd_recv_coroutines_wake_all(BDRVNBDState *s) 184 { 185 int i; 186 187 for (i = 0; i < MAX_NBD_REQUESTS; i++) { 188 NBDClientRequest *req = &s->requests[i]; 189 190 if (req->coroutine && req->receiving) { 191 aio_co_wake(req->coroutine); 192 } 193 } 194 } 195 196 static void reconnect_delay_timer_del(BDRVNBDState *s) 197 { 198 if (s->reconnect_delay_timer) { 199 timer_free(s->reconnect_delay_timer); 200 s->reconnect_delay_timer = NULL; 201 } 202 } 203 204 static void reconnect_delay_timer_cb(void *opaque) 205 { 206 BDRVNBDState *s = opaque; 207 208 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT) { 209 s->state = NBD_CLIENT_CONNECTING_NOWAIT; 210 while (qemu_co_enter_next(&s->free_sema, NULL)) { 211 /* Resume all queued requests */ 212 } 213 } 214 215 reconnect_delay_timer_del(s); 216 } 217 218 static void reconnect_delay_timer_init(BDRVNBDState *s, uint64_t expire_time_ns) 219 { 220 if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTING_WAIT) { 221 return; 222 } 223 224 assert(!s->reconnect_delay_timer); 225 s->reconnect_delay_timer = aio_timer_new(bdrv_get_aio_context(s->bs), 226 QEMU_CLOCK_REALTIME, 227 SCALE_NS, 228 reconnect_delay_timer_cb, s); 229 timer_mod(s->reconnect_delay_timer, expire_time_ns); 230 } 231 232 static void nbd_client_detach_aio_context(BlockDriverState *bs) 233 { 234 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 235 236 /* Timer is deleted in nbd_client_co_drain_begin() */ 237 assert(!s->reconnect_delay_timer); 238 /* 239 * If reconnect is in progress we may have no ->ioc. It will be 240 * re-instantiated in the proper aio context once the connection is 241 * reestablished. 242 */ 243 if (s->ioc) { 244 qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc)); 245 } 246 } 247 248 static void nbd_client_attach_aio_context_bh(void *opaque) 249 { 250 BlockDriverState *bs = opaque; 251 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 252 253 if (s->connection_co) { 254 /* 255 * The node is still drained, so we know the coroutine has yielded in 256 * nbd_read_eof(), the only place where bs->in_flight can reach 0, or 257 * it is entered for the first time. Both places are safe for entering 258 * the coroutine. 259 */ 260 qemu_aio_coroutine_enter(bs->aio_context, s->connection_co); 261 } 262 bdrv_dec_in_flight(bs); 263 } 264 265 static void nbd_client_attach_aio_context(BlockDriverState *bs, 266 AioContext *new_context) 267 { 268 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 269 270 /* 271 * s->connection_co is either yielded from nbd_receive_reply or from 272 * nbd_co_reconnect_loop() 273 */ 274 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTED) { 275 qio_channel_attach_aio_context(QIO_CHANNEL(s->ioc), new_context); 276 } 277 278 bdrv_inc_in_flight(bs); 279 280 /* 281 * Need to wait here for the BH to run because the BH must run while the 282 * node is still drained. 283 */ 284 aio_wait_bh_oneshot(new_context, nbd_client_attach_aio_context_bh, bs); 285 } 286 287 static void coroutine_fn nbd_client_co_drain_begin(BlockDriverState *bs) 288 { 289 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 290 291 s->drained = true; 292 qemu_co_sleep_wake(&s->reconnect_sleep); 293 294 nbd_co_establish_connection_cancel(bs, false); 295 296 reconnect_delay_timer_del(s); 297 298 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT) { 299 s->state = NBD_CLIENT_CONNECTING_NOWAIT; 300 qemu_co_queue_restart_all(&s->free_sema); 301 } 302 } 303 304 static void coroutine_fn nbd_client_co_drain_end(BlockDriverState *bs) 305 { 306 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 307 308 s->drained = false; 309 if (s->wait_drained_end) { 310 s->wait_drained_end = false; 311 aio_co_wake(s->connection_co); 312 } 313 } 314 315 316 static void nbd_teardown_connection(BlockDriverState *bs) 317 { 318 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 319 320 if (s->ioc) { 321 /* finish any pending coroutines */ 322 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL); 323 } else if (s->sioc) { 324 /* abort negotiation */ 325 qio_channel_shutdown(QIO_CHANNEL(s->sioc), QIO_CHANNEL_SHUTDOWN_BOTH, 326 NULL); 327 } 328 329 s->state = NBD_CLIENT_QUIT; 330 if (s->connection_co) { 331 qemu_co_sleep_wake(&s->reconnect_sleep); 332 nbd_co_establish_connection_cancel(bs, true); 333 } 334 if (qemu_in_coroutine()) { 335 s->teardown_co = qemu_coroutine_self(); 336 /* connection_co resumes us when it terminates */ 337 qemu_coroutine_yield(); 338 s->teardown_co = NULL; 339 } else { 340 BDRV_POLL_WHILE(bs, s->connection_co); 341 } 342 assert(!s->connection_co); 343 } 344 345 static bool nbd_client_connecting(BDRVNBDState *s) 346 { 347 NBDClientState state = qatomic_load_acquire(&s->state); 348 return state == NBD_CLIENT_CONNECTING_WAIT || 349 state == NBD_CLIENT_CONNECTING_NOWAIT; 350 } 351 352 static bool nbd_client_connecting_wait(BDRVNBDState *s) 353 { 354 return qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT; 355 } 356 357 static void connect_bh(void *opaque) 358 { 359 BDRVNBDState *state = opaque; 360 361 assert(state->wait_connect); 362 state->wait_connect = false; 363 aio_co_wake(state->connection_co); 364 } 365 366 static void nbd_init_connect_thread(BDRVNBDState *s) 367 { 368 s->connect_thread = g_new(NBDConnectThread, 1); 369 370 *s->connect_thread = (NBDConnectThread) { 371 .saddr = QAPI_CLONE(SocketAddress, s->saddr), 372 .state = CONNECT_THREAD_NONE, 373 .bh_func = connect_bh, 374 .bh_opaque = s, 375 }; 376 377 qemu_mutex_init(&s->connect_thread->mutex); 378 } 379 380 static void nbd_free_connect_thread(NBDConnectThread *thr) 381 { 382 if (thr->sioc) { 383 qio_channel_close(QIO_CHANNEL(thr->sioc), NULL); 384 } 385 error_free(thr->err); 386 qapi_free_SocketAddress(thr->saddr); 387 g_free(thr); 388 } 389 390 static void *connect_thread_func(void *opaque) 391 { 392 NBDConnectThread *thr = opaque; 393 int ret; 394 bool do_free = false; 395 396 thr->sioc = qio_channel_socket_new(); 397 398 error_free(thr->err); 399 thr->err = NULL; 400 ret = qio_channel_socket_connect_sync(thr->sioc, thr->saddr, &thr->err); 401 if (ret < 0) { 402 object_unref(OBJECT(thr->sioc)); 403 thr->sioc = NULL; 404 } 405 406 qemu_mutex_lock(&thr->mutex); 407 408 switch (thr->state) { 409 case CONNECT_THREAD_RUNNING: 410 thr->state = ret < 0 ? CONNECT_THREAD_FAIL : CONNECT_THREAD_SUCCESS; 411 if (thr->bh_ctx) { 412 aio_bh_schedule_oneshot(thr->bh_ctx, thr->bh_func, thr->bh_opaque); 413 414 /* play safe, don't reuse bh_ctx on further connection attempts */ 415 thr->bh_ctx = NULL; 416 } 417 break; 418 case CONNECT_THREAD_RUNNING_DETACHED: 419 do_free = true; 420 break; 421 default: 422 abort(); 423 } 424 425 qemu_mutex_unlock(&thr->mutex); 426 427 if (do_free) { 428 nbd_free_connect_thread(thr); 429 } 430 431 return NULL; 432 } 433 434 static int coroutine_fn 435 nbd_co_establish_connection(BlockDriverState *bs, Error **errp) 436 { 437 int ret; 438 QemuThread thread; 439 BDRVNBDState *s = bs->opaque; 440 NBDConnectThread *thr = s->connect_thread; 441 442 if (!thr) { 443 /* detached */ 444 return -1; 445 } 446 447 qemu_mutex_lock(&thr->mutex); 448 449 switch (thr->state) { 450 case CONNECT_THREAD_FAIL: 451 case CONNECT_THREAD_NONE: 452 error_free(thr->err); 453 thr->err = NULL; 454 thr->state = CONNECT_THREAD_RUNNING; 455 qemu_thread_create(&thread, "nbd-connect", 456 connect_thread_func, thr, QEMU_THREAD_DETACHED); 457 break; 458 case CONNECT_THREAD_SUCCESS: 459 /* Previous attempt finally succeeded in background */ 460 thr->state = CONNECT_THREAD_NONE; 461 s->sioc = thr->sioc; 462 thr->sioc = NULL; 463 yank_register_function(BLOCKDEV_YANK_INSTANCE(bs->node_name), 464 nbd_yank, bs); 465 qemu_mutex_unlock(&thr->mutex); 466 return 0; 467 case CONNECT_THREAD_RUNNING: 468 /* Already running, will wait */ 469 break; 470 default: 471 abort(); 472 } 473 474 thr->bh_ctx = qemu_get_current_aio_context(); 475 476 qemu_mutex_unlock(&thr->mutex); 477 478 479 /* 480 * We are going to wait for connect-thread finish, but 481 * nbd_client_co_drain_begin() can interrupt. 482 * 483 * Note that wait_connect variable is not visible for connect-thread. It 484 * doesn't need mutex protection, it used only inside home aio context of 485 * bs. 486 */ 487 s->wait_connect = true; 488 qemu_coroutine_yield(); 489 490 if (!s->connect_thread) { 491 /* detached */ 492 return -1; 493 } 494 assert(thr == s->connect_thread); 495 496 qemu_mutex_lock(&thr->mutex); 497 498 switch (thr->state) { 499 case CONNECT_THREAD_SUCCESS: 500 case CONNECT_THREAD_FAIL: 501 thr->state = CONNECT_THREAD_NONE; 502 error_propagate(errp, thr->err); 503 thr->err = NULL; 504 s->sioc = thr->sioc; 505 thr->sioc = NULL; 506 if (s->sioc) { 507 yank_register_function(BLOCKDEV_YANK_INSTANCE(bs->node_name), 508 nbd_yank, bs); 509 } 510 ret = (s->sioc ? 0 : -1); 511 break; 512 case CONNECT_THREAD_RUNNING: 513 case CONNECT_THREAD_RUNNING_DETACHED: 514 /* 515 * Obviously, drained section wants to start. Report the attempt as 516 * failed. Still connect thread is executing in background, and its 517 * result may be used for next connection attempt. 518 */ 519 ret = -1; 520 error_setg(errp, "Connection attempt cancelled by other operation"); 521 break; 522 523 case CONNECT_THREAD_NONE: 524 /* 525 * Impossible. We've seen this thread running. So it should be 526 * running or at least give some results. 527 */ 528 abort(); 529 530 default: 531 abort(); 532 } 533 534 qemu_mutex_unlock(&thr->mutex); 535 536 return ret; 537 } 538 539 /* 540 * nbd_co_establish_connection_cancel 541 * Cancel nbd_co_establish_connection asynchronously: it will finish soon, to 542 * allow drained section to begin. 543 * 544 * If detach is true, also cleanup the state (or if thread is running, move it 545 * to CONNECT_THREAD_RUNNING_DETACHED state). s->connect_thread becomes NULL if 546 * detach is true. 547 */ 548 static void nbd_co_establish_connection_cancel(BlockDriverState *bs, 549 bool detach) 550 { 551 BDRVNBDState *s = bs->opaque; 552 NBDConnectThread *thr = s->connect_thread; 553 bool wake = false; 554 bool do_free = false; 555 556 qemu_mutex_lock(&thr->mutex); 557 558 if (thr->state == CONNECT_THREAD_RUNNING) { 559 /* We can cancel only in running state, when bh is not yet scheduled */ 560 thr->bh_ctx = NULL; 561 if (s->wait_connect) { 562 s->wait_connect = false; 563 wake = true; 564 } 565 if (detach) { 566 thr->state = CONNECT_THREAD_RUNNING_DETACHED; 567 s->connect_thread = NULL; 568 } 569 } else if (detach) { 570 do_free = true; 571 } 572 573 qemu_mutex_unlock(&thr->mutex); 574 575 if (do_free) { 576 nbd_free_connect_thread(thr); 577 s->connect_thread = NULL; 578 } 579 580 if (wake) { 581 aio_co_wake(s->connection_co); 582 } 583 } 584 585 static coroutine_fn void nbd_reconnect_attempt(BDRVNBDState *s) 586 { 587 int ret; 588 Error *local_err = NULL; 589 590 if (!nbd_client_connecting(s)) { 591 return; 592 } 593 594 /* Wait for completion of all in-flight requests */ 595 596 qemu_co_mutex_lock(&s->send_mutex); 597 598 while (s->in_flight > 0) { 599 qemu_co_mutex_unlock(&s->send_mutex); 600 nbd_recv_coroutines_wake_all(s); 601 s->wait_in_flight = true; 602 qemu_coroutine_yield(); 603 s->wait_in_flight = false; 604 qemu_co_mutex_lock(&s->send_mutex); 605 } 606 607 qemu_co_mutex_unlock(&s->send_mutex); 608 609 if (!nbd_client_connecting(s)) { 610 return; 611 } 612 613 /* 614 * Now we are sure that nobody is accessing the channel, and no one will 615 * try until we set the state to CONNECTED. 616 */ 617 618 /* Finalize previous connection if any */ 619 if (s->ioc) { 620 qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc)); 621 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name), 622 nbd_yank, s->bs); 623 object_unref(OBJECT(s->sioc)); 624 s->sioc = NULL; 625 object_unref(OBJECT(s->ioc)); 626 s->ioc = NULL; 627 } 628 629 if (nbd_co_establish_connection(s->bs, &local_err) < 0) { 630 ret = -ECONNREFUSED; 631 goto out; 632 } 633 634 bdrv_dec_in_flight(s->bs); 635 636 ret = nbd_client_handshake(s->bs, &local_err); 637 638 if (s->drained) { 639 s->wait_drained_end = true; 640 while (s->drained) { 641 /* 642 * We may be entered once from nbd_client_attach_aio_context_bh 643 * and then from nbd_client_co_drain_end. So here is a loop. 644 */ 645 qemu_coroutine_yield(); 646 } 647 } 648 bdrv_inc_in_flight(s->bs); 649 650 out: 651 s->connect_status = ret; 652 error_free(s->connect_err); 653 s->connect_err = NULL; 654 error_propagate(&s->connect_err, local_err); 655 656 if (ret >= 0) { 657 /* successfully connected */ 658 s->state = NBD_CLIENT_CONNECTED; 659 qemu_co_queue_restart_all(&s->free_sema); 660 } 661 } 662 663 static coroutine_fn void nbd_co_reconnect_loop(BDRVNBDState *s) 664 { 665 uint64_t timeout = 1 * NANOSECONDS_PER_SECOND; 666 uint64_t max_timeout = 16 * NANOSECONDS_PER_SECOND; 667 668 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT) { 669 reconnect_delay_timer_init(s, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + 670 s->reconnect_delay * NANOSECONDS_PER_SECOND); 671 } 672 673 nbd_reconnect_attempt(s); 674 675 while (nbd_client_connecting(s)) { 676 if (s->drained) { 677 bdrv_dec_in_flight(s->bs); 678 s->wait_drained_end = true; 679 while (s->drained) { 680 /* 681 * We may be entered once from nbd_client_attach_aio_context_bh 682 * and then from nbd_client_co_drain_end. So here is a loop. 683 */ 684 qemu_coroutine_yield(); 685 } 686 bdrv_inc_in_flight(s->bs); 687 } else { 688 qemu_co_sleep_ns_wakeable(&s->reconnect_sleep, 689 QEMU_CLOCK_REALTIME, timeout); 690 if (s->drained) { 691 continue; 692 } 693 if (timeout < max_timeout) { 694 timeout *= 2; 695 } 696 } 697 698 nbd_reconnect_attempt(s); 699 } 700 701 reconnect_delay_timer_del(s); 702 } 703 704 static coroutine_fn void nbd_connection_entry(void *opaque) 705 { 706 BDRVNBDState *s = opaque; 707 uint64_t i; 708 int ret = 0; 709 Error *local_err = NULL; 710 711 while (qatomic_load_acquire(&s->state) != NBD_CLIENT_QUIT) { 712 /* 713 * The NBD client can only really be considered idle when it has 714 * yielded from qio_channel_readv_all_eof(), waiting for data. This is 715 * the point where the additional scheduled coroutine entry happens 716 * after nbd_client_attach_aio_context(). 717 * 718 * Therefore we keep an additional in_flight reference all the time and 719 * only drop it temporarily here. 720 */ 721 722 if (nbd_client_connecting(s)) { 723 nbd_co_reconnect_loop(s); 724 } 725 726 if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTED) { 727 continue; 728 } 729 730 assert(s->reply.handle == 0); 731 ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, &local_err); 732 733 if (local_err) { 734 trace_nbd_read_reply_entry_fail(ret, error_get_pretty(local_err)); 735 error_free(local_err); 736 local_err = NULL; 737 } 738 if (ret <= 0) { 739 nbd_channel_error(s, ret ? ret : -EIO); 740 continue; 741 } 742 743 /* 744 * There's no need for a mutex on the receive side, because the 745 * handler acts as a synchronization point and ensures that only 746 * one coroutine is called until the reply finishes. 747 */ 748 i = HANDLE_TO_INDEX(s, s->reply.handle); 749 if (i >= MAX_NBD_REQUESTS || 750 !s->requests[i].coroutine || 751 !s->requests[i].receiving || 752 (nbd_reply_is_structured(&s->reply) && !s->info.structured_reply)) 753 { 754 nbd_channel_error(s, -EINVAL); 755 continue; 756 } 757 758 /* 759 * We're woken up again by the request itself. Note that there 760 * is no race between yielding and reentering connection_co. This 761 * is because: 762 * 763 * - if the request runs on the same AioContext, it is only 764 * entered after we yield 765 * 766 * - if the request runs on a different AioContext, reentering 767 * connection_co happens through a bottom half, which can only 768 * run after we yield. 769 */ 770 aio_co_wake(s->requests[i].coroutine); 771 qemu_coroutine_yield(); 772 } 773 774 qemu_co_queue_restart_all(&s->free_sema); 775 nbd_recv_coroutines_wake_all(s); 776 bdrv_dec_in_flight(s->bs); 777 778 s->connection_co = NULL; 779 if (s->ioc) { 780 qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc)); 781 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name), 782 nbd_yank, s->bs); 783 object_unref(OBJECT(s->sioc)); 784 s->sioc = NULL; 785 object_unref(OBJECT(s->ioc)); 786 s->ioc = NULL; 787 } 788 789 if (s->teardown_co) { 790 aio_co_wake(s->teardown_co); 791 } 792 aio_wait_kick(); 793 } 794 795 static int nbd_co_send_request(BlockDriverState *bs, 796 NBDRequest *request, 797 QEMUIOVector *qiov) 798 { 799 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 800 int rc, i = -1; 801 802 qemu_co_mutex_lock(&s->send_mutex); 803 while (s->in_flight == MAX_NBD_REQUESTS || nbd_client_connecting_wait(s)) { 804 qemu_co_queue_wait(&s->free_sema, &s->send_mutex); 805 } 806 807 if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTED) { 808 rc = -EIO; 809 goto err; 810 } 811 812 s->in_flight++; 813 814 for (i = 0; i < MAX_NBD_REQUESTS; i++) { 815 if (s->requests[i].coroutine == NULL) { 816 break; 817 } 818 } 819 820 g_assert(qemu_in_coroutine()); 821 assert(i < MAX_NBD_REQUESTS); 822 823 s->requests[i].coroutine = qemu_coroutine_self(); 824 s->requests[i].offset = request->from; 825 s->requests[i].receiving = false; 826 827 request->handle = INDEX_TO_HANDLE(s, i); 828 829 assert(s->ioc); 830 831 if (qiov) { 832 qio_channel_set_cork(s->ioc, true); 833 rc = nbd_send_request(s->ioc, request); 834 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTED && 835 rc >= 0) { 836 if (qio_channel_writev_all(s->ioc, qiov->iov, qiov->niov, 837 NULL) < 0) { 838 rc = -EIO; 839 } 840 } else if (rc >= 0) { 841 rc = -EIO; 842 } 843 qio_channel_set_cork(s->ioc, false); 844 } else { 845 rc = nbd_send_request(s->ioc, request); 846 } 847 848 err: 849 if (rc < 0) { 850 nbd_channel_error(s, rc); 851 if (i != -1) { 852 s->requests[i].coroutine = NULL; 853 s->in_flight--; 854 } 855 if (s->in_flight == 0 && s->wait_in_flight) { 856 aio_co_wake(s->connection_co); 857 } else { 858 qemu_co_queue_next(&s->free_sema); 859 } 860 } 861 qemu_co_mutex_unlock(&s->send_mutex); 862 return rc; 863 } 864 865 static inline uint16_t payload_advance16(uint8_t **payload) 866 { 867 *payload += 2; 868 return lduw_be_p(*payload - 2); 869 } 870 871 static inline uint32_t payload_advance32(uint8_t **payload) 872 { 873 *payload += 4; 874 return ldl_be_p(*payload - 4); 875 } 876 877 static inline uint64_t payload_advance64(uint8_t **payload) 878 { 879 *payload += 8; 880 return ldq_be_p(*payload - 8); 881 } 882 883 static int nbd_parse_offset_hole_payload(BDRVNBDState *s, 884 NBDStructuredReplyChunk *chunk, 885 uint8_t *payload, uint64_t orig_offset, 886 QEMUIOVector *qiov, Error **errp) 887 { 888 uint64_t offset; 889 uint32_t hole_size; 890 891 if (chunk->length != sizeof(offset) + sizeof(hole_size)) { 892 error_setg(errp, "Protocol error: invalid payload for " 893 "NBD_REPLY_TYPE_OFFSET_HOLE"); 894 return -EINVAL; 895 } 896 897 offset = payload_advance64(&payload); 898 hole_size = payload_advance32(&payload); 899 900 if (!hole_size || offset < orig_offset || hole_size > qiov->size || 901 offset > orig_offset + qiov->size - hole_size) { 902 error_setg(errp, "Protocol error: server sent chunk exceeding requested" 903 " region"); 904 return -EINVAL; 905 } 906 if (s->info.min_block && 907 !QEMU_IS_ALIGNED(hole_size, s->info.min_block)) { 908 trace_nbd_structured_read_compliance("hole"); 909 } 910 911 qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size); 912 913 return 0; 914 } 915 916 /* 917 * nbd_parse_blockstatus_payload 918 * Based on our request, we expect only one extent in reply, for the 919 * base:allocation context. 920 */ 921 static int nbd_parse_blockstatus_payload(BDRVNBDState *s, 922 NBDStructuredReplyChunk *chunk, 923 uint8_t *payload, uint64_t orig_length, 924 NBDExtent *extent, Error **errp) 925 { 926 uint32_t context_id; 927 928 /* The server succeeded, so it must have sent [at least] one extent */ 929 if (chunk->length < sizeof(context_id) + sizeof(*extent)) { 930 error_setg(errp, "Protocol error: invalid payload for " 931 "NBD_REPLY_TYPE_BLOCK_STATUS"); 932 return -EINVAL; 933 } 934 935 context_id = payload_advance32(&payload); 936 if (s->info.context_id != context_id) { 937 error_setg(errp, "Protocol error: unexpected context id %d for " 938 "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context " 939 "id is %d", context_id, 940 s->info.context_id); 941 return -EINVAL; 942 } 943 944 extent->length = payload_advance32(&payload); 945 extent->flags = payload_advance32(&payload); 946 947 if (extent->length == 0) { 948 error_setg(errp, "Protocol error: server sent status chunk with " 949 "zero length"); 950 return -EINVAL; 951 } 952 953 /* 954 * A server sending unaligned block status is in violation of the 955 * protocol, but as qemu-nbd 3.1 is such a server (at least for 956 * POSIX files that are not a multiple of 512 bytes, since qemu 957 * rounds files up to 512-byte multiples but lseek(SEEK_HOLE) 958 * still sees an implicit hole beyond the real EOF), it's nicer to 959 * work around the misbehaving server. If the request included 960 * more than the final unaligned block, truncate it back to an 961 * aligned result; if the request was only the final block, round 962 * up to the full block and change the status to fully-allocated 963 * (always a safe status, even if it loses information). 964 */ 965 if (s->info.min_block && !QEMU_IS_ALIGNED(extent->length, 966 s->info.min_block)) { 967 trace_nbd_parse_blockstatus_compliance("extent length is unaligned"); 968 if (extent->length > s->info.min_block) { 969 extent->length = QEMU_ALIGN_DOWN(extent->length, 970 s->info.min_block); 971 } else { 972 extent->length = s->info.min_block; 973 extent->flags = 0; 974 } 975 } 976 977 /* 978 * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have 979 * sent us any more than one extent, nor should it have included 980 * status beyond our request in that extent. However, it's easy 981 * enough to ignore the server's noncompliance without killing the 982 * connection; just ignore trailing extents, and clamp things to 983 * the length of our request. 984 */ 985 if (chunk->length > sizeof(context_id) + sizeof(*extent)) { 986 trace_nbd_parse_blockstatus_compliance("more than one extent"); 987 } 988 if (extent->length > orig_length) { 989 extent->length = orig_length; 990 trace_nbd_parse_blockstatus_compliance("extent length too large"); 991 } 992 993 /* 994 * HACK: if we are using x-dirty-bitmaps to access 995 * qemu:allocation-depth, treat all depths > 2 the same as 2, 996 * since nbd_client_co_block_status is only expecting the low two 997 * bits to be set. 998 */ 999 if (s->alloc_depth && extent->flags > 2) { 1000 extent->flags = 2; 1001 } 1002 1003 return 0; 1004 } 1005 1006 /* 1007 * nbd_parse_error_payload 1008 * on success @errp contains message describing nbd error reply 1009 */ 1010 static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk, 1011 uint8_t *payload, int *request_ret, 1012 Error **errp) 1013 { 1014 uint32_t error; 1015 uint16_t message_size; 1016 1017 assert(chunk->type & (1 << 15)); 1018 1019 if (chunk->length < sizeof(error) + sizeof(message_size)) { 1020 error_setg(errp, 1021 "Protocol error: invalid payload for structured error"); 1022 return -EINVAL; 1023 } 1024 1025 error = nbd_errno_to_system_errno(payload_advance32(&payload)); 1026 if (error == 0) { 1027 error_setg(errp, "Protocol error: server sent structured error chunk " 1028 "with error = 0"); 1029 return -EINVAL; 1030 } 1031 1032 *request_ret = -error; 1033 message_size = payload_advance16(&payload); 1034 1035 if (message_size > chunk->length - sizeof(error) - sizeof(message_size)) { 1036 error_setg(errp, "Protocol error: server sent structured error chunk " 1037 "with incorrect message size"); 1038 return -EINVAL; 1039 } 1040 1041 /* TODO: Add a trace point to mention the server complaint */ 1042 1043 /* TODO handle ERROR_OFFSET */ 1044 1045 return 0; 1046 } 1047 1048 static int nbd_co_receive_offset_data_payload(BDRVNBDState *s, 1049 uint64_t orig_offset, 1050 QEMUIOVector *qiov, Error **errp) 1051 { 1052 QEMUIOVector sub_qiov; 1053 uint64_t offset; 1054 size_t data_size; 1055 int ret; 1056 NBDStructuredReplyChunk *chunk = &s->reply.structured; 1057 1058 assert(nbd_reply_is_structured(&s->reply)); 1059 1060 /* The NBD spec requires at least one byte of payload */ 1061 if (chunk->length <= sizeof(offset)) { 1062 error_setg(errp, "Protocol error: invalid payload for " 1063 "NBD_REPLY_TYPE_OFFSET_DATA"); 1064 return -EINVAL; 1065 } 1066 1067 if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) { 1068 return -EIO; 1069 } 1070 1071 data_size = chunk->length - sizeof(offset); 1072 assert(data_size); 1073 if (offset < orig_offset || data_size > qiov->size || 1074 offset > orig_offset + qiov->size - data_size) { 1075 error_setg(errp, "Protocol error: server sent chunk exceeding requested" 1076 " region"); 1077 return -EINVAL; 1078 } 1079 if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) { 1080 trace_nbd_structured_read_compliance("data"); 1081 } 1082 1083 qemu_iovec_init(&sub_qiov, qiov->niov); 1084 qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size); 1085 ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp); 1086 qemu_iovec_destroy(&sub_qiov); 1087 1088 return ret < 0 ? -EIO : 0; 1089 } 1090 1091 #define NBD_MAX_MALLOC_PAYLOAD 1000 1092 static coroutine_fn int nbd_co_receive_structured_payload( 1093 BDRVNBDState *s, void **payload, Error **errp) 1094 { 1095 int ret; 1096 uint32_t len; 1097 1098 assert(nbd_reply_is_structured(&s->reply)); 1099 1100 len = s->reply.structured.length; 1101 1102 if (len == 0) { 1103 return 0; 1104 } 1105 1106 if (payload == NULL) { 1107 error_setg(errp, "Unexpected structured payload"); 1108 return -EINVAL; 1109 } 1110 1111 if (len > NBD_MAX_MALLOC_PAYLOAD) { 1112 error_setg(errp, "Payload too large"); 1113 return -EINVAL; 1114 } 1115 1116 *payload = g_new(char, len); 1117 ret = nbd_read(s->ioc, *payload, len, "structured payload", errp); 1118 if (ret < 0) { 1119 g_free(*payload); 1120 *payload = NULL; 1121 return ret; 1122 } 1123 1124 return 0; 1125 } 1126 1127 /* 1128 * nbd_co_do_receive_one_chunk 1129 * for simple reply: 1130 * set request_ret to received reply error 1131 * if qiov is not NULL: read payload to @qiov 1132 * for structured reply chunk: 1133 * if error chunk: read payload, set @request_ret, do not set @payload 1134 * else if offset_data chunk: read payload data to @qiov, do not set @payload 1135 * else: read payload to @payload 1136 * 1137 * If function fails, @errp contains corresponding error message, and the 1138 * connection with the server is suspect. If it returns 0, then the 1139 * transaction succeeded (although @request_ret may be a negative errno 1140 * corresponding to the server's error reply), and errp is unchanged. 1141 */ 1142 static coroutine_fn int nbd_co_do_receive_one_chunk( 1143 BDRVNBDState *s, uint64_t handle, bool only_structured, 1144 int *request_ret, QEMUIOVector *qiov, void **payload, Error **errp) 1145 { 1146 int ret; 1147 int i = HANDLE_TO_INDEX(s, handle); 1148 void *local_payload = NULL; 1149 NBDStructuredReplyChunk *chunk; 1150 1151 if (payload) { 1152 *payload = NULL; 1153 } 1154 *request_ret = 0; 1155 1156 /* Wait until we're woken up by nbd_connection_entry. */ 1157 s->requests[i].receiving = true; 1158 qemu_coroutine_yield(); 1159 s->requests[i].receiving = false; 1160 if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTED) { 1161 error_setg(errp, "Connection closed"); 1162 return -EIO; 1163 } 1164 assert(s->ioc); 1165 1166 assert(s->reply.handle == handle); 1167 1168 if (nbd_reply_is_simple(&s->reply)) { 1169 if (only_structured) { 1170 error_setg(errp, "Protocol error: simple reply when structured " 1171 "reply chunk was expected"); 1172 return -EINVAL; 1173 } 1174 1175 *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error); 1176 if (*request_ret < 0 || !qiov) { 1177 return 0; 1178 } 1179 1180 return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov, 1181 errp) < 0 ? -EIO : 0; 1182 } 1183 1184 /* handle structured reply chunk */ 1185 assert(s->info.structured_reply); 1186 chunk = &s->reply.structured; 1187 1188 if (chunk->type == NBD_REPLY_TYPE_NONE) { 1189 if (!(chunk->flags & NBD_REPLY_FLAG_DONE)) { 1190 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk without" 1191 " NBD_REPLY_FLAG_DONE flag set"); 1192 return -EINVAL; 1193 } 1194 if (chunk->length) { 1195 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with" 1196 " nonzero length"); 1197 return -EINVAL; 1198 } 1199 return 0; 1200 } 1201 1202 if (chunk->type == NBD_REPLY_TYPE_OFFSET_DATA) { 1203 if (!qiov) { 1204 error_setg(errp, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk"); 1205 return -EINVAL; 1206 } 1207 1208 return nbd_co_receive_offset_data_payload(s, s->requests[i].offset, 1209 qiov, errp); 1210 } 1211 1212 if (nbd_reply_type_is_error(chunk->type)) { 1213 payload = &local_payload; 1214 } 1215 1216 ret = nbd_co_receive_structured_payload(s, payload, errp); 1217 if (ret < 0) { 1218 return ret; 1219 } 1220 1221 if (nbd_reply_type_is_error(chunk->type)) { 1222 ret = nbd_parse_error_payload(chunk, local_payload, request_ret, errp); 1223 g_free(local_payload); 1224 return ret; 1225 } 1226 1227 return 0; 1228 } 1229 1230 /* 1231 * nbd_co_receive_one_chunk 1232 * Read reply, wake up connection_co and set s->quit if needed. 1233 * Return value is a fatal error code or normal nbd reply error code 1234 */ 1235 static coroutine_fn int nbd_co_receive_one_chunk( 1236 BDRVNBDState *s, uint64_t handle, bool only_structured, 1237 int *request_ret, QEMUIOVector *qiov, NBDReply *reply, void **payload, 1238 Error **errp) 1239 { 1240 int ret = nbd_co_do_receive_one_chunk(s, handle, only_structured, 1241 request_ret, qiov, payload, errp); 1242 1243 if (ret < 0) { 1244 memset(reply, 0, sizeof(*reply)); 1245 nbd_channel_error(s, ret); 1246 } else { 1247 /* For assert at loop start in nbd_connection_entry */ 1248 *reply = s->reply; 1249 } 1250 s->reply.handle = 0; 1251 1252 if (s->connection_co && !s->wait_in_flight) { 1253 /* 1254 * We must check s->wait_in_flight, because we may entered by 1255 * nbd_recv_coroutines_wake_all(), in this case we should not 1256 * wake connection_co here, it will woken by last request. 1257 */ 1258 aio_co_wake(s->connection_co); 1259 } 1260 1261 return ret; 1262 } 1263 1264 typedef struct NBDReplyChunkIter { 1265 int ret; 1266 int request_ret; 1267 Error *err; 1268 bool done, only_structured; 1269 } NBDReplyChunkIter; 1270 1271 static void nbd_iter_channel_error(NBDReplyChunkIter *iter, 1272 int ret, Error **local_err) 1273 { 1274 assert(local_err && *local_err); 1275 assert(ret < 0); 1276 1277 if (!iter->ret) { 1278 iter->ret = ret; 1279 error_propagate(&iter->err, *local_err); 1280 } else { 1281 error_free(*local_err); 1282 } 1283 1284 *local_err = NULL; 1285 } 1286 1287 static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret) 1288 { 1289 assert(ret < 0); 1290 1291 if (!iter->request_ret) { 1292 iter->request_ret = ret; 1293 } 1294 } 1295 1296 /* 1297 * NBD_FOREACH_REPLY_CHUNK 1298 * The pointer stored in @payload requires g_free() to free it. 1299 */ 1300 #define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \ 1301 qiov, reply, payload) \ 1302 for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \ 1303 nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);) 1304 1305 /* 1306 * nbd_reply_chunk_iter_receive 1307 * The pointer stored in @payload requires g_free() to free it. 1308 */ 1309 static bool nbd_reply_chunk_iter_receive(BDRVNBDState *s, 1310 NBDReplyChunkIter *iter, 1311 uint64_t handle, 1312 QEMUIOVector *qiov, NBDReply *reply, 1313 void **payload) 1314 { 1315 int ret, request_ret; 1316 NBDReply local_reply; 1317 NBDStructuredReplyChunk *chunk; 1318 Error *local_err = NULL; 1319 if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTED) { 1320 error_setg(&local_err, "Connection closed"); 1321 nbd_iter_channel_error(iter, -EIO, &local_err); 1322 goto break_loop; 1323 } 1324 1325 if (iter->done) { 1326 /* Previous iteration was last. */ 1327 goto break_loop; 1328 } 1329 1330 if (reply == NULL) { 1331 reply = &local_reply; 1332 } 1333 1334 ret = nbd_co_receive_one_chunk(s, handle, iter->only_structured, 1335 &request_ret, qiov, reply, payload, 1336 &local_err); 1337 if (ret < 0) { 1338 nbd_iter_channel_error(iter, ret, &local_err); 1339 } else if (request_ret < 0) { 1340 nbd_iter_request_error(iter, request_ret); 1341 } 1342 1343 /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */ 1344 if (nbd_reply_is_simple(reply) || 1345 qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTED) { 1346 goto break_loop; 1347 } 1348 1349 chunk = &reply->structured; 1350 iter->only_structured = true; 1351 1352 if (chunk->type == NBD_REPLY_TYPE_NONE) { 1353 /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */ 1354 assert(chunk->flags & NBD_REPLY_FLAG_DONE); 1355 goto break_loop; 1356 } 1357 1358 if (chunk->flags & NBD_REPLY_FLAG_DONE) { 1359 /* This iteration is last. */ 1360 iter->done = true; 1361 } 1362 1363 /* Execute the loop body */ 1364 return true; 1365 1366 break_loop: 1367 s->requests[HANDLE_TO_INDEX(s, handle)].coroutine = NULL; 1368 1369 qemu_co_mutex_lock(&s->send_mutex); 1370 s->in_flight--; 1371 if (s->in_flight == 0 && s->wait_in_flight) { 1372 aio_co_wake(s->connection_co); 1373 } else { 1374 qemu_co_queue_next(&s->free_sema); 1375 } 1376 qemu_co_mutex_unlock(&s->send_mutex); 1377 1378 return false; 1379 } 1380 1381 static int nbd_co_receive_return_code(BDRVNBDState *s, uint64_t handle, 1382 int *request_ret, Error **errp) 1383 { 1384 NBDReplyChunkIter iter; 1385 1386 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, NULL, NULL) { 1387 /* nbd_reply_chunk_iter_receive does all the work */ 1388 } 1389 1390 error_propagate(errp, iter.err); 1391 *request_ret = iter.request_ret; 1392 return iter.ret; 1393 } 1394 1395 static int nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t handle, 1396 uint64_t offset, QEMUIOVector *qiov, 1397 int *request_ret, Error **errp) 1398 { 1399 NBDReplyChunkIter iter; 1400 NBDReply reply; 1401 void *payload = NULL; 1402 Error *local_err = NULL; 1403 1404 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, s->info.structured_reply, 1405 qiov, &reply, &payload) 1406 { 1407 int ret; 1408 NBDStructuredReplyChunk *chunk = &reply.structured; 1409 1410 assert(nbd_reply_is_structured(&reply)); 1411 1412 switch (chunk->type) { 1413 case NBD_REPLY_TYPE_OFFSET_DATA: 1414 /* 1415 * special cased in nbd_co_receive_one_chunk, data is already 1416 * in qiov 1417 */ 1418 break; 1419 case NBD_REPLY_TYPE_OFFSET_HOLE: 1420 ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload, 1421 offset, qiov, &local_err); 1422 if (ret < 0) { 1423 nbd_channel_error(s, ret); 1424 nbd_iter_channel_error(&iter, ret, &local_err); 1425 } 1426 break; 1427 default: 1428 if (!nbd_reply_type_is_error(chunk->type)) { 1429 /* not allowed reply type */ 1430 nbd_channel_error(s, -EINVAL); 1431 error_setg(&local_err, 1432 "Unexpected reply type: %d (%s) for CMD_READ", 1433 chunk->type, nbd_reply_type_lookup(chunk->type)); 1434 nbd_iter_channel_error(&iter, -EINVAL, &local_err); 1435 } 1436 } 1437 1438 g_free(payload); 1439 payload = NULL; 1440 } 1441 1442 error_propagate(errp, iter.err); 1443 *request_ret = iter.request_ret; 1444 return iter.ret; 1445 } 1446 1447 static int nbd_co_receive_blockstatus_reply(BDRVNBDState *s, 1448 uint64_t handle, uint64_t length, 1449 NBDExtent *extent, 1450 int *request_ret, Error **errp) 1451 { 1452 NBDReplyChunkIter iter; 1453 NBDReply reply; 1454 void *payload = NULL; 1455 Error *local_err = NULL; 1456 bool received = false; 1457 1458 assert(!extent->length); 1459 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, &reply, &payload) { 1460 int ret; 1461 NBDStructuredReplyChunk *chunk = &reply.structured; 1462 1463 assert(nbd_reply_is_structured(&reply)); 1464 1465 switch (chunk->type) { 1466 case NBD_REPLY_TYPE_BLOCK_STATUS: 1467 if (received) { 1468 nbd_channel_error(s, -EINVAL); 1469 error_setg(&local_err, "Several BLOCK_STATUS chunks in reply"); 1470 nbd_iter_channel_error(&iter, -EINVAL, &local_err); 1471 } 1472 received = true; 1473 1474 ret = nbd_parse_blockstatus_payload(s, &reply.structured, 1475 payload, length, extent, 1476 &local_err); 1477 if (ret < 0) { 1478 nbd_channel_error(s, ret); 1479 nbd_iter_channel_error(&iter, ret, &local_err); 1480 } 1481 break; 1482 default: 1483 if (!nbd_reply_type_is_error(chunk->type)) { 1484 nbd_channel_error(s, -EINVAL); 1485 error_setg(&local_err, 1486 "Unexpected reply type: %d (%s) " 1487 "for CMD_BLOCK_STATUS", 1488 chunk->type, nbd_reply_type_lookup(chunk->type)); 1489 nbd_iter_channel_error(&iter, -EINVAL, &local_err); 1490 } 1491 } 1492 1493 g_free(payload); 1494 payload = NULL; 1495 } 1496 1497 if (!extent->length && !iter.request_ret) { 1498 error_setg(&local_err, "Server did not reply with any status extents"); 1499 nbd_iter_channel_error(&iter, -EIO, &local_err); 1500 } 1501 1502 error_propagate(errp, iter.err); 1503 *request_ret = iter.request_ret; 1504 return iter.ret; 1505 } 1506 1507 static int nbd_co_request(BlockDriverState *bs, NBDRequest *request, 1508 QEMUIOVector *write_qiov) 1509 { 1510 int ret, request_ret; 1511 Error *local_err = NULL; 1512 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 1513 1514 assert(request->type != NBD_CMD_READ); 1515 if (write_qiov) { 1516 assert(request->type == NBD_CMD_WRITE); 1517 assert(request->len == iov_size(write_qiov->iov, write_qiov->niov)); 1518 } else { 1519 assert(request->type != NBD_CMD_WRITE); 1520 } 1521 1522 do { 1523 ret = nbd_co_send_request(bs, request, write_qiov); 1524 if (ret < 0) { 1525 continue; 1526 } 1527 1528 ret = nbd_co_receive_return_code(s, request->handle, 1529 &request_ret, &local_err); 1530 if (local_err) { 1531 trace_nbd_co_request_fail(request->from, request->len, 1532 request->handle, request->flags, 1533 request->type, 1534 nbd_cmd_lookup(request->type), 1535 ret, error_get_pretty(local_err)); 1536 error_free(local_err); 1537 local_err = NULL; 1538 } 1539 } while (ret < 0 && nbd_client_connecting_wait(s)); 1540 1541 return ret ? ret : request_ret; 1542 } 1543 1544 static int nbd_client_co_preadv(BlockDriverState *bs, uint64_t offset, 1545 uint64_t bytes, QEMUIOVector *qiov, int flags) 1546 { 1547 int ret, request_ret; 1548 Error *local_err = NULL; 1549 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 1550 NBDRequest request = { 1551 .type = NBD_CMD_READ, 1552 .from = offset, 1553 .len = bytes, 1554 }; 1555 1556 assert(bytes <= NBD_MAX_BUFFER_SIZE); 1557 assert(!flags); 1558 1559 if (!bytes) { 1560 return 0; 1561 } 1562 /* 1563 * Work around the fact that the block layer doesn't do 1564 * byte-accurate sizing yet - if the read exceeds the server's 1565 * advertised size because the block layer rounded size up, then 1566 * truncate the request to the server and tail-pad with zero. 1567 */ 1568 if (offset >= s->info.size) { 1569 assert(bytes < BDRV_SECTOR_SIZE); 1570 qemu_iovec_memset(qiov, 0, 0, bytes); 1571 return 0; 1572 } 1573 if (offset + bytes > s->info.size) { 1574 uint64_t slop = offset + bytes - s->info.size; 1575 1576 assert(slop < BDRV_SECTOR_SIZE); 1577 qemu_iovec_memset(qiov, bytes - slop, 0, slop); 1578 request.len -= slop; 1579 } 1580 1581 do { 1582 ret = nbd_co_send_request(bs, &request, NULL); 1583 if (ret < 0) { 1584 continue; 1585 } 1586 1587 ret = nbd_co_receive_cmdread_reply(s, request.handle, offset, qiov, 1588 &request_ret, &local_err); 1589 if (local_err) { 1590 trace_nbd_co_request_fail(request.from, request.len, request.handle, 1591 request.flags, request.type, 1592 nbd_cmd_lookup(request.type), 1593 ret, error_get_pretty(local_err)); 1594 error_free(local_err); 1595 local_err = NULL; 1596 } 1597 } while (ret < 0 && nbd_client_connecting_wait(s)); 1598 1599 return ret ? ret : request_ret; 1600 } 1601 1602 static int nbd_client_co_pwritev(BlockDriverState *bs, uint64_t offset, 1603 uint64_t bytes, QEMUIOVector *qiov, int flags) 1604 { 1605 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 1606 NBDRequest request = { 1607 .type = NBD_CMD_WRITE, 1608 .from = offset, 1609 .len = bytes, 1610 }; 1611 1612 assert(!(s->info.flags & NBD_FLAG_READ_ONLY)); 1613 if (flags & BDRV_REQ_FUA) { 1614 assert(s->info.flags & NBD_FLAG_SEND_FUA); 1615 request.flags |= NBD_CMD_FLAG_FUA; 1616 } 1617 1618 assert(bytes <= NBD_MAX_BUFFER_SIZE); 1619 1620 if (!bytes) { 1621 return 0; 1622 } 1623 return nbd_co_request(bs, &request, qiov); 1624 } 1625 1626 static int nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset, 1627 int bytes, BdrvRequestFlags flags) 1628 { 1629 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 1630 NBDRequest request = { 1631 .type = NBD_CMD_WRITE_ZEROES, 1632 .from = offset, 1633 .len = bytes, 1634 }; 1635 1636 assert(!(s->info.flags & NBD_FLAG_READ_ONLY)); 1637 if (!(s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) { 1638 return -ENOTSUP; 1639 } 1640 1641 if (flags & BDRV_REQ_FUA) { 1642 assert(s->info.flags & NBD_FLAG_SEND_FUA); 1643 request.flags |= NBD_CMD_FLAG_FUA; 1644 } 1645 if (!(flags & BDRV_REQ_MAY_UNMAP)) { 1646 request.flags |= NBD_CMD_FLAG_NO_HOLE; 1647 } 1648 if (flags & BDRV_REQ_NO_FALLBACK) { 1649 assert(s->info.flags & NBD_FLAG_SEND_FAST_ZERO); 1650 request.flags |= NBD_CMD_FLAG_FAST_ZERO; 1651 } 1652 1653 if (!bytes) { 1654 return 0; 1655 } 1656 return nbd_co_request(bs, &request, NULL); 1657 } 1658 1659 static int nbd_client_co_flush(BlockDriverState *bs) 1660 { 1661 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 1662 NBDRequest request = { .type = NBD_CMD_FLUSH }; 1663 1664 if (!(s->info.flags & NBD_FLAG_SEND_FLUSH)) { 1665 return 0; 1666 } 1667 1668 request.from = 0; 1669 request.len = 0; 1670 1671 return nbd_co_request(bs, &request, NULL); 1672 } 1673 1674 static int nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset, 1675 int bytes) 1676 { 1677 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 1678 NBDRequest request = { 1679 .type = NBD_CMD_TRIM, 1680 .from = offset, 1681 .len = bytes, 1682 }; 1683 1684 assert(!(s->info.flags & NBD_FLAG_READ_ONLY)); 1685 if (!(s->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) { 1686 return 0; 1687 } 1688 1689 return nbd_co_request(bs, &request, NULL); 1690 } 1691 1692 static int coroutine_fn nbd_client_co_block_status( 1693 BlockDriverState *bs, bool want_zero, int64_t offset, int64_t bytes, 1694 int64_t *pnum, int64_t *map, BlockDriverState **file) 1695 { 1696 int ret, request_ret; 1697 NBDExtent extent = { 0 }; 1698 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 1699 Error *local_err = NULL; 1700 1701 NBDRequest request = { 1702 .type = NBD_CMD_BLOCK_STATUS, 1703 .from = offset, 1704 .len = MIN(QEMU_ALIGN_DOWN(INT_MAX, bs->bl.request_alignment), 1705 MIN(bytes, s->info.size - offset)), 1706 .flags = NBD_CMD_FLAG_REQ_ONE, 1707 }; 1708 1709 if (!s->info.base_allocation) { 1710 *pnum = bytes; 1711 *map = offset; 1712 *file = bs; 1713 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID; 1714 } 1715 1716 /* 1717 * Work around the fact that the block layer doesn't do 1718 * byte-accurate sizing yet - if the status request exceeds the 1719 * server's advertised size because the block layer rounded size 1720 * up, we truncated the request to the server (above), or are 1721 * called on just the hole. 1722 */ 1723 if (offset >= s->info.size) { 1724 *pnum = bytes; 1725 assert(bytes < BDRV_SECTOR_SIZE); 1726 /* Intentionally don't report offset_valid for the hole */ 1727 return BDRV_BLOCK_ZERO; 1728 } 1729 1730 if (s->info.min_block) { 1731 assert(QEMU_IS_ALIGNED(request.len, s->info.min_block)); 1732 } 1733 do { 1734 ret = nbd_co_send_request(bs, &request, NULL); 1735 if (ret < 0) { 1736 continue; 1737 } 1738 1739 ret = nbd_co_receive_blockstatus_reply(s, request.handle, bytes, 1740 &extent, &request_ret, 1741 &local_err); 1742 if (local_err) { 1743 trace_nbd_co_request_fail(request.from, request.len, request.handle, 1744 request.flags, request.type, 1745 nbd_cmd_lookup(request.type), 1746 ret, error_get_pretty(local_err)); 1747 error_free(local_err); 1748 local_err = NULL; 1749 } 1750 } while (ret < 0 && nbd_client_connecting_wait(s)); 1751 1752 if (ret < 0 || request_ret < 0) { 1753 return ret ? ret : request_ret; 1754 } 1755 1756 assert(extent.length); 1757 *pnum = extent.length; 1758 *map = offset; 1759 *file = bs; 1760 return (extent.flags & NBD_STATE_HOLE ? 0 : BDRV_BLOCK_DATA) | 1761 (extent.flags & NBD_STATE_ZERO ? BDRV_BLOCK_ZERO : 0) | 1762 BDRV_BLOCK_OFFSET_VALID; 1763 } 1764 1765 static int nbd_client_reopen_prepare(BDRVReopenState *state, 1766 BlockReopenQueue *queue, Error **errp) 1767 { 1768 BDRVNBDState *s = (BDRVNBDState *)state->bs->opaque; 1769 1770 if ((state->flags & BDRV_O_RDWR) && (s->info.flags & NBD_FLAG_READ_ONLY)) { 1771 error_setg(errp, "Can't reopen read-only NBD mount as read/write"); 1772 return -EACCES; 1773 } 1774 return 0; 1775 } 1776 1777 static void nbd_yank(void *opaque) 1778 { 1779 BlockDriverState *bs = opaque; 1780 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 1781 1782 qatomic_store_release(&s->state, NBD_CLIENT_QUIT); 1783 qio_channel_shutdown(QIO_CHANNEL(s->sioc), QIO_CHANNEL_SHUTDOWN_BOTH, NULL); 1784 } 1785 1786 static void nbd_client_close(BlockDriverState *bs) 1787 { 1788 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 1789 NBDRequest request = { .type = NBD_CMD_DISC }; 1790 1791 if (s->ioc) { 1792 nbd_send_request(s->ioc, &request); 1793 } 1794 1795 nbd_teardown_connection(bs); 1796 } 1797 1798 static int nbd_establish_connection(BlockDriverState *bs, 1799 SocketAddress *saddr, 1800 Error **errp) 1801 { 1802 ERRP_GUARD(); 1803 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 1804 1805 s->sioc = qio_channel_socket_new(); 1806 qio_channel_set_name(QIO_CHANNEL(s->sioc), "nbd-client"); 1807 1808 qio_channel_socket_connect_sync(s->sioc, saddr, errp); 1809 if (*errp) { 1810 object_unref(OBJECT(s->sioc)); 1811 s->sioc = NULL; 1812 return -1; 1813 } 1814 1815 yank_register_function(BLOCKDEV_YANK_INSTANCE(bs->node_name), nbd_yank, bs); 1816 qio_channel_set_delay(QIO_CHANNEL(s->sioc), false); 1817 1818 return 0; 1819 } 1820 1821 /* nbd_client_handshake takes ownership on s->sioc. On failure it's unref'ed. */ 1822 static int nbd_client_handshake(BlockDriverState *bs, Error **errp) 1823 { 1824 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 1825 AioContext *aio_context = bdrv_get_aio_context(bs); 1826 int ret; 1827 1828 trace_nbd_client_handshake(s->export); 1829 qio_channel_set_blocking(QIO_CHANNEL(s->sioc), false, NULL); 1830 qio_channel_attach_aio_context(QIO_CHANNEL(s->sioc), aio_context); 1831 1832 s->info.request_sizes = true; 1833 s->info.structured_reply = true; 1834 s->info.base_allocation = true; 1835 s->info.x_dirty_bitmap = g_strdup(s->x_dirty_bitmap); 1836 s->info.name = g_strdup(s->export ?: ""); 1837 ret = nbd_receive_negotiate(aio_context, QIO_CHANNEL(s->sioc), s->tlscreds, 1838 s->hostname, &s->ioc, &s->info, errp); 1839 g_free(s->info.x_dirty_bitmap); 1840 g_free(s->info.name); 1841 if (ret < 0) { 1842 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(bs->node_name), 1843 nbd_yank, bs); 1844 object_unref(OBJECT(s->sioc)); 1845 s->sioc = NULL; 1846 return ret; 1847 } 1848 if (s->x_dirty_bitmap) { 1849 if (!s->info.base_allocation) { 1850 error_setg(errp, "requested x-dirty-bitmap %s not found", 1851 s->x_dirty_bitmap); 1852 ret = -EINVAL; 1853 goto fail; 1854 } 1855 if (strcmp(s->x_dirty_bitmap, "qemu:allocation-depth") == 0) { 1856 s->alloc_depth = true; 1857 } 1858 } 1859 if (s->info.flags & NBD_FLAG_READ_ONLY) { 1860 ret = bdrv_apply_auto_read_only(bs, "NBD export is read-only", errp); 1861 if (ret < 0) { 1862 goto fail; 1863 } 1864 } 1865 if (s->info.flags & NBD_FLAG_SEND_FUA) { 1866 bs->supported_write_flags = BDRV_REQ_FUA; 1867 bs->supported_zero_flags |= BDRV_REQ_FUA; 1868 } 1869 if (s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES) { 1870 bs->supported_zero_flags |= BDRV_REQ_MAY_UNMAP; 1871 if (s->info.flags & NBD_FLAG_SEND_FAST_ZERO) { 1872 bs->supported_zero_flags |= BDRV_REQ_NO_FALLBACK; 1873 } 1874 } 1875 1876 if (!s->ioc) { 1877 s->ioc = QIO_CHANNEL(s->sioc); 1878 object_ref(OBJECT(s->ioc)); 1879 } 1880 1881 trace_nbd_client_handshake_success(s->export); 1882 1883 return 0; 1884 1885 fail: 1886 /* 1887 * We have connected, but must fail for other reasons. 1888 * Send NBD_CMD_DISC as a courtesy to the server. 1889 */ 1890 { 1891 NBDRequest request = { .type = NBD_CMD_DISC }; 1892 1893 nbd_send_request(s->ioc ?: QIO_CHANNEL(s->sioc), &request); 1894 1895 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(bs->node_name), 1896 nbd_yank, bs); 1897 object_unref(OBJECT(s->sioc)); 1898 s->sioc = NULL; 1899 1900 return ret; 1901 } 1902 } 1903 1904 /* 1905 * Parse nbd_open options 1906 */ 1907 1908 static int nbd_parse_uri(const char *filename, QDict *options) 1909 { 1910 URI *uri; 1911 const char *p; 1912 QueryParams *qp = NULL; 1913 int ret = 0; 1914 bool is_unix; 1915 1916 uri = uri_parse(filename); 1917 if (!uri) { 1918 return -EINVAL; 1919 } 1920 1921 /* transport */ 1922 if (!g_strcmp0(uri->scheme, "nbd")) { 1923 is_unix = false; 1924 } else if (!g_strcmp0(uri->scheme, "nbd+tcp")) { 1925 is_unix = false; 1926 } else if (!g_strcmp0(uri->scheme, "nbd+unix")) { 1927 is_unix = true; 1928 } else { 1929 ret = -EINVAL; 1930 goto out; 1931 } 1932 1933 p = uri->path ? uri->path : ""; 1934 if (p[0] == '/') { 1935 p++; 1936 } 1937 if (p[0]) { 1938 qdict_put_str(options, "export", p); 1939 } 1940 1941 qp = query_params_parse(uri->query); 1942 if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) { 1943 ret = -EINVAL; 1944 goto out; 1945 } 1946 1947 if (is_unix) { 1948 /* nbd+unix:///export?socket=path */ 1949 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) { 1950 ret = -EINVAL; 1951 goto out; 1952 } 1953 qdict_put_str(options, "server.type", "unix"); 1954 qdict_put_str(options, "server.path", qp->p[0].value); 1955 } else { 1956 QString *host; 1957 char *port_str; 1958 1959 /* nbd[+tcp]://host[:port]/export */ 1960 if (!uri->server) { 1961 ret = -EINVAL; 1962 goto out; 1963 } 1964 1965 /* strip braces from literal IPv6 address */ 1966 if (uri->server[0] == '[') { 1967 host = qstring_from_substr(uri->server, 1, 1968 strlen(uri->server) - 1); 1969 } else { 1970 host = qstring_from_str(uri->server); 1971 } 1972 1973 qdict_put_str(options, "server.type", "inet"); 1974 qdict_put(options, "server.host", host); 1975 1976 port_str = g_strdup_printf("%d", uri->port ?: NBD_DEFAULT_PORT); 1977 qdict_put_str(options, "server.port", port_str); 1978 g_free(port_str); 1979 } 1980 1981 out: 1982 if (qp) { 1983 query_params_free(qp); 1984 } 1985 uri_free(uri); 1986 return ret; 1987 } 1988 1989 static bool nbd_has_filename_options_conflict(QDict *options, Error **errp) 1990 { 1991 const QDictEntry *e; 1992 1993 for (e = qdict_first(options); e; e = qdict_next(options, e)) { 1994 if (!strcmp(e->key, "host") || 1995 !strcmp(e->key, "port") || 1996 !strcmp(e->key, "path") || 1997 !strcmp(e->key, "export") || 1998 strstart(e->key, "server.", NULL)) 1999 { 2000 error_setg(errp, "Option '%s' cannot be used with a file name", 2001 e->key); 2002 return true; 2003 } 2004 } 2005 2006 return false; 2007 } 2008 2009 static void nbd_parse_filename(const char *filename, QDict *options, 2010 Error **errp) 2011 { 2012 g_autofree char *file = NULL; 2013 char *export_name; 2014 const char *host_spec; 2015 const char *unixpath; 2016 2017 if (nbd_has_filename_options_conflict(options, errp)) { 2018 return; 2019 } 2020 2021 if (strstr(filename, "://")) { 2022 int ret = nbd_parse_uri(filename, options); 2023 if (ret < 0) { 2024 error_setg(errp, "No valid URL specified"); 2025 } 2026 return; 2027 } 2028 2029 file = g_strdup(filename); 2030 2031 export_name = strstr(file, EN_OPTSTR); 2032 if (export_name) { 2033 if (export_name[strlen(EN_OPTSTR)] == 0) { 2034 return; 2035 } 2036 export_name[0] = 0; /* truncate 'file' */ 2037 export_name += strlen(EN_OPTSTR); 2038 2039 qdict_put_str(options, "export", export_name); 2040 } 2041 2042 /* extract the host_spec - fail if it's not nbd:... */ 2043 if (!strstart(file, "nbd:", &host_spec)) { 2044 error_setg(errp, "File name string for NBD must start with 'nbd:'"); 2045 return; 2046 } 2047 2048 if (!*host_spec) { 2049 return; 2050 } 2051 2052 /* are we a UNIX or TCP socket? */ 2053 if (strstart(host_spec, "unix:", &unixpath)) { 2054 qdict_put_str(options, "server.type", "unix"); 2055 qdict_put_str(options, "server.path", unixpath); 2056 } else { 2057 InetSocketAddress *addr = g_new(InetSocketAddress, 1); 2058 2059 if (inet_parse(addr, host_spec, errp)) { 2060 goto out_inet; 2061 } 2062 2063 qdict_put_str(options, "server.type", "inet"); 2064 qdict_put_str(options, "server.host", addr->host); 2065 qdict_put_str(options, "server.port", addr->port); 2066 out_inet: 2067 qapi_free_InetSocketAddress(addr); 2068 } 2069 } 2070 2071 static bool nbd_process_legacy_socket_options(QDict *output_options, 2072 QemuOpts *legacy_opts, 2073 Error **errp) 2074 { 2075 const char *path = qemu_opt_get(legacy_opts, "path"); 2076 const char *host = qemu_opt_get(legacy_opts, "host"); 2077 const char *port = qemu_opt_get(legacy_opts, "port"); 2078 const QDictEntry *e; 2079 2080 if (!path && !host && !port) { 2081 return true; 2082 } 2083 2084 for (e = qdict_first(output_options); e; e = qdict_next(output_options, e)) 2085 { 2086 if (strstart(e->key, "server.", NULL)) { 2087 error_setg(errp, "Cannot use 'server' and path/host/port at the " 2088 "same time"); 2089 return false; 2090 } 2091 } 2092 2093 if (path && host) { 2094 error_setg(errp, "path and host may not be used at the same time"); 2095 return false; 2096 } else if (path) { 2097 if (port) { 2098 error_setg(errp, "port may not be used without host"); 2099 return false; 2100 } 2101 2102 qdict_put_str(output_options, "server.type", "unix"); 2103 qdict_put_str(output_options, "server.path", path); 2104 } else if (host) { 2105 qdict_put_str(output_options, "server.type", "inet"); 2106 qdict_put_str(output_options, "server.host", host); 2107 qdict_put_str(output_options, "server.port", 2108 port ?: stringify(NBD_DEFAULT_PORT)); 2109 } 2110 2111 return true; 2112 } 2113 2114 static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options, 2115 Error **errp) 2116 { 2117 SocketAddress *saddr = NULL; 2118 QDict *addr = NULL; 2119 Visitor *iv = NULL; 2120 2121 qdict_extract_subqdict(options, &addr, "server."); 2122 if (!qdict_size(addr)) { 2123 error_setg(errp, "NBD server address missing"); 2124 goto done; 2125 } 2126 2127 iv = qobject_input_visitor_new_flat_confused(addr, errp); 2128 if (!iv) { 2129 goto done; 2130 } 2131 2132 if (!visit_type_SocketAddress(iv, NULL, &saddr, errp)) { 2133 goto done; 2134 } 2135 2136 done: 2137 qobject_unref(addr); 2138 visit_free(iv); 2139 return saddr; 2140 } 2141 2142 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp) 2143 { 2144 Object *obj; 2145 QCryptoTLSCreds *creds; 2146 2147 obj = object_resolve_path_component( 2148 object_get_objects_root(), id); 2149 if (!obj) { 2150 error_setg(errp, "No TLS credentials with id '%s'", 2151 id); 2152 return NULL; 2153 } 2154 creds = (QCryptoTLSCreds *) 2155 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS); 2156 if (!creds) { 2157 error_setg(errp, "Object with id '%s' is not TLS credentials", 2158 id); 2159 return NULL; 2160 } 2161 2162 if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) { 2163 error_setg(errp, 2164 "Expecting TLS credentials with a client endpoint"); 2165 return NULL; 2166 } 2167 object_ref(obj); 2168 return creds; 2169 } 2170 2171 2172 static QemuOptsList nbd_runtime_opts = { 2173 .name = "nbd", 2174 .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head), 2175 .desc = { 2176 { 2177 .name = "host", 2178 .type = QEMU_OPT_STRING, 2179 .help = "TCP host to connect to", 2180 }, 2181 { 2182 .name = "port", 2183 .type = QEMU_OPT_STRING, 2184 .help = "TCP port to connect to", 2185 }, 2186 { 2187 .name = "path", 2188 .type = QEMU_OPT_STRING, 2189 .help = "Unix socket path to connect to", 2190 }, 2191 { 2192 .name = "export", 2193 .type = QEMU_OPT_STRING, 2194 .help = "Name of the NBD export to open", 2195 }, 2196 { 2197 .name = "tls-creds", 2198 .type = QEMU_OPT_STRING, 2199 .help = "ID of the TLS credentials to use", 2200 }, 2201 { 2202 .name = "x-dirty-bitmap", 2203 .type = QEMU_OPT_STRING, 2204 .help = "experimental: expose named dirty bitmap in place of " 2205 "block status", 2206 }, 2207 { 2208 .name = "reconnect-delay", 2209 .type = QEMU_OPT_NUMBER, 2210 .help = "On an unexpected disconnect, the nbd client tries to " 2211 "connect again until succeeding or encountering a serious " 2212 "error. During the first @reconnect-delay seconds, all " 2213 "requests are paused and will be rerun on a successful " 2214 "reconnect. After that time, any delayed requests and all " 2215 "future requests before a successful reconnect will " 2216 "immediately fail. Default 0", 2217 }, 2218 { /* end of list */ } 2219 }, 2220 }; 2221 2222 static int nbd_process_options(BlockDriverState *bs, QDict *options, 2223 Error **errp) 2224 { 2225 BDRVNBDState *s = bs->opaque; 2226 QemuOpts *opts; 2227 int ret = -EINVAL; 2228 2229 opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort); 2230 if (!qemu_opts_absorb_qdict(opts, options, errp)) { 2231 goto error; 2232 } 2233 2234 /* Translate @host, @port, and @path to a SocketAddress */ 2235 if (!nbd_process_legacy_socket_options(options, opts, errp)) { 2236 goto error; 2237 } 2238 2239 /* Pop the config into our state object. Exit if invalid. */ 2240 s->saddr = nbd_config(s, options, errp); 2241 if (!s->saddr) { 2242 goto error; 2243 } 2244 2245 s->export = g_strdup(qemu_opt_get(opts, "export")); 2246 if (s->export && strlen(s->export) > NBD_MAX_STRING_SIZE) { 2247 error_setg(errp, "export name too long to send to server"); 2248 goto error; 2249 } 2250 2251 s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds")); 2252 if (s->tlscredsid) { 2253 s->tlscreds = nbd_get_tls_creds(s->tlscredsid, errp); 2254 if (!s->tlscreds) { 2255 goto error; 2256 } 2257 2258 /* TODO SOCKET_ADDRESS_KIND_FD where fd has AF_INET or AF_INET6 */ 2259 if (s->saddr->type != SOCKET_ADDRESS_TYPE_INET) { 2260 error_setg(errp, "TLS only supported over IP sockets"); 2261 goto error; 2262 } 2263 s->hostname = s->saddr->u.inet.host; 2264 } 2265 2266 s->x_dirty_bitmap = g_strdup(qemu_opt_get(opts, "x-dirty-bitmap")); 2267 if (s->x_dirty_bitmap && strlen(s->x_dirty_bitmap) > NBD_MAX_STRING_SIZE) { 2268 error_setg(errp, "x-dirty-bitmap query too long to send to server"); 2269 goto error; 2270 } 2271 2272 s->reconnect_delay = qemu_opt_get_number(opts, "reconnect-delay", 0); 2273 2274 ret = 0; 2275 2276 error: 2277 if (ret < 0) { 2278 nbd_clear_bdrvstate(s); 2279 } 2280 qemu_opts_del(opts); 2281 return ret; 2282 } 2283 2284 static int nbd_open(BlockDriverState *bs, QDict *options, int flags, 2285 Error **errp) 2286 { 2287 int ret; 2288 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 2289 2290 ret = nbd_process_options(bs, options, errp); 2291 if (ret < 0) { 2292 return ret; 2293 } 2294 2295 s->bs = bs; 2296 qemu_co_mutex_init(&s->send_mutex); 2297 qemu_co_queue_init(&s->free_sema); 2298 2299 if (!yank_register_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name), errp)) { 2300 return -EEXIST; 2301 } 2302 2303 /* 2304 * establish TCP connection, return error if it fails 2305 * TODO: Configurable retry-until-timeout behaviour. 2306 */ 2307 if (nbd_establish_connection(bs, s->saddr, errp) < 0) { 2308 yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name)); 2309 return -ECONNREFUSED; 2310 } 2311 2312 ret = nbd_client_handshake(bs, errp); 2313 if (ret < 0) { 2314 yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name)); 2315 nbd_clear_bdrvstate(s); 2316 return ret; 2317 } 2318 /* successfully connected */ 2319 s->state = NBD_CLIENT_CONNECTED; 2320 2321 nbd_init_connect_thread(s); 2322 2323 s->connection_co = qemu_coroutine_create(nbd_connection_entry, s); 2324 bdrv_inc_in_flight(bs); 2325 aio_co_schedule(bdrv_get_aio_context(bs), s->connection_co); 2326 2327 return 0; 2328 } 2329 2330 static int nbd_co_flush(BlockDriverState *bs) 2331 { 2332 return nbd_client_co_flush(bs); 2333 } 2334 2335 static void nbd_refresh_limits(BlockDriverState *bs, Error **errp) 2336 { 2337 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 2338 uint32_t min = s->info.min_block; 2339 uint32_t max = MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE, s->info.max_block); 2340 2341 /* 2342 * If the server did not advertise an alignment: 2343 * - a size that is not sector-aligned implies that an alignment 2344 * of 1 can be used to access those tail bytes 2345 * - advertisement of block status requires an alignment of 1, so 2346 * that we don't violate block layer constraints that block 2347 * status is always aligned (as we can't control whether the 2348 * server will report sub-sector extents, such as a hole at EOF 2349 * on an unaligned POSIX file) 2350 * - otherwise, assume the server is so old that we are safer avoiding 2351 * sub-sector requests 2352 */ 2353 if (!min) { 2354 min = (!QEMU_IS_ALIGNED(s->info.size, BDRV_SECTOR_SIZE) || 2355 s->info.base_allocation) ? 1 : BDRV_SECTOR_SIZE; 2356 } 2357 2358 bs->bl.request_alignment = min; 2359 bs->bl.max_pdiscard = QEMU_ALIGN_DOWN(INT_MAX, min); 2360 bs->bl.max_pwrite_zeroes = max; 2361 bs->bl.max_transfer = max; 2362 2363 if (s->info.opt_block && 2364 s->info.opt_block > bs->bl.opt_transfer) { 2365 bs->bl.opt_transfer = s->info.opt_block; 2366 } 2367 } 2368 2369 static void nbd_close(BlockDriverState *bs) 2370 { 2371 BDRVNBDState *s = bs->opaque; 2372 2373 nbd_client_close(bs); 2374 yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name)); 2375 nbd_clear_bdrvstate(s); 2376 } 2377 2378 /* 2379 * NBD cannot truncate, but if the caller asks to truncate to the same size, or 2380 * to a smaller size with exact=false, there is no reason to fail the 2381 * operation. 2382 * 2383 * Preallocation mode is ignored since it does not seems useful to fail when 2384 * we never change anything. 2385 */ 2386 static int coroutine_fn nbd_co_truncate(BlockDriverState *bs, int64_t offset, 2387 bool exact, PreallocMode prealloc, 2388 BdrvRequestFlags flags, Error **errp) 2389 { 2390 BDRVNBDState *s = bs->opaque; 2391 2392 if (offset != s->info.size && exact) { 2393 error_setg(errp, "Cannot resize NBD nodes"); 2394 return -ENOTSUP; 2395 } 2396 2397 if (offset > s->info.size) { 2398 error_setg(errp, "Cannot grow NBD nodes"); 2399 return -EINVAL; 2400 } 2401 2402 return 0; 2403 } 2404 2405 static int64_t nbd_getlength(BlockDriverState *bs) 2406 { 2407 BDRVNBDState *s = bs->opaque; 2408 2409 return s->info.size; 2410 } 2411 2412 static void nbd_refresh_filename(BlockDriverState *bs) 2413 { 2414 BDRVNBDState *s = bs->opaque; 2415 const char *host = NULL, *port = NULL, *path = NULL; 2416 size_t len = 0; 2417 2418 if (s->saddr->type == SOCKET_ADDRESS_TYPE_INET) { 2419 const InetSocketAddress *inet = &s->saddr->u.inet; 2420 if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) { 2421 host = inet->host; 2422 port = inet->port; 2423 } 2424 } else if (s->saddr->type == SOCKET_ADDRESS_TYPE_UNIX) { 2425 path = s->saddr->u.q_unix.path; 2426 } /* else can't represent as pseudo-filename */ 2427 2428 if (path && s->export) { 2429 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename), 2430 "nbd+unix:///%s?socket=%s", s->export, path); 2431 } else if (path && !s->export) { 2432 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename), 2433 "nbd+unix://?socket=%s", path); 2434 } else if (host && s->export) { 2435 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename), 2436 "nbd://%s:%s/%s", host, port, s->export); 2437 } else if (host && !s->export) { 2438 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename), 2439 "nbd://%s:%s", host, port); 2440 } 2441 if (len >= sizeof(bs->exact_filename)) { 2442 /* Name is too long to represent exactly, so leave it empty. */ 2443 bs->exact_filename[0] = '\0'; 2444 } 2445 } 2446 2447 static char *nbd_dirname(BlockDriverState *bs, Error **errp) 2448 { 2449 /* The generic bdrv_dirname() implementation is able to work out some 2450 * directory name for NBD nodes, but that would be wrong. So far there is no 2451 * specification for how "export paths" would work, so NBD does not have 2452 * directory names. */ 2453 error_setg(errp, "Cannot generate a base directory for NBD nodes"); 2454 return NULL; 2455 } 2456 2457 static const char *const nbd_strong_runtime_opts[] = { 2458 "path", 2459 "host", 2460 "port", 2461 "export", 2462 "tls-creds", 2463 "server.", 2464 2465 NULL 2466 }; 2467 2468 static void nbd_cancel_in_flight(BlockDriverState *bs) 2469 { 2470 BDRVNBDState *s = (BDRVNBDState *)bs->opaque; 2471 2472 reconnect_delay_timer_del(s); 2473 2474 if (s->state == NBD_CLIENT_CONNECTING_WAIT) { 2475 s->state = NBD_CLIENT_CONNECTING_NOWAIT; 2476 qemu_co_queue_restart_all(&s->free_sema); 2477 } 2478 } 2479 2480 static BlockDriver bdrv_nbd = { 2481 .format_name = "nbd", 2482 .protocol_name = "nbd", 2483 .instance_size = sizeof(BDRVNBDState), 2484 .bdrv_parse_filename = nbd_parse_filename, 2485 .bdrv_co_create_opts = bdrv_co_create_opts_simple, 2486 .create_opts = &bdrv_create_opts_simple, 2487 .bdrv_file_open = nbd_open, 2488 .bdrv_reopen_prepare = nbd_client_reopen_prepare, 2489 .bdrv_co_preadv = nbd_client_co_preadv, 2490 .bdrv_co_pwritev = nbd_client_co_pwritev, 2491 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes, 2492 .bdrv_close = nbd_close, 2493 .bdrv_co_flush_to_os = nbd_co_flush, 2494 .bdrv_co_pdiscard = nbd_client_co_pdiscard, 2495 .bdrv_refresh_limits = nbd_refresh_limits, 2496 .bdrv_co_truncate = nbd_co_truncate, 2497 .bdrv_getlength = nbd_getlength, 2498 .bdrv_detach_aio_context = nbd_client_detach_aio_context, 2499 .bdrv_attach_aio_context = nbd_client_attach_aio_context, 2500 .bdrv_co_drain_begin = nbd_client_co_drain_begin, 2501 .bdrv_co_drain_end = nbd_client_co_drain_end, 2502 .bdrv_refresh_filename = nbd_refresh_filename, 2503 .bdrv_co_block_status = nbd_client_co_block_status, 2504 .bdrv_dirname = nbd_dirname, 2505 .strong_runtime_opts = nbd_strong_runtime_opts, 2506 .bdrv_cancel_in_flight = nbd_cancel_in_flight, 2507 }; 2508 2509 static BlockDriver bdrv_nbd_tcp = { 2510 .format_name = "nbd", 2511 .protocol_name = "nbd+tcp", 2512 .instance_size = sizeof(BDRVNBDState), 2513 .bdrv_parse_filename = nbd_parse_filename, 2514 .bdrv_co_create_opts = bdrv_co_create_opts_simple, 2515 .create_opts = &bdrv_create_opts_simple, 2516 .bdrv_file_open = nbd_open, 2517 .bdrv_reopen_prepare = nbd_client_reopen_prepare, 2518 .bdrv_co_preadv = nbd_client_co_preadv, 2519 .bdrv_co_pwritev = nbd_client_co_pwritev, 2520 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes, 2521 .bdrv_close = nbd_close, 2522 .bdrv_co_flush_to_os = nbd_co_flush, 2523 .bdrv_co_pdiscard = nbd_client_co_pdiscard, 2524 .bdrv_refresh_limits = nbd_refresh_limits, 2525 .bdrv_co_truncate = nbd_co_truncate, 2526 .bdrv_getlength = nbd_getlength, 2527 .bdrv_detach_aio_context = nbd_client_detach_aio_context, 2528 .bdrv_attach_aio_context = nbd_client_attach_aio_context, 2529 .bdrv_co_drain_begin = nbd_client_co_drain_begin, 2530 .bdrv_co_drain_end = nbd_client_co_drain_end, 2531 .bdrv_refresh_filename = nbd_refresh_filename, 2532 .bdrv_co_block_status = nbd_client_co_block_status, 2533 .bdrv_dirname = nbd_dirname, 2534 .strong_runtime_opts = nbd_strong_runtime_opts, 2535 .bdrv_cancel_in_flight = nbd_cancel_in_flight, 2536 }; 2537 2538 static BlockDriver bdrv_nbd_unix = { 2539 .format_name = "nbd", 2540 .protocol_name = "nbd+unix", 2541 .instance_size = sizeof(BDRVNBDState), 2542 .bdrv_parse_filename = nbd_parse_filename, 2543 .bdrv_co_create_opts = bdrv_co_create_opts_simple, 2544 .create_opts = &bdrv_create_opts_simple, 2545 .bdrv_file_open = nbd_open, 2546 .bdrv_reopen_prepare = nbd_client_reopen_prepare, 2547 .bdrv_co_preadv = nbd_client_co_preadv, 2548 .bdrv_co_pwritev = nbd_client_co_pwritev, 2549 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes, 2550 .bdrv_close = nbd_close, 2551 .bdrv_co_flush_to_os = nbd_co_flush, 2552 .bdrv_co_pdiscard = nbd_client_co_pdiscard, 2553 .bdrv_refresh_limits = nbd_refresh_limits, 2554 .bdrv_co_truncate = nbd_co_truncate, 2555 .bdrv_getlength = nbd_getlength, 2556 .bdrv_detach_aio_context = nbd_client_detach_aio_context, 2557 .bdrv_attach_aio_context = nbd_client_attach_aio_context, 2558 .bdrv_co_drain_begin = nbd_client_co_drain_begin, 2559 .bdrv_co_drain_end = nbd_client_co_drain_end, 2560 .bdrv_refresh_filename = nbd_refresh_filename, 2561 .bdrv_co_block_status = nbd_client_co_block_status, 2562 .bdrv_dirname = nbd_dirname, 2563 .strong_runtime_opts = nbd_strong_runtime_opts, 2564 .bdrv_cancel_in_flight = nbd_cancel_in_flight, 2565 }; 2566 2567 static void bdrv_nbd_init(void) 2568 { 2569 bdrv_register(&bdrv_nbd); 2570 bdrv_register(&bdrv_nbd_tcp); 2571 bdrv_register(&bdrv_nbd_unix); 2572 } 2573 2574 block_init(bdrv_nbd_init); 2575