block/nbd: Delete reconnect delay timer when done
[qemu/armbru.git] / block / nbd.c
blob16cd7fef77c84f9f9812bfd0aa68d70c09b88ab0
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 bool reply_possible; /* reply header not yet received */
62 } NBDClientRequest;
64 typedef enum NBDClientState {
65 NBD_CLIENT_CONNECTING_WAIT,
66 NBD_CLIENT_CONNECTING_NOWAIT,
67 NBD_CLIENT_CONNECTED,
68 NBD_CLIENT_QUIT
69 } NBDClientState;
71 typedef struct BDRVNBDState {
72 QIOChannel *ioc; /* The current I/O channel */
73 NBDExportInfo info;
75 CoMutex send_mutex;
76 CoQueue free_sema;
78 CoMutex receive_mutex;
79 int in_flight;
80 NBDClientState state;
82 QEMUTimer *reconnect_delay_timer;
83 QEMUTimer *open_timer;
85 NBDClientRequest requests[MAX_NBD_REQUESTS];
86 NBDReply reply;
87 BlockDriverState *bs;
89 /* Connection parameters */
90 uint32_t reconnect_delay;
91 uint32_t open_timeout;
92 SocketAddress *saddr;
93 char *export, *tlscredsid;
94 QCryptoTLSCreds *tlscreds;
95 const char *hostname;
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 object_unref(OBJECT(s->tlscreds));
114 qapi_free_SocketAddress(s->saddr);
115 s->saddr = NULL;
116 g_free(s->export);
117 s->export = NULL;
118 g_free(s->tlscredsid);
119 s->tlscredsid = NULL;
120 g_free(s->x_dirty_bitmap);
121 s->x_dirty_bitmap = NULL;
124 static bool nbd_client_connected(BDRVNBDState *s)
126 return qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTED;
129 static bool nbd_recv_coroutine_wake_one(NBDClientRequest *req)
131 if (req->receiving) {
132 req->receiving = false;
133 aio_co_wake(req->coroutine);
134 return true;
137 return false;
140 static void nbd_recv_coroutines_wake(BDRVNBDState *s, bool all)
142 int i;
144 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
145 if (nbd_recv_coroutine_wake_one(&s->requests[i]) && !all) {
146 return;
151 static void nbd_channel_error(BDRVNBDState *s, int ret)
153 if (nbd_client_connected(s)) {
154 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
157 if (ret == -EIO) {
158 if (nbd_client_connected(s)) {
159 s->state = s->reconnect_delay ? NBD_CLIENT_CONNECTING_WAIT :
160 NBD_CLIENT_CONNECTING_NOWAIT;
162 } else {
163 s->state = NBD_CLIENT_QUIT;
166 nbd_recv_coroutines_wake(s, true);
169 static void reconnect_delay_timer_del(BDRVNBDState *s)
171 if (s->reconnect_delay_timer) {
172 timer_free(s->reconnect_delay_timer);
173 s->reconnect_delay_timer = NULL;
177 static void reconnect_delay_timer_cb(void *opaque)
179 BDRVNBDState *s = opaque;
181 if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT) {
182 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
183 nbd_co_establish_connection_cancel(s->conn);
184 while (qemu_co_enter_next(&s->free_sema, NULL)) {
185 /* Resume all queued requests */
189 reconnect_delay_timer_del(s);
192 static void reconnect_delay_timer_init(BDRVNBDState *s, uint64_t expire_time_ns)
194 if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTING_WAIT) {
195 return;
198 assert(!s->reconnect_delay_timer);
199 s->reconnect_delay_timer = aio_timer_new(bdrv_get_aio_context(s->bs),
200 QEMU_CLOCK_REALTIME,
201 SCALE_NS,
202 reconnect_delay_timer_cb, s);
203 timer_mod(s->reconnect_delay_timer, expire_time_ns);
206 static void nbd_teardown_connection(BlockDriverState *bs)
208 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
210 assert(!s->in_flight);
212 if (s->ioc) {
213 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
214 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
215 nbd_yank, s->bs);
216 object_unref(OBJECT(s->ioc));
217 s->ioc = NULL;
220 s->state = NBD_CLIENT_QUIT;
223 static void open_timer_del(BDRVNBDState *s)
225 if (s->open_timer) {
226 timer_free(s->open_timer);
227 s->open_timer = NULL;
231 static void open_timer_cb(void *opaque)
233 BDRVNBDState *s = opaque;
235 nbd_co_establish_connection_cancel(s->conn);
236 open_timer_del(s);
239 static void open_timer_init(BDRVNBDState *s, uint64_t expire_time_ns)
241 assert(!s->open_timer);
242 s->open_timer = aio_timer_new(bdrv_get_aio_context(s->bs),
243 QEMU_CLOCK_REALTIME,
244 SCALE_NS,
245 open_timer_cb, s);
246 timer_mod(s->open_timer, expire_time_ns);
249 static bool nbd_client_connecting(BDRVNBDState *s)
251 NBDClientState state = qatomic_load_acquire(&s->state);
252 return state == NBD_CLIENT_CONNECTING_WAIT ||
253 state == NBD_CLIENT_CONNECTING_NOWAIT;
256 static bool nbd_client_connecting_wait(BDRVNBDState *s)
258 return qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT;
262 * Update @bs with information learned during a completed negotiation process.
263 * Return failure if the server's advertised options are incompatible with the
264 * client's needs.
266 static int nbd_handle_updated_info(BlockDriverState *bs, Error **errp)
268 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
269 int ret;
271 if (s->x_dirty_bitmap) {
272 if (!s->info.base_allocation) {
273 error_setg(errp, "requested x-dirty-bitmap %s not found",
274 s->x_dirty_bitmap);
275 return -EINVAL;
277 if (strcmp(s->x_dirty_bitmap, "qemu:allocation-depth") == 0) {
278 s->alloc_depth = true;
282 if (s->info.flags & NBD_FLAG_READ_ONLY) {
283 ret = bdrv_apply_auto_read_only(bs, "NBD export is read-only", errp);
284 if (ret < 0) {
285 return ret;
289 if (s->info.flags & NBD_FLAG_SEND_FUA) {
290 bs->supported_write_flags = BDRV_REQ_FUA;
291 bs->supported_zero_flags |= BDRV_REQ_FUA;
294 if (s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES) {
295 bs->supported_zero_flags |= BDRV_REQ_MAY_UNMAP;
296 if (s->info.flags & NBD_FLAG_SEND_FAST_ZERO) {
297 bs->supported_zero_flags |= BDRV_REQ_NO_FALLBACK;
301 trace_nbd_client_handshake_success(s->export);
303 return 0;
306 int coroutine_fn nbd_co_do_establish_connection(BlockDriverState *bs,
307 Error **errp)
309 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
310 int ret;
311 bool blocking = nbd_client_connecting_wait(s);
313 assert(!s->ioc);
315 s->ioc = nbd_co_establish_connection(s->conn, &s->info, blocking, errp);
316 if (!s->ioc) {
317 return -ECONNREFUSED;
320 yank_register_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name), nbd_yank,
321 bs);
323 ret = nbd_handle_updated_info(s->bs, NULL);
324 if (ret < 0) {
326 * We have connected, but must fail for other reasons.
327 * Send NBD_CMD_DISC as a courtesy to the server.
329 NBDRequest request = { .type = NBD_CMD_DISC };
331 nbd_send_request(s->ioc, &request);
333 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
334 nbd_yank, bs);
335 object_unref(OBJECT(s->ioc));
336 s->ioc = NULL;
338 return ret;
341 qio_channel_set_blocking(s->ioc, false, NULL);
342 qio_channel_attach_aio_context(s->ioc, bdrv_get_aio_context(bs));
344 /* successfully connected */
345 s->state = NBD_CLIENT_CONNECTED;
346 qemu_co_queue_restart_all(&s->free_sema);
348 return 0;
351 /* called under s->send_mutex */
352 static coroutine_fn void nbd_reconnect_attempt(BDRVNBDState *s)
354 assert(nbd_client_connecting(s));
355 assert(s->in_flight == 0);
357 if (nbd_client_connecting_wait(s) && s->reconnect_delay &&
358 !s->reconnect_delay_timer)
361 * It's first reconnect attempt after switching to
362 * NBD_CLIENT_CONNECTING_WAIT
364 reconnect_delay_timer_init(s,
365 qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
366 s->reconnect_delay * NANOSECONDS_PER_SECOND);
370 * Now we are sure that nobody is accessing the channel, and no one will
371 * try until we set the state to CONNECTED.
374 /* Finalize previous connection if any */
375 if (s->ioc) {
376 qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
377 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
378 nbd_yank, s->bs);
379 object_unref(OBJECT(s->ioc));
380 s->ioc = NULL;
383 nbd_co_do_establish_connection(s->bs, NULL);
386 * The reconnect attempt is done (maybe successfully, maybe not), so
387 * we no longer need this timer. Delete it so it will not outlive
388 * this I/O request (so draining removes all timers).
390 reconnect_delay_timer_del(s);
393 static coroutine_fn int nbd_receive_replies(BDRVNBDState *s, uint64_t handle)
395 int ret;
396 uint64_t ind = HANDLE_TO_INDEX(s, handle), ind2;
397 QEMU_LOCK_GUARD(&s->receive_mutex);
399 while (true) {
400 if (s->reply.handle == handle) {
401 /* We are done */
402 return 0;
405 if (!nbd_client_connected(s)) {
406 return -EIO;
409 if (s->reply.handle != 0) {
411 * Some other request is being handled now. It should already be
412 * woken by whoever set s->reply.handle (or never wait in this
413 * yield). So, we should not wake it here.
415 ind2 = HANDLE_TO_INDEX(s, s->reply.handle);
416 assert(!s->requests[ind2].receiving);
418 s->requests[ind].receiving = true;
419 qemu_co_mutex_unlock(&s->receive_mutex);
421 qemu_coroutine_yield();
423 * We may be woken for 3 reasons:
424 * 1. From this function, executing in parallel coroutine, when our
425 * handle is received.
426 * 2. From nbd_channel_error(), when connection is lost.
427 * 3. From nbd_co_receive_one_chunk(), when previous request is
428 * finished and s->reply.handle set to 0.
429 * Anyway, it's OK to lock the mutex and go to the next iteration.
432 qemu_co_mutex_lock(&s->receive_mutex);
433 assert(!s->requests[ind].receiving);
434 continue;
437 /* We are under mutex and handle is 0. We have to do the dirty work. */
438 assert(s->reply.handle == 0);
439 ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, NULL);
440 if (ret <= 0) {
441 ret = ret ? ret : -EIO;
442 nbd_channel_error(s, ret);
443 return ret;
445 if (nbd_reply_is_structured(&s->reply) && !s->info.structured_reply) {
446 nbd_channel_error(s, -EINVAL);
447 return -EINVAL;
449 if (s->reply.handle == handle) {
450 /* We are done */
451 return 0;
453 ind2 = HANDLE_TO_INDEX(s, s->reply.handle);
454 if (ind2 >= MAX_NBD_REQUESTS || !s->requests[ind2].reply_possible) {
455 nbd_channel_error(s, -EINVAL);
456 return -EINVAL;
458 nbd_recv_coroutine_wake_one(&s->requests[ind2]);
462 static int nbd_co_send_request(BlockDriverState *bs,
463 NBDRequest *request,
464 QEMUIOVector *qiov)
466 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
467 int rc, i = -1;
469 qemu_co_mutex_lock(&s->send_mutex);
471 while (s->in_flight == MAX_NBD_REQUESTS ||
472 (!nbd_client_connected(s) && s->in_flight > 0))
474 qemu_co_queue_wait(&s->free_sema, &s->send_mutex);
477 if (nbd_client_connecting(s)) {
478 nbd_reconnect_attempt(s);
481 if (!nbd_client_connected(s)) {
482 rc = -EIO;
483 goto err;
486 s->in_flight++;
488 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
489 if (s->requests[i].coroutine == NULL) {
490 break;
494 g_assert(qemu_in_coroutine());
495 assert(i < MAX_NBD_REQUESTS);
497 s->requests[i].coroutine = qemu_coroutine_self();
498 s->requests[i].offset = request->from;
499 s->requests[i].receiving = false;
500 s->requests[i].reply_possible = true;
502 request->handle = INDEX_TO_HANDLE(s, i);
504 assert(s->ioc);
506 if (qiov) {
507 qio_channel_set_cork(s->ioc, true);
508 rc = nbd_send_request(s->ioc, request);
509 if (nbd_client_connected(s) && rc >= 0) {
510 if (qio_channel_writev_all(s->ioc, qiov->iov, qiov->niov,
511 NULL) < 0) {
512 rc = -EIO;
514 } else if (rc >= 0) {
515 rc = -EIO;
517 qio_channel_set_cork(s->ioc, false);
518 } else {
519 rc = nbd_send_request(s->ioc, request);
522 err:
523 if (rc < 0) {
524 nbd_channel_error(s, rc);
525 if (i != -1) {
526 s->requests[i].coroutine = NULL;
527 s->in_flight--;
528 qemu_co_queue_next(&s->free_sema);
531 qemu_co_mutex_unlock(&s->send_mutex);
532 return rc;
535 static inline uint16_t payload_advance16(uint8_t **payload)
537 *payload += 2;
538 return lduw_be_p(*payload - 2);
541 static inline uint32_t payload_advance32(uint8_t **payload)
543 *payload += 4;
544 return ldl_be_p(*payload - 4);
547 static inline uint64_t payload_advance64(uint8_t **payload)
549 *payload += 8;
550 return ldq_be_p(*payload - 8);
553 static int nbd_parse_offset_hole_payload(BDRVNBDState *s,
554 NBDStructuredReplyChunk *chunk,
555 uint8_t *payload, uint64_t orig_offset,
556 QEMUIOVector *qiov, Error **errp)
558 uint64_t offset;
559 uint32_t hole_size;
561 if (chunk->length != sizeof(offset) + sizeof(hole_size)) {
562 error_setg(errp, "Protocol error: invalid payload for "
563 "NBD_REPLY_TYPE_OFFSET_HOLE");
564 return -EINVAL;
567 offset = payload_advance64(&payload);
568 hole_size = payload_advance32(&payload);
570 if (!hole_size || offset < orig_offset || hole_size > qiov->size ||
571 offset > orig_offset + qiov->size - hole_size) {
572 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
573 " region");
574 return -EINVAL;
576 if (s->info.min_block &&
577 !QEMU_IS_ALIGNED(hole_size, s->info.min_block)) {
578 trace_nbd_structured_read_compliance("hole");
581 qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size);
583 return 0;
587 * nbd_parse_blockstatus_payload
588 * Based on our request, we expect only one extent in reply, for the
589 * base:allocation context.
591 static int nbd_parse_blockstatus_payload(BDRVNBDState *s,
592 NBDStructuredReplyChunk *chunk,
593 uint8_t *payload, uint64_t orig_length,
594 NBDExtent *extent, Error **errp)
596 uint32_t context_id;
598 /* The server succeeded, so it must have sent [at least] one extent */
599 if (chunk->length < sizeof(context_id) + sizeof(*extent)) {
600 error_setg(errp, "Protocol error: invalid payload for "
601 "NBD_REPLY_TYPE_BLOCK_STATUS");
602 return -EINVAL;
605 context_id = payload_advance32(&payload);
606 if (s->info.context_id != context_id) {
607 error_setg(errp, "Protocol error: unexpected context id %d for "
608 "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
609 "id is %d", context_id,
610 s->info.context_id);
611 return -EINVAL;
614 extent->length = payload_advance32(&payload);
615 extent->flags = payload_advance32(&payload);
617 if (extent->length == 0) {
618 error_setg(errp, "Protocol error: server sent status chunk with "
619 "zero length");
620 return -EINVAL;
624 * A server sending unaligned block status is in violation of the
625 * protocol, but as qemu-nbd 3.1 is such a server (at least for
626 * POSIX files that are not a multiple of 512 bytes, since qemu
627 * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
628 * still sees an implicit hole beyond the real EOF), it's nicer to
629 * work around the misbehaving server. If the request included
630 * more than the final unaligned block, truncate it back to an
631 * aligned result; if the request was only the final block, round
632 * up to the full block and change the status to fully-allocated
633 * (always a safe status, even if it loses information).
635 if (s->info.min_block && !QEMU_IS_ALIGNED(extent->length,
636 s->info.min_block)) {
637 trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
638 if (extent->length > s->info.min_block) {
639 extent->length = QEMU_ALIGN_DOWN(extent->length,
640 s->info.min_block);
641 } else {
642 extent->length = s->info.min_block;
643 extent->flags = 0;
648 * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
649 * sent us any more than one extent, nor should it have included
650 * status beyond our request in that extent. However, it's easy
651 * enough to ignore the server's noncompliance without killing the
652 * connection; just ignore trailing extents, and clamp things to
653 * the length of our request.
655 if (chunk->length > sizeof(context_id) + sizeof(*extent)) {
656 trace_nbd_parse_blockstatus_compliance("more than one extent");
658 if (extent->length > orig_length) {
659 extent->length = orig_length;
660 trace_nbd_parse_blockstatus_compliance("extent length too large");
664 * HACK: if we are using x-dirty-bitmaps to access
665 * qemu:allocation-depth, treat all depths > 2 the same as 2,
666 * since nbd_client_co_block_status is only expecting the low two
667 * bits to be set.
669 if (s->alloc_depth && extent->flags > 2) {
670 extent->flags = 2;
673 return 0;
677 * nbd_parse_error_payload
678 * on success @errp contains message describing nbd error reply
680 static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
681 uint8_t *payload, int *request_ret,
682 Error **errp)
684 uint32_t error;
685 uint16_t message_size;
687 assert(chunk->type & (1 << 15));
689 if (chunk->length < sizeof(error) + sizeof(message_size)) {
690 error_setg(errp,
691 "Protocol error: invalid payload for structured error");
692 return -EINVAL;
695 error = nbd_errno_to_system_errno(payload_advance32(&payload));
696 if (error == 0) {
697 error_setg(errp, "Protocol error: server sent structured error chunk "
698 "with error = 0");
699 return -EINVAL;
702 *request_ret = -error;
703 message_size = payload_advance16(&payload);
705 if (message_size > chunk->length - sizeof(error) - sizeof(message_size)) {
706 error_setg(errp, "Protocol error: server sent structured error chunk "
707 "with incorrect message size");
708 return -EINVAL;
711 /* TODO: Add a trace point to mention the server complaint */
713 /* TODO handle ERROR_OFFSET */
715 return 0;
718 static int nbd_co_receive_offset_data_payload(BDRVNBDState *s,
719 uint64_t orig_offset,
720 QEMUIOVector *qiov, Error **errp)
722 QEMUIOVector sub_qiov;
723 uint64_t offset;
724 size_t data_size;
725 int ret;
726 NBDStructuredReplyChunk *chunk = &s->reply.structured;
728 assert(nbd_reply_is_structured(&s->reply));
730 /* The NBD spec requires at least one byte of payload */
731 if (chunk->length <= sizeof(offset)) {
732 error_setg(errp, "Protocol error: invalid payload for "
733 "NBD_REPLY_TYPE_OFFSET_DATA");
734 return -EINVAL;
737 if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) {
738 return -EIO;
741 data_size = chunk->length - sizeof(offset);
742 assert(data_size);
743 if (offset < orig_offset || data_size > qiov->size ||
744 offset > orig_offset + qiov->size - data_size) {
745 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
746 " region");
747 return -EINVAL;
749 if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) {
750 trace_nbd_structured_read_compliance("data");
753 qemu_iovec_init(&sub_qiov, qiov->niov);
754 qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size);
755 ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);
756 qemu_iovec_destroy(&sub_qiov);
758 return ret < 0 ? -EIO : 0;
761 #define NBD_MAX_MALLOC_PAYLOAD 1000
762 static coroutine_fn int nbd_co_receive_structured_payload(
763 BDRVNBDState *s, void **payload, Error **errp)
765 int ret;
766 uint32_t len;
768 assert(nbd_reply_is_structured(&s->reply));
770 len = s->reply.structured.length;
772 if (len == 0) {
773 return 0;
776 if (payload == NULL) {
777 error_setg(errp, "Unexpected structured payload");
778 return -EINVAL;
781 if (len > NBD_MAX_MALLOC_PAYLOAD) {
782 error_setg(errp, "Payload too large");
783 return -EINVAL;
786 *payload = g_new(char, len);
787 ret = nbd_read(s->ioc, *payload, len, "structured payload", errp);
788 if (ret < 0) {
789 g_free(*payload);
790 *payload = NULL;
791 return ret;
794 return 0;
798 * nbd_co_do_receive_one_chunk
799 * for simple reply:
800 * set request_ret to received reply error
801 * if qiov is not NULL: read payload to @qiov
802 * for structured reply chunk:
803 * if error chunk: read payload, set @request_ret, do not set @payload
804 * else if offset_data chunk: read payload data to @qiov, do not set @payload
805 * else: read payload to @payload
807 * If function fails, @errp contains corresponding error message, and the
808 * connection with the server is suspect. If it returns 0, then the
809 * transaction succeeded (although @request_ret may be a negative errno
810 * corresponding to the server's error reply), and errp is unchanged.
812 static coroutine_fn int nbd_co_do_receive_one_chunk(
813 BDRVNBDState *s, uint64_t handle, bool only_structured,
814 int *request_ret, QEMUIOVector *qiov, void **payload, Error **errp)
816 int ret;
817 int i = HANDLE_TO_INDEX(s, handle);
818 void *local_payload = NULL;
819 NBDStructuredReplyChunk *chunk;
821 if (payload) {
822 *payload = NULL;
824 *request_ret = 0;
826 nbd_receive_replies(s, handle);
827 if (!nbd_client_connected(s)) {
828 error_setg(errp, "Connection closed");
829 return -EIO;
831 assert(s->ioc);
833 assert(s->reply.handle == handle);
835 if (nbd_reply_is_simple(&s->reply)) {
836 if (only_structured) {
837 error_setg(errp, "Protocol error: simple reply when structured "
838 "reply chunk was expected");
839 return -EINVAL;
842 *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error);
843 if (*request_ret < 0 || !qiov) {
844 return 0;
847 return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov,
848 errp) < 0 ? -EIO : 0;
851 /* handle structured reply chunk */
852 assert(s->info.structured_reply);
853 chunk = &s->reply.structured;
855 if (chunk->type == NBD_REPLY_TYPE_NONE) {
856 if (!(chunk->flags & NBD_REPLY_FLAG_DONE)) {
857 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
858 " NBD_REPLY_FLAG_DONE flag set");
859 return -EINVAL;
861 if (chunk->length) {
862 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
863 " nonzero length");
864 return -EINVAL;
866 return 0;
869 if (chunk->type == NBD_REPLY_TYPE_OFFSET_DATA) {
870 if (!qiov) {
871 error_setg(errp, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
872 return -EINVAL;
875 return nbd_co_receive_offset_data_payload(s, s->requests[i].offset,
876 qiov, errp);
879 if (nbd_reply_type_is_error(chunk->type)) {
880 payload = &local_payload;
883 ret = nbd_co_receive_structured_payload(s, payload, errp);
884 if (ret < 0) {
885 return ret;
888 if (nbd_reply_type_is_error(chunk->type)) {
889 ret = nbd_parse_error_payload(chunk, local_payload, request_ret, errp);
890 g_free(local_payload);
891 return ret;
894 return 0;
898 * nbd_co_receive_one_chunk
899 * Read reply, wake up connection_co and set s->quit if needed.
900 * Return value is a fatal error code or normal nbd reply error code
902 static coroutine_fn int nbd_co_receive_one_chunk(
903 BDRVNBDState *s, uint64_t handle, bool only_structured,
904 int *request_ret, QEMUIOVector *qiov, NBDReply *reply, void **payload,
905 Error **errp)
907 int ret = nbd_co_do_receive_one_chunk(s, handle, only_structured,
908 request_ret, qiov, payload, errp);
910 if (ret < 0) {
911 memset(reply, 0, sizeof(*reply));
912 nbd_channel_error(s, ret);
913 } else {
914 /* For assert at loop start in nbd_connection_entry */
915 *reply = s->reply;
917 s->reply.handle = 0;
919 nbd_recv_coroutines_wake(s, false);
921 return ret;
924 typedef struct NBDReplyChunkIter {
925 int ret;
926 int request_ret;
927 Error *err;
928 bool done, only_structured;
929 } NBDReplyChunkIter;
931 static void nbd_iter_channel_error(NBDReplyChunkIter *iter,
932 int ret, Error **local_err)
934 assert(local_err && *local_err);
935 assert(ret < 0);
937 if (!iter->ret) {
938 iter->ret = ret;
939 error_propagate(&iter->err, *local_err);
940 } else {
941 error_free(*local_err);
944 *local_err = NULL;
947 static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret)
949 assert(ret < 0);
951 if (!iter->request_ret) {
952 iter->request_ret = ret;
957 * NBD_FOREACH_REPLY_CHUNK
958 * The pointer stored in @payload requires g_free() to free it.
960 #define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
961 qiov, reply, payload) \
962 for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
963 nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
966 * nbd_reply_chunk_iter_receive
967 * The pointer stored in @payload requires g_free() to free it.
969 static bool nbd_reply_chunk_iter_receive(BDRVNBDState *s,
970 NBDReplyChunkIter *iter,
971 uint64_t handle,
972 QEMUIOVector *qiov, NBDReply *reply,
973 void **payload)
975 int ret, request_ret;
976 NBDReply local_reply;
977 NBDStructuredReplyChunk *chunk;
978 Error *local_err = NULL;
979 if (!nbd_client_connected(s)) {
980 error_setg(&local_err, "Connection closed");
981 nbd_iter_channel_error(iter, -EIO, &local_err);
982 goto break_loop;
985 if (iter->done) {
986 /* Previous iteration was last. */
987 goto break_loop;
990 if (reply == NULL) {
991 reply = &local_reply;
994 ret = nbd_co_receive_one_chunk(s, handle, iter->only_structured,
995 &request_ret, qiov, reply, payload,
996 &local_err);
997 if (ret < 0) {
998 nbd_iter_channel_error(iter, ret, &local_err);
999 } else if (request_ret < 0) {
1000 nbd_iter_request_error(iter, request_ret);
1003 /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
1004 if (nbd_reply_is_simple(reply) || !nbd_client_connected(s)) {
1005 goto break_loop;
1008 chunk = &reply->structured;
1009 iter->only_structured = true;
1011 if (chunk->type == NBD_REPLY_TYPE_NONE) {
1012 /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
1013 assert(chunk->flags & NBD_REPLY_FLAG_DONE);
1014 goto break_loop;
1017 if (chunk->flags & NBD_REPLY_FLAG_DONE) {
1018 /* This iteration is last. */
1019 iter->done = true;
1022 /* Execute the loop body */
1023 return true;
1025 break_loop:
1026 s->requests[HANDLE_TO_INDEX(s, handle)].coroutine = NULL;
1028 qemu_co_mutex_lock(&s->send_mutex);
1029 s->in_flight--;
1030 qemu_co_queue_next(&s->free_sema);
1031 qemu_co_mutex_unlock(&s->send_mutex);
1033 return false;
1036 static int nbd_co_receive_return_code(BDRVNBDState *s, uint64_t handle,
1037 int *request_ret, Error **errp)
1039 NBDReplyChunkIter iter;
1041 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, NULL, NULL) {
1042 /* nbd_reply_chunk_iter_receive does all the work */
1045 error_propagate(errp, iter.err);
1046 *request_ret = iter.request_ret;
1047 return iter.ret;
1050 static int nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t handle,
1051 uint64_t offset, QEMUIOVector *qiov,
1052 int *request_ret, Error **errp)
1054 NBDReplyChunkIter iter;
1055 NBDReply reply;
1056 void *payload = NULL;
1057 Error *local_err = NULL;
1059 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, s->info.structured_reply,
1060 qiov, &reply, &payload)
1062 int ret;
1063 NBDStructuredReplyChunk *chunk = &reply.structured;
1065 assert(nbd_reply_is_structured(&reply));
1067 switch (chunk->type) {
1068 case NBD_REPLY_TYPE_OFFSET_DATA:
1070 * special cased in nbd_co_receive_one_chunk, data is already
1071 * in qiov
1073 break;
1074 case NBD_REPLY_TYPE_OFFSET_HOLE:
1075 ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload,
1076 offset, qiov, &local_err);
1077 if (ret < 0) {
1078 nbd_channel_error(s, ret);
1079 nbd_iter_channel_error(&iter, ret, &local_err);
1081 break;
1082 default:
1083 if (!nbd_reply_type_is_error(chunk->type)) {
1084 /* not allowed reply type */
1085 nbd_channel_error(s, -EINVAL);
1086 error_setg(&local_err,
1087 "Unexpected reply type: %d (%s) for CMD_READ",
1088 chunk->type, nbd_reply_type_lookup(chunk->type));
1089 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1093 g_free(payload);
1094 payload = NULL;
1097 error_propagate(errp, iter.err);
1098 *request_ret = iter.request_ret;
1099 return iter.ret;
1102 static int nbd_co_receive_blockstatus_reply(BDRVNBDState *s,
1103 uint64_t handle, uint64_t length,
1104 NBDExtent *extent,
1105 int *request_ret, Error **errp)
1107 NBDReplyChunkIter iter;
1108 NBDReply reply;
1109 void *payload = NULL;
1110 Error *local_err = NULL;
1111 bool received = false;
1113 assert(!extent->length);
1114 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, &reply, &payload) {
1115 int ret;
1116 NBDStructuredReplyChunk *chunk = &reply.structured;
1118 assert(nbd_reply_is_structured(&reply));
1120 switch (chunk->type) {
1121 case NBD_REPLY_TYPE_BLOCK_STATUS:
1122 if (received) {
1123 nbd_channel_error(s, -EINVAL);
1124 error_setg(&local_err, "Several BLOCK_STATUS chunks in reply");
1125 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1127 received = true;
1129 ret = nbd_parse_blockstatus_payload(s, &reply.structured,
1130 payload, length, extent,
1131 &local_err);
1132 if (ret < 0) {
1133 nbd_channel_error(s, ret);
1134 nbd_iter_channel_error(&iter, ret, &local_err);
1136 break;
1137 default:
1138 if (!nbd_reply_type_is_error(chunk->type)) {
1139 nbd_channel_error(s, -EINVAL);
1140 error_setg(&local_err,
1141 "Unexpected reply type: %d (%s) "
1142 "for CMD_BLOCK_STATUS",
1143 chunk->type, nbd_reply_type_lookup(chunk->type));
1144 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1148 g_free(payload);
1149 payload = NULL;
1152 if (!extent->length && !iter.request_ret) {
1153 error_setg(&local_err, "Server did not reply with any status extents");
1154 nbd_iter_channel_error(&iter, -EIO, &local_err);
1157 error_propagate(errp, iter.err);
1158 *request_ret = iter.request_ret;
1159 return iter.ret;
1162 static int nbd_co_request(BlockDriverState *bs, NBDRequest *request,
1163 QEMUIOVector *write_qiov)
1165 int ret, request_ret;
1166 Error *local_err = NULL;
1167 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1169 assert(request->type != NBD_CMD_READ);
1170 if (write_qiov) {
1171 assert(request->type == NBD_CMD_WRITE);
1172 assert(request->len == iov_size(write_qiov->iov, write_qiov->niov));
1173 } else {
1174 assert(request->type != NBD_CMD_WRITE);
1177 do {
1178 ret = nbd_co_send_request(bs, request, write_qiov);
1179 if (ret < 0) {
1180 continue;
1183 ret = nbd_co_receive_return_code(s, request->handle,
1184 &request_ret, &local_err);
1185 if (local_err) {
1186 trace_nbd_co_request_fail(request->from, request->len,
1187 request->handle, request->flags,
1188 request->type,
1189 nbd_cmd_lookup(request->type),
1190 ret, error_get_pretty(local_err));
1191 error_free(local_err);
1192 local_err = NULL;
1194 } while (ret < 0 && nbd_client_connecting_wait(s));
1196 return ret ? ret : request_ret;
1199 static int nbd_client_co_preadv(BlockDriverState *bs, int64_t offset,
1200 int64_t bytes, QEMUIOVector *qiov,
1201 BdrvRequestFlags flags)
1203 int ret, request_ret;
1204 Error *local_err = NULL;
1205 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1206 NBDRequest request = {
1207 .type = NBD_CMD_READ,
1208 .from = offset,
1209 .len = bytes,
1212 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1213 assert(!flags);
1215 if (!bytes) {
1216 return 0;
1219 * Work around the fact that the block layer doesn't do
1220 * byte-accurate sizing yet - if the read exceeds the server's
1221 * advertised size because the block layer rounded size up, then
1222 * truncate the request to the server and tail-pad with zero.
1224 if (offset >= s->info.size) {
1225 assert(bytes < BDRV_SECTOR_SIZE);
1226 qemu_iovec_memset(qiov, 0, 0, bytes);
1227 return 0;
1229 if (offset + bytes > s->info.size) {
1230 uint64_t slop = offset + bytes - s->info.size;
1232 assert(slop < BDRV_SECTOR_SIZE);
1233 qemu_iovec_memset(qiov, bytes - slop, 0, slop);
1234 request.len -= slop;
1237 do {
1238 ret = nbd_co_send_request(bs, &request, NULL);
1239 if (ret < 0) {
1240 continue;
1243 ret = nbd_co_receive_cmdread_reply(s, request.handle, offset, qiov,
1244 &request_ret, &local_err);
1245 if (local_err) {
1246 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1247 request.flags, request.type,
1248 nbd_cmd_lookup(request.type),
1249 ret, error_get_pretty(local_err));
1250 error_free(local_err);
1251 local_err = NULL;
1253 } while (ret < 0 && nbd_client_connecting_wait(s));
1255 return ret ? ret : request_ret;
1258 static int nbd_client_co_pwritev(BlockDriverState *bs, int64_t offset,
1259 int64_t bytes, QEMUIOVector *qiov,
1260 BdrvRequestFlags flags)
1262 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1263 NBDRequest request = {
1264 .type = NBD_CMD_WRITE,
1265 .from = offset,
1266 .len = bytes,
1269 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1270 if (flags & BDRV_REQ_FUA) {
1271 assert(s->info.flags & NBD_FLAG_SEND_FUA);
1272 request.flags |= NBD_CMD_FLAG_FUA;
1275 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1277 if (!bytes) {
1278 return 0;
1280 return nbd_co_request(bs, &request, qiov);
1283 static int nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1284 int64_t bytes, BdrvRequestFlags flags)
1286 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1287 NBDRequest request = {
1288 .type = NBD_CMD_WRITE_ZEROES,
1289 .from = offset,
1290 .len = bytes, /* .len is uint32_t actually */
1293 assert(bytes <= UINT32_MAX); /* rely on max_pwrite_zeroes */
1295 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1296 if (!(s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {
1297 return -ENOTSUP;
1300 if (flags & BDRV_REQ_FUA) {
1301 assert(s->info.flags & NBD_FLAG_SEND_FUA);
1302 request.flags |= NBD_CMD_FLAG_FUA;
1304 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1305 request.flags |= NBD_CMD_FLAG_NO_HOLE;
1307 if (flags & BDRV_REQ_NO_FALLBACK) {
1308 assert(s->info.flags & NBD_FLAG_SEND_FAST_ZERO);
1309 request.flags |= NBD_CMD_FLAG_FAST_ZERO;
1312 if (!bytes) {
1313 return 0;
1315 return nbd_co_request(bs, &request, NULL);
1318 static int nbd_client_co_flush(BlockDriverState *bs)
1320 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1321 NBDRequest request = { .type = NBD_CMD_FLUSH };
1323 if (!(s->info.flags & NBD_FLAG_SEND_FLUSH)) {
1324 return 0;
1327 request.from = 0;
1328 request.len = 0;
1330 return nbd_co_request(bs, &request, NULL);
1333 static int nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset,
1334 int64_t bytes)
1336 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1337 NBDRequest request = {
1338 .type = NBD_CMD_TRIM,
1339 .from = offset,
1340 .len = bytes, /* len is uint32_t */
1343 assert(bytes <= UINT32_MAX); /* rely on max_pdiscard */
1345 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1346 if (!(s->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) {
1347 return 0;
1350 return nbd_co_request(bs, &request, NULL);
1353 static int coroutine_fn nbd_client_co_block_status(
1354 BlockDriverState *bs, bool want_zero, int64_t offset, int64_t bytes,
1355 int64_t *pnum, int64_t *map, BlockDriverState **file)
1357 int ret, request_ret;
1358 NBDExtent extent = { 0 };
1359 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1360 Error *local_err = NULL;
1362 NBDRequest request = {
1363 .type = NBD_CMD_BLOCK_STATUS,
1364 .from = offset,
1365 .len = MIN(QEMU_ALIGN_DOWN(INT_MAX, bs->bl.request_alignment),
1366 MIN(bytes, s->info.size - offset)),
1367 .flags = NBD_CMD_FLAG_REQ_ONE,
1370 if (!s->info.base_allocation) {
1371 *pnum = bytes;
1372 *map = offset;
1373 *file = bs;
1374 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
1378 * Work around the fact that the block layer doesn't do
1379 * byte-accurate sizing yet - if the status request exceeds the
1380 * server's advertised size because the block layer rounded size
1381 * up, we truncated the request to the server (above), or are
1382 * called on just the hole.
1384 if (offset >= s->info.size) {
1385 *pnum = bytes;
1386 assert(bytes < BDRV_SECTOR_SIZE);
1387 /* Intentionally don't report offset_valid for the hole */
1388 return BDRV_BLOCK_ZERO;
1391 if (s->info.min_block) {
1392 assert(QEMU_IS_ALIGNED(request.len, s->info.min_block));
1394 do {
1395 ret = nbd_co_send_request(bs, &request, NULL);
1396 if (ret < 0) {
1397 continue;
1400 ret = nbd_co_receive_blockstatus_reply(s, request.handle, bytes,
1401 &extent, &request_ret,
1402 &local_err);
1403 if (local_err) {
1404 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1405 request.flags, request.type,
1406 nbd_cmd_lookup(request.type),
1407 ret, error_get_pretty(local_err));
1408 error_free(local_err);
1409 local_err = NULL;
1411 } while (ret < 0 && nbd_client_connecting_wait(s));
1413 if (ret < 0 || request_ret < 0) {
1414 return ret ? ret : request_ret;
1417 assert(extent.length);
1418 *pnum = extent.length;
1419 *map = offset;
1420 *file = bs;
1421 return (extent.flags & NBD_STATE_HOLE ? 0 : BDRV_BLOCK_DATA) |
1422 (extent.flags & NBD_STATE_ZERO ? BDRV_BLOCK_ZERO : 0) |
1423 BDRV_BLOCK_OFFSET_VALID;
1426 static int nbd_client_reopen_prepare(BDRVReopenState *state,
1427 BlockReopenQueue *queue, Error **errp)
1429 BDRVNBDState *s = (BDRVNBDState *)state->bs->opaque;
1431 if ((state->flags & BDRV_O_RDWR) && (s->info.flags & NBD_FLAG_READ_ONLY)) {
1432 error_setg(errp, "Can't reopen read-only NBD mount as read/write");
1433 return -EACCES;
1435 return 0;
1438 static void nbd_yank(void *opaque)
1440 BlockDriverState *bs = opaque;
1441 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1443 qatomic_store_release(&s->state, NBD_CLIENT_QUIT);
1444 qio_channel_shutdown(QIO_CHANNEL(s->ioc), QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
1447 static void nbd_client_close(BlockDriverState *bs)
1449 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1450 NBDRequest request = { .type = NBD_CMD_DISC };
1452 if (s->ioc) {
1453 nbd_send_request(s->ioc, &request);
1456 nbd_teardown_connection(bs);
1461 * Parse nbd_open options
1464 static int nbd_parse_uri(const char *filename, QDict *options)
1466 URI *uri;
1467 const char *p;
1468 QueryParams *qp = NULL;
1469 int ret = 0;
1470 bool is_unix;
1472 uri = uri_parse(filename);
1473 if (!uri) {
1474 return -EINVAL;
1477 /* transport */
1478 if (!g_strcmp0(uri->scheme, "nbd")) {
1479 is_unix = false;
1480 } else if (!g_strcmp0(uri->scheme, "nbd+tcp")) {
1481 is_unix = false;
1482 } else if (!g_strcmp0(uri->scheme, "nbd+unix")) {
1483 is_unix = true;
1484 } else {
1485 ret = -EINVAL;
1486 goto out;
1489 p = uri->path ? uri->path : "";
1490 if (p[0] == '/') {
1491 p++;
1493 if (p[0]) {
1494 qdict_put_str(options, "export", p);
1497 qp = query_params_parse(uri->query);
1498 if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
1499 ret = -EINVAL;
1500 goto out;
1503 if (is_unix) {
1504 /* nbd+unix:///export?socket=path */
1505 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
1506 ret = -EINVAL;
1507 goto out;
1509 qdict_put_str(options, "server.type", "unix");
1510 qdict_put_str(options, "server.path", qp->p[0].value);
1511 } else {
1512 QString *host;
1513 char *port_str;
1515 /* nbd[+tcp]://host[:port]/export */
1516 if (!uri->server) {
1517 ret = -EINVAL;
1518 goto out;
1521 /* strip braces from literal IPv6 address */
1522 if (uri->server[0] == '[') {
1523 host = qstring_from_substr(uri->server, 1,
1524 strlen(uri->server) - 1);
1525 } else {
1526 host = qstring_from_str(uri->server);
1529 qdict_put_str(options, "server.type", "inet");
1530 qdict_put(options, "server.host", host);
1532 port_str = g_strdup_printf("%d", uri->port ?: NBD_DEFAULT_PORT);
1533 qdict_put_str(options, "server.port", port_str);
1534 g_free(port_str);
1537 out:
1538 if (qp) {
1539 query_params_free(qp);
1541 uri_free(uri);
1542 return ret;
1545 static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
1547 const QDictEntry *e;
1549 for (e = qdict_first(options); e; e = qdict_next(options, e)) {
1550 if (!strcmp(e->key, "host") ||
1551 !strcmp(e->key, "port") ||
1552 !strcmp(e->key, "path") ||
1553 !strcmp(e->key, "export") ||
1554 strstart(e->key, "server.", NULL))
1556 error_setg(errp, "Option '%s' cannot be used with a file name",
1557 e->key);
1558 return true;
1562 return false;
1565 static void nbd_parse_filename(const char *filename, QDict *options,
1566 Error **errp)
1568 g_autofree char *file = NULL;
1569 char *export_name;
1570 const char *host_spec;
1571 const char *unixpath;
1573 if (nbd_has_filename_options_conflict(options, errp)) {
1574 return;
1577 if (strstr(filename, "://")) {
1578 int ret = nbd_parse_uri(filename, options);
1579 if (ret < 0) {
1580 error_setg(errp, "No valid URL specified");
1582 return;
1585 file = g_strdup(filename);
1587 export_name = strstr(file, EN_OPTSTR);
1588 if (export_name) {
1589 if (export_name[strlen(EN_OPTSTR)] == 0) {
1590 return;
1592 export_name[0] = 0; /* truncate 'file' */
1593 export_name += strlen(EN_OPTSTR);
1595 qdict_put_str(options, "export", export_name);
1598 /* extract the host_spec - fail if it's not nbd:... */
1599 if (!strstart(file, "nbd:", &host_spec)) {
1600 error_setg(errp, "File name string for NBD must start with 'nbd:'");
1601 return;
1604 if (!*host_spec) {
1605 return;
1608 /* are we a UNIX or TCP socket? */
1609 if (strstart(host_spec, "unix:", &unixpath)) {
1610 qdict_put_str(options, "server.type", "unix");
1611 qdict_put_str(options, "server.path", unixpath);
1612 } else {
1613 InetSocketAddress *addr = g_new(InetSocketAddress, 1);
1615 if (inet_parse(addr, host_spec, errp)) {
1616 goto out_inet;
1619 qdict_put_str(options, "server.type", "inet");
1620 qdict_put_str(options, "server.host", addr->host);
1621 qdict_put_str(options, "server.port", addr->port);
1622 out_inet:
1623 qapi_free_InetSocketAddress(addr);
1627 static bool nbd_process_legacy_socket_options(QDict *output_options,
1628 QemuOpts *legacy_opts,
1629 Error **errp)
1631 const char *path = qemu_opt_get(legacy_opts, "path");
1632 const char *host = qemu_opt_get(legacy_opts, "host");
1633 const char *port = qemu_opt_get(legacy_opts, "port");
1634 const QDictEntry *e;
1636 if (!path && !host && !port) {
1637 return true;
1640 for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
1642 if (strstart(e->key, "server.", NULL)) {
1643 error_setg(errp, "Cannot use 'server' and path/host/port at the "
1644 "same time");
1645 return false;
1649 if (path && host) {
1650 error_setg(errp, "path and host may not be used at the same time");
1651 return false;
1652 } else if (path) {
1653 if (port) {
1654 error_setg(errp, "port may not be used without host");
1655 return false;
1658 qdict_put_str(output_options, "server.type", "unix");
1659 qdict_put_str(output_options, "server.path", path);
1660 } else if (host) {
1661 qdict_put_str(output_options, "server.type", "inet");
1662 qdict_put_str(output_options, "server.host", host);
1663 qdict_put_str(output_options, "server.port",
1664 port ?: stringify(NBD_DEFAULT_PORT));
1667 return true;
1670 static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options,
1671 Error **errp)
1673 SocketAddress *saddr = NULL;
1674 QDict *addr = NULL;
1675 Visitor *iv = NULL;
1677 qdict_extract_subqdict(options, &addr, "server.");
1678 if (!qdict_size(addr)) {
1679 error_setg(errp, "NBD server address missing");
1680 goto done;
1683 iv = qobject_input_visitor_new_flat_confused(addr, errp);
1684 if (!iv) {
1685 goto done;
1688 if (!visit_type_SocketAddress(iv, NULL, &saddr, errp)) {
1689 goto done;
1692 if (socket_address_parse_named_fd(saddr, errp) < 0) {
1693 qapi_free_SocketAddress(saddr);
1694 saddr = NULL;
1695 goto done;
1698 done:
1699 qobject_unref(addr);
1700 visit_free(iv);
1701 return saddr;
1704 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
1706 Object *obj;
1707 QCryptoTLSCreds *creds;
1709 obj = object_resolve_path_component(
1710 object_get_objects_root(), id);
1711 if (!obj) {
1712 error_setg(errp, "No TLS credentials with id '%s'",
1713 id);
1714 return NULL;
1716 creds = (QCryptoTLSCreds *)
1717 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
1718 if (!creds) {
1719 error_setg(errp, "Object with id '%s' is not TLS credentials",
1720 id);
1721 return NULL;
1724 if (!qcrypto_tls_creds_check_endpoint(creds,
1725 QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT,
1726 errp)) {
1727 return NULL;
1729 object_ref(obj);
1730 return creds;
1734 static QemuOptsList nbd_runtime_opts = {
1735 .name = "nbd",
1736 .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
1737 .desc = {
1739 .name = "host",
1740 .type = QEMU_OPT_STRING,
1741 .help = "TCP host to connect to",
1744 .name = "port",
1745 .type = QEMU_OPT_STRING,
1746 .help = "TCP port to connect to",
1749 .name = "path",
1750 .type = QEMU_OPT_STRING,
1751 .help = "Unix socket path to connect to",
1754 .name = "export",
1755 .type = QEMU_OPT_STRING,
1756 .help = "Name of the NBD export to open",
1759 .name = "tls-creds",
1760 .type = QEMU_OPT_STRING,
1761 .help = "ID of the TLS credentials to use",
1764 .name = "x-dirty-bitmap",
1765 .type = QEMU_OPT_STRING,
1766 .help = "experimental: expose named dirty bitmap in place of "
1767 "block status",
1770 .name = "reconnect-delay",
1771 .type = QEMU_OPT_NUMBER,
1772 .help = "On an unexpected disconnect, the nbd client tries to "
1773 "connect again until succeeding or encountering a serious "
1774 "error. During the first @reconnect-delay seconds, all "
1775 "requests are paused and will be rerun on a successful "
1776 "reconnect. After that time, any delayed requests and all "
1777 "future requests before a successful reconnect will "
1778 "immediately fail. Default 0",
1781 .name = "open-timeout",
1782 .type = QEMU_OPT_NUMBER,
1783 .help = "In seconds. If zero, the nbd driver tries the connection "
1784 "only once, and fails to open if the connection fails. "
1785 "If non-zero, the nbd driver will repeat connection "
1786 "attempts until successful or until @open-timeout seconds "
1787 "have elapsed. Default 0",
1789 { /* end of list */ }
1793 static int nbd_process_options(BlockDriverState *bs, QDict *options,
1794 Error **errp)
1796 BDRVNBDState *s = bs->opaque;
1797 QemuOpts *opts;
1798 int ret = -EINVAL;
1800 opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
1801 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1802 goto error;
1805 /* Translate @host, @port, and @path to a SocketAddress */
1806 if (!nbd_process_legacy_socket_options(options, opts, errp)) {
1807 goto error;
1810 /* Pop the config into our state object. Exit if invalid. */
1811 s->saddr = nbd_config(s, options, errp);
1812 if (!s->saddr) {
1813 goto error;
1816 s->export = g_strdup(qemu_opt_get(opts, "export"));
1817 if (s->export && strlen(s->export) > NBD_MAX_STRING_SIZE) {
1818 error_setg(errp, "export name too long to send to server");
1819 goto error;
1822 s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
1823 if (s->tlscredsid) {
1824 s->tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
1825 if (!s->tlscreds) {
1826 goto error;
1829 /* TODO SOCKET_ADDRESS_KIND_FD where fd has AF_INET or AF_INET6 */
1830 if (s->saddr->type != SOCKET_ADDRESS_TYPE_INET) {
1831 error_setg(errp, "TLS only supported over IP sockets");
1832 goto error;
1834 s->hostname = s->saddr->u.inet.host;
1837 s->x_dirty_bitmap = g_strdup(qemu_opt_get(opts, "x-dirty-bitmap"));
1838 if (s->x_dirty_bitmap && strlen(s->x_dirty_bitmap) > NBD_MAX_STRING_SIZE) {
1839 error_setg(errp, "x-dirty-bitmap query too long to send to server");
1840 goto error;
1843 s->reconnect_delay = qemu_opt_get_number(opts, "reconnect-delay", 0);
1844 s->open_timeout = qemu_opt_get_number(opts, "open-timeout", 0);
1846 ret = 0;
1848 error:
1849 qemu_opts_del(opts);
1850 return ret;
1853 static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
1854 Error **errp)
1856 int ret;
1857 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1859 s->bs = bs;
1860 qemu_co_mutex_init(&s->send_mutex);
1861 qemu_co_queue_init(&s->free_sema);
1862 qemu_co_mutex_init(&s->receive_mutex);
1864 if (!yank_register_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name), errp)) {
1865 return -EEXIST;
1868 ret = nbd_process_options(bs, options, errp);
1869 if (ret < 0) {
1870 goto fail;
1873 s->conn = nbd_client_connection_new(s->saddr, true, s->export,
1874 s->x_dirty_bitmap, s->tlscreds);
1876 if (s->open_timeout) {
1877 nbd_client_connection_enable_retry(s->conn);
1878 open_timer_init(s, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
1879 s->open_timeout * NANOSECONDS_PER_SECOND);
1882 s->state = NBD_CLIENT_CONNECTING_WAIT;
1883 ret = nbd_do_establish_connection(bs, errp);
1884 if (ret < 0) {
1885 goto fail;
1888 nbd_client_connection_enable_retry(s->conn);
1890 return 0;
1892 fail:
1893 nbd_clear_bdrvstate(bs);
1894 return ret;
1897 static int nbd_co_flush(BlockDriverState *bs)
1899 return nbd_client_co_flush(bs);
1902 static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
1904 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1905 uint32_t min = s->info.min_block;
1906 uint32_t max = MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE, s->info.max_block);
1909 * If the server did not advertise an alignment:
1910 * - a size that is not sector-aligned implies that an alignment
1911 * of 1 can be used to access those tail bytes
1912 * - advertisement of block status requires an alignment of 1, so
1913 * that we don't violate block layer constraints that block
1914 * status is always aligned (as we can't control whether the
1915 * server will report sub-sector extents, such as a hole at EOF
1916 * on an unaligned POSIX file)
1917 * - otherwise, assume the server is so old that we are safer avoiding
1918 * sub-sector requests
1920 if (!min) {
1921 min = (!QEMU_IS_ALIGNED(s->info.size, BDRV_SECTOR_SIZE) ||
1922 s->info.base_allocation) ? 1 : BDRV_SECTOR_SIZE;
1925 bs->bl.request_alignment = min;
1926 bs->bl.max_pdiscard = QEMU_ALIGN_DOWN(INT_MAX, min);
1927 bs->bl.max_pwrite_zeroes = max;
1928 bs->bl.max_transfer = max;
1930 if (s->info.opt_block &&
1931 s->info.opt_block > bs->bl.opt_transfer) {
1932 bs->bl.opt_transfer = s->info.opt_block;
1936 static void nbd_close(BlockDriverState *bs)
1938 nbd_client_close(bs);
1939 nbd_clear_bdrvstate(bs);
1943 * NBD cannot truncate, but if the caller asks to truncate to the same size, or
1944 * to a smaller size with exact=false, there is no reason to fail the
1945 * operation.
1947 * Preallocation mode is ignored since it does not seems useful to fail when
1948 * we never change anything.
1950 static int coroutine_fn nbd_co_truncate(BlockDriverState *bs, int64_t offset,
1951 bool exact, PreallocMode prealloc,
1952 BdrvRequestFlags flags, Error **errp)
1954 BDRVNBDState *s = bs->opaque;
1956 if (offset != s->info.size && exact) {
1957 error_setg(errp, "Cannot resize NBD nodes");
1958 return -ENOTSUP;
1961 if (offset > s->info.size) {
1962 error_setg(errp, "Cannot grow NBD nodes");
1963 return -EINVAL;
1966 return 0;
1969 static int64_t nbd_getlength(BlockDriverState *bs)
1971 BDRVNBDState *s = bs->opaque;
1973 return s->info.size;
1976 static void nbd_refresh_filename(BlockDriverState *bs)
1978 BDRVNBDState *s = bs->opaque;
1979 const char *host = NULL, *port = NULL, *path = NULL;
1980 size_t len = 0;
1982 if (s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
1983 const InetSocketAddress *inet = &s->saddr->u.inet;
1984 if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) {
1985 host = inet->host;
1986 port = inet->port;
1988 } else if (s->saddr->type == SOCKET_ADDRESS_TYPE_UNIX) {
1989 path = s->saddr->u.q_unix.path;
1990 } /* else can't represent as pseudo-filename */
1992 if (path && s->export) {
1993 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1994 "nbd+unix:///%s?socket=%s", s->export, path);
1995 } else if (path && !s->export) {
1996 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1997 "nbd+unix://?socket=%s", path);
1998 } else if (host && s->export) {
1999 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2000 "nbd://%s:%s/%s", host, port, s->export);
2001 } else if (host && !s->export) {
2002 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2003 "nbd://%s:%s", host, port);
2005 if (len >= sizeof(bs->exact_filename)) {
2006 /* Name is too long to represent exactly, so leave it empty. */
2007 bs->exact_filename[0] = '\0';
2011 static char *nbd_dirname(BlockDriverState *bs, Error **errp)
2013 /* The generic bdrv_dirname() implementation is able to work out some
2014 * directory name for NBD nodes, but that would be wrong. So far there is no
2015 * specification for how "export paths" would work, so NBD does not have
2016 * directory names. */
2017 error_setg(errp, "Cannot generate a base directory for NBD nodes");
2018 return NULL;
2021 static const char *const nbd_strong_runtime_opts[] = {
2022 "path",
2023 "host",
2024 "port",
2025 "export",
2026 "tls-creds",
2027 "server.",
2029 NULL
2032 static void nbd_cancel_in_flight(BlockDriverState *bs)
2034 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2036 reconnect_delay_timer_del(s);
2038 if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
2039 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
2040 qemu_co_queue_restart_all(&s->free_sema);
2043 nbd_co_establish_connection_cancel(s->conn);
2046 static BlockDriver bdrv_nbd = {
2047 .format_name = "nbd",
2048 .protocol_name = "nbd",
2049 .instance_size = sizeof(BDRVNBDState),
2050 .bdrv_parse_filename = nbd_parse_filename,
2051 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2052 .create_opts = &bdrv_create_opts_simple,
2053 .bdrv_file_open = nbd_open,
2054 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2055 .bdrv_co_preadv = nbd_client_co_preadv,
2056 .bdrv_co_pwritev = nbd_client_co_pwritev,
2057 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2058 .bdrv_close = nbd_close,
2059 .bdrv_co_flush_to_os = nbd_co_flush,
2060 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2061 .bdrv_refresh_limits = nbd_refresh_limits,
2062 .bdrv_co_truncate = nbd_co_truncate,
2063 .bdrv_getlength = nbd_getlength,
2064 .bdrv_refresh_filename = nbd_refresh_filename,
2065 .bdrv_co_block_status = nbd_client_co_block_status,
2066 .bdrv_dirname = nbd_dirname,
2067 .strong_runtime_opts = nbd_strong_runtime_opts,
2068 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2071 static BlockDriver bdrv_nbd_tcp = {
2072 .format_name = "nbd",
2073 .protocol_name = "nbd+tcp",
2074 .instance_size = sizeof(BDRVNBDState),
2075 .bdrv_parse_filename = nbd_parse_filename,
2076 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2077 .create_opts = &bdrv_create_opts_simple,
2078 .bdrv_file_open = nbd_open,
2079 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2080 .bdrv_co_preadv = nbd_client_co_preadv,
2081 .bdrv_co_pwritev = nbd_client_co_pwritev,
2082 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2083 .bdrv_close = nbd_close,
2084 .bdrv_co_flush_to_os = nbd_co_flush,
2085 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2086 .bdrv_refresh_limits = nbd_refresh_limits,
2087 .bdrv_co_truncate = nbd_co_truncate,
2088 .bdrv_getlength = nbd_getlength,
2089 .bdrv_refresh_filename = nbd_refresh_filename,
2090 .bdrv_co_block_status = nbd_client_co_block_status,
2091 .bdrv_dirname = nbd_dirname,
2092 .strong_runtime_opts = nbd_strong_runtime_opts,
2093 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2096 static BlockDriver bdrv_nbd_unix = {
2097 .format_name = "nbd",
2098 .protocol_name = "nbd+unix",
2099 .instance_size = sizeof(BDRVNBDState),
2100 .bdrv_parse_filename = nbd_parse_filename,
2101 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2102 .create_opts = &bdrv_create_opts_simple,
2103 .bdrv_file_open = nbd_open,
2104 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2105 .bdrv_co_preadv = nbd_client_co_preadv,
2106 .bdrv_co_pwritev = nbd_client_co_pwritev,
2107 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2108 .bdrv_close = nbd_close,
2109 .bdrv_co_flush_to_os = nbd_co_flush,
2110 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2111 .bdrv_refresh_limits = nbd_refresh_limits,
2112 .bdrv_co_truncate = nbd_co_truncate,
2113 .bdrv_getlength = nbd_getlength,
2114 .bdrv_refresh_filename = nbd_refresh_filename,
2115 .bdrv_co_block_status = nbd_client_co_block_status,
2116 .bdrv_dirname = nbd_dirname,
2117 .strong_runtime_opts = nbd_strong_runtime_opts,
2118 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2121 static void bdrv_nbd_init(void)
2123 bdrv_register(&bdrv_nbd);
2124 bdrv_register(&bdrv_nbd_tcp);
2125 bdrv_register(&bdrv_nbd_unix);
2128 block_init(bdrv_nbd_init);