target/arm: Implement SVE2 integer multiply-add (indexed)
[qemu.git] / block / nbd.c
blob616f9ae6c4daf5576c42826f7bc10da01be772b0
1 /*
2 * QEMU Block driver for NBD
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>
9 * Some parts:
10 * Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
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:
19 * The above copyright notice and this permission notice shall be included in
20 * all copies or substantial portions of the Software.
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.
31 #include "qemu/osdep.h"
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"
40 #include "qapi/qapi-visit-sockets.h"
41 #include "qapi/qmp/qstring.h"
42 #include "qapi/clone-visitor.h"
44 #include "block/qdict.h"
45 #include "block/nbd.h"
46 #include "block/block_int.h"
48 #include "qemu/yank.h"
50 #define EN_OPTSTR ":exportname="
51 #define MAX_NBD_REQUESTS 16
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))
56 typedef struct {
57 Coroutine *coroutine;
58 uint64_t offset; /* original offset of the request */
59 bool receiving; /* waiting for connection_co? */
60 } NBDClientRequest;
62 typedef enum NBDClientState {
63 NBD_CLIENT_CONNECTING_WAIT,
64 NBD_CLIENT_CONNECTING_NOWAIT,
65 NBD_CLIENT_CONNECTED,
66 NBD_CLIENT_QUIT
67 } NBDClientState;
69 typedef enum NBDConnectThreadState {
70 /* No thread, no pending results */
71 CONNECT_THREAD_NONE,
73 /* Thread is running, no results for now */
74 CONNECT_THREAD_RUNNING,
77 * Thread is running, but requestor exited. Thread should close
78 * the new socket and free the connect state on exit.
80 CONNECT_THREAD_RUNNING_DETACHED,
82 /* Thread finished, results are stored in a state */
83 CONNECT_THREAD_FAIL,
84 CONNECT_THREAD_SUCCESS
85 } NBDConnectThreadState;
87 typedef struct NBDConnectThread {
88 /* Initialization constants */
89 SocketAddress *saddr; /* address to connect to */
91 * Bottom half to schedule on completion. Scheduled only if bh_ctx is not
92 * NULL
94 QEMUBHFunc *bh_func;
95 void *bh_opaque;
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.
101 QIOChannelSocket *sioc;
102 Error *err;
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;
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;
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;
128 QEMUTimer *reconnect_delay_timer;
130 NBDClientRequest requests[MAX_NBD_REQUESTS];
131 NBDReply reply;
132 BlockDriverState *bs;
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;
143 bool wait_connect;
144 NBDConnectThread *connect_thread;
145 } BDRVNBDState;
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);
155 static void nbd_clear_bdrvstate(BDRVNBDState *s)
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;
168 static void nbd_channel_error(BDRVNBDState *s, int ret)
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;
175 } else {
176 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTED) {
177 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
179 s->state = NBD_CLIENT_QUIT;
183 static void nbd_recv_coroutines_wake_all(BDRVNBDState *s)
185 int i;
187 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
188 NBDClientRequest *req = &s->requests[i];
190 if (req->coroutine && req->receiving) {
191 aio_co_wake(req->coroutine);
196 static void reconnect_delay_timer_del(BDRVNBDState *s)
198 if (s->reconnect_delay_timer) {
199 timer_free(s->reconnect_delay_timer);
200 s->reconnect_delay_timer = NULL;
204 static void reconnect_delay_timer_cb(void *opaque)
206 BDRVNBDState *s = opaque;
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 */
215 reconnect_delay_timer_del(s);
218 static void reconnect_delay_timer_init(BDRVNBDState *s, uint64_t expire_time_ns)
220 if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTING_WAIT) {
221 return;
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);
232 static void nbd_client_detach_aio_context(BlockDriverState *bs)
234 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
236 /* Timer is deleted in nbd_client_co_drain_begin() */
237 assert(!s->reconnect_delay_timer);
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.
243 if (s->ioc) {
244 qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
248 static void nbd_client_attach_aio_context_bh(void *opaque)
250 BlockDriverState *bs = opaque;
251 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
253 if (s->connection_co) {
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.
260 qemu_aio_coroutine_enter(bs->aio_context, s->connection_co);
262 bdrv_dec_in_flight(bs);
265 static void nbd_client_attach_aio_context(BlockDriverState *bs,
266 AioContext *new_context)
268 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
271 * s->connection_co is either yielded from nbd_receive_reply or from
272 * nbd_co_reconnect_loop()
274 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTED) {
275 qio_channel_attach_aio_context(QIO_CHANNEL(s->ioc), new_context);
278 bdrv_inc_in_flight(bs);
281 * Need to wait here for the BH to run because the BH must run while the
282 * node is still drained.
284 aio_wait_bh_oneshot(new_context, nbd_client_attach_aio_context_bh, bs);
287 static void coroutine_fn nbd_client_co_drain_begin(BlockDriverState *bs)
289 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
291 s->drained = true;
292 qemu_co_sleep_wake(&s->reconnect_sleep);
294 nbd_co_establish_connection_cancel(bs, false);
296 reconnect_delay_timer_del(s);
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);
304 static void coroutine_fn nbd_client_co_drain_end(BlockDriverState *bs)
306 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
308 s->drained = false;
309 if (s->wait_drained_end) {
310 s->wait_drained_end = false;
311 aio_co_wake(s->connection_co);
316 static void nbd_teardown_connection(BlockDriverState *bs)
318 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
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);
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);
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);
342 assert(!s->connection_co);
345 static bool nbd_client_connecting(BDRVNBDState *s)
347 NBDClientState state = qatomic_load_acquire(&s->state);
348 return state == NBD_CLIENT_CONNECTING_WAIT ||
349 state == NBD_CLIENT_CONNECTING_NOWAIT;
352 static bool nbd_client_connecting_wait(BDRVNBDState *s)
354 return qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT;
357 static void connect_bh(void *opaque)
359 BDRVNBDState *state = opaque;
361 assert(state->wait_connect);
362 state->wait_connect = false;
363 aio_co_wake(state->connection_co);
366 static void nbd_init_connect_thread(BDRVNBDState *s)
368 s->connect_thread = g_new(NBDConnectThread, 1);
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,
377 qemu_mutex_init(&s->connect_thread->mutex);
380 static void nbd_free_connect_thread(NBDConnectThread *thr)
382 if (thr->sioc) {
383 qio_channel_close(QIO_CHANNEL(thr->sioc), NULL);
385 error_free(thr->err);
386 qapi_free_SocketAddress(thr->saddr);
387 g_free(thr);
390 static void *connect_thread_func(void *opaque)
392 NBDConnectThread *thr = opaque;
393 int ret;
394 bool do_free = false;
396 thr->sioc = qio_channel_socket_new();
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;
406 qemu_mutex_lock(&thr->mutex);
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);
414 /* play safe, don't reuse bh_ctx on further connection attempts */
415 thr->bh_ctx = NULL;
417 break;
418 case CONNECT_THREAD_RUNNING_DETACHED:
419 do_free = true;
420 break;
421 default:
422 abort();
425 qemu_mutex_unlock(&thr->mutex);
427 if (do_free) {
428 nbd_free_connect_thread(thr);
431 return NULL;
434 static int coroutine_fn
435 nbd_co_establish_connection(BlockDriverState *bs, Error **errp)
437 int ret;
438 QemuThread thread;
439 BDRVNBDState *s = bs->opaque;
440 NBDConnectThread *thr = s->connect_thread;
442 if (!thr) {
443 /* detached */
444 return -1;
447 qemu_mutex_lock(&thr->mutex);
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();
474 thr->bh_ctx = qemu_get_current_aio_context();
476 qemu_mutex_unlock(&thr->mutex);
480 * We are going to wait for connect-thread finish, but
481 * nbd_client_co_drain_begin() can interrupt.
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.
487 s->wait_connect = true;
488 qemu_coroutine_yield();
490 if (!s->connect_thread) {
491 /* detached */
492 return -1;
494 assert(thr == s->connect_thread);
496 qemu_mutex_lock(&thr->mutex);
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);
510 ret = (s->sioc ? 0 : -1);
511 break;
512 case CONNECT_THREAD_RUNNING:
513 case CONNECT_THREAD_RUNNING_DETACHED:
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.
519 ret = -1;
520 error_setg(errp, "Connection attempt cancelled by other operation");
521 break;
523 case CONNECT_THREAD_NONE:
525 * Impossible. We've seen this thread running. So it should be
526 * running or at least give some results.
528 abort();
530 default:
531 abort();
534 qemu_mutex_unlock(&thr->mutex);
536 return ret;
540 * nbd_co_establish_connection_cancel
541 * Cancel nbd_co_establish_connection asynchronously: it will finish soon, to
542 * allow drained section to begin.
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.
548 static void nbd_co_establish_connection_cancel(BlockDriverState *bs,
549 bool detach)
551 BDRVNBDState *s = bs->opaque;
552 NBDConnectThread *thr = s->connect_thread;
553 bool wake = false;
554 bool do_free = false;
556 qemu_mutex_lock(&thr->mutex);
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;
565 if (detach) {
566 thr->state = CONNECT_THREAD_RUNNING_DETACHED;
567 s->connect_thread = NULL;
569 } else if (detach) {
570 do_free = true;
573 qemu_mutex_unlock(&thr->mutex);
575 if (do_free) {
576 nbd_free_connect_thread(thr);
577 s->connect_thread = NULL;
580 if (wake) {
581 aio_co_wake(s->connection_co);
585 static coroutine_fn void nbd_reconnect_attempt(BDRVNBDState *s)
587 int ret;
588 Error *local_err = NULL;
590 if (!nbd_client_connecting(s)) {
591 return;
594 /* Wait for completion of all in-flight requests */
596 qemu_co_mutex_lock(&s->send_mutex);
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);
607 qemu_co_mutex_unlock(&s->send_mutex);
609 if (!nbd_client_connecting(s)) {
610 return;
614 * Now we are sure that nobody is accessing the channel, and no one will
615 * try until we set the state to CONNECTED.
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;
629 if (nbd_co_establish_connection(s->bs, &local_err) < 0) {
630 ret = -ECONNREFUSED;
631 goto out;
634 bdrv_dec_in_flight(s->bs);
636 ret = nbd_client_handshake(s->bs, &local_err);
638 if (s->drained) {
639 s->wait_drained_end = true;
640 while (s->drained) {
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.
645 qemu_coroutine_yield();
648 bdrv_inc_in_flight(s->bs);
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);
656 if (ret >= 0) {
657 /* successfully connected */
658 s->state = NBD_CLIENT_CONNECTED;
659 qemu_co_queue_restart_all(&s->free_sema);
663 static coroutine_fn void nbd_co_reconnect_loop(BDRVNBDState *s)
665 uint64_t timeout = 1 * NANOSECONDS_PER_SECOND;
666 uint64_t max_timeout = 16 * NANOSECONDS_PER_SECOND;
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);
673 nbd_reconnect_attempt(s);
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) {
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.
684 qemu_coroutine_yield();
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;
693 if (timeout < max_timeout) {
694 timeout *= 2;
698 nbd_reconnect_attempt(s);
701 reconnect_delay_timer_del(s);
704 static coroutine_fn void nbd_connection_entry(void *opaque)
706 BDRVNBDState *s = opaque;
707 uint64_t i;
708 int ret = 0;
709 Error *local_err = NULL;
711 while (qatomic_load_acquire(&s->state) != NBD_CLIENT_QUIT) {
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().
718 * Therefore we keep an additional in_flight reference all the time and
719 * only drop it temporarily here.
722 if (nbd_client_connecting(s)) {
723 nbd_co_reconnect_loop(s);
726 if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTED) {
727 continue;
730 assert(s->reply.handle == 0);
731 ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, &local_err);
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;
738 if (ret <= 0) {
739 nbd_channel_error(s, ret ? ret : -EIO);
740 continue;
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.
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))
754 nbd_channel_error(s, -EINVAL);
755 continue;
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:
763 * - if the request runs on the same AioContext, it is only
764 * entered after we yield
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.
770 aio_co_wake(s->requests[i].coroutine);
771 qemu_coroutine_yield();
774 qemu_co_queue_restart_all(&s->free_sema);
775 nbd_recv_coroutines_wake_all(s);
776 bdrv_dec_in_flight(s->bs);
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;
789 if (s->teardown_co) {
790 aio_co_wake(s->teardown_co);
792 aio_wait_kick();
795 static int nbd_co_send_request(BlockDriverState *bs,
796 NBDRequest *request,
797 QEMUIOVector *qiov)
799 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
800 int rc, i = -1;
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);
807 if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTED) {
808 rc = -EIO;
809 goto err;
812 s->in_flight++;
814 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
815 if (s->requests[i].coroutine == NULL) {
816 break;
820 g_assert(qemu_in_coroutine());
821 assert(i < MAX_NBD_REQUESTS);
823 s->requests[i].coroutine = qemu_coroutine_self();
824 s->requests[i].offset = request->from;
825 s->requests[i].receiving = false;
827 request->handle = INDEX_TO_HANDLE(s, i);
829 assert(s->ioc);
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;
840 } else if (rc >= 0) {
841 rc = -EIO;
843 qio_channel_set_cork(s->ioc, false);
844 } else {
845 rc = nbd_send_request(s->ioc, request);
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--;
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);
861 qemu_co_mutex_unlock(&s->send_mutex);
862 return rc;
865 static inline uint16_t payload_advance16(uint8_t **payload)
867 *payload += 2;
868 return lduw_be_p(*payload - 2);
871 static inline uint32_t payload_advance32(uint8_t **payload)
873 *payload += 4;
874 return ldl_be_p(*payload - 4);
877 static inline uint64_t payload_advance64(uint8_t **payload)
879 *payload += 8;
880 return ldq_be_p(*payload - 8);
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)
888 uint64_t offset;
889 uint32_t hole_size;
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;
897 offset = payload_advance64(&payload);
898 hole_size = payload_advance32(&payload);
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;
906 if (s->info.min_block &&
907 !QEMU_IS_ALIGNED(hole_size, s->info.min_block)) {
908 trace_nbd_structured_read_compliance("hole");
911 qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size);
913 return 0;
917 * nbd_parse_blockstatus_payload
918 * Based on our request, we expect only one extent in reply, for the
919 * base:allocation context.
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)
926 uint32_t context_id;
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;
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;
944 extent->length = payload_advance32(&payload);
945 extent->flags = payload_advance32(&payload);
947 if (extent->length == 0) {
948 error_setg(errp, "Protocol error: server sent status chunk with "
949 "zero length");
950 return -EINVAL;
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).
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;
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.
985 if (chunk->length > sizeof(context_id) + sizeof(*extent)) {
986 trace_nbd_parse_blockstatus_compliance("more than one extent");
988 if (extent->length > orig_length) {
989 extent->length = orig_length;
990 trace_nbd_parse_blockstatus_compliance("extent length too large");
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.
999 if (s->alloc_depth && extent->flags > 2) {
1000 extent->flags = 2;
1003 return 0;
1007 * nbd_parse_error_payload
1008 * on success @errp contains message describing nbd error reply
1010 static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
1011 uint8_t *payload, int *request_ret,
1012 Error **errp)
1014 uint32_t error;
1015 uint16_t message_size;
1017 assert(chunk->type & (1 << 15));
1019 if (chunk->length < sizeof(error) + sizeof(message_size)) {
1020 error_setg(errp,
1021 "Protocol error: invalid payload for structured error");
1022 return -EINVAL;
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;
1032 *request_ret = -error;
1033 message_size = payload_advance16(&payload);
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;
1041 /* TODO: Add a trace point to mention the server complaint */
1043 /* TODO handle ERROR_OFFSET */
1045 return 0;
1048 static int nbd_co_receive_offset_data_payload(BDRVNBDState *s,
1049 uint64_t orig_offset,
1050 QEMUIOVector *qiov, Error **errp)
1052 QEMUIOVector sub_qiov;
1053 uint64_t offset;
1054 size_t data_size;
1055 int ret;
1056 NBDStructuredReplyChunk *chunk = &s->reply.structured;
1058 assert(nbd_reply_is_structured(&s->reply));
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;
1067 if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) {
1068 return -EIO;
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;
1079 if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) {
1080 trace_nbd_structured_read_compliance("data");
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);
1088 return ret < 0 ? -EIO : 0;
1091 #define NBD_MAX_MALLOC_PAYLOAD 1000
1092 static coroutine_fn int nbd_co_receive_structured_payload(
1093 BDRVNBDState *s, void **payload, Error **errp)
1095 int ret;
1096 uint32_t len;
1098 assert(nbd_reply_is_structured(&s->reply));
1100 len = s->reply.structured.length;
1102 if (len == 0) {
1103 return 0;
1106 if (payload == NULL) {
1107 error_setg(errp, "Unexpected structured payload");
1108 return -EINVAL;
1111 if (len > NBD_MAX_MALLOC_PAYLOAD) {
1112 error_setg(errp, "Payload too large");
1113 return -EINVAL;
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;
1124 return 0;
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
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.
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)
1146 int ret;
1147 int i = HANDLE_TO_INDEX(s, handle);
1148 void *local_payload = NULL;
1149 NBDStructuredReplyChunk *chunk;
1151 if (payload) {
1152 *payload = NULL;
1154 *request_ret = 0;
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;
1164 assert(s->ioc);
1166 assert(s->reply.handle == handle);
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;
1175 *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error);
1176 if (*request_ret < 0 || !qiov) {
1177 return 0;
1180 return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov,
1181 errp) < 0 ? -EIO : 0;
1184 /* handle structured reply chunk */
1185 assert(s->info.structured_reply);
1186 chunk = &s->reply.structured;
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;
1194 if (chunk->length) {
1195 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
1196 " nonzero length");
1197 return -EINVAL;
1199 return 0;
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;
1208 return nbd_co_receive_offset_data_payload(s, s->requests[i].offset,
1209 qiov, errp);
1212 if (nbd_reply_type_is_error(chunk->type)) {
1213 payload = &local_payload;
1216 ret = nbd_co_receive_structured_payload(s, payload, errp);
1217 if (ret < 0) {
1218 return ret;
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;
1227 return 0;
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
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)
1240 int ret = nbd_co_do_receive_one_chunk(s, handle, only_structured,
1241 request_ret, qiov, payload, errp);
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;
1250 s->reply.handle = 0;
1252 if (s->connection_co && !s->wait_in_flight) {
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.
1258 aio_co_wake(s->connection_co);
1261 return ret;
1264 typedef struct NBDReplyChunkIter {
1265 int ret;
1266 int request_ret;
1267 Error *err;
1268 bool done, only_structured;
1269 } NBDReplyChunkIter;
1271 static void nbd_iter_channel_error(NBDReplyChunkIter *iter,
1272 int ret, Error **local_err)
1274 assert(local_err && *local_err);
1275 assert(ret < 0);
1277 if (!iter->ret) {
1278 iter->ret = ret;
1279 error_propagate(&iter->err, *local_err);
1280 } else {
1281 error_free(*local_err);
1284 *local_err = NULL;
1287 static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret)
1289 assert(ret < 0);
1291 if (!iter->request_ret) {
1292 iter->request_ret = ret;
1297 * NBD_FOREACH_REPLY_CHUNK
1298 * The pointer stored in @payload requires g_free() to free it.
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);)
1306 * nbd_reply_chunk_iter_receive
1307 * The pointer stored in @payload requires g_free() to free it.
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)
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;
1325 if (iter->done) {
1326 /* Previous iteration was last. */
1327 goto break_loop;
1330 if (reply == NULL) {
1331 reply = &local_reply;
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);
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;
1349 chunk = &reply->structured;
1350 iter->only_structured = true;
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;
1358 if (chunk->flags & NBD_REPLY_FLAG_DONE) {
1359 /* This iteration is last. */
1360 iter->done = true;
1363 /* Execute the loop body */
1364 return true;
1366 break_loop:
1367 s->requests[HANDLE_TO_INDEX(s, handle)].coroutine = NULL;
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);
1376 qemu_co_mutex_unlock(&s->send_mutex);
1378 return false;
1381 static int nbd_co_receive_return_code(BDRVNBDState *s, uint64_t handle,
1382 int *request_ret, Error **errp)
1384 NBDReplyChunkIter iter;
1386 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, NULL, NULL) {
1387 /* nbd_reply_chunk_iter_receive does all the work */
1390 error_propagate(errp, iter.err);
1391 *request_ret = iter.request_ret;
1392 return iter.ret;
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)
1399 NBDReplyChunkIter iter;
1400 NBDReply reply;
1401 void *payload = NULL;
1402 Error *local_err = NULL;
1404 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, s->info.structured_reply,
1405 qiov, &reply, &payload)
1407 int ret;
1408 NBDStructuredReplyChunk *chunk = &reply.structured;
1410 assert(nbd_reply_is_structured(&reply));
1412 switch (chunk->type) {
1413 case NBD_REPLY_TYPE_OFFSET_DATA:
1415 * special cased in nbd_co_receive_one_chunk, data is already
1416 * in qiov
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);
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);
1438 g_free(payload);
1439 payload = NULL;
1442 error_propagate(errp, iter.err);
1443 *request_ret = iter.request_ret;
1444 return iter.ret;
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)
1452 NBDReplyChunkIter iter;
1453 NBDReply reply;
1454 void *payload = NULL;
1455 Error *local_err = NULL;
1456 bool received = false;
1458 assert(!extent->length);
1459 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, &reply, &payload) {
1460 int ret;
1461 NBDStructuredReplyChunk *chunk = &reply.structured;
1463 assert(nbd_reply_is_structured(&reply));
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);
1472 received = true;
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);
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);
1493 g_free(payload);
1494 payload = NULL;
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);
1502 error_propagate(errp, iter.err);
1503 *request_ret = iter.request_ret;
1504 return iter.ret;
1507 static int nbd_co_request(BlockDriverState *bs, NBDRequest *request,
1508 QEMUIOVector *write_qiov)
1510 int ret, request_ret;
1511 Error *local_err = NULL;
1512 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
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);
1522 do {
1523 ret = nbd_co_send_request(bs, request, write_qiov);
1524 if (ret < 0) {
1525 continue;
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;
1539 } while (ret < 0 && nbd_client_connecting_wait(s));
1541 return ret ? ret : request_ret;
1544 static int nbd_client_co_preadv(BlockDriverState *bs, uint64_t offset,
1545 uint64_t bytes, QEMUIOVector *qiov, int flags)
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,
1556 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1557 assert(!flags);
1559 if (!bytes) {
1560 return 0;
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.
1568 if (offset >= s->info.size) {
1569 assert(bytes < BDRV_SECTOR_SIZE);
1570 qemu_iovec_memset(qiov, 0, 0, bytes);
1571 return 0;
1573 if (offset + bytes > s->info.size) {
1574 uint64_t slop = offset + bytes - s->info.size;
1576 assert(slop < BDRV_SECTOR_SIZE);
1577 qemu_iovec_memset(qiov, bytes - slop, 0, slop);
1578 request.len -= slop;
1581 do {
1582 ret = nbd_co_send_request(bs, &request, NULL);
1583 if (ret < 0) {
1584 continue;
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;
1597 } while (ret < 0 && nbd_client_connecting_wait(s));
1599 return ret ? ret : request_ret;
1602 static int nbd_client_co_pwritev(BlockDriverState *bs, uint64_t offset,
1603 uint64_t bytes, QEMUIOVector *qiov, int flags)
1605 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1606 NBDRequest request = {
1607 .type = NBD_CMD_WRITE,
1608 .from = offset,
1609 .len = bytes,
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;
1618 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1620 if (!bytes) {
1621 return 0;
1623 return nbd_co_request(bs, &request, qiov);
1626 static int nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1627 int bytes, BdrvRequestFlags flags)
1629 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1630 NBDRequest request = {
1631 .type = NBD_CMD_WRITE_ZEROES,
1632 .from = offset,
1633 .len = bytes,
1636 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1637 if (!(s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {
1638 return -ENOTSUP;
1641 if (flags & BDRV_REQ_FUA) {
1642 assert(s->info.flags & NBD_FLAG_SEND_FUA);
1643 request.flags |= NBD_CMD_FLAG_FUA;
1645 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1646 request.flags |= NBD_CMD_FLAG_NO_HOLE;
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;
1653 if (!bytes) {
1654 return 0;
1656 return nbd_co_request(bs, &request, NULL);
1659 static int nbd_client_co_flush(BlockDriverState *bs)
1661 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1662 NBDRequest request = { .type = NBD_CMD_FLUSH };
1664 if (!(s->info.flags & NBD_FLAG_SEND_FLUSH)) {
1665 return 0;
1668 request.from = 0;
1669 request.len = 0;
1671 return nbd_co_request(bs, &request, NULL);
1674 static int nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset,
1675 int bytes)
1677 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1678 NBDRequest request = {
1679 .type = NBD_CMD_TRIM,
1680 .from = offset,
1681 .len = bytes,
1684 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1685 if (!(s->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) {
1686 return 0;
1689 return nbd_co_request(bs, &request, NULL);
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)
1696 int ret, request_ret;
1697 NBDExtent extent = { 0 };
1698 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1699 Error *local_err = NULL;
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,
1709 if (!s->info.base_allocation) {
1710 *pnum = bytes;
1711 *map = offset;
1712 *file = bs;
1713 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
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.
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;
1730 if (s->info.min_block) {
1731 assert(QEMU_IS_ALIGNED(request.len, s->info.min_block));
1733 do {
1734 ret = nbd_co_send_request(bs, &request, NULL);
1735 if (ret < 0) {
1736 continue;
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;
1750 } while (ret < 0 && nbd_client_connecting_wait(s));
1752 if (ret < 0 || request_ret < 0) {
1753 return ret ? ret : request_ret;
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;
1765 static int nbd_client_reopen_prepare(BDRVReopenState *state,
1766 BlockReopenQueue *queue, Error **errp)
1768 BDRVNBDState *s = (BDRVNBDState *)state->bs->opaque;
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;
1774 return 0;
1777 static void nbd_yank(void *opaque)
1779 BlockDriverState *bs = opaque;
1780 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1782 qatomic_store_release(&s->state, NBD_CLIENT_QUIT);
1783 qio_channel_shutdown(QIO_CHANNEL(s->sioc), QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
1786 static void nbd_client_close(BlockDriverState *bs)
1788 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1789 NBDRequest request = { .type = NBD_CMD_DISC };
1791 if (s->ioc) {
1792 nbd_send_request(s->ioc, &request);
1795 nbd_teardown_connection(bs);
1798 static int nbd_establish_connection(BlockDriverState *bs,
1799 SocketAddress *saddr,
1800 Error **errp)
1802 ERRP_GUARD();
1803 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1805 s->sioc = qio_channel_socket_new();
1806 qio_channel_set_name(QIO_CHANNEL(s->sioc), "nbd-client");
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;
1815 yank_register_function(BLOCKDEV_YANK_INSTANCE(bs->node_name), nbd_yank, bs);
1816 qio_channel_set_delay(QIO_CHANNEL(s->sioc), false);
1818 return 0;
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)
1824 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1825 AioContext *aio_context = bdrv_get_aio_context(bs);
1826 int ret;
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);
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;
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;
1855 if (strcmp(s->x_dirty_bitmap, "qemu:allocation-depth") == 0) {
1856 s->alloc_depth = true;
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;
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;
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;
1876 if (!s->ioc) {
1877 s->ioc = QIO_CHANNEL(s->sioc);
1878 object_ref(OBJECT(s->ioc));
1881 trace_nbd_client_handshake_success(s->export);
1883 return 0;
1885 fail:
1887 * We have connected, but must fail for other reasons.
1888 * Send NBD_CMD_DISC as a courtesy to the server.
1891 NBDRequest request = { .type = NBD_CMD_DISC };
1893 nbd_send_request(s->ioc ?: QIO_CHANNEL(s->sioc), &request);
1895 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(bs->node_name),
1896 nbd_yank, bs);
1897 object_unref(OBJECT(s->sioc));
1898 s->sioc = NULL;
1900 return ret;
1905 * Parse nbd_open options
1908 static int nbd_parse_uri(const char *filename, QDict *options)
1910 URI *uri;
1911 const char *p;
1912 QueryParams *qp = NULL;
1913 int ret = 0;
1914 bool is_unix;
1916 uri = uri_parse(filename);
1917 if (!uri) {
1918 return -EINVAL;
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;
1933 p = uri->path ? uri->path : "";
1934 if (p[0] == '/') {
1935 p++;
1937 if (p[0]) {
1938 qdict_put_str(options, "export", p);
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;
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;
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;
1959 /* nbd[+tcp]://host[:port]/export */
1960 if (!uri->server) {
1961 ret = -EINVAL;
1962 goto out;
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);
1973 qdict_put_str(options, "server.type", "inet");
1974 qdict_put(options, "server.host", host);
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);
1981 out:
1982 if (qp) {
1983 query_params_free(qp);
1985 uri_free(uri);
1986 return ret;
1989 static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
1991 const QDictEntry *e;
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))
2000 error_setg(errp, "Option '%s' cannot be used with a file name",
2001 e->key);
2002 return true;
2006 return false;
2009 static void nbd_parse_filename(const char *filename, QDict *options,
2010 Error **errp)
2012 g_autofree char *file = NULL;
2013 char *export_name;
2014 const char *host_spec;
2015 const char *unixpath;
2017 if (nbd_has_filename_options_conflict(options, errp)) {
2018 return;
2021 if (strstr(filename, "://")) {
2022 int ret = nbd_parse_uri(filename, options);
2023 if (ret < 0) {
2024 error_setg(errp, "No valid URL specified");
2026 return;
2029 file = g_strdup(filename);
2031 export_name = strstr(file, EN_OPTSTR);
2032 if (export_name) {
2033 if (export_name[strlen(EN_OPTSTR)] == 0) {
2034 return;
2036 export_name[0] = 0; /* truncate 'file' */
2037 export_name += strlen(EN_OPTSTR);
2039 qdict_put_str(options, "export", export_name);
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;
2048 if (!*host_spec) {
2049 return;
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);
2059 if (inet_parse(addr, host_spec, errp)) {
2060 goto out_inet;
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);
2071 static bool nbd_process_legacy_socket_options(QDict *output_options,
2072 QemuOpts *legacy_opts,
2073 Error **errp)
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;
2080 if (!path && !host && !port) {
2081 return true;
2084 for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
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;
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;
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));
2111 return true;
2114 static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options,
2115 Error **errp)
2117 SocketAddress *saddr = NULL;
2118 QDict *addr = NULL;
2119 Visitor *iv = NULL;
2121 qdict_extract_subqdict(options, &addr, "server.");
2122 if (!qdict_size(addr)) {
2123 error_setg(errp, "NBD server address missing");
2124 goto done;
2127 iv = qobject_input_visitor_new_flat_confused(addr, errp);
2128 if (!iv) {
2129 goto done;
2132 if (!visit_type_SocketAddress(iv, NULL, &saddr, errp)) {
2133 goto done;
2136 done:
2137 qobject_unref(addr);
2138 visit_free(iv);
2139 return saddr;
2142 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
2144 Object *obj;
2145 QCryptoTLSCreds *creds;
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;
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;
2162 if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
2163 error_setg(errp,
2164 "Expecting TLS credentials with a client endpoint");
2165 return NULL;
2167 object_ref(obj);
2168 return creds;
2172 static QemuOptsList nbd_runtime_opts = {
2173 .name = "nbd",
2174 .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
2175 .desc = {
2177 .name = "host",
2178 .type = QEMU_OPT_STRING,
2179 .help = "TCP host to connect to",
2182 .name = "port",
2183 .type = QEMU_OPT_STRING,
2184 .help = "TCP port to connect to",
2187 .name = "path",
2188 .type = QEMU_OPT_STRING,
2189 .help = "Unix socket path to connect to",
2192 .name = "export",
2193 .type = QEMU_OPT_STRING,
2194 .help = "Name of the NBD export to open",
2197 .name = "tls-creds",
2198 .type = QEMU_OPT_STRING,
2199 .help = "ID of the TLS credentials to use",
2202 .name = "x-dirty-bitmap",
2203 .type = QEMU_OPT_STRING,
2204 .help = "experimental: expose named dirty bitmap in place of "
2205 "block status",
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",
2218 { /* end of list */ }
2222 static int nbd_process_options(BlockDriverState *bs, QDict *options,
2223 Error **errp)
2225 BDRVNBDState *s = bs->opaque;
2226 QemuOpts *opts;
2227 int ret = -EINVAL;
2229 opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
2230 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
2231 goto error;
2234 /* Translate @host, @port, and @path to a SocketAddress */
2235 if (!nbd_process_legacy_socket_options(options, opts, errp)) {
2236 goto error;
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;
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;
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;
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;
2263 s->hostname = s->saddr->u.inet.host;
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;
2272 s->reconnect_delay = qemu_opt_get_number(opts, "reconnect-delay", 0);
2274 ret = 0;
2276 error:
2277 if (ret < 0) {
2278 nbd_clear_bdrvstate(s);
2280 qemu_opts_del(opts);
2281 return ret;
2284 static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
2285 Error **errp)
2287 int ret;
2288 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2290 ret = nbd_process_options(bs, options, errp);
2291 if (ret < 0) {
2292 return ret;
2295 s->bs = bs;
2296 qemu_co_mutex_init(&s->send_mutex);
2297 qemu_co_queue_init(&s->free_sema);
2299 if (!yank_register_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name), errp)) {
2300 return -EEXIST;
2304 * establish TCP connection, return error if it fails
2305 * TODO: Configurable retry-until-timeout behaviour.
2307 if (nbd_establish_connection(bs, s->saddr, errp) < 0) {
2308 yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name));
2309 return -ECONNREFUSED;
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;
2318 /* successfully connected */
2319 s->state = NBD_CLIENT_CONNECTED;
2321 nbd_init_connect_thread(s);
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);
2327 return 0;
2330 static int nbd_co_flush(BlockDriverState *bs)
2332 return nbd_client_co_flush(bs);
2335 static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
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);
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
2353 if (!min) {
2354 min = (!QEMU_IS_ALIGNED(s->info.size, BDRV_SECTOR_SIZE) ||
2355 s->info.base_allocation) ? 1 : BDRV_SECTOR_SIZE;
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;
2363 if (s->info.opt_block &&
2364 s->info.opt_block > bs->bl.opt_transfer) {
2365 bs->bl.opt_transfer = s->info.opt_block;
2369 static void nbd_close(BlockDriverState *bs)
2371 BDRVNBDState *s = bs->opaque;
2373 nbd_client_close(bs);
2374 yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name));
2375 nbd_clear_bdrvstate(s);
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.
2383 * Preallocation mode is ignored since it does not seems useful to fail when
2384 * we never change anything.
2386 static int coroutine_fn nbd_co_truncate(BlockDriverState *bs, int64_t offset,
2387 bool exact, PreallocMode prealloc,
2388 BdrvRequestFlags flags, Error **errp)
2390 BDRVNBDState *s = bs->opaque;
2392 if (offset != s->info.size && exact) {
2393 error_setg(errp, "Cannot resize NBD nodes");
2394 return -ENOTSUP;
2397 if (offset > s->info.size) {
2398 error_setg(errp, "Cannot grow NBD nodes");
2399 return -EINVAL;
2402 return 0;
2405 static int64_t nbd_getlength(BlockDriverState *bs)
2407 BDRVNBDState *s = bs->opaque;
2409 return s->info.size;
2412 static void nbd_refresh_filename(BlockDriverState *bs)
2414 BDRVNBDState *s = bs->opaque;
2415 const char *host = NULL, *port = NULL, *path = NULL;
2416 size_t len = 0;
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;
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 */
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);
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';
2447 static char *nbd_dirname(BlockDriverState *bs, Error **errp)
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;
2457 static const char *const nbd_strong_runtime_opts[] = {
2458 "path",
2459 "host",
2460 "port",
2461 "export",
2462 "tls-creds",
2463 "server.",
2465 NULL
2468 static void nbd_cancel_in_flight(BlockDriverState *bs)
2470 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2472 reconnect_delay_timer_del(s);
2474 if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
2475 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
2476 qemu_co_queue_restart_all(&s->free_sema);
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,
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,
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,
2567 static void bdrv_nbd_init(void)
2569 bdrv_register(&bdrv_nbd);
2570 bdrv_register(&bdrv_nbd_tcp);
2571 bdrv_register(&bdrv_nbd_unix);
2574 block_init(bdrv_nbd_init);