nbd: remove peppering of nbd_client_connected
[qemu.git] / block / nbd.c
blob326546f6cd4c79a369fee9ac5479d1a12a751f2f
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"
47 #include "block/coroutines.h"
49 #include "qemu/yank.h"
51 #define EN_OPTSTR ":exportname="
52 #define MAX_NBD_REQUESTS 16
54 #define HANDLE_TO_INDEX(bs, handle) ((handle) ^ (uint64_t)(intptr_t)(bs))
55 #define INDEX_TO_HANDLE(bs, index) ((index) ^ (uint64_t)(intptr_t)(bs))
57 typedef struct {
58 Coroutine *coroutine;
59 uint64_t offset; /* original offset of the request */
60 bool receiving; /* sleeping in the yield in nbd_receive_replies */
61 } NBDClientRequest;
63 typedef enum NBDClientState {
64 NBD_CLIENT_CONNECTING_WAIT,
65 NBD_CLIENT_CONNECTING_NOWAIT,
66 NBD_CLIENT_CONNECTED,
67 NBD_CLIENT_QUIT
68 } NBDClientState;
70 typedef struct BDRVNBDState {
71 QIOChannel *ioc; /* The current I/O channel */
72 NBDExportInfo info;
74 CoMutex send_mutex;
75 CoQueue free_sema;
77 CoMutex receive_mutex;
78 int in_flight;
79 NBDClientState state;
81 QEMUTimer *reconnect_delay_timer;
82 QEMUTimer *open_timer;
84 NBDClientRequest requests[MAX_NBD_REQUESTS];
85 NBDReply reply;
86 BlockDriverState *bs;
88 /* Connection parameters */
89 uint32_t reconnect_delay;
90 uint32_t open_timeout;
91 SocketAddress *saddr;
92 char *export;
93 char *tlscredsid;
94 QCryptoTLSCreds *tlscreds;
95 char *tlshostname;
96 char *x_dirty_bitmap;
97 bool alloc_depth;
99 NBDClientConnection *conn;
100 } BDRVNBDState;
102 static void nbd_yank(void *opaque);
104 static void nbd_clear_bdrvstate(BlockDriverState *bs)
106 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
108 nbd_client_connection_release(s->conn);
109 s->conn = NULL;
111 yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name));
113 /* Must not leave timers behind that would access freed data */
114 assert(!s->reconnect_delay_timer);
115 assert(!s->open_timer);
117 object_unref(OBJECT(s->tlscreds));
118 qapi_free_SocketAddress(s->saddr);
119 s->saddr = NULL;
120 g_free(s->export);
121 s->export = NULL;
122 g_free(s->tlscredsid);
123 s->tlscredsid = NULL;
124 g_free(s->tlshostname);
125 s->tlshostname = NULL;
126 g_free(s->x_dirty_bitmap);
127 s->x_dirty_bitmap = NULL;
130 static bool nbd_client_connected(BDRVNBDState *s)
132 return qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTED;
135 static bool coroutine_fn nbd_recv_coroutine_wake_one(NBDClientRequest *req)
137 if (req->receiving) {
138 req->receiving = false;
139 aio_co_wake(req->coroutine);
140 return true;
143 return false;
146 static void coroutine_fn nbd_recv_coroutines_wake(BDRVNBDState *s, bool all)
148 int i;
150 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
151 if (nbd_recv_coroutine_wake_one(&s->requests[i]) && !all) {
152 return;
157 static void coroutine_fn nbd_channel_error(BDRVNBDState *s, int ret)
159 if (nbd_client_connected(s)) {
160 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
163 if (ret == -EIO) {
164 if (nbd_client_connected(s)) {
165 s->state = s->reconnect_delay ? NBD_CLIENT_CONNECTING_WAIT :
166 NBD_CLIENT_CONNECTING_NOWAIT;
168 } else {
169 s->state = NBD_CLIENT_QUIT;
172 nbd_recv_coroutines_wake(s, true);
175 static void reconnect_delay_timer_del(BDRVNBDState *s)
177 if (s->reconnect_delay_timer) {
178 timer_free(s->reconnect_delay_timer);
179 s->reconnect_delay_timer = NULL;
183 static void reconnect_delay_timer_cb(void *opaque)
185 BDRVNBDState *s = opaque;
187 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT) {
188 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
189 nbd_co_establish_connection_cancel(s->conn);
190 while (qemu_co_enter_next(&s->free_sema, NULL)) {
191 /* Resume all queued requests */
195 reconnect_delay_timer_del(s);
198 static void reconnect_delay_timer_init(BDRVNBDState *s, uint64_t expire_time_ns)
200 if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTING_WAIT) {
201 return;
204 assert(!s->reconnect_delay_timer);
205 s->reconnect_delay_timer = aio_timer_new(bdrv_get_aio_context(s->bs),
206 QEMU_CLOCK_REALTIME,
207 SCALE_NS,
208 reconnect_delay_timer_cb, s);
209 timer_mod(s->reconnect_delay_timer, expire_time_ns);
212 static void nbd_teardown_connection(BlockDriverState *bs)
214 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
216 assert(!s->in_flight);
218 if (s->ioc) {
219 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
220 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
221 nbd_yank, s->bs);
222 object_unref(OBJECT(s->ioc));
223 s->ioc = NULL;
226 s->state = NBD_CLIENT_QUIT;
229 static void open_timer_del(BDRVNBDState *s)
231 if (s->open_timer) {
232 timer_free(s->open_timer);
233 s->open_timer = NULL;
237 static void open_timer_cb(void *opaque)
239 BDRVNBDState *s = opaque;
241 nbd_co_establish_connection_cancel(s->conn);
242 open_timer_del(s);
245 static void open_timer_init(BDRVNBDState *s, uint64_t expire_time_ns)
247 assert(!s->open_timer);
248 s->open_timer = aio_timer_new(bdrv_get_aio_context(s->bs),
249 QEMU_CLOCK_REALTIME,
250 SCALE_NS,
251 open_timer_cb, s);
252 timer_mod(s->open_timer, expire_time_ns);
255 static bool nbd_client_connecting(BDRVNBDState *s)
257 NBDClientState state = qatomic_load_acquire(&s->state);
258 return state == NBD_CLIENT_CONNECTING_WAIT ||
259 state == NBD_CLIENT_CONNECTING_NOWAIT;
262 static bool nbd_client_connecting_wait(BDRVNBDState *s)
264 return qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT;
268 * Update @bs with information learned during a completed negotiation process.
269 * Return failure if the server's advertised options are incompatible with the
270 * client's needs.
272 static int nbd_handle_updated_info(BlockDriverState *bs, Error **errp)
274 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
275 int ret;
277 if (s->x_dirty_bitmap) {
278 if (!s->info.base_allocation) {
279 error_setg(errp, "requested x-dirty-bitmap %s not found",
280 s->x_dirty_bitmap);
281 return -EINVAL;
283 if (strcmp(s->x_dirty_bitmap, "qemu:allocation-depth") == 0) {
284 s->alloc_depth = true;
288 if (s->info.flags & NBD_FLAG_READ_ONLY) {
289 ret = bdrv_apply_auto_read_only(bs, "NBD export is read-only", errp);
290 if (ret < 0) {
291 return ret;
295 if (s->info.flags & NBD_FLAG_SEND_FUA) {
296 bs->supported_write_flags = BDRV_REQ_FUA;
297 bs->supported_zero_flags |= BDRV_REQ_FUA;
300 if (s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES) {
301 bs->supported_zero_flags |= BDRV_REQ_MAY_UNMAP;
302 if (s->info.flags & NBD_FLAG_SEND_FAST_ZERO) {
303 bs->supported_zero_flags |= BDRV_REQ_NO_FALLBACK;
307 trace_nbd_client_handshake_success(s->export);
309 return 0;
312 int coroutine_fn nbd_co_do_establish_connection(BlockDriverState *bs,
313 Error **errp)
315 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
316 int ret;
317 bool blocking = nbd_client_connecting_wait(s);
318 IO_CODE();
320 assert(!s->ioc);
322 s->ioc = nbd_co_establish_connection(s->conn, &s->info, blocking, errp);
323 if (!s->ioc) {
324 return -ECONNREFUSED;
327 yank_register_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name), nbd_yank,
328 bs);
330 ret = nbd_handle_updated_info(s->bs, NULL);
331 if (ret < 0) {
333 * We have connected, but must fail for other reasons.
334 * Send NBD_CMD_DISC as a courtesy to the server.
336 NBDRequest request = { .type = NBD_CMD_DISC };
338 nbd_send_request(s->ioc, &request);
340 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
341 nbd_yank, bs);
342 object_unref(OBJECT(s->ioc));
343 s->ioc = NULL;
345 return ret;
348 qio_channel_set_blocking(s->ioc, false, NULL);
349 qio_channel_attach_aio_context(s->ioc, bdrv_get_aio_context(bs));
351 /* successfully connected */
352 s->state = NBD_CLIENT_CONNECTED;
353 qemu_co_queue_restart_all(&s->free_sema);
355 return 0;
358 /* called under s->send_mutex */
359 static coroutine_fn void nbd_reconnect_attempt(BDRVNBDState *s)
361 assert(nbd_client_connecting(s));
362 assert(s->in_flight == 0);
364 if (nbd_client_connecting_wait(s) && s->reconnect_delay &&
365 !s->reconnect_delay_timer)
368 * It's first reconnect attempt after switching to
369 * NBD_CLIENT_CONNECTING_WAIT
371 reconnect_delay_timer_init(s,
372 qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
373 s->reconnect_delay * NANOSECONDS_PER_SECOND);
377 * Now we are sure that nobody is accessing the channel, and no one will
378 * try until we set the state to CONNECTED.
381 /* Finalize previous connection if any */
382 if (s->ioc) {
383 qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
384 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
385 nbd_yank, s->bs);
386 object_unref(OBJECT(s->ioc));
387 s->ioc = NULL;
390 nbd_co_do_establish_connection(s->bs, NULL);
393 * The reconnect attempt is done (maybe successfully, maybe not), so
394 * we no longer need this timer. Delete it so it will not outlive
395 * this I/O request (so draining removes all timers).
397 reconnect_delay_timer_del(s);
400 static coroutine_fn int nbd_receive_replies(BDRVNBDState *s, uint64_t handle)
402 int ret;
403 uint64_t ind = HANDLE_TO_INDEX(s, handle), ind2;
404 QEMU_LOCK_GUARD(&s->receive_mutex);
406 while (true) {
407 if (s->reply.handle == handle) {
408 /* We are done */
409 return 0;
412 if (s->reply.handle != 0) {
414 * Some other request is being handled now. It should already be
415 * woken by whoever set s->reply.handle (or never wait in this
416 * yield). So, we should not wake it here.
418 ind2 = HANDLE_TO_INDEX(s, s->reply.handle);
419 assert(!s->requests[ind2].receiving);
421 s->requests[ind].receiving = true;
422 qemu_co_mutex_unlock(&s->receive_mutex);
424 qemu_coroutine_yield();
426 * We may be woken for 3 reasons:
427 * 1. From this function, executing in parallel coroutine, when our
428 * handle is received.
429 * 2. From nbd_channel_error(), when connection is lost.
430 * 3. From nbd_co_receive_one_chunk(), when previous request is
431 * finished and s->reply.handle set to 0.
432 * Anyway, it's OK to lock the mutex and go to the next iteration.
435 qemu_co_mutex_lock(&s->receive_mutex);
436 assert(!s->requests[ind].receiving);
437 continue;
440 /* We are under mutex and handle is 0. We have to do the dirty work. */
441 assert(s->reply.handle == 0);
442 ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, NULL);
443 if (ret <= 0) {
444 ret = ret ? ret : -EIO;
445 nbd_channel_error(s, ret);
446 return ret;
448 if (nbd_reply_is_structured(&s->reply) && !s->info.structured_reply) {
449 nbd_channel_error(s, -EINVAL);
450 return -EINVAL;
452 ind2 = HANDLE_TO_INDEX(s, s->reply.handle);
453 if (ind2 >= MAX_NBD_REQUESTS || !s->requests[ind2].coroutine) {
454 nbd_channel_error(s, -EINVAL);
455 return -EINVAL;
457 if (s->reply.handle == handle) {
458 /* We are done */
459 return 0;
461 nbd_recv_coroutine_wake_one(&s->requests[ind2]);
465 static int coroutine_fn nbd_co_send_request(BlockDriverState *bs,
466 NBDRequest *request,
467 QEMUIOVector *qiov)
469 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
470 int rc, i = -1;
472 qemu_co_mutex_lock(&s->send_mutex);
474 while (s->in_flight == MAX_NBD_REQUESTS ||
475 (!nbd_client_connected(s) && s->in_flight > 0))
477 qemu_co_queue_wait(&s->free_sema, &s->send_mutex);
480 if (nbd_client_connecting(s)) {
481 nbd_reconnect_attempt(s);
484 if (!nbd_client_connected(s)) {
485 rc = -EIO;
486 goto err;
489 s->in_flight++;
491 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
492 if (s->requests[i].coroutine == NULL) {
493 break;
497 g_assert(qemu_in_coroutine());
498 assert(i < MAX_NBD_REQUESTS);
500 s->requests[i].coroutine = qemu_coroutine_self();
501 s->requests[i].offset = request->from;
502 s->requests[i].receiving = false;
504 request->handle = INDEX_TO_HANDLE(s, i);
506 assert(s->ioc);
508 if (qiov) {
509 qio_channel_set_cork(s->ioc, true);
510 rc = nbd_send_request(s->ioc, request);
511 if (rc >= 0) {
512 if (qio_channel_writev_all(s->ioc, qiov->iov, qiov->niov,
513 NULL) < 0) {
514 rc = -EIO;
516 } else if (rc >= 0) {
517 rc = -EIO;
519 qio_channel_set_cork(s->ioc, false);
520 } else {
521 rc = nbd_send_request(s->ioc, request);
524 err:
525 if (rc < 0) {
526 nbd_channel_error(s, rc);
527 if (i != -1) {
528 s->requests[i].coroutine = NULL;
529 s->in_flight--;
531 qemu_co_queue_next(&s->free_sema);
533 qemu_co_mutex_unlock(&s->send_mutex);
534 return rc;
537 static inline uint16_t payload_advance16(uint8_t **payload)
539 *payload += 2;
540 return lduw_be_p(*payload - 2);
543 static inline uint32_t payload_advance32(uint8_t **payload)
545 *payload += 4;
546 return ldl_be_p(*payload - 4);
549 static inline uint64_t payload_advance64(uint8_t **payload)
551 *payload += 8;
552 return ldq_be_p(*payload - 8);
555 static int nbd_parse_offset_hole_payload(BDRVNBDState *s,
556 NBDStructuredReplyChunk *chunk,
557 uint8_t *payload, uint64_t orig_offset,
558 QEMUIOVector *qiov, Error **errp)
560 uint64_t offset;
561 uint32_t hole_size;
563 if (chunk->length != sizeof(offset) + sizeof(hole_size)) {
564 error_setg(errp, "Protocol error: invalid payload for "
565 "NBD_REPLY_TYPE_OFFSET_HOLE");
566 return -EINVAL;
569 offset = payload_advance64(&payload);
570 hole_size = payload_advance32(&payload);
572 if (!hole_size || offset < orig_offset || hole_size > qiov->size ||
573 offset > orig_offset + qiov->size - hole_size) {
574 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
575 " region");
576 return -EINVAL;
578 if (s->info.min_block &&
579 !QEMU_IS_ALIGNED(hole_size, s->info.min_block)) {
580 trace_nbd_structured_read_compliance("hole");
583 qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size);
585 return 0;
589 * nbd_parse_blockstatus_payload
590 * Based on our request, we expect only one extent in reply, for the
591 * base:allocation context.
593 static int nbd_parse_blockstatus_payload(BDRVNBDState *s,
594 NBDStructuredReplyChunk *chunk,
595 uint8_t *payload, uint64_t orig_length,
596 NBDExtent *extent, Error **errp)
598 uint32_t context_id;
600 /* The server succeeded, so it must have sent [at least] one extent */
601 if (chunk->length < sizeof(context_id) + sizeof(*extent)) {
602 error_setg(errp, "Protocol error: invalid payload for "
603 "NBD_REPLY_TYPE_BLOCK_STATUS");
604 return -EINVAL;
607 context_id = payload_advance32(&payload);
608 if (s->info.context_id != context_id) {
609 error_setg(errp, "Protocol error: unexpected context id %d for "
610 "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
611 "id is %d", context_id,
612 s->info.context_id);
613 return -EINVAL;
616 extent->length = payload_advance32(&payload);
617 extent->flags = payload_advance32(&payload);
619 if (extent->length == 0) {
620 error_setg(errp, "Protocol error: server sent status chunk with "
621 "zero length");
622 return -EINVAL;
626 * A server sending unaligned block status is in violation of the
627 * protocol, but as qemu-nbd 3.1 is such a server (at least for
628 * POSIX files that are not a multiple of 512 bytes, since qemu
629 * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
630 * still sees an implicit hole beyond the real EOF), it's nicer to
631 * work around the misbehaving server. If the request included
632 * more than the final unaligned block, truncate it back to an
633 * aligned result; if the request was only the final block, round
634 * up to the full block and change the status to fully-allocated
635 * (always a safe status, even if it loses information).
637 if (s->info.min_block && !QEMU_IS_ALIGNED(extent->length,
638 s->info.min_block)) {
639 trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
640 if (extent->length > s->info.min_block) {
641 extent->length = QEMU_ALIGN_DOWN(extent->length,
642 s->info.min_block);
643 } else {
644 extent->length = s->info.min_block;
645 extent->flags = 0;
650 * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
651 * sent us any more than one extent, nor should it have included
652 * status beyond our request in that extent. However, it's easy
653 * enough to ignore the server's noncompliance without killing the
654 * connection; just ignore trailing extents, and clamp things to
655 * the length of our request.
657 if (chunk->length > sizeof(context_id) + sizeof(*extent)) {
658 trace_nbd_parse_blockstatus_compliance("more than one extent");
660 if (extent->length > orig_length) {
661 extent->length = orig_length;
662 trace_nbd_parse_blockstatus_compliance("extent length too large");
666 * HACK: if we are using x-dirty-bitmaps to access
667 * qemu:allocation-depth, treat all depths > 2 the same as 2,
668 * since nbd_client_co_block_status is only expecting the low two
669 * bits to be set.
671 if (s->alloc_depth && extent->flags > 2) {
672 extent->flags = 2;
675 return 0;
679 * nbd_parse_error_payload
680 * on success @errp contains message describing nbd error reply
682 static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
683 uint8_t *payload, int *request_ret,
684 Error **errp)
686 uint32_t error;
687 uint16_t message_size;
689 assert(chunk->type & (1 << 15));
691 if (chunk->length < sizeof(error) + sizeof(message_size)) {
692 error_setg(errp,
693 "Protocol error: invalid payload for structured error");
694 return -EINVAL;
697 error = nbd_errno_to_system_errno(payload_advance32(&payload));
698 if (error == 0) {
699 error_setg(errp, "Protocol error: server sent structured error chunk "
700 "with error = 0");
701 return -EINVAL;
704 *request_ret = -error;
705 message_size = payload_advance16(&payload);
707 if (message_size > chunk->length - sizeof(error) - sizeof(message_size)) {
708 error_setg(errp, "Protocol error: server sent structured error chunk "
709 "with incorrect message size");
710 return -EINVAL;
713 /* TODO: Add a trace point to mention the server complaint */
715 /* TODO handle ERROR_OFFSET */
717 return 0;
720 static int coroutine_fn
721 nbd_co_receive_offset_data_payload(BDRVNBDState *s, uint64_t orig_offset,
722 QEMUIOVector *qiov, Error **errp)
724 QEMUIOVector sub_qiov;
725 uint64_t offset;
726 size_t data_size;
727 int ret;
728 NBDStructuredReplyChunk *chunk = &s->reply.structured;
730 assert(nbd_reply_is_structured(&s->reply));
732 /* The NBD spec requires at least one byte of payload */
733 if (chunk->length <= sizeof(offset)) {
734 error_setg(errp, "Protocol error: invalid payload for "
735 "NBD_REPLY_TYPE_OFFSET_DATA");
736 return -EINVAL;
739 if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) {
740 return -EIO;
743 data_size = chunk->length - sizeof(offset);
744 assert(data_size);
745 if (offset < orig_offset || data_size > qiov->size ||
746 offset > orig_offset + qiov->size - data_size) {
747 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
748 " region");
749 return -EINVAL;
751 if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) {
752 trace_nbd_structured_read_compliance("data");
755 qemu_iovec_init(&sub_qiov, qiov->niov);
756 qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size);
757 ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);
758 qemu_iovec_destroy(&sub_qiov);
760 return ret < 0 ? -EIO : 0;
763 #define NBD_MAX_MALLOC_PAYLOAD 1000
764 static coroutine_fn int nbd_co_receive_structured_payload(
765 BDRVNBDState *s, void **payload, Error **errp)
767 int ret;
768 uint32_t len;
770 assert(nbd_reply_is_structured(&s->reply));
772 len = s->reply.structured.length;
774 if (len == 0) {
775 return 0;
778 if (payload == NULL) {
779 error_setg(errp, "Unexpected structured payload");
780 return -EINVAL;
783 if (len > NBD_MAX_MALLOC_PAYLOAD) {
784 error_setg(errp, "Payload too large");
785 return -EINVAL;
788 *payload = g_new(char, len);
789 ret = nbd_read(s->ioc, *payload, len, "structured payload", errp);
790 if (ret < 0) {
791 g_free(*payload);
792 *payload = NULL;
793 return ret;
796 return 0;
800 * nbd_co_do_receive_one_chunk
801 * for simple reply:
802 * set request_ret to received reply error
803 * if qiov is not NULL: read payload to @qiov
804 * for structured reply chunk:
805 * if error chunk: read payload, set @request_ret, do not set @payload
806 * else if offset_data chunk: read payload data to @qiov, do not set @payload
807 * else: read payload to @payload
809 * If function fails, @errp contains corresponding error message, and the
810 * connection with the server is suspect. If it returns 0, then the
811 * transaction succeeded (although @request_ret may be a negative errno
812 * corresponding to the server's error reply), and errp is unchanged.
814 static coroutine_fn int nbd_co_do_receive_one_chunk(
815 BDRVNBDState *s, uint64_t handle, bool only_structured,
816 int *request_ret, QEMUIOVector *qiov, void **payload, Error **errp)
818 int ret;
819 int i = HANDLE_TO_INDEX(s, handle);
820 void *local_payload = NULL;
821 NBDStructuredReplyChunk *chunk;
823 if (payload) {
824 *payload = NULL;
826 *request_ret = 0;
828 ret = nbd_receive_replies(s, handle);
829 if (ret < 0) {
830 error_setg(errp, "Connection closed");
831 return -EIO;
833 assert(s->ioc);
835 assert(s->reply.handle == handle);
837 if (nbd_reply_is_simple(&s->reply)) {
838 if (only_structured) {
839 error_setg(errp, "Protocol error: simple reply when structured "
840 "reply chunk was expected");
841 return -EINVAL;
844 *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error);
845 if (*request_ret < 0 || !qiov) {
846 return 0;
849 return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov,
850 errp) < 0 ? -EIO : 0;
853 /* handle structured reply chunk */
854 assert(s->info.structured_reply);
855 chunk = &s->reply.structured;
857 if (chunk->type == NBD_REPLY_TYPE_NONE) {
858 if (!(chunk->flags & NBD_REPLY_FLAG_DONE)) {
859 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
860 " NBD_REPLY_FLAG_DONE flag set");
861 return -EINVAL;
863 if (chunk->length) {
864 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
865 " nonzero length");
866 return -EINVAL;
868 return 0;
871 if (chunk->type == NBD_REPLY_TYPE_OFFSET_DATA) {
872 if (!qiov) {
873 error_setg(errp, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
874 return -EINVAL;
877 return nbd_co_receive_offset_data_payload(s, s->requests[i].offset,
878 qiov, errp);
881 if (nbd_reply_type_is_error(chunk->type)) {
882 payload = &local_payload;
885 ret = nbd_co_receive_structured_payload(s, payload, errp);
886 if (ret < 0) {
887 return ret;
890 if (nbd_reply_type_is_error(chunk->type)) {
891 ret = nbd_parse_error_payload(chunk, local_payload, request_ret, errp);
892 g_free(local_payload);
893 return ret;
896 return 0;
900 * nbd_co_receive_one_chunk
901 * Read reply, wake up connection_co and set s->quit if needed.
902 * Return value is a fatal error code or normal nbd reply error code
904 static coroutine_fn int nbd_co_receive_one_chunk(
905 BDRVNBDState *s, uint64_t handle, bool only_structured,
906 int *request_ret, QEMUIOVector *qiov, NBDReply *reply, void **payload,
907 Error **errp)
909 int ret = nbd_co_do_receive_one_chunk(s, handle, only_structured,
910 request_ret, qiov, payload, errp);
912 if (ret < 0) {
913 memset(reply, 0, sizeof(*reply));
914 nbd_channel_error(s, ret);
915 } else {
916 /* For assert at loop start in nbd_connection_entry */
917 *reply = s->reply;
919 s->reply.handle = 0;
921 nbd_recv_coroutines_wake(s, false);
923 return ret;
926 typedef struct NBDReplyChunkIter {
927 int ret;
928 int request_ret;
929 Error *err;
930 bool done, only_structured;
931 } NBDReplyChunkIter;
933 static void nbd_iter_channel_error(NBDReplyChunkIter *iter,
934 int ret, Error **local_err)
936 assert(local_err && *local_err);
937 assert(ret < 0);
939 if (!iter->ret) {
940 iter->ret = ret;
941 error_propagate(&iter->err, *local_err);
942 } else {
943 error_free(*local_err);
946 *local_err = NULL;
949 static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret)
951 assert(ret < 0);
953 if (!iter->request_ret) {
954 iter->request_ret = ret;
959 * NBD_FOREACH_REPLY_CHUNK
960 * The pointer stored in @payload requires g_free() to free it.
962 #define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
963 qiov, reply, payload) \
964 for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
965 nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
968 * nbd_reply_chunk_iter_receive
969 * The pointer stored in @payload requires g_free() to free it.
971 static bool nbd_reply_chunk_iter_receive(BDRVNBDState *s,
972 NBDReplyChunkIter *iter,
973 uint64_t handle,
974 QEMUIOVector *qiov, NBDReply *reply,
975 void **payload)
977 int ret, request_ret;
978 NBDReply local_reply;
979 NBDStructuredReplyChunk *chunk;
980 Error *local_err = NULL;
982 if (iter->done) {
983 /* Previous iteration was last. */
984 goto break_loop;
987 if (reply == NULL) {
988 reply = &local_reply;
991 ret = nbd_co_receive_one_chunk(s, handle, iter->only_structured,
992 &request_ret, qiov, reply, payload,
993 &local_err);
994 if (ret < 0) {
995 nbd_iter_channel_error(iter, ret, &local_err);
996 } else if (request_ret < 0) {
997 nbd_iter_request_error(iter, request_ret);
1000 /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
1001 if (nbd_reply_is_simple(reply) || iter->ret < 0) {
1002 goto break_loop;
1005 chunk = &reply->structured;
1006 iter->only_structured = true;
1008 if (chunk->type == NBD_REPLY_TYPE_NONE) {
1009 /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
1010 assert(chunk->flags & NBD_REPLY_FLAG_DONE);
1011 goto break_loop;
1014 if (chunk->flags & NBD_REPLY_FLAG_DONE) {
1015 /* This iteration is last. */
1016 iter->done = true;
1019 /* Execute the loop body */
1020 return true;
1022 break_loop:
1023 s->requests[HANDLE_TO_INDEX(s, handle)].coroutine = NULL;
1025 qemu_co_mutex_lock(&s->send_mutex);
1026 s->in_flight--;
1027 qemu_co_queue_next(&s->free_sema);
1028 qemu_co_mutex_unlock(&s->send_mutex);
1030 return false;
1033 static int coroutine_fn nbd_co_receive_return_code(BDRVNBDState *s, uint64_t handle,
1034 int *request_ret, Error **errp)
1036 NBDReplyChunkIter iter;
1038 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, NULL, NULL) {
1039 /* nbd_reply_chunk_iter_receive does all the work */
1042 error_propagate(errp, iter.err);
1043 *request_ret = iter.request_ret;
1044 return iter.ret;
1047 static int coroutine_fn nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t handle,
1048 uint64_t offset, QEMUIOVector *qiov,
1049 int *request_ret, Error **errp)
1051 NBDReplyChunkIter iter;
1052 NBDReply reply;
1053 void *payload = NULL;
1054 Error *local_err = NULL;
1056 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, s->info.structured_reply,
1057 qiov, &reply, &payload)
1059 int ret;
1060 NBDStructuredReplyChunk *chunk = &reply.structured;
1062 assert(nbd_reply_is_structured(&reply));
1064 switch (chunk->type) {
1065 case NBD_REPLY_TYPE_OFFSET_DATA:
1067 * special cased in nbd_co_receive_one_chunk, data is already
1068 * in qiov
1070 break;
1071 case NBD_REPLY_TYPE_OFFSET_HOLE:
1072 ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload,
1073 offset, qiov, &local_err);
1074 if (ret < 0) {
1075 nbd_channel_error(s, ret);
1076 nbd_iter_channel_error(&iter, ret, &local_err);
1078 break;
1079 default:
1080 if (!nbd_reply_type_is_error(chunk->type)) {
1081 /* not allowed reply type */
1082 nbd_channel_error(s, -EINVAL);
1083 error_setg(&local_err,
1084 "Unexpected reply type: %d (%s) for CMD_READ",
1085 chunk->type, nbd_reply_type_lookup(chunk->type));
1086 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1090 g_free(payload);
1091 payload = NULL;
1094 error_propagate(errp, iter.err);
1095 *request_ret = iter.request_ret;
1096 return iter.ret;
1099 static int coroutine_fn nbd_co_receive_blockstatus_reply(BDRVNBDState *s,
1100 uint64_t handle, uint64_t length,
1101 NBDExtent *extent,
1102 int *request_ret, Error **errp)
1104 NBDReplyChunkIter iter;
1105 NBDReply reply;
1106 void *payload = NULL;
1107 Error *local_err = NULL;
1108 bool received = false;
1110 assert(!extent->length);
1111 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, &reply, &payload) {
1112 int ret;
1113 NBDStructuredReplyChunk *chunk = &reply.structured;
1115 assert(nbd_reply_is_structured(&reply));
1117 switch (chunk->type) {
1118 case NBD_REPLY_TYPE_BLOCK_STATUS:
1119 if (received) {
1120 nbd_channel_error(s, -EINVAL);
1121 error_setg(&local_err, "Several BLOCK_STATUS chunks in reply");
1122 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1124 received = true;
1126 ret = nbd_parse_blockstatus_payload(s, &reply.structured,
1127 payload, length, extent,
1128 &local_err);
1129 if (ret < 0) {
1130 nbd_channel_error(s, ret);
1131 nbd_iter_channel_error(&iter, ret, &local_err);
1133 break;
1134 default:
1135 if (!nbd_reply_type_is_error(chunk->type)) {
1136 nbd_channel_error(s, -EINVAL);
1137 error_setg(&local_err,
1138 "Unexpected reply type: %d (%s) "
1139 "for CMD_BLOCK_STATUS",
1140 chunk->type, nbd_reply_type_lookup(chunk->type));
1141 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1145 g_free(payload);
1146 payload = NULL;
1149 if (!extent->length && !iter.request_ret) {
1150 error_setg(&local_err, "Server did not reply with any status extents");
1151 nbd_iter_channel_error(&iter, -EIO, &local_err);
1154 error_propagate(errp, iter.err);
1155 *request_ret = iter.request_ret;
1156 return iter.ret;
1159 static int coroutine_fn nbd_co_request(BlockDriverState *bs, NBDRequest *request,
1160 QEMUIOVector *write_qiov)
1162 int ret, request_ret;
1163 Error *local_err = NULL;
1164 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1166 assert(request->type != NBD_CMD_READ);
1167 if (write_qiov) {
1168 assert(request->type == NBD_CMD_WRITE);
1169 assert(request->len == iov_size(write_qiov->iov, write_qiov->niov));
1170 } else {
1171 assert(request->type != NBD_CMD_WRITE);
1174 do {
1175 ret = nbd_co_send_request(bs, request, write_qiov);
1176 if (ret < 0) {
1177 continue;
1180 ret = nbd_co_receive_return_code(s, request->handle,
1181 &request_ret, &local_err);
1182 if (local_err) {
1183 trace_nbd_co_request_fail(request->from, request->len,
1184 request->handle, request->flags,
1185 request->type,
1186 nbd_cmd_lookup(request->type),
1187 ret, error_get_pretty(local_err));
1188 error_free(local_err);
1189 local_err = NULL;
1191 } while (ret < 0 && nbd_client_connecting_wait(s));
1193 return ret ? ret : request_ret;
1196 static int coroutine_fn nbd_client_co_preadv(BlockDriverState *bs, int64_t offset,
1197 int64_t bytes, QEMUIOVector *qiov,
1198 BdrvRequestFlags flags)
1200 int ret, request_ret;
1201 Error *local_err = NULL;
1202 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1203 NBDRequest request = {
1204 .type = NBD_CMD_READ,
1205 .from = offset,
1206 .len = bytes,
1209 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1210 assert(!flags);
1212 if (!bytes) {
1213 return 0;
1216 * Work around the fact that the block layer doesn't do
1217 * byte-accurate sizing yet - if the read exceeds the server's
1218 * advertised size because the block layer rounded size up, then
1219 * truncate the request to the server and tail-pad with zero.
1221 if (offset >= s->info.size) {
1222 assert(bytes < BDRV_SECTOR_SIZE);
1223 qemu_iovec_memset(qiov, 0, 0, bytes);
1224 return 0;
1226 if (offset + bytes > s->info.size) {
1227 uint64_t slop = offset + bytes - s->info.size;
1229 assert(slop < BDRV_SECTOR_SIZE);
1230 qemu_iovec_memset(qiov, bytes - slop, 0, slop);
1231 request.len -= slop;
1234 do {
1235 ret = nbd_co_send_request(bs, &request, NULL);
1236 if (ret < 0) {
1237 continue;
1240 ret = nbd_co_receive_cmdread_reply(s, request.handle, offset, qiov,
1241 &request_ret, &local_err);
1242 if (local_err) {
1243 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1244 request.flags, request.type,
1245 nbd_cmd_lookup(request.type),
1246 ret, error_get_pretty(local_err));
1247 error_free(local_err);
1248 local_err = NULL;
1250 } while (ret < 0 && nbd_client_connecting_wait(s));
1252 return ret ? ret : request_ret;
1255 static int coroutine_fn nbd_client_co_pwritev(BlockDriverState *bs, int64_t offset,
1256 int64_t bytes, QEMUIOVector *qiov,
1257 BdrvRequestFlags flags)
1259 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1260 NBDRequest request = {
1261 .type = NBD_CMD_WRITE,
1262 .from = offset,
1263 .len = bytes,
1266 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1267 if (flags & BDRV_REQ_FUA) {
1268 assert(s->info.flags & NBD_FLAG_SEND_FUA);
1269 request.flags |= NBD_CMD_FLAG_FUA;
1272 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1274 if (!bytes) {
1275 return 0;
1277 return nbd_co_request(bs, &request, qiov);
1280 static int coroutine_fn nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1281 int64_t bytes, BdrvRequestFlags flags)
1283 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1284 NBDRequest request = {
1285 .type = NBD_CMD_WRITE_ZEROES,
1286 .from = offset,
1287 .len = bytes, /* .len is uint32_t actually */
1290 assert(bytes <= UINT32_MAX); /* rely on max_pwrite_zeroes */
1292 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1293 if (!(s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {
1294 return -ENOTSUP;
1297 if (flags & BDRV_REQ_FUA) {
1298 assert(s->info.flags & NBD_FLAG_SEND_FUA);
1299 request.flags |= NBD_CMD_FLAG_FUA;
1301 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1302 request.flags |= NBD_CMD_FLAG_NO_HOLE;
1304 if (flags & BDRV_REQ_NO_FALLBACK) {
1305 assert(s->info.flags & NBD_FLAG_SEND_FAST_ZERO);
1306 request.flags |= NBD_CMD_FLAG_FAST_ZERO;
1309 if (!bytes) {
1310 return 0;
1312 return nbd_co_request(bs, &request, NULL);
1315 static int coroutine_fn nbd_client_co_flush(BlockDriverState *bs)
1317 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1318 NBDRequest request = { .type = NBD_CMD_FLUSH };
1320 if (!(s->info.flags & NBD_FLAG_SEND_FLUSH)) {
1321 return 0;
1324 request.from = 0;
1325 request.len = 0;
1327 return nbd_co_request(bs, &request, NULL);
1330 static int coroutine_fn nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset,
1331 int64_t bytes)
1333 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1334 NBDRequest request = {
1335 .type = NBD_CMD_TRIM,
1336 .from = offset,
1337 .len = bytes, /* len is uint32_t */
1340 assert(bytes <= UINT32_MAX); /* rely on max_pdiscard */
1342 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1343 if (!(s->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) {
1344 return 0;
1347 return nbd_co_request(bs, &request, NULL);
1350 static int coroutine_fn nbd_client_co_block_status(
1351 BlockDriverState *bs, bool want_zero, int64_t offset, int64_t bytes,
1352 int64_t *pnum, int64_t *map, BlockDriverState **file)
1354 int ret, request_ret;
1355 NBDExtent extent = { 0 };
1356 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1357 Error *local_err = NULL;
1359 NBDRequest request = {
1360 .type = NBD_CMD_BLOCK_STATUS,
1361 .from = offset,
1362 .len = MIN(QEMU_ALIGN_DOWN(INT_MAX, bs->bl.request_alignment),
1363 MIN(bytes, s->info.size - offset)),
1364 .flags = NBD_CMD_FLAG_REQ_ONE,
1367 if (!s->info.base_allocation) {
1368 *pnum = bytes;
1369 *map = offset;
1370 *file = bs;
1371 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
1375 * Work around the fact that the block layer doesn't do
1376 * byte-accurate sizing yet - if the status request exceeds the
1377 * server's advertised size because the block layer rounded size
1378 * up, we truncated the request to the server (above), or are
1379 * called on just the hole.
1381 if (offset >= s->info.size) {
1382 *pnum = bytes;
1383 assert(bytes < BDRV_SECTOR_SIZE);
1384 /* Intentionally don't report offset_valid for the hole */
1385 return BDRV_BLOCK_ZERO;
1388 if (s->info.min_block) {
1389 assert(QEMU_IS_ALIGNED(request.len, s->info.min_block));
1391 do {
1392 ret = nbd_co_send_request(bs, &request, NULL);
1393 if (ret < 0) {
1394 continue;
1397 ret = nbd_co_receive_blockstatus_reply(s, request.handle, bytes,
1398 &extent, &request_ret,
1399 &local_err);
1400 if (local_err) {
1401 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1402 request.flags, request.type,
1403 nbd_cmd_lookup(request.type),
1404 ret, error_get_pretty(local_err));
1405 error_free(local_err);
1406 local_err = NULL;
1408 } while (ret < 0 && nbd_client_connecting_wait(s));
1410 if (ret < 0 || request_ret < 0) {
1411 return ret ? ret : request_ret;
1414 assert(extent.length);
1415 *pnum = extent.length;
1416 *map = offset;
1417 *file = bs;
1418 return (extent.flags & NBD_STATE_HOLE ? 0 : BDRV_BLOCK_DATA) |
1419 (extent.flags & NBD_STATE_ZERO ? BDRV_BLOCK_ZERO : 0) |
1420 BDRV_BLOCK_OFFSET_VALID;
1423 static int nbd_client_reopen_prepare(BDRVReopenState *state,
1424 BlockReopenQueue *queue, Error **errp)
1426 BDRVNBDState *s = (BDRVNBDState *)state->bs->opaque;
1428 if ((state->flags & BDRV_O_RDWR) && (s->info.flags & NBD_FLAG_READ_ONLY)) {
1429 error_setg(errp, "Can't reopen read-only NBD mount as read/write");
1430 return -EACCES;
1432 return 0;
1435 static void nbd_yank(void *opaque)
1437 BlockDriverState *bs = opaque;
1438 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1440 qatomic_store_release(&s->state, NBD_CLIENT_QUIT);
1441 qio_channel_shutdown(QIO_CHANNEL(s->ioc), QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
1444 static void nbd_client_close(BlockDriverState *bs)
1446 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1447 NBDRequest request = { .type = NBD_CMD_DISC };
1449 if (s->ioc) {
1450 nbd_send_request(s->ioc, &request);
1453 nbd_teardown_connection(bs);
1458 * Parse nbd_open options
1461 static int nbd_parse_uri(const char *filename, QDict *options)
1463 URI *uri;
1464 const char *p;
1465 QueryParams *qp = NULL;
1466 int ret = 0;
1467 bool is_unix;
1469 uri = uri_parse(filename);
1470 if (!uri) {
1471 return -EINVAL;
1474 /* transport */
1475 if (!g_strcmp0(uri->scheme, "nbd")) {
1476 is_unix = false;
1477 } else if (!g_strcmp0(uri->scheme, "nbd+tcp")) {
1478 is_unix = false;
1479 } else if (!g_strcmp0(uri->scheme, "nbd+unix")) {
1480 is_unix = true;
1481 } else {
1482 ret = -EINVAL;
1483 goto out;
1486 p = uri->path ? uri->path : "";
1487 if (p[0] == '/') {
1488 p++;
1490 if (p[0]) {
1491 qdict_put_str(options, "export", p);
1494 qp = query_params_parse(uri->query);
1495 if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
1496 ret = -EINVAL;
1497 goto out;
1500 if (is_unix) {
1501 /* nbd+unix:///export?socket=path */
1502 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
1503 ret = -EINVAL;
1504 goto out;
1506 qdict_put_str(options, "server.type", "unix");
1507 qdict_put_str(options, "server.path", qp->p[0].value);
1508 } else {
1509 QString *host;
1510 char *port_str;
1512 /* nbd[+tcp]://host[:port]/export */
1513 if (!uri->server) {
1514 ret = -EINVAL;
1515 goto out;
1518 /* strip braces from literal IPv6 address */
1519 if (uri->server[0] == '[') {
1520 host = qstring_from_substr(uri->server, 1,
1521 strlen(uri->server) - 1);
1522 } else {
1523 host = qstring_from_str(uri->server);
1526 qdict_put_str(options, "server.type", "inet");
1527 qdict_put(options, "server.host", host);
1529 port_str = g_strdup_printf("%d", uri->port ?: NBD_DEFAULT_PORT);
1530 qdict_put_str(options, "server.port", port_str);
1531 g_free(port_str);
1534 out:
1535 if (qp) {
1536 query_params_free(qp);
1538 uri_free(uri);
1539 return ret;
1542 static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
1544 const QDictEntry *e;
1546 for (e = qdict_first(options); e; e = qdict_next(options, e)) {
1547 if (!strcmp(e->key, "host") ||
1548 !strcmp(e->key, "port") ||
1549 !strcmp(e->key, "path") ||
1550 !strcmp(e->key, "export") ||
1551 strstart(e->key, "server.", NULL))
1553 error_setg(errp, "Option '%s' cannot be used with a file name",
1554 e->key);
1555 return true;
1559 return false;
1562 static void nbd_parse_filename(const char *filename, QDict *options,
1563 Error **errp)
1565 g_autofree char *file = NULL;
1566 char *export_name;
1567 const char *host_spec;
1568 const char *unixpath;
1570 if (nbd_has_filename_options_conflict(options, errp)) {
1571 return;
1574 if (strstr(filename, "://")) {
1575 int ret = nbd_parse_uri(filename, options);
1576 if (ret < 0) {
1577 error_setg(errp, "No valid URL specified");
1579 return;
1582 file = g_strdup(filename);
1584 export_name = strstr(file, EN_OPTSTR);
1585 if (export_name) {
1586 if (export_name[strlen(EN_OPTSTR)] == 0) {
1587 return;
1589 export_name[0] = 0; /* truncate 'file' */
1590 export_name += strlen(EN_OPTSTR);
1592 qdict_put_str(options, "export", export_name);
1595 /* extract the host_spec - fail if it's not nbd:... */
1596 if (!strstart(file, "nbd:", &host_spec)) {
1597 error_setg(errp, "File name string for NBD must start with 'nbd:'");
1598 return;
1601 if (!*host_spec) {
1602 return;
1605 /* are we a UNIX or TCP socket? */
1606 if (strstart(host_spec, "unix:", &unixpath)) {
1607 qdict_put_str(options, "server.type", "unix");
1608 qdict_put_str(options, "server.path", unixpath);
1609 } else {
1610 InetSocketAddress *addr = g_new(InetSocketAddress, 1);
1612 if (inet_parse(addr, host_spec, errp)) {
1613 goto out_inet;
1616 qdict_put_str(options, "server.type", "inet");
1617 qdict_put_str(options, "server.host", addr->host);
1618 qdict_put_str(options, "server.port", addr->port);
1619 out_inet:
1620 qapi_free_InetSocketAddress(addr);
1624 static bool nbd_process_legacy_socket_options(QDict *output_options,
1625 QemuOpts *legacy_opts,
1626 Error **errp)
1628 const char *path = qemu_opt_get(legacy_opts, "path");
1629 const char *host = qemu_opt_get(legacy_opts, "host");
1630 const char *port = qemu_opt_get(legacy_opts, "port");
1631 const QDictEntry *e;
1633 if (!path && !host && !port) {
1634 return true;
1637 for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
1639 if (strstart(e->key, "server.", NULL)) {
1640 error_setg(errp, "Cannot use 'server' and path/host/port at the "
1641 "same time");
1642 return false;
1646 if (path && host) {
1647 error_setg(errp, "path and host may not be used at the same time");
1648 return false;
1649 } else if (path) {
1650 if (port) {
1651 error_setg(errp, "port may not be used without host");
1652 return false;
1655 qdict_put_str(output_options, "server.type", "unix");
1656 qdict_put_str(output_options, "server.path", path);
1657 } else if (host) {
1658 qdict_put_str(output_options, "server.type", "inet");
1659 qdict_put_str(output_options, "server.host", host);
1660 qdict_put_str(output_options, "server.port",
1661 port ?: stringify(NBD_DEFAULT_PORT));
1664 return true;
1667 static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options,
1668 Error **errp)
1670 SocketAddress *saddr = NULL;
1671 QDict *addr = NULL;
1672 Visitor *iv = NULL;
1674 qdict_extract_subqdict(options, &addr, "server.");
1675 if (!qdict_size(addr)) {
1676 error_setg(errp, "NBD server address missing");
1677 goto done;
1680 iv = qobject_input_visitor_new_flat_confused(addr, errp);
1681 if (!iv) {
1682 goto done;
1685 if (!visit_type_SocketAddress(iv, NULL, &saddr, errp)) {
1686 goto done;
1689 if (socket_address_parse_named_fd(saddr, errp) < 0) {
1690 qapi_free_SocketAddress(saddr);
1691 saddr = NULL;
1692 goto done;
1695 done:
1696 qobject_unref(addr);
1697 visit_free(iv);
1698 return saddr;
1701 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
1703 Object *obj;
1704 QCryptoTLSCreds *creds;
1706 obj = object_resolve_path_component(
1707 object_get_objects_root(), id);
1708 if (!obj) {
1709 error_setg(errp, "No TLS credentials with id '%s'",
1710 id);
1711 return NULL;
1713 creds = (QCryptoTLSCreds *)
1714 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
1715 if (!creds) {
1716 error_setg(errp, "Object with id '%s' is not TLS credentials",
1717 id);
1718 return NULL;
1721 if (!qcrypto_tls_creds_check_endpoint(creds,
1722 QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT,
1723 errp)) {
1724 return NULL;
1726 object_ref(obj);
1727 return creds;
1731 static QemuOptsList nbd_runtime_opts = {
1732 .name = "nbd",
1733 .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
1734 .desc = {
1736 .name = "host",
1737 .type = QEMU_OPT_STRING,
1738 .help = "TCP host to connect to",
1741 .name = "port",
1742 .type = QEMU_OPT_STRING,
1743 .help = "TCP port to connect to",
1746 .name = "path",
1747 .type = QEMU_OPT_STRING,
1748 .help = "Unix socket path to connect to",
1751 .name = "export",
1752 .type = QEMU_OPT_STRING,
1753 .help = "Name of the NBD export to open",
1756 .name = "tls-creds",
1757 .type = QEMU_OPT_STRING,
1758 .help = "ID of the TLS credentials to use",
1761 .name = "tls-hostname",
1762 .type = QEMU_OPT_STRING,
1763 .help = "Override hostname for validating TLS x509 certificate",
1766 .name = "x-dirty-bitmap",
1767 .type = QEMU_OPT_STRING,
1768 .help = "experimental: expose named dirty bitmap in place of "
1769 "block status",
1772 .name = "reconnect-delay",
1773 .type = QEMU_OPT_NUMBER,
1774 .help = "On an unexpected disconnect, the nbd client tries to "
1775 "connect again until succeeding or encountering a serious "
1776 "error. During the first @reconnect-delay seconds, all "
1777 "requests are paused and will be rerun on a successful "
1778 "reconnect. After that time, any delayed requests and all "
1779 "future requests before a successful reconnect will "
1780 "immediately fail. Default 0",
1783 .name = "open-timeout",
1784 .type = QEMU_OPT_NUMBER,
1785 .help = "In seconds. If zero, the nbd driver tries the connection "
1786 "only once, and fails to open if the connection fails. "
1787 "If non-zero, the nbd driver will repeat connection "
1788 "attempts until successful or until @open-timeout seconds "
1789 "have elapsed. Default 0",
1791 { /* end of list */ }
1795 static int nbd_process_options(BlockDriverState *bs, QDict *options,
1796 Error **errp)
1798 BDRVNBDState *s = bs->opaque;
1799 QemuOpts *opts;
1800 int ret = -EINVAL;
1802 opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
1803 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1804 goto error;
1807 /* Translate @host, @port, and @path to a SocketAddress */
1808 if (!nbd_process_legacy_socket_options(options, opts, errp)) {
1809 goto error;
1812 /* Pop the config into our state object. Exit if invalid. */
1813 s->saddr = nbd_config(s, options, errp);
1814 if (!s->saddr) {
1815 goto error;
1818 s->export = g_strdup(qemu_opt_get(opts, "export"));
1819 if (s->export && strlen(s->export) > NBD_MAX_STRING_SIZE) {
1820 error_setg(errp, "export name too long to send to server");
1821 goto error;
1824 s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
1825 if (s->tlscredsid) {
1826 s->tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
1827 if (!s->tlscreds) {
1828 goto error;
1831 s->tlshostname = g_strdup(qemu_opt_get(opts, "tls-hostname"));
1832 if (!s->tlshostname &&
1833 s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
1834 s->tlshostname = g_strdup(s->saddr->u.inet.host);
1838 s->x_dirty_bitmap = g_strdup(qemu_opt_get(opts, "x-dirty-bitmap"));
1839 if (s->x_dirty_bitmap && strlen(s->x_dirty_bitmap) > NBD_MAX_STRING_SIZE) {
1840 error_setg(errp, "x-dirty-bitmap query too long to send to server");
1841 goto error;
1844 s->reconnect_delay = qemu_opt_get_number(opts, "reconnect-delay", 0);
1845 s->open_timeout = qemu_opt_get_number(opts, "open-timeout", 0);
1847 ret = 0;
1849 error:
1850 qemu_opts_del(opts);
1851 return ret;
1854 static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
1855 Error **errp)
1857 int ret;
1858 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1860 s->bs = bs;
1861 qemu_co_mutex_init(&s->send_mutex);
1862 qemu_co_queue_init(&s->free_sema);
1863 qemu_co_mutex_init(&s->receive_mutex);
1865 if (!yank_register_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name), errp)) {
1866 return -EEXIST;
1869 ret = nbd_process_options(bs, options, errp);
1870 if (ret < 0) {
1871 goto fail;
1874 s->conn = nbd_client_connection_new(s->saddr, true, s->export,
1875 s->x_dirty_bitmap, s->tlscreds,
1876 s->tlshostname);
1878 if (s->open_timeout) {
1879 nbd_client_connection_enable_retry(s->conn);
1880 open_timer_init(s, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
1881 s->open_timeout * NANOSECONDS_PER_SECOND);
1884 s->state = NBD_CLIENT_CONNECTING_WAIT;
1885 ret = nbd_do_establish_connection(bs, errp);
1886 if (ret < 0) {
1887 goto fail;
1891 * The connect attempt is done, so we no longer need this timer.
1892 * Delete it, because we do not want it to be around when this node
1893 * is drained or closed.
1895 open_timer_del(s);
1897 nbd_client_connection_enable_retry(s->conn);
1899 return 0;
1901 fail:
1902 open_timer_del(s);
1903 nbd_clear_bdrvstate(bs);
1904 return ret;
1907 static int coroutine_fn nbd_co_flush(BlockDriverState *bs)
1909 return nbd_client_co_flush(bs);
1912 static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
1914 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1915 uint32_t min = s->info.min_block;
1916 uint32_t max = MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE, s->info.max_block);
1919 * If the server did not advertise an alignment:
1920 * - a size that is not sector-aligned implies that an alignment
1921 * of 1 can be used to access those tail bytes
1922 * - advertisement of block status requires an alignment of 1, so
1923 * that we don't violate block layer constraints that block
1924 * status is always aligned (as we can't control whether the
1925 * server will report sub-sector extents, such as a hole at EOF
1926 * on an unaligned POSIX file)
1927 * - otherwise, assume the server is so old that we are safer avoiding
1928 * sub-sector requests
1930 if (!min) {
1931 min = (!QEMU_IS_ALIGNED(s->info.size, BDRV_SECTOR_SIZE) ||
1932 s->info.base_allocation) ? 1 : BDRV_SECTOR_SIZE;
1935 bs->bl.request_alignment = min;
1936 bs->bl.max_pdiscard = QEMU_ALIGN_DOWN(INT_MAX, min);
1937 bs->bl.max_pwrite_zeroes = max;
1938 bs->bl.max_transfer = max;
1940 if (s->info.opt_block &&
1941 s->info.opt_block > bs->bl.opt_transfer) {
1942 bs->bl.opt_transfer = s->info.opt_block;
1946 static void nbd_close(BlockDriverState *bs)
1948 nbd_client_close(bs);
1949 nbd_clear_bdrvstate(bs);
1953 * NBD cannot truncate, but if the caller asks to truncate to the same size, or
1954 * to a smaller size with exact=false, there is no reason to fail the
1955 * operation.
1957 * Preallocation mode is ignored since it does not seems useful to fail when
1958 * we never change anything.
1960 static int coroutine_fn nbd_co_truncate(BlockDriverState *bs, int64_t offset,
1961 bool exact, PreallocMode prealloc,
1962 BdrvRequestFlags flags, Error **errp)
1964 BDRVNBDState *s = bs->opaque;
1966 if (offset != s->info.size && exact) {
1967 error_setg(errp, "Cannot resize NBD nodes");
1968 return -ENOTSUP;
1971 if (offset > s->info.size) {
1972 error_setg(errp, "Cannot grow NBD nodes");
1973 return -EINVAL;
1976 return 0;
1979 static int64_t nbd_getlength(BlockDriverState *bs)
1981 BDRVNBDState *s = bs->opaque;
1983 return s->info.size;
1986 static void nbd_refresh_filename(BlockDriverState *bs)
1988 BDRVNBDState *s = bs->opaque;
1989 const char *host = NULL, *port = NULL, *path = NULL;
1990 size_t len = 0;
1992 if (s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
1993 const InetSocketAddress *inet = &s->saddr->u.inet;
1994 if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) {
1995 host = inet->host;
1996 port = inet->port;
1998 } else if (s->saddr->type == SOCKET_ADDRESS_TYPE_UNIX) {
1999 path = s->saddr->u.q_unix.path;
2000 } /* else can't represent as pseudo-filename */
2002 if (path && s->export) {
2003 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2004 "nbd+unix:///%s?socket=%s", s->export, path);
2005 } else if (path && !s->export) {
2006 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2007 "nbd+unix://?socket=%s", path);
2008 } else if (host && s->export) {
2009 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2010 "nbd://%s:%s/%s", host, port, s->export);
2011 } else if (host && !s->export) {
2012 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2013 "nbd://%s:%s", host, port);
2015 if (len >= sizeof(bs->exact_filename)) {
2016 /* Name is too long to represent exactly, so leave it empty. */
2017 bs->exact_filename[0] = '\0';
2021 static char *nbd_dirname(BlockDriverState *bs, Error **errp)
2023 /* The generic bdrv_dirname() implementation is able to work out some
2024 * directory name for NBD nodes, but that would be wrong. So far there is no
2025 * specification for how "export paths" would work, so NBD does not have
2026 * directory names. */
2027 error_setg(errp, "Cannot generate a base directory for NBD nodes");
2028 return NULL;
2031 static const char *const nbd_strong_runtime_opts[] = {
2032 "path",
2033 "host",
2034 "port",
2035 "export",
2036 "tls-creds",
2037 "tls-hostname",
2038 "server.",
2040 NULL
2043 static void nbd_cancel_in_flight(BlockDriverState *bs)
2045 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2047 reconnect_delay_timer_del(s);
2049 if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
2050 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
2051 qemu_co_queue_restart_all(&s->free_sema);
2054 nbd_co_establish_connection_cancel(s->conn);
2057 static void nbd_attach_aio_context(BlockDriverState *bs,
2058 AioContext *new_context)
2060 BDRVNBDState *s = bs->opaque;
2062 /* The open_timer is used only during nbd_open() */
2063 assert(!s->open_timer);
2066 * The reconnect_delay_timer is scheduled in I/O paths when the
2067 * connection is lost, to cancel the reconnection attempt after a
2068 * given time. Once this attempt is done (successfully or not),
2069 * nbd_reconnect_attempt() ensures the timer is deleted before the
2070 * respective I/O request is resumed.
2071 * Since the AioContext can only be changed when a node is drained,
2072 * the reconnect_delay_timer cannot be active here.
2074 assert(!s->reconnect_delay_timer);
2076 if (s->ioc) {
2077 qio_channel_attach_aio_context(s->ioc, new_context);
2081 static void nbd_detach_aio_context(BlockDriverState *bs)
2083 BDRVNBDState *s = bs->opaque;
2085 assert(!s->open_timer);
2086 assert(!s->reconnect_delay_timer);
2088 if (s->ioc) {
2089 qio_channel_detach_aio_context(s->ioc);
2093 static BlockDriver bdrv_nbd = {
2094 .format_name = "nbd",
2095 .protocol_name = "nbd",
2096 .instance_size = sizeof(BDRVNBDState),
2097 .bdrv_parse_filename = nbd_parse_filename,
2098 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2099 .create_opts = &bdrv_create_opts_simple,
2100 .bdrv_file_open = nbd_open,
2101 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2102 .bdrv_co_preadv = nbd_client_co_preadv,
2103 .bdrv_co_pwritev = nbd_client_co_pwritev,
2104 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2105 .bdrv_close = nbd_close,
2106 .bdrv_co_flush_to_os = nbd_co_flush,
2107 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2108 .bdrv_refresh_limits = nbd_refresh_limits,
2109 .bdrv_co_truncate = nbd_co_truncate,
2110 .bdrv_getlength = nbd_getlength,
2111 .bdrv_refresh_filename = nbd_refresh_filename,
2112 .bdrv_co_block_status = nbd_client_co_block_status,
2113 .bdrv_dirname = nbd_dirname,
2114 .strong_runtime_opts = nbd_strong_runtime_opts,
2115 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2117 .bdrv_attach_aio_context = nbd_attach_aio_context,
2118 .bdrv_detach_aio_context = nbd_detach_aio_context,
2121 static BlockDriver bdrv_nbd_tcp = {
2122 .format_name = "nbd",
2123 .protocol_name = "nbd+tcp",
2124 .instance_size = sizeof(BDRVNBDState),
2125 .bdrv_parse_filename = nbd_parse_filename,
2126 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2127 .create_opts = &bdrv_create_opts_simple,
2128 .bdrv_file_open = nbd_open,
2129 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2130 .bdrv_co_preadv = nbd_client_co_preadv,
2131 .bdrv_co_pwritev = nbd_client_co_pwritev,
2132 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2133 .bdrv_close = nbd_close,
2134 .bdrv_co_flush_to_os = nbd_co_flush,
2135 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2136 .bdrv_refresh_limits = nbd_refresh_limits,
2137 .bdrv_co_truncate = nbd_co_truncate,
2138 .bdrv_getlength = nbd_getlength,
2139 .bdrv_refresh_filename = nbd_refresh_filename,
2140 .bdrv_co_block_status = nbd_client_co_block_status,
2141 .bdrv_dirname = nbd_dirname,
2142 .strong_runtime_opts = nbd_strong_runtime_opts,
2143 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2145 .bdrv_attach_aio_context = nbd_attach_aio_context,
2146 .bdrv_detach_aio_context = nbd_detach_aio_context,
2149 static BlockDriver bdrv_nbd_unix = {
2150 .format_name = "nbd",
2151 .protocol_name = "nbd+unix",
2152 .instance_size = sizeof(BDRVNBDState),
2153 .bdrv_parse_filename = nbd_parse_filename,
2154 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2155 .create_opts = &bdrv_create_opts_simple,
2156 .bdrv_file_open = nbd_open,
2157 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2158 .bdrv_co_preadv = nbd_client_co_preadv,
2159 .bdrv_co_pwritev = nbd_client_co_pwritev,
2160 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2161 .bdrv_close = nbd_close,
2162 .bdrv_co_flush_to_os = nbd_co_flush,
2163 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2164 .bdrv_refresh_limits = nbd_refresh_limits,
2165 .bdrv_co_truncate = nbd_co_truncate,
2166 .bdrv_getlength = nbd_getlength,
2167 .bdrv_refresh_filename = nbd_refresh_filename,
2168 .bdrv_co_block_status = nbd_client_co_block_status,
2169 .bdrv_dirname = nbd_dirname,
2170 .strong_runtime_opts = nbd_strong_runtime_opts,
2171 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2173 .bdrv_attach_aio_context = nbd_attach_aio_context,
2174 .bdrv_detach_aio_context = nbd_detach_aio_context,
2177 static void bdrv_nbd_init(void)
2179 bdrv_register(&bdrv_nbd);
2180 bdrv_register(&bdrv_nbd_tcp);
2181 bdrv_register(&bdrv_nbd_unix);
2184 block_init(bdrv_nbd_init);