block/nbd: bs-independent interface for nbd_co_establish_connection()
[qemu.git] / block / nbd.c
blob15b569a899fdde29e52ccf80302da43eca1c00a8
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 struct NBDConnectThread {
70 /* Initialization constants */
71 SocketAddress *saddr; /* address to connect to */
73 QemuMutex mutex;
76 * @sioc and @err represent a connection attempt. While running
77 * is true, they are only used by the connection thread, and mutex
78 * locking is not needed. Once the thread finishes,
79 * nbd_co_establish_connection then steals these pointers while
80 * under the mutex.
82 QIOChannelSocket *sioc;
83 Error *err;
85 /* All further fields are accessed only under mutex */
86 bool running; /* thread is running now */
87 bool detached; /* thread is detached and should cleanup the state */
90 * wait_co: if non-NULL, which coroutine to wake in
91 * nbd_co_establish_connection() after yield()
93 Coroutine *wait_co;
94 } NBDConnectThread;
96 typedef struct BDRVNBDState {
97 QIOChannelSocket *sioc; /* The master data channel */
98 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
99 NBDExportInfo info;
101 CoMutex send_mutex;
102 CoQueue free_sema;
103 Coroutine *connection_co;
104 Coroutine *teardown_co;
105 QemuCoSleep reconnect_sleep;
106 bool drained;
107 bool wait_drained_end;
108 int in_flight;
109 NBDClientState state;
110 bool wait_in_flight;
112 QEMUTimer *reconnect_delay_timer;
114 NBDClientRequest requests[MAX_NBD_REQUESTS];
115 NBDReply reply;
116 BlockDriverState *bs;
118 /* Connection parameters */
119 uint32_t reconnect_delay;
120 SocketAddress *saddr;
121 char *export, *tlscredsid;
122 QCryptoTLSCreds *tlscreds;
123 const char *hostname;
124 char *x_dirty_bitmap;
125 bool alloc_depth;
127 NBDConnectThread *connect_thread;
128 } BDRVNBDState;
130 static void nbd_free_connect_thread(NBDConnectThread *thr);
131 static int nbd_establish_connection(BlockDriverState *bs, SocketAddress *saddr,
132 Error **errp);
133 static coroutine_fn QIOChannelSocket *
134 nbd_co_establish_connection(NBDConnectThread *thr, Error **errp);
135 static void nbd_co_establish_connection_cancel(BlockDriverState *bs);
136 static int nbd_client_handshake(BlockDriverState *bs, Error **errp);
137 static void nbd_yank(void *opaque);
139 static void nbd_clear_bdrvstate(BlockDriverState *bs)
141 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
142 NBDConnectThread *thr = s->connect_thread;
143 bool do_free = false;
145 qemu_mutex_lock(&thr->mutex);
146 assert(!thr->detached);
147 if (thr->running) {
148 thr->detached = true;
149 } else {
150 do_free = true;
152 qemu_mutex_unlock(&thr->mutex);
154 /* the runaway thread will clean up itself */
155 if (do_free) {
156 nbd_free_connect_thread(thr);
159 yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name));
161 object_unref(OBJECT(s->tlscreds));
162 qapi_free_SocketAddress(s->saddr);
163 s->saddr = NULL;
164 g_free(s->export);
165 s->export = NULL;
166 g_free(s->tlscredsid);
167 s->tlscredsid = NULL;
168 g_free(s->x_dirty_bitmap);
169 s->x_dirty_bitmap = NULL;
172 static void nbd_channel_error(BDRVNBDState *s, int ret)
174 if (ret == -EIO) {
175 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTED) {
176 s->state = s->reconnect_delay ? NBD_CLIENT_CONNECTING_WAIT :
177 NBD_CLIENT_CONNECTING_NOWAIT;
179 } else {
180 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTED) {
181 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
183 s->state = NBD_CLIENT_QUIT;
187 static void nbd_recv_coroutines_wake_all(BDRVNBDState *s)
189 int i;
191 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
192 NBDClientRequest *req = &s->requests[i];
194 if (req->coroutine && req->receiving) {
195 aio_co_wake(req->coroutine);
200 static void reconnect_delay_timer_del(BDRVNBDState *s)
202 if (s->reconnect_delay_timer) {
203 timer_free(s->reconnect_delay_timer);
204 s->reconnect_delay_timer = NULL;
208 static void reconnect_delay_timer_cb(void *opaque)
210 BDRVNBDState *s = opaque;
212 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT) {
213 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
214 while (qemu_co_enter_next(&s->free_sema, NULL)) {
215 /* Resume all queued requests */
219 reconnect_delay_timer_del(s);
222 static void reconnect_delay_timer_init(BDRVNBDState *s, uint64_t expire_time_ns)
224 if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTING_WAIT) {
225 return;
228 assert(!s->reconnect_delay_timer);
229 s->reconnect_delay_timer = aio_timer_new(bdrv_get_aio_context(s->bs),
230 QEMU_CLOCK_REALTIME,
231 SCALE_NS,
232 reconnect_delay_timer_cb, s);
233 timer_mod(s->reconnect_delay_timer, expire_time_ns);
236 static void nbd_client_detach_aio_context(BlockDriverState *bs)
238 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
240 /* Timer is deleted in nbd_client_co_drain_begin() */
241 assert(!s->reconnect_delay_timer);
243 * If reconnect is in progress we may have no ->ioc. It will be
244 * re-instantiated in the proper aio context once the connection is
245 * reestablished.
247 if (s->ioc) {
248 qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
252 static void nbd_client_attach_aio_context_bh(void *opaque)
254 BlockDriverState *bs = opaque;
255 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
257 if (s->connection_co) {
259 * The node is still drained, so we know the coroutine has yielded in
260 * nbd_read_eof(), the only place where bs->in_flight can reach 0, or
261 * it is entered for the first time. Both places are safe for entering
262 * the coroutine.
264 qemu_aio_coroutine_enter(bs->aio_context, s->connection_co);
266 bdrv_dec_in_flight(bs);
269 static void nbd_client_attach_aio_context(BlockDriverState *bs,
270 AioContext *new_context)
272 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
275 * s->connection_co is either yielded from nbd_receive_reply or from
276 * nbd_co_reconnect_loop()
278 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTED) {
279 qio_channel_attach_aio_context(QIO_CHANNEL(s->ioc), new_context);
282 bdrv_inc_in_flight(bs);
285 * Need to wait here for the BH to run because the BH must run while the
286 * node is still drained.
288 aio_wait_bh_oneshot(new_context, nbd_client_attach_aio_context_bh, bs);
291 static void coroutine_fn nbd_client_co_drain_begin(BlockDriverState *bs)
293 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
295 s->drained = true;
296 qemu_co_sleep_wake(&s->reconnect_sleep);
298 nbd_co_establish_connection_cancel(bs);
300 reconnect_delay_timer_del(s);
302 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT) {
303 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
304 qemu_co_queue_restart_all(&s->free_sema);
308 static void coroutine_fn nbd_client_co_drain_end(BlockDriverState *bs)
310 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
312 s->drained = false;
313 if (s->wait_drained_end) {
314 s->wait_drained_end = false;
315 aio_co_wake(s->connection_co);
320 static void nbd_teardown_connection(BlockDriverState *bs)
322 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
324 if (s->ioc) {
325 /* finish any pending coroutines */
326 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
327 } else if (s->sioc) {
328 /* abort negotiation */
329 qio_channel_shutdown(QIO_CHANNEL(s->sioc), QIO_CHANNEL_SHUTDOWN_BOTH,
330 NULL);
333 s->state = NBD_CLIENT_QUIT;
334 if (s->connection_co) {
335 qemu_co_sleep_wake(&s->reconnect_sleep);
336 nbd_co_establish_connection_cancel(bs);
338 if (qemu_in_coroutine()) {
339 s->teardown_co = qemu_coroutine_self();
340 /* connection_co resumes us when it terminates */
341 qemu_coroutine_yield();
342 s->teardown_co = NULL;
343 } else {
344 BDRV_POLL_WHILE(bs, s->connection_co);
346 assert(!s->connection_co);
349 static bool nbd_client_connecting(BDRVNBDState *s)
351 NBDClientState state = qatomic_load_acquire(&s->state);
352 return state == NBD_CLIENT_CONNECTING_WAIT ||
353 state == NBD_CLIENT_CONNECTING_NOWAIT;
356 static bool nbd_client_connecting_wait(BDRVNBDState *s)
358 return qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT;
361 static void nbd_init_connect_thread(BDRVNBDState *s)
363 s->connect_thread = g_new(NBDConnectThread, 1);
365 *s->connect_thread = (NBDConnectThread) {
366 .saddr = QAPI_CLONE(SocketAddress, s->saddr),
369 qemu_mutex_init(&s->connect_thread->mutex);
372 static void nbd_free_connect_thread(NBDConnectThread *thr)
374 if (thr->sioc) {
375 qio_channel_close(QIO_CHANNEL(thr->sioc), NULL);
376 object_unref(OBJECT(thr->sioc));
378 error_free(thr->err);
379 qapi_free_SocketAddress(thr->saddr);
380 g_free(thr);
383 static void *connect_thread_func(void *opaque)
385 NBDConnectThread *thr = opaque;
386 int ret;
387 bool do_free;
389 thr->sioc = qio_channel_socket_new();
391 error_free(thr->err);
392 thr->err = NULL;
393 ret = qio_channel_socket_connect_sync(thr->sioc, thr->saddr, &thr->err);
394 if (ret < 0) {
395 object_unref(OBJECT(thr->sioc));
396 thr->sioc = NULL;
399 qio_channel_set_delay(QIO_CHANNEL(thr->sioc), false);
401 qemu_mutex_lock(&thr->mutex);
403 assert(thr->running);
404 thr->running = false;
405 if (thr->wait_co) {
406 aio_co_wake(thr->wait_co);
407 thr->wait_co = NULL;
409 do_free = thr->detached;
411 qemu_mutex_unlock(&thr->mutex);
413 if (do_free) {
414 nbd_free_connect_thread(thr);
417 return NULL;
421 * Get a new connection in context of @thr:
422 * if the thread is running, wait for completion
423 * if the thread already succeeded in the background, and user didn't get the
424 * result, just return it now
425 * otherwise the thread is not running, so start a thread and wait for
426 * completion
428 static coroutine_fn QIOChannelSocket *
429 nbd_co_establish_connection(NBDConnectThread *thr, Error **errp)
431 QIOChannelSocket *sioc = NULL;
432 QemuThread thread;
434 qemu_mutex_lock(&thr->mutex);
437 * Don't call nbd_co_establish_connection() in several coroutines in
438 * parallel. Only one call at once is supported.
440 assert(!thr->wait_co);
442 if (!thr->running) {
443 if (thr->sioc) {
444 /* Previous attempt finally succeeded in background */
445 sioc = g_steal_pointer(&thr->sioc);
446 qemu_mutex_unlock(&thr->mutex);
448 return sioc;
451 thr->running = true;
452 error_free(thr->err);
453 thr->err = NULL;
454 qemu_thread_create(&thread, "nbd-connect",
455 connect_thread_func, thr, QEMU_THREAD_DETACHED);
458 thr->wait_co = qemu_coroutine_self();
460 qemu_mutex_unlock(&thr->mutex);
463 * We are going to wait for connect-thread finish, but
464 * nbd_co_establish_connection_cancel() can interrupt.
466 qemu_coroutine_yield();
468 qemu_mutex_lock(&thr->mutex);
470 if (thr->running) {
472 * The connection attempt was canceled and the coroutine resumed
473 * before the connection thread finished its job. Report the
474 * attempt as failed, but leave the connection thread running,
475 * to reuse it for the next connection attempt.
477 error_setg(errp, "Connection attempt cancelled by other operation");
478 } else {
479 error_propagate(errp, thr->err);
480 thr->err = NULL;
481 sioc = g_steal_pointer(&thr->sioc);
484 qemu_mutex_unlock(&thr->mutex);
486 return sioc;
490 * nbd_co_establish_connection_cancel
491 * Cancel nbd_co_establish_connection asynchronously: it will finish soon, to
492 * allow drained section to begin.
494 static void nbd_co_establish_connection_cancel(BlockDriverState *bs)
496 BDRVNBDState *s = bs->opaque;
497 NBDConnectThread *thr = s->connect_thread;
498 Coroutine *wait_co;
500 qemu_mutex_lock(&thr->mutex);
502 wait_co = g_steal_pointer(&thr->wait_co);
504 qemu_mutex_unlock(&thr->mutex);
506 if (wait_co) {
507 aio_co_wake(wait_co);
511 static coroutine_fn void nbd_reconnect_attempt(BDRVNBDState *s)
513 int ret;
515 if (!nbd_client_connecting(s)) {
516 return;
519 /* Wait for completion of all in-flight requests */
521 qemu_co_mutex_lock(&s->send_mutex);
523 while (s->in_flight > 0) {
524 qemu_co_mutex_unlock(&s->send_mutex);
525 nbd_recv_coroutines_wake_all(s);
526 s->wait_in_flight = true;
527 qemu_coroutine_yield();
528 s->wait_in_flight = false;
529 qemu_co_mutex_lock(&s->send_mutex);
532 qemu_co_mutex_unlock(&s->send_mutex);
534 if (!nbd_client_connecting(s)) {
535 return;
539 * Now we are sure that nobody is accessing the channel, and no one will
540 * try until we set the state to CONNECTED.
543 /* Finalize previous connection if any */
544 if (s->ioc) {
545 qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
546 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
547 nbd_yank, s->bs);
548 object_unref(OBJECT(s->sioc));
549 s->sioc = NULL;
550 object_unref(OBJECT(s->ioc));
551 s->ioc = NULL;
554 s->sioc = nbd_co_establish_connection(s->connect_thread, NULL);
555 if (!s->sioc) {
556 ret = -ECONNREFUSED;
557 goto out;
560 yank_register_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name), nbd_yank,
561 s->bs);
563 bdrv_dec_in_flight(s->bs);
565 ret = nbd_client_handshake(s->bs, NULL);
567 if (s->drained) {
568 s->wait_drained_end = true;
569 while (s->drained) {
571 * We may be entered once from nbd_client_attach_aio_context_bh
572 * and then from nbd_client_co_drain_end. So here is a loop.
574 qemu_coroutine_yield();
577 bdrv_inc_in_flight(s->bs);
579 out:
580 if (ret >= 0) {
581 /* successfully connected */
582 s->state = NBD_CLIENT_CONNECTED;
583 qemu_co_queue_restart_all(&s->free_sema);
587 static coroutine_fn void nbd_co_reconnect_loop(BDRVNBDState *s)
589 uint64_t timeout = 1 * NANOSECONDS_PER_SECOND;
590 uint64_t max_timeout = 16 * NANOSECONDS_PER_SECOND;
592 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT) {
593 reconnect_delay_timer_init(s, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
594 s->reconnect_delay * NANOSECONDS_PER_SECOND);
597 nbd_reconnect_attempt(s);
599 while (nbd_client_connecting(s)) {
600 if (s->drained) {
601 bdrv_dec_in_flight(s->bs);
602 s->wait_drained_end = true;
603 while (s->drained) {
605 * We may be entered once from nbd_client_attach_aio_context_bh
606 * and then from nbd_client_co_drain_end. So here is a loop.
608 qemu_coroutine_yield();
610 bdrv_inc_in_flight(s->bs);
611 } else {
612 qemu_co_sleep_ns_wakeable(&s->reconnect_sleep,
613 QEMU_CLOCK_REALTIME, timeout);
614 if (s->drained) {
615 continue;
617 if (timeout < max_timeout) {
618 timeout *= 2;
622 nbd_reconnect_attempt(s);
625 reconnect_delay_timer_del(s);
628 static coroutine_fn void nbd_connection_entry(void *opaque)
630 BDRVNBDState *s = opaque;
631 uint64_t i;
632 int ret = 0;
633 Error *local_err = NULL;
635 while (qatomic_load_acquire(&s->state) != NBD_CLIENT_QUIT) {
637 * The NBD client can only really be considered idle when it has
638 * yielded from qio_channel_readv_all_eof(), waiting for data. This is
639 * the point where the additional scheduled coroutine entry happens
640 * after nbd_client_attach_aio_context().
642 * Therefore we keep an additional in_flight reference all the time and
643 * only drop it temporarily here.
646 if (nbd_client_connecting(s)) {
647 nbd_co_reconnect_loop(s);
650 if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTED) {
651 continue;
654 assert(s->reply.handle == 0);
655 ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, &local_err);
657 if (local_err) {
658 trace_nbd_read_reply_entry_fail(ret, error_get_pretty(local_err));
659 error_free(local_err);
660 local_err = NULL;
662 if (ret <= 0) {
663 nbd_channel_error(s, ret ? ret : -EIO);
664 continue;
668 * There's no need for a mutex on the receive side, because the
669 * handler acts as a synchronization point and ensures that only
670 * one coroutine is called until the reply finishes.
672 i = HANDLE_TO_INDEX(s, s->reply.handle);
673 if (i >= MAX_NBD_REQUESTS ||
674 !s->requests[i].coroutine ||
675 !s->requests[i].receiving ||
676 (nbd_reply_is_structured(&s->reply) && !s->info.structured_reply))
678 nbd_channel_error(s, -EINVAL);
679 continue;
683 * We're woken up again by the request itself. Note that there
684 * is no race between yielding and reentering connection_co. This
685 * is because:
687 * - if the request runs on the same AioContext, it is only
688 * entered after we yield
690 * - if the request runs on a different AioContext, reentering
691 * connection_co happens through a bottom half, which can only
692 * run after we yield.
694 aio_co_wake(s->requests[i].coroutine);
695 qemu_coroutine_yield();
698 qemu_co_queue_restart_all(&s->free_sema);
699 nbd_recv_coroutines_wake_all(s);
700 bdrv_dec_in_flight(s->bs);
702 s->connection_co = NULL;
703 if (s->ioc) {
704 qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
705 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
706 nbd_yank, s->bs);
707 object_unref(OBJECT(s->sioc));
708 s->sioc = NULL;
709 object_unref(OBJECT(s->ioc));
710 s->ioc = NULL;
713 if (s->teardown_co) {
714 aio_co_wake(s->teardown_co);
716 aio_wait_kick();
719 static int nbd_co_send_request(BlockDriverState *bs,
720 NBDRequest *request,
721 QEMUIOVector *qiov)
723 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
724 int rc, i = -1;
726 qemu_co_mutex_lock(&s->send_mutex);
727 while (s->in_flight == MAX_NBD_REQUESTS || nbd_client_connecting_wait(s)) {
728 qemu_co_queue_wait(&s->free_sema, &s->send_mutex);
731 if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTED) {
732 rc = -EIO;
733 goto err;
736 s->in_flight++;
738 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
739 if (s->requests[i].coroutine == NULL) {
740 break;
744 g_assert(qemu_in_coroutine());
745 assert(i < MAX_NBD_REQUESTS);
747 s->requests[i].coroutine = qemu_coroutine_self();
748 s->requests[i].offset = request->from;
749 s->requests[i].receiving = false;
751 request->handle = INDEX_TO_HANDLE(s, i);
753 assert(s->ioc);
755 if (qiov) {
756 qio_channel_set_cork(s->ioc, true);
757 rc = nbd_send_request(s->ioc, request);
758 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTED &&
759 rc >= 0) {
760 if (qio_channel_writev_all(s->ioc, qiov->iov, qiov->niov,
761 NULL) < 0) {
762 rc = -EIO;
764 } else if (rc >= 0) {
765 rc = -EIO;
767 qio_channel_set_cork(s->ioc, false);
768 } else {
769 rc = nbd_send_request(s->ioc, request);
772 err:
773 if (rc < 0) {
774 nbd_channel_error(s, rc);
775 if (i != -1) {
776 s->requests[i].coroutine = NULL;
777 s->in_flight--;
779 if (s->in_flight == 0 && s->wait_in_flight) {
780 aio_co_wake(s->connection_co);
781 } else {
782 qemu_co_queue_next(&s->free_sema);
785 qemu_co_mutex_unlock(&s->send_mutex);
786 return rc;
789 static inline uint16_t payload_advance16(uint8_t **payload)
791 *payload += 2;
792 return lduw_be_p(*payload - 2);
795 static inline uint32_t payload_advance32(uint8_t **payload)
797 *payload += 4;
798 return ldl_be_p(*payload - 4);
801 static inline uint64_t payload_advance64(uint8_t **payload)
803 *payload += 8;
804 return ldq_be_p(*payload - 8);
807 static int nbd_parse_offset_hole_payload(BDRVNBDState *s,
808 NBDStructuredReplyChunk *chunk,
809 uint8_t *payload, uint64_t orig_offset,
810 QEMUIOVector *qiov, Error **errp)
812 uint64_t offset;
813 uint32_t hole_size;
815 if (chunk->length != sizeof(offset) + sizeof(hole_size)) {
816 error_setg(errp, "Protocol error: invalid payload for "
817 "NBD_REPLY_TYPE_OFFSET_HOLE");
818 return -EINVAL;
821 offset = payload_advance64(&payload);
822 hole_size = payload_advance32(&payload);
824 if (!hole_size || offset < orig_offset || hole_size > qiov->size ||
825 offset > orig_offset + qiov->size - hole_size) {
826 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
827 " region");
828 return -EINVAL;
830 if (s->info.min_block &&
831 !QEMU_IS_ALIGNED(hole_size, s->info.min_block)) {
832 trace_nbd_structured_read_compliance("hole");
835 qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size);
837 return 0;
841 * nbd_parse_blockstatus_payload
842 * Based on our request, we expect only one extent in reply, for the
843 * base:allocation context.
845 static int nbd_parse_blockstatus_payload(BDRVNBDState *s,
846 NBDStructuredReplyChunk *chunk,
847 uint8_t *payload, uint64_t orig_length,
848 NBDExtent *extent, Error **errp)
850 uint32_t context_id;
852 /* The server succeeded, so it must have sent [at least] one extent */
853 if (chunk->length < sizeof(context_id) + sizeof(*extent)) {
854 error_setg(errp, "Protocol error: invalid payload for "
855 "NBD_REPLY_TYPE_BLOCK_STATUS");
856 return -EINVAL;
859 context_id = payload_advance32(&payload);
860 if (s->info.context_id != context_id) {
861 error_setg(errp, "Protocol error: unexpected context id %d for "
862 "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
863 "id is %d", context_id,
864 s->info.context_id);
865 return -EINVAL;
868 extent->length = payload_advance32(&payload);
869 extent->flags = payload_advance32(&payload);
871 if (extent->length == 0) {
872 error_setg(errp, "Protocol error: server sent status chunk with "
873 "zero length");
874 return -EINVAL;
878 * A server sending unaligned block status is in violation of the
879 * protocol, but as qemu-nbd 3.1 is such a server (at least for
880 * POSIX files that are not a multiple of 512 bytes, since qemu
881 * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
882 * still sees an implicit hole beyond the real EOF), it's nicer to
883 * work around the misbehaving server. If the request included
884 * more than the final unaligned block, truncate it back to an
885 * aligned result; if the request was only the final block, round
886 * up to the full block and change the status to fully-allocated
887 * (always a safe status, even if it loses information).
889 if (s->info.min_block && !QEMU_IS_ALIGNED(extent->length,
890 s->info.min_block)) {
891 trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
892 if (extent->length > s->info.min_block) {
893 extent->length = QEMU_ALIGN_DOWN(extent->length,
894 s->info.min_block);
895 } else {
896 extent->length = s->info.min_block;
897 extent->flags = 0;
902 * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
903 * sent us any more than one extent, nor should it have included
904 * status beyond our request in that extent. However, it's easy
905 * enough to ignore the server's noncompliance without killing the
906 * connection; just ignore trailing extents, and clamp things to
907 * the length of our request.
909 if (chunk->length > sizeof(context_id) + sizeof(*extent)) {
910 trace_nbd_parse_blockstatus_compliance("more than one extent");
912 if (extent->length > orig_length) {
913 extent->length = orig_length;
914 trace_nbd_parse_blockstatus_compliance("extent length too large");
918 * HACK: if we are using x-dirty-bitmaps to access
919 * qemu:allocation-depth, treat all depths > 2 the same as 2,
920 * since nbd_client_co_block_status is only expecting the low two
921 * bits to be set.
923 if (s->alloc_depth && extent->flags > 2) {
924 extent->flags = 2;
927 return 0;
931 * nbd_parse_error_payload
932 * on success @errp contains message describing nbd error reply
934 static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
935 uint8_t *payload, int *request_ret,
936 Error **errp)
938 uint32_t error;
939 uint16_t message_size;
941 assert(chunk->type & (1 << 15));
943 if (chunk->length < sizeof(error) + sizeof(message_size)) {
944 error_setg(errp,
945 "Protocol error: invalid payload for structured error");
946 return -EINVAL;
949 error = nbd_errno_to_system_errno(payload_advance32(&payload));
950 if (error == 0) {
951 error_setg(errp, "Protocol error: server sent structured error chunk "
952 "with error = 0");
953 return -EINVAL;
956 *request_ret = -error;
957 message_size = payload_advance16(&payload);
959 if (message_size > chunk->length - sizeof(error) - sizeof(message_size)) {
960 error_setg(errp, "Protocol error: server sent structured error chunk "
961 "with incorrect message size");
962 return -EINVAL;
965 /* TODO: Add a trace point to mention the server complaint */
967 /* TODO handle ERROR_OFFSET */
969 return 0;
972 static int nbd_co_receive_offset_data_payload(BDRVNBDState *s,
973 uint64_t orig_offset,
974 QEMUIOVector *qiov, Error **errp)
976 QEMUIOVector sub_qiov;
977 uint64_t offset;
978 size_t data_size;
979 int ret;
980 NBDStructuredReplyChunk *chunk = &s->reply.structured;
982 assert(nbd_reply_is_structured(&s->reply));
984 /* The NBD spec requires at least one byte of payload */
985 if (chunk->length <= sizeof(offset)) {
986 error_setg(errp, "Protocol error: invalid payload for "
987 "NBD_REPLY_TYPE_OFFSET_DATA");
988 return -EINVAL;
991 if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) {
992 return -EIO;
995 data_size = chunk->length - sizeof(offset);
996 assert(data_size);
997 if (offset < orig_offset || data_size > qiov->size ||
998 offset > orig_offset + qiov->size - data_size) {
999 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
1000 " region");
1001 return -EINVAL;
1003 if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) {
1004 trace_nbd_structured_read_compliance("data");
1007 qemu_iovec_init(&sub_qiov, qiov->niov);
1008 qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size);
1009 ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);
1010 qemu_iovec_destroy(&sub_qiov);
1012 return ret < 0 ? -EIO : 0;
1015 #define NBD_MAX_MALLOC_PAYLOAD 1000
1016 static coroutine_fn int nbd_co_receive_structured_payload(
1017 BDRVNBDState *s, void **payload, Error **errp)
1019 int ret;
1020 uint32_t len;
1022 assert(nbd_reply_is_structured(&s->reply));
1024 len = s->reply.structured.length;
1026 if (len == 0) {
1027 return 0;
1030 if (payload == NULL) {
1031 error_setg(errp, "Unexpected structured payload");
1032 return -EINVAL;
1035 if (len > NBD_MAX_MALLOC_PAYLOAD) {
1036 error_setg(errp, "Payload too large");
1037 return -EINVAL;
1040 *payload = g_new(char, len);
1041 ret = nbd_read(s->ioc, *payload, len, "structured payload", errp);
1042 if (ret < 0) {
1043 g_free(*payload);
1044 *payload = NULL;
1045 return ret;
1048 return 0;
1052 * nbd_co_do_receive_one_chunk
1053 * for simple reply:
1054 * set request_ret to received reply error
1055 * if qiov is not NULL: read payload to @qiov
1056 * for structured reply chunk:
1057 * if error chunk: read payload, set @request_ret, do not set @payload
1058 * else if offset_data chunk: read payload data to @qiov, do not set @payload
1059 * else: read payload to @payload
1061 * If function fails, @errp contains corresponding error message, and the
1062 * connection with the server is suspect. If it returns 0, then the
1063 * transaction succeeded (although @request_ret may be a negative errno
1064 * corresponding to the server's error reply), and errp is unchanged.
1066 static coroutine_fn int nbd_co_do_receive_one_chunk(
1067 BDRVNBDState *s, uint64_t handle, bool only_structured,
1068 int *request_ret, QEMUIOVector *qiov, void **payload, Error **errp)
1070 int ret;
1071 int i = HANDLE_TO_INDEX(s, handle);
1072 void *local_payload = NULL;
1073 NBDStructuredReplyChunk *chunk;
1075 if (payload) {
1076 *payload = NULL;
1078 *request_ret = 0;
1080 /* Wait until we're woken up by nbd_connection_entry. */
1081 s->requests[i].receiving = true;
1082 qemu_coroutine_yield();
1083 s->requests[i].receiving = false;
1084 if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTED) {
1085 error_setg(errp, "Connection closed");
1086 return -EIO;
1088 assert(s->ioc);
1090 assert(s->reply.handle == handle);
1092 if (nbd_reply_is_simple(&s->reply)) {
1093 if (only_structured) {
1094 error_setg(errp, "Protocol error: simple reply when structured "
1095 "reply chunk was expected");
1096 return -EINVAL;
1099 *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error);
1100 if (*request_ret < 0 || !qiov) {
1101 return 0;
1104 return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov,
1105 errp) < 0 ? -EIO : 0;
1108 /* handle structured reply chunk */
1109 assert(s->info.structured_reply);
1110 chunk = &s->reply.structured;
1112 if (chunk->type == NBD_REPLY_TYPE_NONE) {
1113 if (!(chunk->flags & NBD_REPLY_FLAG_DONE)) {
1114 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
1115 " NBD_REPLY_FLAG_DONE flag set");
1116 return -EINVAL;
1118 if (chunk->length) {
1119 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
1120 " nonzero length");
1121 return -EINVAL;
1123 return 0;
1126 if (chunk->type == NBD_REPLY_TYPE_OFFSET_DATA) {
1127 if (!qiov) {
1128 error_setg(errp, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
1129 return -EINVAL;
1132 return nbd_co_receive_offset_data_payload(s, s->requests[i].offset,
1133 qiov, errp);
1136 if (nbd_reply_type_is_error(chunk->type)) {
1137 payload = &local_payload;
1140 ret = nbd_co_receive_structured_payload(s, payload, errp);
1141 if (ret < 0) {
1142 return ret;
1145 if (nbd_reply_type_is_error(chunk->type)) {
1146 ret = nbd_parse_error_payload(chunk, local_payload, request_ret, errp);
1147 g_free(local_payload);
1148 return ret;
1151 return 0;
1155 * nbd_co_receive_one_chunk
1156 * Read reply, wake up connection_co and set s->quit if needed.
1157 * Return value is a fatal error code or normal nbd reply error code
1159 static coroutine_fn int nbd_co_receive_one_chunk(
1160 BDRVNBDState *s, uint64_t handle, bool only_structured,
1161 int *request_ret, QEMUIOVector *qiov, NBDReply *reply, void **payload,
1162 Error **errp)
1164 int ret = nbd_co_do_receive_one_chunk(s, handle, only_structured,
1165 request_ret, qiov, payload, errp);
1167 if (ret < 0) {
1168 memset(reply, 0, sizeof(*reply));
1169 nbd_channel_error(s, ret);
1170 } else {
1171 /* For assert at loop start in nbd_connection_entry */
1172 *reply = s->reply;
1174 s->reply.handle = 0;
1176 if (s->connection_co && !s->wait_in_flight) {
1178 * We must check s->wait_in_flight, because we may entered by
1179 * nbd_recv_coroutines_wake_all(), in this case we should not
1180 * wake connection_co here, it will woken by last request.
1182 aio_co_wake(s->connection_co);
1185 return ret;
1188 typedef struct NBDReplyChunkIter {
1189 int ret;
1190 int request_ret;
1191 Error *err;
1192 bool done, only_structured;
1193 } NBDReplyChunkIter;
1195 static void nbd_iter_channel_error(NBDReplyChunkIter *iter,
1196 int ret, Error **local_err)
1198 assert(local_err && *local_err);
1199 assert(ret < 0);
1201 if (!iter->ret) {
1202 iter->ret = ret;
1203 error_propagate(&iter->err, *local_err);
1204 } else {
1205 error_free(*local_err);
1208 *local_err = NULL;
1211 static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret)
1213 assert(ret < 0);
1215 if (!iter->request_ret) {
1216 iter->request_ret = ret;
1221 * NBD_FOREACH_REPLY_CHUNK
1222 * The pointer stored in @payload requires g_free() to free it.
1224 #define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
1225 qiov, reply, payload) \
1226 for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
1227 nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
1230 * nbd_reply_chunk_iter_receive
1231 * The pointer stored in @payload requires g_free() to free it.
1233 static bool nbd_reply_chunk_iter_receive(BDRVNBDState *s,
1234 NBDReplyChunkIter *iter,
1235 uint64_t handle,
1236 QEMUIOVector *qiov, NBDReply *reply,
1237 void **payload)
1239 int ret, request_ret;
1240 NBDReply local_reply;
1241 NBDStructuredReplyChunk *chunk;
1242 Error *local_err = NULL;
1243 if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTED) {
1244 error_setg(&local_err, "Connection closed");
1245 nbd_iter_channel_error(iter, -EIO, &local_err);
1246 goto break_loop;
1249 if (iter->done) {
1250 /* Previous iteration was last. */
1251 goto break_loop;
1254 if (reply == NULL) {
1255 reply = &local_reply;
1258 ret = nbd_co_receive_one_chunk(s, handle, iter->only_structured,
1259 &request_ret, qiov, reply, payload,
1260 &local_err);
1261 if (ret < 0) {
1262 nbd_iter_channel_error(iter, ret, &local_err);
1263 } else if (request_ret < 0) {
1264 nbd_iter_request_error(iter, request_ret);
1267 /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
1268 if (nbd_reply_is_simple(reply) ||
1269 qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTED) {
1270 goto break_loop;
1273 chunk = &reply->structured;
1274 iter->only_structured = true;
1276 if (chunk->type == NBD_REPLY_TYPE_NONE) {
1277 /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
1278 assert(chunk->flags & NBD_REPLY_FLAG_DONE);
1279 goto break_loop;
1282 if (chunk->flags & NBD_REPLY_FLAG_DONE) {
1283 /* This iteration is last. */
1284 iter->done = true;
1287 /* Execute the loop body */
1288 return true;
1290 break_loop:
1291 s->requests[HANDLE_TO_INDEX(s, handle)].coroutine = NULL;
1293 qemu_co_mutex_lock(&s->send_mutex);
1294 s->in_flight--;
1295 if (s->in_flight == 0 && s->wait_in_flight) {
1296 aio_co_wake(s->connection_co);
1297 } else {
1298 qemu_co_queue_next(&s->free_sema);
1300 qemu_co_mutex_unlock(&s->send_mutex);
1302 return false;
1305 static int nbd_co_receive_return_code(BDRVNBDState *s, uint64_t handle,
1306 int *request_ret, Error **errp)
1308 NBDReplyChunkIter iter;
1310 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, NULL, NULL) {
1311 /* nbd_reply_chunk_iter_receive does all the work */
1314 error_propagate(errp, iter.err);
1315 *request_ret = iter.request_ret;
1316 return iter.ret;
1319 static int nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t handle,
1320 uint64_t offset, QEMUIOVector *qiov,
1321 int *request_ret, Error **errp)
1323 NBDReplyChunkIter iter;
1324 NBDReply reply;
1325 void *payload = NULL;
1326 Error *local_err = NULL;
1328 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, s->info.structured_reply,
1329 qiov, &reply, &payload)
1331 int ret;
1332 NBDStructuredReplyChunk *chunk = &reply.structured;
1334 assert(nbd_reply_is_structured(&reply));
1336 switch (chunk->type) {
1337 case NBD_REPLY_TYPE_OFFSET_DATA:
1339 * special cased in nbd_co_receive_one_chunk, data is already
1340 * in qiov
1342 break;
1343 case NBD_REPLY_TYPE_OFFSET_HOLE:
1344 ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload,
1345 offset, qiov, &local_err);
1346 if (ret < 0) {
1347 nbd_channel_error(s, ret);
1348 nbd_iter_channel_error(&iter, ret, &local_err);
1350 break;
1351 default:
1352 if (!nbd_reply_type_is_error(chunk->type)) {
1353 /* not allowed reply type */
1354 nbd_channel_error(s, -EINVAL);
1355 error_setg(&local_err,
1356 "Unexpected reply type: %d (%s) for CMD_READ",
1357 chunk->type, nbd_reply_type_lookup(chunk->type));
1358 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1362 g_free(payload);
1363 payload = NULL;
1366 error_propagate(errp, iter.err);
1367 *request_ret = iter.request_ret;
1368 return iter.ret;
1371 static int nbd_co_receive_blockstatus_reply(BDRVNBDState *s,
1372 uint64_t handle, uint64_t length,
1373 NBDExtent *extent,
1374 int *request_ret, Error **errp)
1376 NBDReplyChunkIter iter;
1377 NBDReply reply;
1378 void *payload = NULL;
1379 Error *local_err = NULL;
1380 bool received = false;
1382 assert(!extent->length);
1383 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, &reply, &payload) {
1384 int ret;
1385 NBDStructuredReplyChunk *chunk = &reply.structured;
1387 assert(nbd_reply_is_structured(&reply));
1389 switch (chunk->type) {
1390 case NBD_REPLY_TYPE_BLOCK_STATUS:
1391 if (received) {
1392 nbd_channel_error(s, -EINVAL);
1393 error_setg(&local_err, "Several BLOCK_STATUS chunks in reply");
1394 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1396 received = true;
1398 ret = nbd_parse_blockstatus_payload(s, &reply.structured,
1399 payload, length, extent,
1400 &local_err);
1401 if (ret < 0) {
1402 nbd_channel_error(s, ret);
1403 nbd_iter_channel_error(&iter, ret, &local_err);
1405 break;
1406 default:
1407 if (!nbd_reply_type_is_error(chunk->type)) {
1408 nbd_channel_error(s, -EINVAL);
1409 error_setg(&local_err,
1410 "Unexpected reply type: %d (%s) "
1411 "for CMD_BLOCK_STATUS",
1412 chunk->type, nbd_reply_type_lookup(chunk->type));
1413 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1417 g_free(payload);
1418 payload = NULL;
1421 if (!extent->length && !iter.request_ret) {
1422 error_setg(&local_err, "Server did not reply with any status extents");
1423 nbd_iter_channel_error(&iter, -EIO, &local_err);
1426 error_propagate(errp, iter.err);
1427 *request_ret = iter.request_ret;
1428 return iter.ret;
1431 static int nbd_co_request(BlockDriverState *bs, NBDRequest *request,
1432 QEMUIOVector *write_qiov)
1434 int ret, request_ret;
1435 Error *local_err = NULL;
1436 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1438 assert(request->type != NBD_CMD_READ);
1439 if (write_qiov) {
1440 assert(request->type == NBD_CMD_WRITE);
1441 assert(request->len == iov_size(write_qiov->iov, write_qiov->niov));
1442 } else {
1443 assert(request->type != NBD_CMD_WRITE);
1446 do {
1447 ret = nbd_co_send_request(bs, request, write_qiov);
1448 if (ret < 0) {
1449 continue;
1452 ret = nbd_co_receive_return_code(s, request->handle,
1453 &request_ret, &local_err);
1454 if (local_err) {
1455 trace_nbd_co_request_fail(request->from, request->len,
1456 request->handle, request->flags,
1457 request->type,
1458 nbd_cmd_lookup(request->type),
1459 ret, error_get_pretty(local_err));
1460 error_free(local_err);
1461 local_err = NULL;
1463 } while (ret < 0 && nbd_client_connecting_wait(s));
1465 return ret ? ret : request_ret;
1468 static int nbd_client_co_preadv(BlockDriverState *bs, uint64_t offset,
1469 uint64_t bytes, QEMUIOVector *qiov, int flags)
1471 int ret, request_ret;
1472 Error *local_err = NULL;
1473 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1474 NBDRequest request = {
1475 .type = NBD_CMD_READ,
1476 .from = offset,
1477 .len = bytes,
1480 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1481 assert(!flags);
1483 if (!bytes) {
1484 return 0;
1487 * Work around the fact that the block layer doesn't do
1488 * byte-accurate sizing yet - if the read exceeds the server's
1489 * advertised size because the block layer rounded size up, then
1490 * truncate the request to the server and tail-pad with zero.
1492 if (offset >= s->info.size) {
1493 assert(bytes < BDRV_SECTOR_SIZE);
1494 qemu_iovec_memset(qiov, 0, 0, bytes);
1495 return 0;
1497 if (offset + bytes > s->info.size) {
1498 uint64_t slop = offset + bytes - s->info.size;
1500 assert(slop < BDRV_SECTOR_SIZE);
1501 qemu_iovec_memset(qiov, bytes - slop, 0, slop);
1502 request.len -= slop;
1505 do {
1506 ret = nbd_co_send_request(bs, &request, NULL);
1507 if (ret < 0) {
1508 continue;
1511 ret = nbd_co_receive_cmdread_reply(s, request.handle, offset, qiov,
1512 &request_ret, &local_err);
1513 if (local_err) {
1514 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1515 request.flags, request.type,
1516 nbd_cmd_lookup(request.type),
1517 ret, error_get_pretty(local_err));
1518 error_free(local_err);
1519 local_err = NULL;
1521 } while (ret < 0 && nbd_client_connecting_wait(s));
1523 return ret ? ret : request_ret;
1526 static int nbd_client_co_pwritev(BlockDriverState *bs, uint64_t offset,
1527 uint64_t bytes, QEMUIOVector *qiov, int flags)
1529 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1530 NBDRequest request = {
1531 .type = NBD_CMD_WRITE,
1532 .from = offset,
1533 .len = bytes,
1536 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1537 if (flags & BDRV_REQ_FUA) {
1538 assert(s->info.flags & NBD_FLAG_SEND_FUA);
1539 request.flags |= NBD_CMD_FLAG_FUA;
1542 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1544 if (!bytes) {
1545 return 0;
1547 return nbd_co_request(bs, &request, qiov);
1550 static int nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1551 int bytes, BdrvRequestFlags flags)
1553 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1554 NBDRequest request = {
1555 .type = NBD_CMD_WRITE_ZEROES,
1556 .from = offset,
1557 .len = bytes,
1560 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1561 if (!(s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {
1562 return -ENOTSUP;
1565 if (flags & BDRV_REQ_FUA) {
1566 assert(s->info.flags & NBD_FLAG_SEND_FUA);
1567 request.flags |= NBD_CMD_FLAG_FUA;
1569 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1570 request.flags |= NBD_CMD_FLAG_NO_HOLE;
1572 if (flags & BDRV_REQ_NO_FALLBACK) {
1573 assert(s->info.flags & NBD_FLAG_SEND_FAST_ZERO);
1574 request.flags |= NBD_CMD_FLAG_FAST_ZERO;
1577 if (!bytes) {
1578 return 0;
1580 return nbd_co_request(bs, &request, NULL);
1583 static int nbd_client_co_flush(BlockDriverState *bs)
1585 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1586 NBDRequest request = { .type = NBD_CMD_FLUSH };
1588 if (!(s->info.flags & NBD_FLAG_SEND_FLUSH)) {
1589 return 0;
1592 request.from = 0;
1593 request.len = 0;
1595 return nbd_co_request(bs, &request, NULL);
1598 static int nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset,
1599 int bytes)
1601 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1602 NBDRequest request = {
1603 .type = NBD_CMD_TRIM,
1604 .from = offset,
1605 .len = bytes,
1608 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1609 if (!(s->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) {
1610 return 0;
1613 return nbd_co_request(bs, &request, NULL);
1616 static int coroutine_fn nbd_client_co_block_status(
1617 BlockDriverState *bs, bool want_zero, int64_t offset, int64_t bytes,
1618 int64_t *pnum, int64_t *map, BlockDriverState **file)
1620 int ret, request_ret;
1621 NBDExtent extent = { 0 };
1622 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1623 Error *local_err = NULL;
1625 NBDRequest request = {
1626 .type = NBD_CMD_BLOCK_STATUS,
1627 .from = offset,
1628 .len = MIN(QEMU_ALIGN_DOWN(INT_MAX, bs->bl.request_alignment),
1629 MIN(bytes, s->info.size - offset)),
1630 .flags = NBD_CMD_FLAG_REQ_ONE,
1633 if (!s->info.base_allocation) {
1634 *pnum = bytes;
1635 *map = offset;
1636 *file = bs;
1637 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
1641 * Work around the fact that the block layer doesn't do
1642 * byte-accurate sizing yet - if the status request exceeds the
1643 * server's advertised size because the block layer rounded size
1644 * up, we truncated the request to the server (above), or are
1645 * called on just the hole.
1647 if (offset >= s->info.size) {
1648 *pnum = bytes;
1649 assert(bytes < BDRV_SECTOR_SIZE);
1650 /* Intentionally don't report offset_valid for the hole */
1651 return BDRV_BLOCK_ZERO;
1654 if (s->info.min_block) {
1655 assert(QEMU_IS_ALIGNED(request.len, s->info.min_block));
1657 do {
1658 ret = nbd_co_send_request(bs, &request, NULL);
1659 if (ret < 0) {
1660 continue;
1663 ret = nbd_co_receive_blockstatus_reply(s, request.handle, bytes,
1664 &extent, &request_ret,
1665 &local_err);
1666 if (local_err) {
1667 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1668 request.flags, request.type,
1669 nbd_cmd_lookup(request.type),
1670 ret, error_get_pretty(local_err));
1671 error_free(local_err);
1672 local_err = NULL;
1674 } while (ret < 0 && nbd_client_connecting_wait(s));
1676 if (ret < 0 || request_ret < 0) {
1677 return ret ? ret : request_ret;
1680 assert(extent.length);
1681 *pnum = extent.length;
1682 *map = offset;
1683 *file = bs;
1684 return (extent.flags & NBD_STATE_HOLE ? 0 : BDRV_BLOCK_DATA) |
1685 (extent.flags & NBD_STATE_ZERO ? BDRV_BLOCK_ZERO : 0) |
1686 BDRV_BLOCK_OFFSET_VALID;
1689 static int nbd_client_reopen_prepare(BDRVReopenState *state,
1690 BlockReopenQueue *queue, Error **errp)
1692 BDRVNBDState *s = (BDRVNBDState *)state->bs->opaque;
1694 if ((state->flags & BDRV_O_RDWR) && (s->info.flags & NBD_FLAG_READ_ONLY)) {
1695 error_setg(errp, "Can't reopen read-only NBD mount as read/write");
1696 return -EACCES;
1698 return 0;
1701 static void nbd_yank(void *opaque)
1703 BlockDriverState *bs = opaque;
1704 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1706 qatomic_store_release(&s->state, NBD_CLIENT_QUIT);
1707 qio_channel_shutdown(QIO_CHANNEL(s->sioc), QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
1710 static void nbd_client_close(BlockDriverState *bs)
1712 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1713 NBDRequest request = { .type = NBD_CMD_DISC };
1715 if (s->ioc) {
1716 nbd_send_request(s->ioc, &request);
1719 nbd_teardown_connection(bs);
1722 static int nbd_establish_connection(BlockDriverState *bs,
1723 SocketAddress *saddr,
1724 Error **errp)
1726 ERRP_GUARD();
1727 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1729 s->sioc = qio_channel_socket_new();
1730 qio_channel_set_name(QIO_CHANNEL(s->sioc), "nbd-client");
1732 qio_channel_socket_connect_sync(s->sioc, saddr, errp);
1733 if (*errp) {
1734 object_unref(OBJECT(s->sioc));
1735 s->sioc = NULL;
1736 return -1;
1739 yank_register_function(BLOCKDEV_YANK_INSTANCE(bs->node_name), nbd_yank, bs);
1740 qio_channel_set_delay(QIO_CHANNEL(s->sioc), false);
1742 return 0;
1745 /* nbd_client_handshake takes ownership on s->sioc. On failure it's unref'ed. */
1746 static int nbd_client_handshake(BlockDriverState *bs, Error **errp)
1748 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1749 AioContext *aio_context = bdrv_get_aio_context(bs);
1750 int ret;
1752 trace_nbd_client_handshake(s->export);
1753 qio_channel_set_blocking(QIO_CHANNEL(s->sioc), false, NULL);
1754 qio_channel_attach_aio_context(QIO_CHANNEL(s->sioc), aio_context);
1756 s->info.request_sizes = true;
1757 s->info.structured_reply = true;
1758 s->info.base_allocation = true;
1759 s->info.x_dirty_bitmap = g_strdup(s->x_dirty_bitmap);
1760 s->info.name = g_strdup(s->export ?: "");
1761 ret = nbd_receive_negotiate(aio_context, QIO_CHANNEL(s->sioc), s->tlscreds,
1762 s->hostname, &s->ioc, &s->info, errp);
1763 g_free(s->info.x_dirty_bitmap);
1764 g_free(s->info.name);
1765 if (ret < 0) {
1766 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(bs->node_name),
1767 nbd_yank, bs);
1768 object_unref(OBJECT(s->sioc));
1769 s->sioc = NULL;
1770 return ret;
1772 if (s->x_dirty_bitmap) {
1773 if (!s->info.base_allocation) {
1774 error_setg(errp, "requested x-dirty-bitmap %s not found",
1775 s->x_dirty_bitmap);
1776 ret = -EINVAL;
1777 goto fail;
1779 if (strcmp(s->x_dirty_bitmap, "qemu:allocation-depth") == 0) {
1780 s->alloc_depth = true;
1783 if (s->info.flags & NBD_FLAG_READ_ONLY) {
1784 ret = bdrv_apply_auto_read_only(bs, "NBD export is read-only", errp);
1785 if (ret < 0) {
1786 goto fail;
1789 if (s->info.flags & NBD_FLAG_SEND_FUA) {
1790 bs->supported_write_flags = BDRV_REQ_FUA;
1791 bs->supported_zero_flags |= BDRV_REQ_FUA;
1793 if (s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES) {
1794 bs->supported_zero_flags |= BDRV_REQ_MAY_UNMAP;
1795 if (s->info.flags & NBD_FLAG_SEND_FAST_ZERO) {
1796 bs->supported_zero_flags |= BDRV_REQ_NO_FALLBACK;
1800 if (!s->ioc) {
1801 s->ioc = QIO_CHANNEL(s->sioc);
1802 object_ref(OBJECT(s->ioc));
1805 trace_nbd_client_handshake_success(s->export);
1807 return 0;
1809 fail:
1811 * We have connected, but must fail for other reasons.
1812 * Send NBD_CMD_DISC as a courtesy to the server.
1815 NBDRequest request = { .type = NBD_CMD_DISC };
1817 nbd_send_request(s->ioc ?: QIO_CHANNEL(s->sioc), &request);
1819 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(bs->node_name),
1820 nbd_yank, bs);
1821 object_unref(OBJECT(s->sioc));
1822 s->sioc = NULL;
1823 object_unref(OBJECT(s->ioc));
1824 s->ioc = NULL;
1826 return ret;
1831 * Parse nbd_open options
1834 static int nbd_parse_uri(const char *filename, QDict *options)
1836 URI *uri;
1837 const char *p;
1838 QueryParams *qp = NULL;
1839 int ret = 0;
1840 bool is_unix;
1842 uri = uri_parse(filename);
1843 if (!uri) {
1844 return -EINVAL;
1847 /* transport */
1848 if (!g_strcmp0(uri->scheme, "nbd")) {
1849 is_unix = false;
1850 } else if (!g_strcmp0(uri->scheme, "nbd+tcp")) {
1851 is_unix = false;
1852 } else if (!g_strcmp0(uri->scheme, "nbd+unix")) {
1853 is_unix = true;
1854 } else {
1855 ret = -EINVAL;
1856 goto out;
1859 p = uri->path ? uri->path : "";
1860 if (p[0] == '/') {
1861 p++;
1863 if (p[0]) {
1864 qdict_put_str(options, "export", p);
1867 qp = query_params_parse(uri->query);
1868 if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
1869 ret = -EINVAL;
1870 goto out;
1873 if (is_unix) {
1874 /* nbd+unix:///export?socket=path */
1875 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
1876 ret = -EINVAL;
1877 goto out;
1879 qdict_put_str(options, "server.type", "unix");
1880 qdict_put_str(options, "server.path", qp->p[0].value);
1881 } else {
1882 QString *host;
1883 char *port_str;
1885 /* nbd[+tcp]://host[:port]/export */
1886 if (!uri->server) {
1887 ret = -EINVAL;
1888 goto out;
1891 /* strip braces from literal IPv6 address */
1892 if (uri->server[0] == '[') {
1893 host = qstring_from_substr(uri->server, 1,
1894 strlen(uri->server) - 1);
1895 } else {
1896 host = qstring_from_str(uri->server);
1899 qdict_put_str(options, "server.type", "inet");
1900 qdict_put(options, "server.host", host);
1902 port_str = g_strdup_printf("%d", uri->port ?: NBD_DEFAULT_PORT);
1903 qdict_put_str(options, "server.port", port_str);
1904 g_free(port_str);
1907 out:
1908 if (qp) {
1909 query_params_free(qp);
1911 uri_free(uri);
1912 return ret;
1915 static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
1917 const QDictEntry *e;
1919 for (e = qdict_first(options); e; e = qdict_next(options, e)) {
1920 if (!strcmp(e->key, "host") ||
1921 !strcmp(e->key, "port") ||
1922 !strcmp(e->key, "path") ||
1923 !strcmp(e->key, "export") ||
1924 strstart(e->key, "server.", NULL))
1926 error_setg(errp, "Option '%s' cannot be used with a file name",
1927 e->key);
1928 return true;
1932 return false;
1935 static void nbd_parse_filename(const char *filename, QDict *options,
1936 Error **errp)
1938 g_autofree char *file = NULL;
1939 char *export_name;
1940 const char *host_spec;
1941 const char *unixpath;
1943 if (nbd_has_filename_options_conflict(options, errp)) {
1944 return;
1947 if (strstr(filename, "://")) {
1948 int ret = nbd_parse_uri(filename, options);
1949 if (ret < 0) {
1950 error_setg(errp, "No valid URL specified");
1952 return;
1955 file = g_strdup(filename);
1957 export_name = strstr(file, EN_OPTSTR);
1958 if (export_name) {
1959 if (export_name[strlen(EN_OPTSTR)] == 0) {
1960 return;
1962 export_name[0] = 0; /* truncate 'file' */
1963 export_name += strlen(EN_OPTSTR);
1965 qdict_put_str(options, "export", export_name);
1968 /* extract the host_spec - fail if it's not nbd:... */
1969 if (!strstart(file, "nbd:", &host_spec)) {
1970 error_setg(errp, "File name string for NBD must start with 'nbd:'");
1971 return;
1974 if (!*host_spec) {
1975 return;
1978 /* are we a UNIX or TCP socket? */
1979 if (strstart(host_spec, "unix:", &unixpath)) {
1980 qdict_put_str(options, "server.type", "unix");
1981 qdict_put_str(options, "server.path", unixpath);
1982 } else {
1983 InetSocketAddress *addr = g_new(InetSocketAddress, 1);
1985 if (inet_parse(addr, host_spec, errp)) {
1986 goto out_inet;
1989 qdict_put_str(options, "server.type", "inet");
1990 qdict_put_str(options, "server.host", addr->host);
1991 qdict_put_str(options, "server.port", addr->port);
1992 out_inet:
1993 qapi_free_InetSocketAddress(addr);
1997 static bool nbd_process_legacy_socket_options(QDict *output_options,
1998 QemuOpts *legacy_opts,
1999 Error **errp)
2001 const char *path = qemu_opt_get(legacy_opts, "path");
2002 const char *host = qemu_opt_get(legacy_opts, "host");
2003 const char *port = qemu_opt_get(legacy_opts, "port");
2004 const QDictEntry *e;
2006 if (!path && !host && !port) {
2007 return true;
2010 for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
2012 if (strstart(e->key, "server.", NULL)) {
2013 error_setg(errp, "Cannot use 'server' and path/host/port at the "
2014 "same time");
2015 return false;
2019 if (path && host) {
2020 error_setg(errp, "path and host may not be used at the same time");
2021 return false;
2022 } else if (path) {
2023 if (port) {
2024 error_setg(errp, "port may not be used without host");
2025 return false;
2028 qdict_put_str(output_options, "server.type", "unix");
2029 qdict_put_str(output_options, "server.path", path);
2030 } else if (host) {
2031 qdict_put_str(output_options, "server.type", "inet");
2032 qdict_put_str(output_options, "server.host", host);
2033 qdict_put_str(output_options, "server.port",
2034 port ?: stringify(NBD_DEFAULT_PORT));
2037 return true;
2040 static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options,
2041 Error **errp)
2043 SocketAddress *saddr = NULL;
2044 QDict *addr = NULL;
2045 Visitor *iv = NULL;
2047 qdict_extract_subqdict(options, &addr, "server.");
2048 if (!qdict_size(addr)) {
2049 error_setg(errp, "NBD server address missing");
2050 goto done;
2053 iv = qobject_input_visitor_new_flat_confused(addr, errp);
2054 if (!iv) {
2055 goto done;
2058 if (!visit_type_SocketAddress(iv, NULL, &saddr, errp)) {
2059 goto done;
2062 if (socket_address_parse_named_fd(saddr, errp) < 0) {
2063 qapi_free_SocketAddress(saddr);
2064 saddr = NULL;
2065 goto done;
2068 done:
2069 qobject_unref(addr);
2070 visit_free(iv);
2071 return saddr;
2074 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
2076 Object *obj;
2077 QCryptoTLSCreds *creds;
2079 obj = object_resolve_path_component(
2080 object_get_objects_root(), id);
2081 if (!obj) {
2082 error_setg(errp, "No TLS credentials with id '%s'",
2083 id);
2084 return NULL;
2086 creds = (QCryptoTLSCreds *)
2087 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
2088 if (!creds) {
2089 error_setg(errp, "Object with id '%s' is not TLS credentials",
2090 id);
2091 return NULL;
2094 if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
2095 error_setg(errp,
2096 "Expecting TLS credentials with a client endpoint");
2097 return NULL;
2099 object_ref(obj);
2100 return creds;
2104 static QemuOptsList nbd_runtime_opts = {
2105 .name = "nbd",
2106 .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
2107 .desc = {
2109 .name = "host",
2110 .type = QEMU_OPT_STRING,
2111 .help = "TCP host to connect to",
2114 .name = "port",
2115 .type = QEMU_OPT_STRING,
2116 .help = "TCP port to connect to",
2119 .name = "path",
2120 .type = QEMU_OPT_STRING,
2121 .help = "Unix socket path to connect to",
2124 .name = "export",
2125 .type = QEMU_OPT_STRING,
2126 .help = "Name of the NBD export to open",
2129 .name = "tls-creds",
2130 .type = QEMU_OPT_STRING,
2131 .help = "ID of the TLS credentials to use",
2134 .name = "x-dirty-bitmap",
2135 .type = QEMU_OPT_STRING,
2136 .help = "experimental: expose named dirty bitmap in place of "
2137 "block status",
2140 .name = "reconnect-delay",
2141 .type = QEMU_OPT_NUMBER,
2142 .help = "On an unexpected disconnect, the nbd client tries to "
2143 "connect again until succeeding or encountering a serious "
2144 "error. During the first @reconnect-delay seconds, all "
2145 "requests are paused and will be rerun on a successful "
2146 "reconnect. After that time, any delayed requests and all "
2147 "future requests before a successful reconnect will "
2148 "immediately fail. Default 0",
2150 { /* end of list */ }
2154 static int nbd_process_options(BlockDriverState *bs, QDict *options,
2155 Error **errp)
2157 BDRVNBDState *s = bs->opaque;
2158 QemuOpts *opts;
2159 int ret = -EINVAL;
2161 opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
2162 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
2163 goto error;
2166 /* Translate @host, @port, and @path to a SocketAddress */
2167 if (!nbd_process_legacy_socket_options(options, opts, errp)) {
2168 goto error;
2171 /* Pop the config into our state object. Exit if invalid. */
2172 s->saddr = nbd_config(s, options, errp);
2173 if (!s->saddr) {
2174 goto error;
2177 s->export = g_strdup(qemu_opt_get(opts, "export"));
2178 if (s->export && strlen(s->export) > NBD_MAX_STRING_SIZE) {
2179 error_setg(errp, "export name too long to send to server");
2180 goto error;
2183 s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
2184 if (s->tlscredsid) {
2185 s->tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
2186 if (!s->tlscreds) {
2187 goto error;
2190 /* TODO SOCKET_ADDRESS_KIND_FD where fd has AF_INET or AF_INET6 */
2191 if (s->saddr->type != SOCKET_ADDRESS_TYPE_INET) {
2192 error_setg(errp, "TLS only supported over IP sockets");
2193 goto error;
2195 s->hostname = s->saddr->u.inet.host;
2198 s->x_dirty_bitmap = g_strdup(qemu_opt_get(opts, "x-dirty-bitmap"));
2199 if (s->x_dirty_bitmap && strlen(s->x_dirty_bitmap) > NBD_MAX_STRING_SIZE) {
2200 error_setg(errp, "x-dirty-bitmap query too long to send to server");
2201 goto error;
2204 s->reconnect_delay = qemu_opt_get_number(opts, "reconnect-delay", 0);
2206 ret = 0;
2208 error:
2209 qemu_opts_del(opts);
2210 return ret;
2213 static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
2214 Error **errp)
2216 int ret;
2217 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2219 s->bs = bs;
2220 qemu_co_mutex_init(&s->send_mutex);
2221 qemu_co_queue_init(&s->free_sema);
2223 if (!yank_register_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name), errp)) {
2224 return -EEXIST;
2227 ret = nbd_process_options(bs, options, errp);
2228 if (ret < 0) {
2229 goto fail;
2232 nbd_init_connect_thread(s);
2235 * establish TCP connection, return error if it fails
2236 * TODO: Configurable retry-until-timeout behaviour.
2238 if (nbd_establish_connection(bs, s->saddr, errp) < 0) {
2239 ret = -ECONNREFUSED;
2240 goto fail;
2243 ret = nbd_client_handshake(bs, errp);
2244 if (ret < 0) {
2245 goto fail;
2247 /* successfully connected */
2248 s->state = NBD_CLIENT_CONNECTED;
2250 s->connection_co = qemu_coroutine_create(nbd_connection_entry, s);
2251 bdrv_inc_in_flight(bs);
2252 aio_co_schedule(bdrv_get_aio_context(bs), s->connection_co);
2254 return 0;
2256 fail:
2257 nbd_clear_bdrvstate(bs);
2258 return ret;
2261 static int nbd_co_flush(BlockDriverState *bs)
2263 return nbd_client_co_flush(bs);
2266 static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
2268 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2269 uint32_t min = s->info.min_block;
2270 uint32_t max = MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE, s->info.max_block);
2273 * If the server did not advertise an alignment:
2274 * - a size that is not sector-aligned implies that an alignment
2275 * of 1 can be used to access those tail bytes
2276 * - advertisement of block status requires an alignment of 1, so
2277 * that we don't violate block layer constraints that block
2278 * status is always aligned (as we can't control whether the
2279 * server will report sub-sector extents, such as a hole at EOF
2280 * on an unaligned POSIX file)
2281 * - otherwise, assume the server is so old that we are safer avoiding
2282 * sub-sector requests
2284 if (!min) {
2285 min = (!QEMU_IS_ALIGNED(s->info.size, BDRV_SECTOR_SIZE) ||
2286 s->info.base_allocation) ? 1 : BDRV_SECTOR_SIZE;
2289 bs->bl.request_alignment = min;
2290 bs->bl.max_pdiscard = QEMU_ALIGN_DOWN(INT_MAX, min);
2291 bs->bl.max_pwrite_zeroes = max;
2292 bs->bl.max_transfer = max;
2294 if (s->info.opt_block &&
2295 s->info.opt_block > bs->bl.opt_transfer) {
2296 bs->bl.opt_transfer = s->info.opt_block;
2300 static void nbd_close(BlockDriverState *bs)
2302 nbd_client_close(bs);
2303 nbd_clear_bdrvstate(bs);
2307 * NBD cannot truncate, but if the caller asks to truncate to the same size, or
2308 * to a smaller size with exact=false, there is no reason to fail the
2309 * operation.
2311 * Preallocation mode is ignored since it does not seems useful to fail when
2312 * we never change anything.
2314 static int coroutine_fn nbd_co_truncate(BlockDriverState *bs, int64_t offset,
2315 bool exact, PreallocMode prealloc,
2316 BdrvRequestFlags flags, Error **errp)
2318 BDRVNBDState *s = bs->opaque;
2320 if (offset != s->info.size && exact) {
2321 error_setg(errp, "Cannot resize NBD nodes");
2322 return -ENOTSUP;
2325 if (offset > s->info.size) {
2326 error_setg(errp, "Cannot grow NBD nodes");
2327 return -EINVAL;
2330 return 0;
2333 static int64_t nbd_getlength(BlockDriverState *bs)
2335 BDRVNBDState *s = bs->opaque;
2337 return s->info.size;
2340 static void nbd_refresh_filename(BlockDriverState *bs)
2342 BDRVNBDState *s = bs->opaque;
2343 const char *host = NULL, *port = NULL, *path = NULL;
2344 size_t len = 0;
2346 if (s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
2347 const InetSocketAddress *inet = &s->saddr->u.inet;
2348 if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) {
2349 host = inet->host;
2350 port = inet->port;
2352 } else if (s->saddr->type == SOCKET_ADDRESS_TYPE_UNIX) {
2353 path = s->saddr->u.q_unix.path;
2354 } /* else can't represent as pseudo-filename */
2356 if (path && s->export) {
2357 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2358 "nbd+unix:///%s?socket=%s", s->export, path);
2359 } else if (path && !s->export) {
2360 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2361 "nbd+unix://?socket=%s", path);
2362 } else if (host && s->export) {
2363 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2364 "nbd://%s:%s/%s", host, port, s->export);
2365 } else if (host && !s->export) {
2366 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2367 "nbd://%s:%s", host, port);
2369 if (len >= sizeof(bs->exact_filename)) {
2370 /* Name is too long to represent exactly, so leave it empty. */
2371 bs->exact_filename[0] = '\0';
2375 static char *nbd_dirname(BlockDriverState *bs, Error **errp)
2377 /* The generic bdrv_dirname() implementation is able to work out some
2378 * directory name for NBD nodes, but that would be wrong. So far there is no
2379 * specification for how "export paths" would work, so NBD does not have
2380 * directory names. */
2381 error_setg(errp, "Cannot generate a base directory for NBD nodes");
2382 return NULL;
2385 static const char *const nbd_strong_runtime_opts[] = {
2386 "path",
2387 "host",
2388 "port",
2389 "export",
2390 "tls-creds",
2391 "server.",
2393 NULL
2396 static void nbd_cancel_in_flight(BlockDriverState *bs)
2398 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2400 reconnect_delay_timer_del(s);
2402 if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
2403 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
2404 qemu_co_queue_restart_all(&s->free_sema);
2408 static BlockDriver bdrv_nbd = {
2409 .format_name = "nbd",
2410 .protocol_name = "nbd",
2411 .instance_size = sizeof(BDRVNBDState),
2412 .bdrv_parse_filename = nbd_parse_filename,
2413 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2414 .create_opts = &bdrv_create_opts_simple,
2415 .bdrv_file_open = nbd_open,
2416 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2417 .bdrv_co_preadv = nbd_client_co_preadv,
2418 .bdrv_co_pwritev = nbd_client_co_pwritev,
2419 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2420 .bdrv_close = nbd_close,
2421 .bdrv_co_flush_to_os = nbd_co_flush,
2422 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2423 .bdrv_refresh_limits = nbd_refresh_limits,
2424 .bdrv_co_truncate = nbd_co_truncate,
2425 .bdrv_getlength = nbd_getlength,
2426 .bdrv_detach_aio_context = nbd_client_detach_aio_context,
2427 .bdrv_attach_aio_context = nbd_client_attach_aio_context,
2428 .bdrv_co_drain_begin = nbd_client_co_drain_begin,
2429 .bdrv_co_drain_end = nbd_client_co_drain_end,
2430 .bdrv_refresh_filename = nbd_refresh_filename,
2431 .bdrv_co_block_status = nbd_client_co_block_status,
2432 .bdrv_dirname = nbd_dirname,
2433 .strong_runtime_opts = nbd_strong_runtime_opts,
2434 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2437 static BlockDriver bdrv_nbd_tcp = {
2438 .format_name = "nbd",
2439 .protocol_name = "nbd+tcp",
2440 .instance_size = sizeof(BDRVNBDState),
2441 .bdrv_parse_filename = nbd_parse_filename,
2442 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2443 .create_opts = &bdrv_create_opts_simple,
2444 .bdrv_file_open = nbd_open,
2445 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2446 .bdrv_co_preadv = nbd_client_co_preadv,
2447 .bdrv_co_pwritev = nbd_client_co_pwritev,
2448 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2449 .bdrv_close = nbd_close,
2450 .bdrv_co_flush_to_os = nbd_co_flush,
2451 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2452 .bdrv_refresh_limits = nbd_refresh_limits,
2453 .bdrv_co_truncate = nbd_co_truncate,
2454 .bdrv_getlength = nbd_getlength,
2455 .bdrv_detach_aio_context = nbd_client_detach_aio_context,
2456 .bdrv_attach_aio_context = nbd_client_attach_aio_context,
2457 .bdrv_co_drain_begin = nbd_client_co_drain_begin,
2458 .bdrv_co_drain_end = nbd_client_co_drain_end,
2459 .bdrv_refresh_filename = nbd_refresh_filename,
2460 .bdrv_co_block_status = nbd_client_co_block_status,
2461 .bdrv_dirname = nbd_dirname,
2462 .strong_runtime_opts = nbd_strong_runtime_opts,
2463 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2466 static BlockDriver bdrv_nbd_unix = {
2467 .format_name = "nbd",
2468 .protocol_name = "nbd+unix",
2469 .instance_size = sizeof(BDRVNBDState),
2470 .bdrv_parse_filename = nbd_parse_filename,
2471 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2472 .create_opts = &bdrv_create_opts_simple,
2473 .bdrv_file_open = nbd_open,
2474 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2475 .bdrv_co_preadv = nbd_client_co_preadv,
2476 .bdrv_co_pwritev = nbd_client_co_pwritev,
2477 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2478 .bdrv_close = nbd_close,
2479 .bdrv_co_flush_to_os = nbd_co_flush,
2480 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2481 .bdrv_refresh_limits = nbd_refresh_limits,
2482 .bdrv_co_truncate = nbd_co_truncate,
2483 .bdrv_getlength = nbd_getlength,
2484 .bdrv_detach_aio_context = nbd_client_detach_aio_context,
2485 .bdrv_attach_aio_context = nbd_client_attach_aio_context,
2486 .bdrv_co_drain_begin = nbd_client_co_drain_begin,
2487 .bdrv_co_drain_end = nbd_client_co_drain_end,
2488 .bdrv_refresh_filename = nbd_refresh_filename,
2489 .bdrv_co_block_status = nbd_client_co_block_status,
2490 .bdrv_dirname = nbd_dirname,
2491 .strong_runtime_opts = nbd_strong_runtime_opts,
2492 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2495 static void bdrv_nbd_init(void)
2497 bdrv_register(&bdrv_nbd);
2498 bdrv_register(&bdrv_nbd_tcp);
2499 bdrv_register(&bdrv_nbd_unix);
2502 block_init(bdrv_nbd_init);