virtiofsd: Add mount ID to the lo_inode key
[qemu/ar7.git] / block / nbd.c
blob42536702b6f9ca996c8adbf8c5feb6b89111f621
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"
39 #include "qapi/qapi-visit-sockets.h"
40 #include "qapi/qmp/qstring.h"
41 #include "qapi/clone-visitor.h"
43 #include "block/qdict.h"
44 #include "block/nbd.h"
45 #include "block/block_int.h"
47 #define EN_OPTSTR ":exportname="
48 #define MAX_NBD_REQUESTS 16
50 #define HANDLE_TO_INDEX(bs, handle) ((handle) ^ (uint64_t)(intptr_t)(bs))
51 #define INDEX_TO_HANDLE(bs, index) ((index) ^ (uint64_t)(intptr_t)(bs))
53 typedef struct {
54 Coroutine *coroutine;
55 uint64_t offset; /* original offset of the request */
56 bool receiving; /* waiting for connection_co? */
57 } NBDClientRequest;
59 typedef enum NBDClientState {
60 NBD_CLIENT_CONNECTING_WAIT,
61 NBD_CLIENT_CONNECTING_NOWAIT,
62 NBD_CLIENT_CONNECTED,
63 NBD_CLIENT_QUIT
64 } NBDClientState;
66 typedef enum NBDConnectThreadState {
67 /* No thread, no pending results */
68 CONNECT_THREAD_NONE,
70 /* Thread is running, no results for now */
71 CONNECT_THREAD_RUNNING,
74 * Thread is running, but requestor exited. Thread should close
75 * the new socket and free the connect state on exit.
77 CONNECT_THREAD_RUNNING_DETACHED,
79 /* Thread finished, results are stored in a state */
80 CONNECT_THREAD_FAIL,
81 CONNECT_THREAD_SUCCESS
82 } NBDConnectThreadState;
84 typedef struct NBDConnectThread {
85 /* Initialization constants */
86 SocketAddress *saddr; /* address to connect to */
88 * Bottom half to schedule on completion. Scheduled only if bh_ctx is not
89 * NULL
91 QEMUBHFunc *bh_func;
92 void *bh_opaque;
95 * Result of last attempt. Valid in FAIL and SUCCESS states.
96 * If you want to steal error, don't forget to set pointer to NULL.
98 QIOChannelSocket *sioc;
99 Error *err;
101 /* state and bh_ctx are protected by mutex */
102 QemuMutex mutex;
103 NBDConnectThreadState state; /* current state of the thread */
104 AioContext *bh_ctx; /* where to schedule bh (NULL means don't schedule) */
105 } NBDConnectThread;
107 typedef struct BDRVNBDState {
108 QIOChannelSocket *sioc; /* The master data channel */
109 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
110 NBDExportInfo info;
112 CoMutex send_mutex;
113 CoQueue free_sema;
114 Coroutine *connection_co;
115 Coroutine *teardown_co;
116 QemuCoSleepState *connection_co_sleep_ns_state;
117 bool drained;
118 bool wait_drained_end;
119 int in_flight;
120 NBDClientState state;
121 int connect_status;
122 Error *connect_err;
123 bool wait_in_flight;
125 QEMUTimer *reconnect_delay_timer;
127 NBDClientRequest requests[MAX_NBD_REQUESTS];
128 NBDReply reply;
129 BlockDriverState *bs;
131 /* Connection parameters */
132 uint32_t reconnect_delay;
133 SocketAddress *saddr;
134 char *export, *tlscredsid;
135 QCryptoTLSCreds *tlscreds;
136 const char *hostname;
137 char *x_dirty_bitmap;
138 bool alloc_depth;
140 bool wait_connect;
141 NBDConnectThread *connect_thread;
142 } BDRVNBDState;
144 static QIOChannelSocket *nbd_establish_connection(SocketAddress *saddr,
145 Error **errp);
146 static QIOChannelSocket *nbd_co_establish_connection(BlockDriverState *bs,
147 Error **errp);
148 static void nbd_co_establish_connection_cancel(BlockDriverState *bs,
149 bool detach);
150 static int nbd_client_handshake(BlockDriverState *bs, QIOChannelSocket *sioc,
151 Error **errp);
153 static void nbd_clear_bdrvstate(BDRVNBDState *s)
155 object_unref(OBJECT(s->tlscreds));
156 qapi_free_SocketAddress(s->saddr);
157 s->saddr = NULL;
158 g_free(s->export);
159 s->export = NULL;
160 g_free(s->tlscredsid);
161 s->tlscredsid = NULL;
162 g_free(s->x_dirty_bitmap);
163 s->x_dirty_bitmap = NULL;
166 static void nbd_channel_error(BDRVNBDState *s, int ret)
168 if (ret == -EIO) {
169 if (s->state == NBD_CLIENT_CONNECTED) {
170 s->state = s->reconnect_delay ? NBD_CLIENT_CONNECTING_WAIT :
171 NBD_CLIENT_CONNECTING_NOWAIT;
173 } else {
174 if (s->state == NBD_CLIENT_CONNECTED) {
175 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
177 s->state = NBD_CLIENT_QUIT;
181 static void nbd_recv_coroutines_wake_all(BDRVNBDState *s)
183 int i;
185 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
186 NBDClientRequest *req = &s->requests[i];
188 if (req->coroutine && req->receiving) {
189 aio_co_wake(req->coroutine);
194 static void reconnect_delay_timer_del(BDRVNBDState *s)
196 if (s->reconnect_delay_timer) {
197 timer_del(s->reconnect_delay_timer);
198 timer_free(s->reconnect_delay_timer);
199 s->reconnect_delay_timer = NULL;
203 static void reconnect_delay_timer_cb(void *opaque)
205 BDRVNBDState *s = opaque;
207 if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
208 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
209 while (qemu_co_enter_next(&s->free_sema, NULL)) {
210 /* Resume all queued requests */
214 reconnect_delay_timer_del(s);
217 static void reconnect_delay_timer_init(BDRVNBDState *s, uint64_t expire_time_ns)
219 if (s->state != NBD_CLIENT_CONNECTING_WAIT) {
220 return;
223 assert(!s->reconnect_delay_timer);
224 s->reconnect_delay_timer = aio_timer_new(bdrv_get_aio_context(s->bs),
225 QEMU_CLOCK_REALTIME,
226 SCALE_NS,
227 reconnect_delay_timer_cb, s);
228 timer_mod(s->reconnect_delay_timer, expire_time_ns);
231 static void nbd_client_detach_aio_context(BlockDriverState *bs)
233 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
235 /* Timer is deleted in nbd_client_co_drain_begin() */
236 assert(!s->reconnect_delay_timer);
237 qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
240 static void nbd_client_attach_aio_context_bh(void *opaque)
242 BlockDriverState *bs = opaque;
243 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
246 * The node is still drained, so we know the coroutine has yielded in
247 * nbd_read_eof(), the only place where bs->in_flight can reach 0, or it is
248 * entered for the first time. Both places are safe for entering the
249 * coroutine.
251 qemu_aio_coroutine_enter(bs->aio_context, s->connection_co);
252 bdrv_dec_in_flight(bs);
255 static void nbd_client_attach_aio_context(BlockDriverState *bs,
256 AioContext *new_context)
258 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
261 * s->connection_co is either yielded from nbd_receive_reply or from
262 * nbd_co_reconnect_loop()
264 if (s->state == NBD_CLIENT_CONNECTED) {
265 qio_channel_attach_aio_context(QIO_CHANNEL(s->ioc), new_context);
268 bdrv_inc_in_flight(bs);
271 * Need to wait here for the BH to run because the BH must run while the
272 * node is still drained.
274 aio_wait_bh_oneshot(new_context, nbd_client_attach_aio_context_bh, bs);
277 static void coroutine_fn nbd_client_co_drain_begin(BlockDriverState *bs)
279 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
281 s->drained = true;
282 if (s->connection_co_sleep_ns_state) {
283 qemu_co_sleep_wake(s->connection_co_sleep_ns_state);
286 nbd_co_establish_connection_cancel(bs, false);
288 reconnect_delay_timer_del(s);
290 if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
291 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
292 qemu_co_queue_restart_all(&s->free_sema);
296 static void coroutine_fn nbd_client_co_drain_end(BlockDriverState *bs)
298 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
300 s->drained = false;
301 if (s->wait_drained_end) {
302 s->wait_drained_end = false;
303 aio_co_wake(s->connection_co);
308 static void nbd_teardown_connection(BlockDriverState *bs)
310 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
312 if (s->ioc) {
313 /* finish any pending coroutines */
314 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
315 } else if (s->sioc) {
316 /* abort negotiation */
317 qio_channel_shutdown(QIO_CHANNEL(s->sioc), QIO_CHANNEL_SHUTDOWN_BOTH,
318 NULL);
321 s->state = NBD_CLIENT_QUIT;
322 if (s->connection_co) {
323 if (s->connection_co_sleep_ns_state) {
324 qemu_co_sleep_wake(s->connection_co_sleep_ns_state);
326 nbd_co_establish_connection_cancel(bs, true);
328 if (qemu_in_coroutine()) {
329 s->teardown_co = qemu_coroutine_self();
330 /* connection_co resumes us when it terminates */
331 qemu_coroutine_yield();
332 s->teardown_co = NULL;
333 } else {
334 BDRV_POLL_WHILE(bs, s->connection_co);
336 assert(!s->connection_co);
339 static bool nbd_client_connecting(BDRVNBDState *s)
341 return s->state == NBD_CLIENT_CONNECTING_WAIT ||
342 s->state == NBD_CLIENT_CONNECTING_NOWAIT;
345 static bool nbd_client_connecting_wait(BDRVNBDState *s)
347 return s->state == NBD_CLIENT_CONNECTING_WAIT;
350 static void connect_bh(void *opaque)
352 BDRVNBDState *state = opaque;
354 assert(state->wait_connect);
355 state->wait_connect = false;
356 aio_co_wake(state->connection_co);
359 static void nbd_init_connect_thread(BDRVNBDState *s)
361 s->connect_thread = g_new(NBDConnectThread, 1);
363 *s->connect_thread = (NBDConnectThread) {
364 .saddr = QAPI_CLONE(SocketAddress, s->saddr),
365 .state = CONNECT_THREAD_NONE,
366 .bh_func = connect_bh,
367 .bh_opaque = s,
370 qemu_mutex_init(&s->connect_thread->mutex);
373 static void nbd_free_connect_thread(NBDConnectThread *thr)
375 if (thr->sioc) {
376 qio_channel_close(QIO_CHANNEL(thr->sioc), NULL);
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 = false;
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 qemu_mutex_lock(&thr->mutex);
401 switch (thr->state) {
402 case CONNECT_THREAD_RUNNING:
403 thr->state = ret < 0 ? CONNECT_THREAD_FAIL : CONNECT_THREAD_SUCCESS;
404 if (thr->bh_ctx) {
405 aio_bh_schedule_oneshot(thr->bh_ctx, thr->bh_func, thr->bh_opaque);
407 /* play safe, don't reuse bh_ctx on further connection attempts */
408 thr->bh_ctx = NULL;
410 break;
411 case CONNECT_THREAD_RUNNING_DETACHED:
412 do_free = true;
413 break;
414 default:
415 abort();
418 qemu_mutex_unlock(&thr->mutex);
420 if (do_free) {
421 nbd_free_connect_thread(thr);
424 return NULL;
427 static QIOChannelSocket *coroutine_fn
428 nbd_co_establish_connection(BlockDriverState *bs, Error **errp)
430 QemuThread thread;
431 BDRVNBDState *s = bs->opaque;
432 QIOChannelSocket *res;
433 NBDConnectThread *thr = s->connect_thread;
435 qemu_mutex_lock(&thr->mutex);
437 switch (thr->state) {
438 case CONNECT_THREAD_FAIL:
439 case CONNECT_THREAD_NONE:
440 error_free(thr->err);
441 thr->err = NULL;
442 thr->state = CONNECT_THREAD_RUNNING;
443 qemu_thread_create(&thread, "nbd-connect",
444 connect_thread_func, thr, QEMU_THREAD_DETACHED);
445 break;
446 case CONNECT_THREAD_SUCCESS:
447 /* Previous attempt finally succeeded in background */
448 thr->state = CONNECT_THREAD_NONE;
449 res = thr->sioc;
450 thr->sioc = NULL;
451 qemu_mutex_unlock(&thr->mutex);
452 return res;
453 case CONNECT_THREAD_RUNNING:
454 /* Already running, will wait */
455 break;
456 default:
457 abort();
460 thr->bh_ctx = qemu_get_current_aio_context();
462 qemu_mutex_unlock(&thr->mutex);
466 * We are going to wait for connect-thread finish, but
467 * nbd_client_co_drain_begin() can interrupt.
469 * Note that wait_connect variable is not visible for connect-thread. It
470 * doesn't need mutex protection, it used only inside home aio context of
471 * bs.
473 s->wait_connect = true;
474 qemu_coroutine_yield();
476 qemu_mutex_lock(&thr->mutex);
478 switch (thr->state) {
479 case CONNECT_THREAD_SUCCESS:
480 case CONNECT_THREAD_FAIL:
481 thr->state = CONNECT_THREAD_NONE;
482 error_propagate(errp, thr->err);
483 thr->err = NULL;
484 res = thr->sioc;
485 thr->sioc = NULL;
486 break;
487 case CONNECT_THREAD_RUNNING:
488 case CONNECT_THREAD_RUNNING_DETACHED:
490 * Obviously, drained section wants to start. Report the attempt as
491 * failed. Still connect thread is executing in background, and its
492 * result may be used for next connection attempt.
494 res = NULL;
495 error_setg(errp, "Connection attempt cancelled by other operation");
496 break;
498 case CONNECT_THREAD_NONE:
500 * Impossible. We've seen this thread running. So it should be
501 * running or at least give some results.
503 abort();
505 default:
506 abort();
509 qemu_mutex_unlock(&thr->mutex);
511 return res;
515 * nbd_co_establish_connection_cancel
516 * Cancel nbd_co_establish_connection asynchronously: it will finish soon, to
517 * allow drained section to begin.
519 * If detach is true, also cleanup the state (or if thread is running, move it
520 * to CONNECT_THREAD_RUNNING_DETACHED state). s->connect_thread becomes NULL if
521 * detach is true.
523 static void nbd_co_establish_connection_cancel(BlockDriverState *bs,
524 bool detach)
526 BDRVNBDState *s = bs->opaque;
527 NBDConnectThread *thr = s->connect_thread;
528 bool wake = false;
529 bool do_free = false;
531 qemu_mutex_lock(&thr->mutex);
533 if (thr->state == CONNECT_THREAD_RUNNING) {
534 /* We can cancel only in running state, when bh is not yet scheduled */
535 thr->bh_ctx = NULL;
536 if (s->wait_connect) {
537 s->wait_connect = false;
538 wake = true;
540 if (detach) {
541 thr->state = CONNECT_THREAD_RUNNING_DETACHED;
542 s->connect_thread = NULL;
544 } else if (detach) {
545 do_free = true;
548 qemu_mutex_unlock(&thr->mutex);
550 if (do_free) {
551 nbd_free_connect_thread(thr);
552 s->connect_thread = NULL;
555 if (wake) {
556 aio_co_wake(s->connection_co);
560 static coroutine_fn void nbd_reconnect_attempt(BDRVNBDState *s)
562 int ret;
563 Error *local_err = NULL;
564 QIOChannelSocket *sioc;
566 if (!nbd_client_connecting(s)) {
567 return;
570 /* Wait for completion of all in-flight requests */
572 qemu_co_mutex_lock(&s->send_mutex);
574 while (s->in_flight > 0) {
575 qemu_co_mutex_unlock(&s->send_mutex);
576 nbd_recv_coroutines_wake_all(s);
577 s->wait_in_flight = true;
578 qemu_coroutine_yield();
579 s->wait_in_flight = false;
580 qemu_co_mutex_lock(&s->send_mutex);
583 qemu_co_mutex_unlock(&s->send_mutex);
585 if (!nbd_client_connecting(s)) {
586 return;
590 * Now we are sure that nobody is accessing the channel, and no one will
591 * try until we set the state to CONNECTED.
594 /* Finalize previous connection if any */
595 if (s->ioc) {
596 qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
597 object_unref(OBJECT(s->sioc));
598 s->sioc = NULL;
599 object_unref(OBJECT(s->ioc));
600 s->ioc = NULL;
603 sioc = nbd_co_establish_connection(s->bs, &local_err);
604 if (!sioc) {
605 ret = -ECONNREFUSED;
606 goto out;
609 bdrv_dec_in_flight(s->bs);
611 ret = nbd_client_handshake(s->bs, sioc, &local_err);
613 if (s->drained) {
614 s->wait_drained_end = true;
615 while (s->drained) {
617 * We may be entered once from nbd_client_attach_aio_context_bh
618 * and then from nbd_client_co_drain_end. So here is a loop.
620 qemu_coroutine_yield();
623 bdrv_inc_in_flight(s->bs);
625 out:
626 s->connect_status = ret;
627 error_free(s->connect_err);
628 s->connect_err = NULL;
629 error_propagate(&s->connect_err, local_err);
631 if (ret >= 0) {
632 /* successfully connected */
633 s->state = NBD_CLIENT_CONNECTED;
634 qemu_co_queue_restart_all(&s->free_sema);
638 static coroutine_fn void nbd_co_reconnect_loop(BDRVNBDState *s)
640 uint64_t timeout = 1 * NANOSECONDS_PER_SECOND;
641 uint64_t max_timeout = 16 * NANOSECONDS_PER_SECOND;
643 if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
644 reconnect_delay_timer_init(s, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
645 s->reconnect_delay * NANOSECONDS_PER_SECOND);
648 nbd_reconnect_attempt(s);
650 while (nbd_client_connecting(s)) {
651 if (s->drained) {
652 bdrv_dec_in_flight(s->bs);
653 s->wait_drained_end = true;
654 while (s->drained) {
656 * We may be entered once from nbd_client_attach_aio_context_bh
657 * and then from nbd_client_co_drain_end. So here is a loop.
659 qemu_coroutine_yield();
661 bdrv_inc_in_flight(s->bs);
662 } else {
663 qemu_co_sleep_ns_wakeable(QEMU_CLOCK_REALTIME, timeout,
664 &s->connection_co_sleep_ns_state);
665 if (s->drained) {
666 continue;
668 if (timeout < max_timeout) {
669 timeout *= 2;
673 nbd_reconnect_attempt(s);
676 reconnect_delay_timer_del(s);
679 static coroutine_fn void nbd_connection_entry(void *opaque)
681 BDRVNBDState *s = opaque;
682 uint64_t i;
683 int ret = 0;
684 Error *local_err = NULL;
686 while (s->state != NBD_CLIENT_QUIT) {
688 * The NBD client can only really be considered idle when it has
689 * yielded from qio_channel_readv_all_eof(), waiting for data. This is
690 * the point where the additional scheduled coroutine entry happens
691 * after nbd_client_attach_aio_context().
693 * Therefore we keep an additional in_flight reference all the time and
694 * only drop it temporarily here.
697 if (nbd_client_connecting(s)) {
698 nbd_co_reconnect_loop(s);
701 if (s->state != NBD_CLIENT_CONNECTED) {
702 continue;
705 assert(s->reply.handle == 0);
706 ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, &local_err);
708 if (local_err) {
709 trace_nbd_read_reply_entry_fail(ret, error_get_pretty(local_err));
710 error_free(local_err);
711 local_err = NULL;
713 if (ret <= 0) {
714 nbd_channel_error(s, ret ? ret : -EIO);
715 continue;
719 * There's no need for a mutex on the receive side, because the
720 * handler acts as a synchronization point and ensures that only
721 * one coroutine is called until the reply finishes.
723 i = HANDLE_TO_INDEX(s, s->reply.handle);
724 if (i >= MAX_NBD_REQUESTS ||
725 !s->requests[i].coroutine ||
726 !s->requests[i].receiving ||
727 (nbd_reply_is_structured(&s->reply) && !s->info.structured_reply))
729 nbd_channel_error(s, -EINVAL);
730 continue;
734 * We're woken up again by the request itself. Note that there
735 * is no race between yielding and reentering connection_co. This
736 * is because:
738 * - if the request runs on the same AioContext, it is only
739 * entered after we yield
741 * - if the request runs on a different AioContext, reentering
742 * connection_co happens through a bottom half, which can only
743 * run after we yield.
745 aio_co_wake(s->requests[i].coroutine);
746 qemu_coroutine_yield();
749 qemu_co_queue_restart_all(&s->free_sema);
750 nbd_recv_coroutines_wake_all(s);
751 bdrv_dec_in_flight(s->bs);
753 s->connection_co = NULL;
754 if (s->ioc) {
755 qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
756 object_unref(OBJECT(s->sioc));
757 s->sioc = NULL;
758 object_unref(OBJECT(s->ioc));
759 s->ioc = NULL;
762 if (s->teardown_co) {
763 aio_co_wake(s->teardown_co);
765 aio_wait_kick();
768 static int nbd_co_send_request(BlockDriverState *bs,
769 NBDRequest *request,
770 QEMUIOVector *qiov)
772 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
773 int rc, i = -1;
775 qemu_co_mutex_lock(&s->send_mutex);
776 while (s->in_flight == MAX_NBD_REQUESTS || nbd_client_connecting_wait(s)) {
777 qemu_co_queue_wait(&s->free_sema, &s->send_mutex);
780 if (s->state != NBD_CLIENT_CONNECTED) {
781 rc = -EIO;
782 goto err;
785 s->in_flight++;
787 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
788 if (s->requests[i].coroutine == NULL) {
789 break;
793 g_assert(qemu_in_coroutine());
794 assert(i < MAX_NBD_REQUESTS);
796 s->requests[i].coroutine = qemu_coroutine_self();
797 s->requests[i].offset = request->from;
798 s->requests[i].receiving = false;
800 request->handle = INDEX_TO_HANDLE(s, i);
802 assert(s->ioc);
804 if (qiov) {
805 qio_channel_set_cork(s->ioc, true);
806 rc = nbd_send_request(s->ioc, request);
807 if (rc >= 0 && s->state == NBD_CLIENT_CONNECTED) {
808 if (qio_channel_writev_all(s->ioc, qiov->iov, qiov->niov,
809 NULL) < 0) {
810 rc = -EIO;
812 } else if (rc >= 0) {
813 rc = -EIO;
815 qio_channel_set_cork(s->ioc, false);
816 } else {
817 rc = nbd_send_request(s->ioc, request);
820 err:
821 if (rc < 0) {
822 nbd_channel_error(s, rc);
823 if (i != -1) {
824 s->requests[i].coroutine = NULL;
825 s->in_flight--;
827 if (s->in_flight == 0 && s->wait_in_flight) {
828 aio_co_wake(s->connection_co);
829 } else {
830 qemu_co_queue_next(&s->free_sema);
833 qemu_co_mutex_unlock(&s->send_mutex);
834 return rc;
837 static inline uint16_t payload_advance16(uint8_t **payload)
839 *payload += 2;
840 return lduw_be_p(*payload - 2);
843 static inline uint32_t payload_advance32(uint8_t **payload)
845 *payload += 4;
846 return ldl_be_p(*payload - 4);
849 static inline uint64_t payload_advance64(uint8_t **payload)
851 *payload += 8;
852 return ldq_be_p(*payload - 8);
855 static int nbd_parse_offset_hole_payload(BDRVNBDState *s,
856 NBDStructuredReplyChunk *chunk,
857 uint8_t *payload, uint64_t orig_offset,
858 QEMUIOVector *qiov, Error **errp)
860 uint64_t offset;
861 uint32_t hole_size;
863 if (chunk->length != sizeof(offset) + sizeof(hole_size)) {
864 error_setg(errp, "Protocol error: invalid payload for "
865 "NBD_REPLY_TYPE_OFFSET_HOLE");
866 return -EINVAL;
869 offset = payload_advance64(&payload);
870 hole_size = payload_advance32(&payload);
872 if (!hole_size || offset < orig_offset || hole_size > qiov->size ||
873 offset > orig_offset + qiov->size - hole_size) {
874 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
875 " region");
876 return -EINVAL;
878 if (s->info.min_block &&
879 !QEMU_IS_ALIGNED(hole_size, s->info.min_block)) {
880 trace_nbd_structured_read_compliance("hole");
883 qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size);
885 return 0;
889 * nbd_parse_blockstatus_payload
890 * Based on our request, we expect only one extent in reply, for the
891 * base:allocation context.
893 static int nbd_parse_blockstatus_payload(BDRVNBDState *s,
894 NBDStructuredReplyChunk *chunk,
895 uint8_t *payload, uint64_t orig_length,
896 NBDExtent *extent, Error **errp)
898 uint32_t context_id;
900 /* The server succeeded, so it must have sent [at least] one extent */
901 if (chunk->length < sizeof(context_id) + sizeof(*extent)) {
902 error_setg(errp, "Protocol error: invalid payload for "
903 "NBD_REPLY_TYPE_BLOCK_STATUS");
904 return -EINVAL;
907 context_id = payload_advance32(&payload);
908 if (s->info.context_id != context_id) {
909 error_setg(errp, "Protocol error: unexpected context id %d for "
910 "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
911 "id is %d", context_id,
912 s->info.context_id);
913 return -EINVAL;
916 extent->length = payload_advance32(&payload);
917 extent->flags = payload_advance32(&payload);
919 if (extent->length == 0) {
920 error_setg(errp, "Protocol error: server sent status chunk with "
921 "zero length");
922 return -EINVAL;
926 * A server sending unaligned block status is in violation of the
927 * protocol, but as qemu-nbd 3.1 is such a server (at least for
928 * POSIX files that are not a multiple of 512 bytes, since qemu
929 * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
930 * still sees an implicit hole beyond the real EOF), it's nicer to
931 * work around the misbehaving server. If the request included
932 * more than the final unaligned block, truncate it back to an
933 * aligned result; if the request was only the final block, round
934 * up to the full block and change the status to fully-allocated
935 * (always a safe status, even if it loses information).
937 if (s->info.min_block && !QEMU_IS_ALIGNED(extent->length,
938 s->info.min_block)) {
939 trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
940 if (extent->length > s->info.min_block) {
941 extent->length = QEMU_ALIGN_DOWN(extent->length,
942 s->info.min_block);
943 } else {
944 extent->length = s->info.min_block;
945 extent->flags = 0;
950 * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
951 * sent us any more than one extent, nor should it have included
952 * status beyond our request in that extent. However, it's easy
953 * enough to ignore the server's noncompliance without killing the
954 * connection; just ignore trailing extents, and clamp things to
955 * the length of our request.
957 if (chunk->length > sizeof(context_id) + sizeof(*extent)) {
958 trace_nbd_parse_blockstatus_compliance("more than one extent");
960 if (extent->length > orig_length) {
961 extent->length = orig_length;
962 trace_nbd_parse_blockstatus_compliance("extent length too large");
966 * HACK: if we are using x-dirty-bitmaps to access
967 * qemu:allocation-depth, treat all depths > 2 the same as 2,
968 * since nbd_client_co_block_status is only expecting the low two
969 * bits to be set.
971 if (s->alloc_depth && extent->flags > 2) {
972 extent->flags = 2;
975 return 0;
979 * nbd_parse_error_payload
980 * on success @errp contains message describing nbd error reply
982 static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
983 uint8_t *payload, int *request_ret,
984 Error **errp)
986 uint32_t error;
987 uint16_t message_size;
989 assert(chunk->type & (1 << 15));
991 if (chunk->length < sizeof(error) + sizeof(message_size)) {
992 error_setg(errp,
993 "Protocol error: invalid payload for structured error");
994 return -EINVAL;
997 error = nbd_errno_to_system_errno(payload_advance32(&payload));
998 if (error == 0) {
999 error_setg(errp, "Protocol error: server sent structured error chunk "
1000 "with error = 0");
1001 return -EINVAL;
1004 *request_ret = -error;
1005 message_size = payload_advance16(&payload);
1007 if (message_size > chunk->length - sizeof(error) - sizeof(message_size)) {
1008 error_setg(errp, "Protocol error: server sent structured error chunk "
1009 "with incorrect message size");
1010 return -EINVAL;
1013 /* TODO: Add a trace point to mention the server complaint */
1015 /* TODO handle ERROR_OFFSET */
1017 return 0;
1020 static int nbd_co_receive_offset_data_payload(BDRVNBDState *s,
1021 uint64_t orig_offset,
1022 QEMUIOVector *qiov, Error **errp)
1024 QEMUIOVector sub_qiov;
1025 uint64_t offset;
1026 size_t data_size;
1027 int ret;
1028 NBDStructuredReplyChunk *chunk = &s->reply.structured;
1030 assert(nbd_reply_is_structured(&s->reply));
1032 /* The NBD spec requires at least one byte of payload */
1033 if (chunk->length <= sizeof(offset)) {
1034 error_setg(errp, "Protocol error: invalid payload for "
1035 "NBD_REPLY_TYPE_OFFSET_DATA");
1036 return -EINVAL;
1039 if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) {
1040 return -EIO;
1043 data_size = chunk->length - sizeof(offset);
1044 assert(data_size);
1045 if (offset < orig_offset || data_size > qiov->size ||
1046 offset > orig_offset + qiov->size - data_size) {
1047 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
1048 " region");
1049 return -EINVAL;
1051 if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) {
1052 trace_nbd_structured_read_compliance("data");
1055 qemu_iovec_init(&sub_qiov, qiov->niov);
1056 qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size);
1057 ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);
1058 qemu_iovec_destroy(&sub_qiov);
1060 return ret < 0 ? -EIO : 0;
1063 #define NBD_MAX_MALLOC_PAYLOAD 1000
1064 static coroutine_fn int nbd_co_receive_structured_payload(
1065 BDRVNBDState *s, void **payload, Error **errp)
1067 int ret;
1068 uint32_t len;
1070 assert(nbd_reply_is_structured(&s->reply));
1072 len = s->reply.structured.length;
1074 if (len == 0) {
1075 return 0;
1078 if (payload == NULL) {
1079 error_setg(errp, "Unexpected structured payload");
1080 return -EINVAL;
1083 if (len > NBD_MAX_MALLOC_PAYLOAD) {
1084 error_setg(errp, "Payload too large");
1085 return -EINVAL;
1088 *payload = g_new(char, len);
1089 ret = nbd_read(s->ioc, *payload, len, "structured payload", errp);
1090 if (ret < 0) {
1091 g_free(*payload);
1092 *payload = NULL;
1093 return ret;
1096 return 0;
1100 * nbd_co_do_receive_one_chunk
1101 * for simple reply:
1102 * set request_ret to received reply error
1103 * if qiov is not NULL: read payload to @qiov
1104 * for structured reply chunk:
1105 * if error chunk: read payload, set @request_ret, do not set @payload
1106 * else if offset_data chunk: read payload data to @qiov, do not set @payload
1107 * else: read payload to @payload
1109 * If function fails, @errp contains corresponding error message, and the
1110 * connection with the server is suspect. If it returns 0, then the
1111 * transaction succeeded (although @request_ret may be a negative errno
1112 * corresponding to the server's error reply), and errp is unchanged.
1114 static coroutine_fn int nbd_co_do_receive_one_chunk(
1115 BDRVNBDState *s, uint64_t handle, bool only_structured,
1116 int *request_ret, QEMUIOVector *qiov, void **payload, Error **errp)
1118 int ret;
1119 int i = HANDLE_TO_INDEX(s, handle);
1120 void *local_payload = NULL;
1121 NBDStructuredReplyChunk *chunk;
1123 if (payload) {
1124 *payload = NULL;
1126 *request_ret = 0;
1128 /* Wait until we're woken up by nbd_connection_entry. */
1129 s->requests[i].receiving = true;
1130 qemu_coroutine_yield();
1131 s->requests[i].receiving = false;
1132 if (s->state != NBD_CLIENT_CONNECTED) {
1133 error_setg(errp, "Connection closed");
1134 return -EIO;
1136 assert(s->ioc);
1138 assert(s->reply.handle == handle);
1140 if (nbd_reply_is_simple(&s->reply)) {
1141 if (only_structured) {
1142 error_setg(errp, "Protocol error: simple reply when structured "
1143 "reply chunk was expected");
1144 return -EINVAL;
1147 *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error);
1148 if (*request_ret < 0 || !qiov) {
1149 return 0;
1152 return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov,
1153 errp) < 0 ? -EIO : 0;
1156 /* handle structured reply chunk */
1157 assert(s->info.structured_reply);
1158 chunk = &s->reply.structured;
1160 if (chunk->type == NBD_REPLY_TYPE_NONE) {
1161 if (!(chunk->flags & NBD_REPLY_FLAG_DONE)) {
1162 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
1163 " NBD_REPLY_FLAG_DONE flag set");
1164 return -EINVAL;
1166 if (chunk->length) {
1167 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
1168 " nonzero length");
1169 return -EINVAL;
1171 return 0;
1174 if (chunk->type == NBD_REPLY_TYPE_OFFSET_DATA) {
1175 if (!qiov) {
1176 error_setg(errp, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
1177 return -EINVAL;
1180 return nbd_co_receive_offset_data_payload(s, s->requests[i].offset,
1181 qiov, errp);
1184 if (nbd_reply_type_is_error(chunk->type)) {
1185 payload = &local_payload;
1188 ret = nbd_co_receive_structured_payload(s, payload, errp);
1189 if (ret < 0) {
1190 return ret;
1193 if (nbd_reply_type_is_error(chunk->type)) {
1194 ret = nbd_parse_error_payload(chunk, local_payload, request_ret, errp);
1195 g_free(local_payload);
1196 return ret;
1199 return 0;
1203 * nbd_co_receive_one_chunk
1204 * Read reply, wake up connection_co and set s->quit if needed.
1205 * Return value is a fatal error code or normal nbd reply error code
1207 static coroutine_fn int nbd_co_receive_one_chunk(
1208 BDRVNBDState *s, uint64_t handle, bool only_structured,
1209 int *request_ret, QEMUIOVector *qiov, NBDReply *reply, void **payload,
1210 Error **errp)
1212 int ret = nbd_co_do_receive_one_chunk(s, handle, only_structured,
1213 request_ret, qiov, payload, errp);
1215 if (ret < 0) {
1216 memset(reply, 0, sizeof(*reply));
1217 nbd_channel_error(s, ret);
1218 } else {
1219 /* For assert at loop start in nbd_connection_entry */
1220 *reply = s->reply;
1222 s->reply.handle = 0;
1224 if (s->connection_co && !s->wait_in_flight) {
1226 * We must check s->wait_in_flight, because we may entered by
1227 * nbd_recv_coroutines_wake_all(), in this case we should not
1228 * wake connection_co here, it will woken by last request.
1230 aio_co_wake(s->connection_co);
1233 return ret;
1236 typedef struct NBDReplyChunkIter {
1237 int ret;
1238 int request_ret;
1239 Error *err;
1240 bool done, only_structured;
1241 } NBDReplyChunkIter;
1243 static void nbd_iter_channel_error(NBDReplyChunkIter *iter,
1244 int ret, Error **local_err)
1246 assert(local_err && *local_err);
1247 assert(ret < 0);
1249 if (!iter->ret) {
1250 iter->ret = ret;
1251 error_propagate(&iter->err, *local_err);
1252 } else {
1253 error_free(*local_err);
1256 *local_err = NULL;
1259 static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret)
1261 assert(ret < 0);
1263 if (!iter->request_ret) {
1264 iter->request_ret = ret;
1269 * NBD_FOREACH_REPLY_CHUNK
1270 * The pointer stored in @payload requires g_free() to free it.
1272 #define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
1273 qiov, reply, payload) \
1274 for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
1275 nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
1278 * nbd_reply_chunk_iter_receive
1279 * The pointer stored in @payload requires g_free() to free it.
1281 static bool nbd_reply_chunk_iter_receive(BDRVNBDState *s,
1282 NBDReplyChunkIter *iter,
1283 uint64_t handle,
1284 QEMUIOVector *qiov, NBDReply *reply,
1285 void **payload)
1287 int ret, request_ret;
1288 NBDReply local_reply;
1289 NBDStructuredReplyChunk *chunk;
1290 Error *local_err = NULL;
1291 if (s->state != NBD_CLIENT_CONNECTED) {
1292 error_setg(&local_err, "Connection closed");
1293 nbd_iter_channel_error(iter, -EIO, &local_err);
1294 goto break_loop;
1297 if (iter->done) {
1298 /* Previous iteration was last. */
1299 goto break_loop;
1302 if (reply == NULL) {
1303 reply = &local_reply;
1306 ret = nbd_co_receive_one_chunk(s, handle, iter->only_structured,
1307 &request_ret, qiov, reply, payload,
1308 &local_err);
1309 if (ret < 0) {
1310 nbd_iter_channel_error(iter, ret, &local_err);
1311 } else if (request_ret < 0) {
1312 nbd_iter_request_error(iter, request_ret);
1315 /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
1316 if (nbd_reply_is_simple(reply) || s->state != NBD_CLIENT_CONNECTED) {
1317 goto break_loop;
1320 chunk = &reply->structured;
1321 iter->only_structured = true;
1323 if (chunk->type == NBD_REPLY_TYPE_NONE) {
1324 /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
1325 assert(chunk->flags & NBD_REPLY_FLAG_DONE);
1326 goto break_loop;
1329 if (chunk->flags & NBD_REPLY_FLAG_DONE) {
1330 /* This iteration is last. */
1331 iter->done = true;
1334 /* Execute the loop body */
1335 return true;
1337 break_loop:
1338 s->requests[HANDLE_TO_INDEX(s, handle)].coroutine = NULL;
1340 qemu_co_mutex_lock(&s->send_mutex);
1341 s->in_flight--;
1342 if (s->in_flight == 0 && s->wait_in_flight) {
1343 aio_co_wake(s->connection_co);
1344 } else {
1345 qemu_co_queue_next(&s->free_sema);
1347 qemu_co_mutex_unlock(&s->send_mutex);
1349 return false;
1352 static int nbd_co_receive_return_code(BDRVNBDState *s, uint64_t handle,
1353 int *request_ret, Error **errp)
1355 NBDReplyChunkIter iter;
1357 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, NULL, NULL) {
1358 /* nbd_reply_chunk_iter_receive does all the work */
1361 error_propagate(errp, iter.err);
1362 *request_ret = iter.request_ret;
1363 return iter.ret;
1366 static int nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t handle,
1367 uint64_t offset, QEMUIOVector *qiov,
1368 int *request_ret, Error **errp)
1370 NBDReplyChunkIter iter;
1371 NBDReply reply;
1372 void *payload = NULL;
1373 Error *local_err = NULL;
1375 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, s->info.structured_reply,
1376 qiov, &reply, &payload)
1378 int ret;
1379 NBDStructuredReplyChunk *chunk = &reply.structured;
1381 assert(nbd_reply_is_structured(&reply));
1383 switch (chunk->type) {
1384 case NBD_REPLY_TYPE_OFFSET_DATA:
1386 * special cased in nbd_co_receive_one_chunk, data is already
1387 * in qiov
1389 break;
1390 case NBD_REPLY_TYPE_OFFSET_HOLE:
1391 ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload,
1392 offset, qiov, &local_err);
1393 if (ret < 0) {
1394 nbd_channel_error(s, ret);
1395 nbd_iter_channel_error(&iter, ret, &local_err);
1397 break;
1398 default:
1399 if (!nbd_reply_type_is_error(chunk->type)) {
1400 /* not allowed reply type */
1401 nbd_channel_error(s, -EINVAL);
1402 error_setg(&local_err,
1403 "Unexpected reply type: %d (%s) for CMD_READ",
1404 chunk->type, nbd_reply_type_lookup(chunk->type));
1405 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1409 g_free(payload);
1410 payload = NULL;
1413 error_propagate(errp, iter.err);
1414 *request_ret = iter.request_ret;
1415 return iter.ret;
1418 static int nbd_co_receive_blockstatus_reply(BDRVNBDState *s,
1419 uint64_t handle, uint64_t length,
1420 NBDExtent *extent,
1421 int *request_ret, Error **errp)
1423 NBDReplyChunkIter iter;
1424 NBDReply reply;
1425 void *payload = NULL;
1426 Error *local_err = NULL;
1427 bool received = false;
1429 assert(!extent->length);
1430 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, &reply, &payload) {
1431 int ret;
1432 NBDStructuredReplyChunk *chunk = &reply.structured;
1434 assert(nbd_reply_is_structured(&reply));
1436 switch (chunk->type) {
1437 case NBD_REPLY_TYPE_BLOCK_STATUS:
1438 if (received) {
1439 nbd_channel_error(s, -EINVAL);
1440 error_setg(&local_err, "Several BLOCK_STATUS chunks in reply");
1441 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1443 received = true;
1445 ret = nbd_parse_blockstatus_payload(s, &reply.structured,
1446 payload, length, extent,
1447 &local_err);
1448 if (ret < 0) {
1449 nbd_channel_error(s, ret);
1450 nbd_iter_channel_error(&iter, ret, &local_err);
1452 break;
1453 default:
1454 if (!nbd_reply_type_is_error(chunk->type)) {
1455 nbd_channel_error(s, -EINVAL);
1456 error_setg(&local_err,
1457 "Unexpected reply type: %d (%s) "
1458 "for CMD_BLOCK_STATUS",
1459 chunk->type, nbd_reply_type_lookup(chunk->type));
1460 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1464 g_free(payload);
1465 payload = NULL;
1468 if (!extent->length && !iter.request_ret) {
1469 error_setg(&local_err, "Server did not reply with any status extents");
1470 nbd_iter_channel_error(&iter, -EIO, &local_err);
1473 error_propagate(errp, iter.err);
1474 *request_ret = iter.request_ret;
1475 return iter.ret;
1478 static int nbd_co_request(BlockDriverState *bs, NBDRequest *request,
1479 QEMUIOVector *write_qiov)
1481 int ret, request_ret;
1482 Error *local_err = NULL;
1483 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1485 assert(request->type != NBD_CMD_READ);
1486 if (write_qiov) {
1487 assert(request->type == NBD_CMD_WRITE);
1488 assert(request->len == iov_size(write_qiov->iov, write_qiov->niov));
1489 } else {
1490 assert(request->type != NBD_CMD_WRITE);
1493 do {
1494 ret = nbd_co_send_request(bs, request, write_qiov);
1495 if (ret < 0) {
1496 continue;
1499 ret = nbd_co_receive_return_code(s, request->handle,
1500 &request_ret, &local_err);
1501 if (local_err) {
1502 trace_nbd_co_request_fail(request->from, request->len,
1503 request->handle, request->flags,
1504 request->type,
1505 nbd_cmd_lookup(request->type),
1506 ret, error_get_pretty(local_err));
1507 error_free(local_err);
1508 local_err = NULL;
1510 } while (ret < 0 && nbd_client_connecting_wait(s));
1512 return ret ? ret : request_ret;
1515 static int nbd_client_co_preadv(BlockDriverState *bs, uint64_t offset,
1516 uint64_t bytes, QEMUIOVector *qiov, int flags)
1518 int ret, request_ret;
1519 Error *local_err = NULL;
1520 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1521 NBDRequest request = {
1522 .type = NBD_CMD_READ,
1523 .from = offset,
1524 .len = bytes,
1527 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1528 assert(!flags);
1530 if (!bytes) {
1531 return 0;
1534 * Work around the fact that the block layer doesn't do
1535 * byte-accurate sizing yet - if the read exceeds the server's
1536 * advertised size because the block layer rounded size up, then
1537 * truncate the request to the server and tail-pad with zero.
1539 if (offset >= s->info.size) {
1540 assert(bytes < BDRV_SECTOR_SIZE);
1541 qemu_iovec_memset(qiov, 0, 0, bytes);
1542 return 0;
1544 if (offset + bytes > s->info.size) {
1545 uint64_t slop = offset + bytes - s->info.size;
1547 assert(slop < BDRV_SECTOR_SIZE);
1548 qemu_iovec_memset(qiov, bytes - slop, 0, slop);
1549 request.len -= slop;
1552 do {
1553 ret = nbd_co_send_request(bs, &request, NULL);
1554 if (ret < 0) {
1555 continue;
1558 ret = nbd_co_receive_cmdread_reply(s, request.handle, offset, qiov,
1559 &request_ret, &local_err);
1560 if (local_err) {
1561 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1562 request.flags, request.type,
1563 nbd_cmd_lookup(request.type),
1564 ret, error_get_pretty(local_err));
1565 error_free(local_err);
1566 local_err = NULL;
1568 } while (ret < 0 && nbd_client_connecting_wait(s));
1570 return ret ? ret : request_ret;
1573 static int nbd_client_co_pwritev(BlockDriverState *bs, uint64_t offset,
1574 uint64_t bytes, QEMUIOVector *qiov, int flags)
1576 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1577 NBDRequest request = {
1578 .type = NBD_CMD_WRITE,
1579 .from = offset,
1580 .len = bytes,
1583 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1584 if (flags & BDRV_REQ_FUA) {
1585 assert(s->info.flags & NBD_FLAG_SEND_FUA);
1586 request.flags |= NBD_CMD_FLAG_FUA;
1589 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1591 if (!bytes) {
1592 return 0;
1594 return nbd_co_request(bs, &request, qiov);
1597 static int nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1598 int bytes, BdrvRequestFlags flags)
1600 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1601 NBDRequest request = {
1602 .type = NBD_CMD_WRITE_ZEROES,
1603 .from = offset,
1604 .len = bytes,
1607 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1608 if (!(s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {
1609 return -ENOTSUP;
1612 if (flags & BDRV_REQ_FUA) {
1613 assert(s->info.flags & NBD_FLAG_SEND_FUA);
1614 request.flags |= NBD_CMD_FLAG_FUA;
1616 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1617 request.flags |= NBD_CMD_FLAG_NO_HOLE;
1619 if (flags & BDRV_REQ_NO_FALLBACK) {
1620 assert(s->info.flags & NBD_FLAG_SEND_FAST_ZERO);
1621 request.flags |= NBD_CMD_FLAG_FAST_ZERO;
1624 if (!bytes) {
1625 return 0;
1627 return nbd_co_request(bs, &request, NULL);
1630 static int nbd_client_co_flush(BlockDriverState *bs)
1632 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1633 NBDRequest request = { .type = NBD_CMD_FLUSH };
1635 if (!(s->info.flags & NBD_FLAG_SEND_FLUSH)) {
1636 return 0;
1639 request.from = 0;
1640 request.len = 0;
1642 return nbd_co_request(bs, &request, NULL);
1645 static int nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset,
1646 int bytes)
1648 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1649 NBDRequest request = {
1650 .type = NBD_CMD_TRIM,
1651 .from = offset,
1652 .len = bytes,
1655 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1656 if (!(s->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) {
1657 return 0;
1660 return nbd_co_request(bs, &request, NULL);
1663 static int coroutine_fn nbd_client_co_block_status(
1664 BlockDriverState *bs, bool want_zero, int64_t offset, int64_t bytes,
1665 int64_t *pnum, int64_t *map, BlockDriverState **file)
1667 int ret, request_ret;
1668 NBDExtent extent = { 0 };
1669 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1670 Error *local_err = NULL;
1672 NBDRequest request = {
1673 .type = NBD_CMD_BLOCK_STATUS,
1674 .from = offset,
1675 .len = MIN(QEMU_ALIGN_DOWN(INT_MAX, bs->bl.request_alignment),
1676 MIN(bytes, s->info.size - offset)),
1677 .flags = NBD_CMD_FLAG_REQ_ONE,
1680 if (!s->info.base_allocation) {
1681 *pnum = bytes;
1682 *map = offset;
1683 *file = bs;
1684 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
1688 * Work around the fact that the block layer doesn't do
1689 * byte-accurate sizing yet - if the status request exceeds the
1690 * server's advertised size because the block layer rounded size
1691 * up, we truncated the request to the server (above), or are
1692 * called on just the hole.
1694 if (offset >= s->info.size) {
1695 *pnum = bytes;
1696 assert(bytes < BDRV_SECTOR_SIZE);
1697 /* Intentionally don't report offset_valid for the hole */
1698 return BDRV_BLOCK_ZERO;
1701 if (s->info.min_block) {
1702 assert(QEMU_IS_ALIGNED(request.len, s->info.min_block));
1704 do {
1705 ret = nbd_co_send_request(bs, &request, NULL);
1706 if (ret < 0) {
1707 continue;
1710 ret = nbd_co_receive_blockstatus_reply(s, request.handle, bytes,
1711 &extent, &request_ret,
1712 &local_err);
1713 if (local_err) {
1714 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1715 request.flags, request.type,
1716 nbd_cmd_lookup(request.type),
1717 ret, error_get_pretty(local_err));
1718 error_free(local_err);
1719 local_err = NULL;
1721 } while (ret < 0 && nbd_client_connecting_wait(s));
1723 if (ret < 0 || request_ret < 0) {
1724 return ret ? ret : request_ret;
1727 assert(extent.length);
1728 *pnum = extent.length;
1729 *map = offset;
1730 *file = bs;
1731 return (extent.flags & NBD_STATE_HOLE ? 0 : BDRV_BLOCK_DATA) |
1732 (extent.flags & NBD_STATE_ZERO ? BDRV_BLOCK_ZERO : 0) |
1733 BDRV_BLOCK_OFFSET_VALID;
1736 static int nbd_client_reopen_prepare(BDRVReopenState *state,
1737 BlockReopenQueue *queue, Error **errp)
1739 BDRVNBDState *s = (BDRVNBDState *)state->bs->opaque;
1741 if ((state->flags & BDRV_O_RDWR) && (s->info.flags & NBD_FLAG_READ_ONLY)) {
1742 error_setg(errp, "Can't reopen read-only NBD mount as read/write");
1743 return -EACCES;
1745 return 0;
1748 static void nbd_client_close(BlockDriverState *bs)
1750 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1751 NBDRequest request = { .type = NBD_CMD_DISC };
1753 if (s->ioc) {
1754 nbd_send_request(s->ioc, &request);
1757 nbd_teardown_connection(bs);
1760 static QIOChannelSocket *nbd_establish_connection(SocketAddress *saddr,
1761 Error **errp)
1763 ERRP_GUARD();
1764 QIOChannelSocket *sioc;
1766 sioc = qio_channel_socket_new();
1767 qio_channel_set_name(QIO_CHANNEL(sioc), "nbd-client");
1769 qio_channel_socket_connect_sync(sioc, saddr, errp);
1770 if (*errp) {
1771 object_unref(OBJECT(sioc));
1772 return NULL;
1775 qio_channel_set_delay(QIO_CHANNEL(sioc), false);
1777 return sioc;
1780 /* nbd_client_handshake takes ownership on sioc. On failure it is unref'ed. */
1781 static int nbd_client_handshake(BlockDriverState *bs, QIOChannelSocket *sioc,
1782 Error **errp)
1784 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1785 AioContext *aio_context = bdrv_get_aio_context(bs);
1786 int ret;
1788 trace_nbd_client_handshake(s->export);
1790 s->sioc = sioc;
1792 qio_channel_set_blocking(QIO_CHANNEL(sioc), false, NULL);
1793 qio_channel_attach_aio_context(QIO_CHANNEL(sioc), aio_context);
1795 s->info.request_sizes = true;
1796 s->info.structured_reply = true;
1797 s->info.base_allocation = true;
1798 s->info.x_dirty_bitmap = g_strdup(s->x_dirty_bitmap);
1799 s->info.name = g_strdup(s->export ?: "");
1800 ret = nbd_receive_negotiate(aio_context, QIO_CHANNEL(sioc), s->tlscreds,
1801 s->hostname, &s->ioc, &s->info, errp);
1802 g_free(s->info.x_dirty_bitmap);
1803 g_free(s->info.name);
1804 if (ret < 0) {
1805 object_unref(OBJECT(sioc));
1806 s->sioc = NULL;
1807 return ret;
1809 if (s->x_dirty_bitmap) {
1810 if (!s->info.base_allocation) {
1811 error_setg(errp, "requested x-dirty-bitmap %s not found",
1812 s->x_dirty_bitmap);
1813 ret = -EINVAL;
1814 goto fail;
1816 if (strcmp(s->x_dirty_bitmap, "qemu:allocation-depth") == 0) {
1817 s->alloc_depth = true;
1820 if (s->info.flags & NBD_FLAG_READ_ONLY) {
1821 ret = bdrv_apply_auto_read_only(bs, "NBD export is read-only", errp);
1822 if (ret < 0) {
1823 goto fail;
1826 if (s->info.flags & NBD_FLAG_SEND_FUA) {
1827 bs->supported_write_flags = BDRV_REQ_FUA;
1828 bs->supported_zero_flags |= BDRV_REQ_FUA;
1830 if (s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES) {
1831 bs->supported_zero_flags |= BDRV_REQ_MAY_UNMAP;
1832 if (s->info.flags & NBD_FLAG_SEND_FAST_ZERO) {
1833 bs->supported_zero_flags |= BDRV_REQ_NO_FALLBACK;
1837 if (!s->ioc) {
1838 s->ioc = QIO_CHANNEL(sioc);
1839 object_ref(OBJECT(s->ioc));
1842 trace_nbd_client_handshake_success(s->export);
1844 return 0;
1846 fail:
1848 * We have connected, but must fail for other reasons.
1849 * Send NBD_CMD_DISC as a courtesy to the server.
1852 NBDRequest request = { .type = NBD_CMD_DISC };
1854 nbd_send_request(s->ioc ?: QIO_CHANNEL(sioc), &request);
1856 object_unref(OBJECT(sioc));
1857 s->sioc = NULL;
1859 return ret;
1864 * Parse nbd_open options
1867 static int nbd_parse_uri(const char *filename, QDict *options)
1869 URI *uri;
1870 const char *p;
1871 QueryParams *qp = NULL;
1872 int ret = 0;
1873 bool is_unix;
1875 uri = uri_parse(filename);
1876 if (!uri) {
1877 return -EINVAL;
1880 /* transport */
1881 if (!g_strcmp0(uri->scheme, "nbd")) {
1882 is_unix = false;
1883 } else if (!g_strcmp0(uri->scheme, "nbd+tcp")) {
1884 is_unix = false;
1885 } else if (!g_strcmp0(uri->scheme, "nbd+unix")) {
1886 is_unix = true;
1887 } else {
1888 ret = -EINVAL;
1889 goto out;
1892 p = uri->path ? uri->path : "";
1893 if (p[0] == '/') {
1894 p++;
1896 if (p[0]) {
1897 qdict_put_str(options, "export", p);
1900 qp = query_params_parse(uri->query);
1901 if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
1902 ret = -EINVAL;
1903 goto out;
1906 if (is_unix) {
1907 /* nbd+unix:///export?socket=path */
1908 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
1909 ret = -EINVAL;
1910 goto out;
1912 qdict_put_str(options, "server.type", "unix");
1913 qdict_put_str(options, "server.path", qp->p[0].value);
1914 } else {
1915 QString *host;
1916 char *port_str;
1918 /* nbd[+tcp]://host[:port]/export */
1919 if (!uri->server) {
1920 ret = -EINVAL;
1921 goto out;
1924 /* strip braces from literal IPv6 address */
1925 if (uri->server[0] == '[') {
1926 host = qstring_from_substr(uri->server, 1,
1927 strlen(uri->server) - 1);
1928 } else {
1929 host = qstring_from_str(uri->server);
1932 qdict_put_str(options, "server.type", "inet");
1933 qdict_put(options, "server.host", host);
1935 port_str = g_strdup_printf("%d", uri->port ?: NBD_DEFAULT_PORT);
1936 qdict_put_str(options, "server.port", port_str);
1937 g_free(port_str);
1940 out:
1941 if (qp) {
1942 query_params_free(qp);
1944 uri_free(uri);
1945 return ret;
1948 static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
1950 const QDictEntry *e;
1952 for (e = qdict_first(options); e; e = qdict_next(options, e)) {
1953 if (!strcmp(e->key, "host") ||
1954 !strcmp(e->key, "port") ||
1955 !strcmp(e->key, "path") ||
1956 !strcmp(e->key, "export") ||
1957 strstart(e->key, "server.", NULL))
1959 error_setg(errp, "Option '%s' cannot be used with a file name",
1960 e->key);
1961 return true;
1965 return false;
1968 static void nbd_parse_filename(const char *filename, QDict *options,
1969 Error **errp)
1971 g_autofree char *file = NULL;
1972 char *export_name;
1973 const char *host_spec;
1974 const char *unixpath;
1976 if (nbd_has_filename_options_conflict(options, errp)) {
1977 return;
1980 if (strstr(filename, "://")) {
1981 int ret = nbd_parse_uri(filename, options);
1982 if (ret < 0) {
1983 error_setg(errp, "No valid URL specified");
1985 return;
1988 file = g_strdup(filename);
1990 export_name = strstr(file, EN_OPTSTR);
1991 if (export_name) {
1992 if (export_name[strlen(EN_OPTSTR)] == 0) {
1993 return;
1995 export_name[0] = 0; /* truncate 'file' */
1996 export_name += strlen(EN_OPTSTR);
1998 qdict_put_str(options, "export", export_name);
2001 /* extract the host_spec - fail if it's not nbd:... */
2002 if (!strstart(file, "nbd:", &host_spec)) {
2003 error_setg(errp, "File name string for NBD must start with 'nbd:'");
2004 return;
2007 if (!*host_spec) {
2008 return;
2011 /* are we a UNIX or TCP socket? */
2012 if (strstart(host_spec, "unix:", &unixpath)) {
2013 qdict_put_str(options, "server.type", "unix");
2014 qdict_put_str(options, "server.path", unixpath);
2015 } else {
2016 InetSocketAddress *addr = g_new(InetSocketAddress, 1);
2018 if (inet_parse(addr, host_spec, errp)) {
2019 goto out_inet;
2022 qdict_put_str(options, "server.type", "inet");
2023 qdict_put_str(options, "server.host", addr->host);
2024 qdict_put_str(options, "server.port", addr->port);
2025 out_inet:
2026 qapi_free_InetSocketAddress(addr);
2030 static bool nbd_process_legacy_socket_options(QDict *output_options,
2031 QemuOpts *legacy_opts,
2032 Error **errp)
2034 const char *path = qemu_opt_get(legacy_opts, "path");
2035 const char *host = qemu_opt_get(legacy_opts, "host");
2036 const char *port = qemu_opt_get(legacy_opts, "port");
2037 const QDictEntry *e;
2039 if (!path && !host && !port) {
2040 return true;
2043 for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
2045 if (strstart(e->key, "server.", NULL)) {
2046 error_setg(errp, "Cannot use 'server' and path/host/port at the "
2047 "same time");
2048 return false;
2052 if (path && host) {
2053 error_setg(errp, "path and host may not be used at the same time");
2054 return false;
2055 } else if (path) {
2056 if (port) {
2057 error_setg(errp, "port may not be used without host");
2058 return false;
2061 qdict_put_str(output_options, "server.type", "unix");
2062 qdict_put_str(output_options, "server.path", path);
2063 } else if (host) {
2064 qdict_put_str(output_options, "server.type", "inet");
2065 qdict_put_str(output_options, "server.host", host);
2066 qdict_put_str(output_options, "server.port",
2067 port ?: stringify(NBD_DEFAULT_PORT));
2070 return true;
2073 static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options,
2074 Error **errp)
2076 SocketAddress *saddr = NULL;
2077 QDict *addr = NULL;
2078 Visitor *iv = NULL;
2080 qdict_extract_subqdict(options, &addr, "server.");
2081 if (!qdict_size(addr)) {
2082 error_setg(errp, "NBD server address missing");
2083 goto done;
2086 iv = qobject_input_visitor_new_flat_confused(addr, errp);
2087 if (!iv) {
2088 goto done;
2091 if (!visit_type_SocketAddress(iv, NULL, &saddr, errp)) {
2092 goto done;
2095 done:
2096 qobject_unref(addr);
2097 visit_free(iv);
2098 return saddr;
2101 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
2103 Object *obj;
2104 QCryptoTLSCreds *creds;
2106 obj = object_resolve_path_component(
2107 object_get_objects_root(), id);
2108 if (!obj) {
2109 error_setg(errp, "No TLS credentials with id '%s'",
2110 id);
2111 return NULL;
2113 creds = (QCryptoTLSCreds *)
2114 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
2115 if (!creds) {
2116 error_setg(errp, "Object with id '%s' is not TLS credentials",
2117 id);
2118 return NULL;
2121 if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
2122 error_setg(errp,
2123 "Expecting TLS credentials with a client endpoint");
2124 return NULL;
2126 object_ref(obj);
2127 return creds;
2131 static QemuOptsList nbd_runtime_opts = {
2132 .name = "nbd",
2133 .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
2134 .desc = {
2136 .name = "host",
2137 .type = QEMU_OPT_STRING,
2138 .help = "TCP host to connect to",
2141 .name = "port",
2142 .type = QEMU_OPT_STRING,
2143 .help = "TCP port to connect to",
2146 .name = "path",
2147 .type = QEMU_OPT_STRING,
2148 .help = "Unix socket path to connect to",
2151 .name = "export",
2152 .type = QEMU_OPT_STRING,
2153 .help = "Name of the NBD export to open",
2156 .name = "tls-creds",
2157 .type = QEMU_OPT_STRING,
2158 .help = "ID of the TLS credentials to use",
2161 .name = "x-dirty-bitmap",
2162 .type = QEMU_OPT_STRING,
2163 .help = "experimental: expose named dirty bitmap in place of "
2164 "block status",
2167 .name = "reconnect-delay",
2168 .type = QEMU_OPT_NUMBER,
2169 .help = "On an unexpected disconnect, the nbd client tries to "
2170 "connect again until succeeding or encountering a serious "
2171 "error. During the first @reconnect-delay seconds, all "
2172 "requests are paused and will be rerun on a successful "
2173 "reconnect. After that time, any delayed requests and all "
2174 "future requests before a successful reconnect will "
2175 "immediately fail. Default 0",
2177 { /* end of list */ }
2181 static int nbd_process_options(BlockDriverState *bs, QDict *options,
2182 Error **errp)
2184 BDRVNBDState *s = bs->opaque;
2185 QemuOpts *opts;
2186 int ret = -EINVAL;
2188 opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
2189 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
2190 goto error;
2193 /* Translate @host, @port, and @path to a SocketAddress */
2194 if (!nbd_process_legacy_socket_options(options, opts, errp)) {
2195 goto error;
2198 /* Pop the config into our state object. Exit if invalid. */
2199 s->saddr = nbd_config(s, options, errp);
2200 if (!s->saddr) {
2201 goto error;
2204 s->export = g_strdup(qemu_opt_get(opts, "export"));
2205 if (s->export && strlen(s->export) > NBD_MAX_STRING_SIZE) {
2206 error_setg(errp, "export name too long to send to server");
2207 goto error;
2210 s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
2211 if (s->tlscredsid) {
2212 s->tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
2213 if (!s->tlscreds) {
2214 goto error;
2217 /* TODO SOCKET_ADDRESS_KIND_FD where fd has AF_INET or AF_INET6 */
2218 if (s->saddr->type != SOCKET_ADDRESS_TYPE_INET) {
2219 error_setg(errp, "TLS only supported over IP sockets");
2220 goto error;
2222 s->hostname = s->saddr->u.inet.host;
2225 s->x_dirty_bitmap = g_strdup(qemu_opt_get(opts, "x-dirty-bitmap"));
2226 if (s->x_dirty_bitmap && strlen(s->x_dirty_bitmap) > NBD_MAX_STRING_SIZE) {
2227 error_setg(errp, "x-dirty-bitmap query too long to send to server");
2228 goto error;
2231 s->reconnect_delay = qemu_opt_get_number(opts, "reconnect-delay", 0);
2233 ret = 0;
2235 error:
2236 if (ret < 0) {
2237 nbd_clear_bdrvstate(s);
2239 qemu_opts_del(opts);
2240 return ret;
2243 static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
2244 Error **errp)
2246 int ret;
2247 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2248 QIOChannelSocket *sioc;
2250 ret = nbd_process_options(bs, options, errp);
2251 if (ret < 0) {
2252 return ret;
2255 s->bs = bs;
2256 qemu_co_mutex_init(&s->send_mutex);
2257 qemu_co_queue_init(&s->free_sema);
2260 * establish TCP connection, return error if it fails
2261 * TODO: Configurable retry-until-timeout behaviour.
2263 sioc = nbd_establish_connection(s->saddr, errp);
2264 if (!sioc) {
2265 return -ECONNREFUSED;
2268 ret = nbd_client_handshake(bs, sioc, errp);
2269 if (ret < 0) {
2270 nbd_clear_bdrvstate(s);
2271 return ret;
2273 /* successfully connected */
2274 s->state = NBD_CLIENT_CONNECTED;
2276 nbd_init_connect_thread(s);
2278 s->connection_co = qemu_coroutine_create(nbd_connection_entry, s);
2279 bdrv_inc_in_flight(bs);
2280 aio_co_schedule(bdrv_get_aio_context(bs), s->connection_co);
2282 return 0;
2285 static int nbd_co_flush(BlockDriverState *bs)
2287 return nbd_client_co_flush(bs);
2290 static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
2292 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2293 uint32_t min = s->info.min_block;
2294 uint32_t max = MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE, s->info.max_block);
2297 * If the server did not advertise an alignment:
2298 * - a size that is not sector-aligned implies that an alignment
2299 * of 1 can be used to access those tail bytes
2300 * - advertisement of block status requires an alignment of 1, so
2301 * that we don't violate block layer constraints that block
2302 * status is always aligned (as we can't control whether the
2303 * server will report sub-sector extents, such as a hole at EOF
2304 * on an unaligned POSIX file)
2305 * - otherwise, assume the server is so old that we are safer avoiding
2306 * sub-sector requests
2308 if (!min) {
2309 min = (!QEMU_IS_ALIGNED(s->info.size, BDRV_SECTOR_SIZE) ||
2310 s->info.base_allocation) ? 1 : BDRV_SECTOR_SIZE;
2313 bs->bl.request_alignment = min;
2314 bs->bl.max_pdiscard = QEMU_ALIGN_DOWN(INT_MAX, min);
2315 bs->bl.max_pwrite_zeroes = max;
2316 bs->bl.max_transfer = max;
2318 if (s->info.opt_block &&
2319 s->info.opt_block > bs->bl.opt_transfer) {
2320 bs->bl.opt_transfer = s->info.opt_block;
2324 static void nbd_close(BlockDriverState *bs)
2326 BDRVNBDState *s = bs->opaque;
2328 nbd_client_close(bs);
2329 nbd_clear_bdrvstate(s);
2333 * NBD cannot truncate, but if the caller asks to truncate to the same size, or
2334 * to a smaller size with exact=false, there is no reason to fail the
2335 * operation.
2337 * Preallocation mode is ignored since it does not seems useful to fail when
2338 * we never change anything.
2340 static int coroutine_fn nbd_co_truncate(BlockDriverState *bs, int64_t offset,
2341 bool exact, PreallocMode prealloc,
2342 BdrvRequestFlags flags, Error **errp)
2344 BDRVNBDState *s = bs->opaque;
2346 if (offset != s->info.size && exact) {
2347 error_setg(errp, "Cannot resize NBD nodes");
2348 return -ENOTSUP;
2351 if (offset > s->info.size) {
2352 error_setg(errp, "Cannot grow NBD nodes");
2353 return -EINVAL;
2356 return 0;
2359 static int64_t nbd_getlength(BlockDriverState *bs)
2361 BDRVNBDState *s = bs->opaque;
2363 return s->info.size;
2366 static void nbd_refresh_filename(BlockDriverState *bs)
2368 BDRVNBDState *s = bs->opaque;
2369 const char *host = NULL, *port = NULL, *path = NULL;
2370 size_t len = 0;
2372 if (s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
2373 const InetSocketAddress *inet = &s->saddr->u.inet;
2374 if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) {
2375 host = inet->host;
2376 port = inet->port;
2378 } else if (s->saddr->type == SOCKET_ADDRESS_TYPE_UNIX) {
2379 path = s->saddr->u.q_unix.path;
2380 } /* else can't represent as pseudo-filename */
2382 if (path && s->export) {
2383 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2384 "nbd+unix:///%s?socket=%s", s->export, path);
2385 } else if (path && !s->export) {
2386 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2387 "nbd+unix://?socket=%s", path);
2388 } else if (host && s->export) {
2389 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2390 "nbd://%s:%s/%s", host, port, s->export);
2391 } else if (host && !s->export) {
2392 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2393 "nbd://%s:%s", host, port);
2395 if (len >= sizeof(bs->exact_filename)) {
2396 /* Name is too long to represent exactly, so leave it empty. */
2397 bs->exact_filename[0] = '\0';
2401 static char *nbd_dirname(BlockDriverState *bs, Error **errp)
2403 /* The generic bdrv_dirname() implementation is able to work out some
2404 * directory name for NBD nodes, but that would be wrong. So far there is no
2405 * specification for how "export paths" would work, so NBD does not have
2406 * directory names. */
2407 error_setg(errp, "Cannot generate a base directory for NBD nodes");
2408 return NULL;
2411 static const char *const nbd_strong_runtime_opts[] = {
2412 "path",
2413 "host",
2414 "port",
2415 "export",
2416 "tls-creds",
2417 "server.",
2419 NULL
2422 static BlockDriver bdrv_nbd = {
2423 .format_name = "nbd",
2424 .protocol_name = "nbd",
2425 .instance_size = sizeof(BDRVNBDState),
2426 .bdrv_parse_filename = nbd_parse_filename,
2427 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2428 .create_opts = &bdrv_create_opts_simple,
2429 .bdrv_file_open = nbd_open,
2430 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2431 .bdrv_co_preadv = nbd_client_co_preadv,
2432 .bdrv_co_pwritev = nbd_client_co_pwritev,
2433 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2434 .bdrv_close = nbd_close,
2435 .bdrv_co_flush_to_os = nbd_co_flush,
2436 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2437 .bdrv_refresh_limits = nbd_refresh_limits,
2438 .bdrv_co_truncate = nbd_co_truncate,
2439 .bdrv_getlength = nbd_getlength,
2440 .bdrv_detach_aio_context = nbd_client_detach_aio_context,
2441 .bdrv_attach_aio_context = nbd_client_attach_aio_context,
2442 .bdrv_co_drain_begin = nbd_client_co_drain_begin,
2443 .bdrv_co_drain_end = nbd_client_co_drain_end,
2444 .bdrv_refresh_filename = nbd_refresh_filename,
2445 .bdrv_co_block_status = nbd_client_co_block_status,
2446 .bdrv_dirname = nbd_dirname,
2447 .strong_runtime_opts = nbd_strong_runtime_opts,
2450 static BlockDriver bdrv_nbd_tcp = {
2451 .format_name = "nbd",
2452 .protocol_name = "nbd+tcp",
2453 .instance_size = sizeof(BDRVNBDState),
2454 .bdrv_parse_filename = nbd_parse_filename,
2455 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2456 .create_opts = &bdrv_create_opts_simple,
2457 .bdrv_file_open = nbd_open,
2458 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2459 .bdrv_co_preadv = nbd_client_co_preadv,
2460 .bdrv_co_pwritev = nbd_client_co_pwritev,
2461 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2462 .bdrv_close = nbd_close,
2463 .bdrv_co_flush_to_os = nbd_co_flush,
2464 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2465 .bdrv_refresh_limits = nbd_refresh_limits,
2466 .bdrv_co_truncate = nbd_co_truncate,
2467 .bdrv_getlength = nbd_getlength,
2468 .bdrv_detach_aio_context = nbd_client_detach_aio_context,
2469 .bdrv_attach_aio_context = nbd_client_attach_aio_context,
2470 .bdrv_co_drain_begin = nbd_client_co_drain_begin,
2471 .bdrv_co_drain_end = nbd_client_co_drain_end,
2472 .bdrv_refresh_filename = nbd_refresh_filename,
2473 .bdrv_co_block_status = nbd_client_co_block_status,
2474 .bdrv_dirname = nbd_dirname,
2475 .strong_runtime_opts = nbd_strong_runtime_opts,
2478 static BlockDriver bdrv_nbd_unix = {
2479 .format_name = "nbd",
2480 .protocol_name = "nbd+unix",
2481 .instance_size = sizeof(BDRVNBDState),
2482 .bdrv_parse_filename = nbd_parse_filename,
2483 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2484 .create_opts = &bdrv_create_opts_simple,
2485 .bdrv_file_open = nbd_open,
2486 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2487 .bdrv_co_preadv = nbd_client_co_preadv,
2488 .bdrv_co_pwritev = nbd_client_co_pwritev,
2489 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2490 .bdrv_close = nbd_close,
2491 .bdrv_co_flush_to_os = nbd_co_flush,
2492 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2493 .bdrv_refresh_limits = nbd_refresh_limits,
2494 .bdrv_co_truncate = nbd_co_truncate,
2495 .bdrv_getlength = nbd_getlength,
2496 .bdrv_detach_aio_context = nbd_client_detach_aio_context,
2497 .bdrv_attach_aio_context = nbd_client_attach_aio_context,
2498 .bdrv_co_drain_begin = nbd_client_co_drain_begin,
2499 .bdrv_co_drain_end = nbd_client_co_drain_end,
2500 .bdrv_refresh_filename = nbd_refresh_filename,
2501 .bdrv_co_block_status = nbd_client_co_block_status,
2502 .bdrv_dirname = nbd_dirname,
2503 .strong_runtime_opts = nbd_strong_runtime_opts,
2506 static void bdrv_nbd_init(void)
2508 bdrv_register(&bdrv_nbd);
2509 bdrv_register(&bdrv_nbd_tcp);
2510 bdrv_register(&bdrv_nbd_unix);
2513 block_init(bdrv_nbd_init);