nbd: mark more coroutine_fns
[qemu/kevin.git] / block / nbd.c
blob3a6e609203044a1afd085ac769e7144557489d29
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 (!nbd_client_connected(s)) {
413 return -EIO;
416 if (s->reply.handle != 0) {
418 * Some other request is being handled now. It should already be
419 * woken by whoever set s->reply.handle (or never wait in this
420 * yield). So, we should not wake it here.
422 ind2 = HANDLE_TO_INDEX(s, s->reply.handle);
423 assert(!s->requests[ind2].receiving);
425 s->requests[ind].receiving = true;
426 qemu_co_mutex_unlock(&s->receive_mutex);
428 qemu_coroutine_yield();
430 * We may be woken for 3 reasons:
431 * 1. From this function, executing in parallel coroutine, when our
432 * handle is received.
433 * 2. From nbd_channel_error(), when connection is lost.
434 * 3. From nbd_co_receive_one_chunk(), when previous request is
435 * finished and s->reply.handle set to 0.
436 * Anyway, it's OK to lock the mutex and go to the next iteration.
439 qemu_co_mutex_lock(&s->receive_mutex);
440 assert(!s->requests[ind].receiving);
441 continue;
444 /* We are under mutex and handle is 0. We have to do the dirty work. */
445 assert(s->reply.handle == 0);
446 ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, NULL);
447 if (ret <= 0) {
448 ret = ret ? ret : -EIO;
449 nbd_channel_error(s, ret);
450 return ret;
452 if (nbd_reply_is_structured(&s->reply) && !s->info.structured_reply) {
453 nbd_channel_error(s, -EINVAL);
454 return -EINVAL;
456 ind2 = HANDLE_TO_INDEX(s, s->reply.handle);
457 if (ind2 >= MAX_NBD_REQUESTS || !s->requests[ind2].coroutine) {
458 nbd_channel_error(s, -EINVAL);
459 return -EINVAL;
461 if (s->reply.handle == handle) {
462 /* We are done */
463 return 0;
465 nbd_recv_coroutine_wake_one(&s->requests[ind2]);
469 static int coroutine_fn nbd_co_send_request(BlockDriverState *bs,
470 NBDRequest *request,
471 QEMUIOVector *qiov)
473 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
474 int rc, i = -1;
476 qemu_co_mutex_lock(&s->send_mutex);
478 while (s->in_flight == MAX_NBD_REQUESTS ||
479 (!nbd_client_connected(s) && s->in_flight > 0))
481 qemu_co_queue_wait(&s->free_sema, &s->send_mutex);
484 if (nbd_client_connecting(s)) {
485 nbd_reconnect_attempt(s);
488 if (!nbd_client_connected(s)) {
489 rc = -EIO;
490 goto err;
493 s->in_flight++;
495 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
496 if (s->requests[i].coroutine == NULL) {
497 break;
501 g_assert(qemu_in_coroutine());
502 assert(i < MAX_NBD_REQUESTS);
504 s->requests[i].coroutine = qemu_coroutine_self();
505 s->requests[i].offset = request->from;
506 s->requests[i].receiving = false;
508 request->handle = INDEX_TO_HANDLE(s, i);
510 assert(s->ioc);
512 if (qiov) {
513 qio_channel_set_cork(s->ioc, true);
514 rc = nbd_send_request(s->ioc, request);
515 if (nbd_client_connected(s) && rc >= 0) {
516 if (qio_channel_writev_all(s->ioc, qiov->iov, qiov->niov,
517 NULL) < 0) {
518 rc = -EIO;
520 } else if (rc >= 0) {
521 rc = -EIO;
523 qio_channel_set_cork(s->ioc, false);
524 } else {
525 rc = nbd_send_request(s->ioc, request);
528 err:
529 if (rc < 0) {
530 nbd_channel_error(s, rc);
531 if (i != -1) {
532 s->requests[i].coroutine = NULL;
533 s->in_flight--;
535 qemu_co_queue_next(&s->free_sema);
537 qemu_co_mutex_unlock(&s->send_mutex);
538 return rc;
541 static inline uint16_t payload_advance16(uint8_t **payload)
543 *payload += 2;
544 return lduw_be_p(*payload - 2);
547 static inline uint32_t payload_advance32(uint8_t **payload)
549 *payload += 4;
550 return ldl_be_p(*payload - 4);
553 static inline uint64_t payload_advance64(uint8_t **payload)
555 *payload += 8;
556 return ldq_be_p(*payload - 8);
559 static int nbd_parse_offset_hole_payload(BDRVNBDState *s,
560 NBDStructuredReplyChunk *chunk,
561 uint8_t *payload, uint64_t orig_offset,
562 QEMUIOVector *qiov, Error **errp)
564 uint64_t offset;
565 uint32_t hole_size;
567 if (chunk->length != sizeof(offset) + sizeof(hole_size)) {
568 error_setg(errp, "Protocol error: invalid payload for "
569 "NBD_REPLY_TYPE_OFFSET_HOLE");
570 return -EINVAL;
573 offset = payload_advance64(&payload);
574 hole_size = payload_advance32(&payload);
576 if (!hole_size || offset < orig_offset || hole_size > qiov->size ||
577 offset > orig_offset + qiov->size - hole_size) {
578 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
579 " region");
580 return -EINVAL;
582 if (s->info.min_block &&
583 !QEMU_IS_ALIGNED(hole_size, s->info.min_block)) {
584 trace_nbd_structured_read_compliance("hole");
587 qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size);
589 return 0;
593 * nbd_parse_blockstatus_payload
594 * Based on our request, we expect only one extent in reply, for the
595 * base:allocation context.
597 static int nbd_parse_blockstatus_payload(BDRVNBDState *s,
598 NBDStructuredReplyChunk *chunk,
599 uint8_t *payload, uint64_t orig_length,
600 NBDExtent *extent, Error **errp)
602 uint32_t context_id;
604 /* The server succeeded, so it must have sent [at least] one extent */
605 if (chunk->length < sizeof(context_id) + sizeof(*extent)) {
606 error_setg(errp, "Protocol error: invalid payload for "
607 "NBD_REPLY_TYPE_BLOCK_STATUS");
608 return -EINVAL;
611 context_id = payload_advance32(&payload);
612 if (s->info.context_id != context_id) {
613 error_setg(errp, "Protocol error: unexpected context id %d for "
614 "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
615 "id is %d", context_id,
616 s->info.context_id);
617 return -EINVAL;
620 extent->length = payload_advance32(&payload);
621 extent->flags = payload_advance32(&payload);
623 if (extent->length == 0) {
624 error_setg(errp, "Protocol error: server sent status chunk with "
625 "zero length");
626 return -EINVAL;
630 * A server sending unaligned block status is in violation of the
631 * protocol, but as qemu-nbd 3.1 is such a server (at least for
632 * POSIX files that are not a multiple of 512 bytes, since qemu
633 * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
634 * still sees an implicit hole beyond the real EOF), it's nicer to
635 * work around the misbehaving server. If the request included
636 * more than the final unaligned block, truncate it back to an
637 * aligned result; if the request was only the final block, round
638 * up to the full block and change the status to fully-allocated
639 * (always a safe status, even if it loses information).
641 if (s->info.min_block && !QEMU_IS_ALIGNED(extent->length,
642 s->info.min_block)) {
643 trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
644 if (extent->length > s->info.min_block) {
645 extent->length = QEMU_ALIGN_DOWN(extent->length,
646 s->info.min_block);
647 } else {
648 extent->length = s->info.min_block;
649 extent->flags = 0;
654 * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
655 * sent us any more than one extent, nor should it have included
656 * status beyond our request in that extent. However, it's easy
657 * enough to ignore the server's noncompliance without killing the
658 * connection; just ignore trailing extents, and clamp things to
659 * the length of our request.
661 if (chunk->length > sizeof(context_id) + sizeof(*extent)) {
662 trace_nbd_parse_blockstatus_compliance("more than one extent");
664 if (extent->length > orig_length) {
665 extent->length = orig_length;
666 trace_nbd_parse_blockstatus_compliance("extent length too large");
670 * HACK: if we are using x-dirty-bitmaps to access
671 * qemu:allocation-depth, treat all depths > 2 the same as 2,
672 * since nbd_client_co_block_status is only expecting the low two
673 * bits to be set.
675 if (s->alloc_depth && extent->flags > 2) {
676 extent->flags = 2;
679 return 0;
683 * nbd_parse_error_payload
684 * on success @errp contains message describing nbd error reply
686 static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
687 uint8_t *payload, int *request_ret,
688 Error **errp)
690 uint32_t error;
691 uint16_t message_size;
693 assert(chunk->type & (1 << 15));
695 if (chunk->length < sizeof(error) + sizeof(message_size)) {
696 error_setg(errp,
697 "Protocol error: invalid payload for structured error");
698 return -EINVAL;
701 error = nbd_errno_to_system_errno(payload_advance32(&payload));
702 if (error == 0) {
703 error_setg(errp, "Protocol error: server sent structured error chunk "
704 "with error = 0");
705 return -EINVAL;
708 *request_ret = -error;
709 message_size = payload_advance16(&payload);
711 if (message_size > chunk->length - sizeof(error) - sizeof(message_size)) {
712 error_setg(errp, "Protocol error: server sent structured error chunk "
713 "with incorrect message size");
714 return -EINVAL;
717 /* TODO: Add a trace point to mention the server complaint */
719 /* TODO handle ERROR_OFFSET */
721 return 0;
724 static int coroutine_fn
725 nbd_co_receive_offset_data_payload(BDRVNBDState *s, uint64_t orig_offset,
726 QEMUIOVector *qiov, Error **errp)
728 QEMUIOVector sub_qiov;
729 uint64_t offset;
730 size_t data_size;
731 int ret;
732 NBDStructuredReplyChunk *chunk = &s->reply.structured;
734 assert(nbd_reply_is_structured(&s->reply));
736 /* The NBD spec requires at least one byte of payload */
737 if (chunk->length <= sizeof(offset)) {
738 error_setg(errp, "Protocol error: invalid payload for "
739 "NBD_REPLY_TYPE_OFFSET_DATA");
740 return -EINVAL;
743 if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) {
744 return -EIO;
747 data_size = chunk->length - sizeof(offset);
748 assert(data_size);
749 if (offset < orig_offset || data_size > qiov->size ||
750 offset > orig_offset + qiov->size - data_size) {
751 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
752 " region");
753 return -EINVAL;
755 if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) {
756 trace_nbd_structured_read_compliance("data");
759 qemu_iovec_init(&sub_qiov, qiov->niov);
760 qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size);
761 ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);
762 qemu_iovec_destroy(&sub_qiov);
764 return ret < 0 ? -EIO : 0;
767 #define NBD_MAX_MALLOC_PAYLOAD 1000
768 static coroutine_fn int nbd_co_receive_structured_payload(
769 BDRVNBDState *s, void **payload, Error **errp)
771 int ret;
772 uint32_t len;
774 assert(nbd_reply_is_structured(&s->reply));
776 len = s->reply.structured.length;
778 if (len == 0) {
779 return 0;
782 if (payload == NULL) {
783 error_setg(errp, "Unexpected structured payload");
784 return -EINVAL;
787 if (len > NBD_MAX_MALLOC_PAYLOAD) {
788 error_setg(errp, "Payload too large");
789 return -EINVAL;
792 *payload = g_new(char, len);
793 ret = nbd_read(s->ioc, *payload, len, "structured payload", errp);
794 if (ret < 0) {
795 g_free(*payload);
796 *payload = NULL;
797 return ret;
800 return 0;
804 * nbd_co_do_receive_one_chunk
805 * for simple reply:
806 * set request_ret to received reply error
807 * if qiov is not NULL: read payload to @qiov
808 * for structured reply chunk:
809 * if error chunk: read payload, set @request_ret, do not set @payload
810 * else if offset_data chunk: read payload data to @qiov, do not set @payload
811 * else: read payload to @payload
813 * If function fails, @errp contains corresponding error message, and the
814 * connection with the server is suspect. If it returns 0, then the
815 * transaction succeeded (although @request_ret may be a negative errno
816 * corresponding to the server's error reply), and errp is unchanged.
818 static coroutine_fn int nbd_co_do_receive_one_chunk(
819 BDRVNBDState *s, uint64_t handle, bool only_structured,
820 int *request_ret, QEMUIOVector *qiov, void **payload, Error **errp)
822 int ret;
823 int i = HANDLE_TO_INDEX(s, handle);
824 void *local_payload = NULL;
825 NBDStructuredReplyChunk *chunk;
827 if (payload) {
828 *payload = NULL;
830 *request_ret = 0;
832 nbd_receive_replies(s, handle);
833 if (!nbd_client_connected(s)) {
834 error_setg(errp, "Connection closed");
835 return -EIO;
837 assert(s->ioc);
839 assert(s->reply.handle == handle);
841 if (nbd_reply_is_simple(&s->reply)) {
842 if (only_structured) {
843 error_setg(errp, "Protocol error: simple reply when structured "
844 "reply chunk was expected");
845 return -EINVAL;
848 *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error);
849 if (*request_ret < 0 || !qiov) {
850 return 0;
853 return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov,
854 errp) < 0 ? -EIO : 0;
857 /* handle structured reply chunk */
858 assert(s->info.structured_reply);
859 chunk = &s->reply.structured;
861 if (chunk->type == NBD_REPLY_TYPE_NONE) {
862 if (!(chunk->flags & NBD_REPLY_FLAG_DONE)) {
863 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
864 " NBD_REPLY_FLAG_DONE flag set");
865 return -EINVAL;
867 if (chunk->length) {
868 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
869 " nonzero length");
870 return -EINVAL;
872 return 0;
875 if (chunk->type == NBD_REPLY_TYPE_OFFSET_DATA) {
876 if (!qiov) {
877 error_setg(errp, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
878 return -EINVAL;
881 return nbd_co_receive_offset_data_payload(s, s->requests[i].offset,
882 qiov, errp);
885 if (nbd_reply_type_is_error(chunk->type)) {
886 payload = &local_payload;
889 ret = nbd_co_receive_structured_payload(s, payload, errp);
890 if (ret < 0) {
891 return ret;
894 if (nbd_reply_type_is_error(chunk->type)) {
895 ret = nbd_parse_error_payload(chunk, local_payload, request_ret, errp);
896 g_free(local_payload);
897 return ret;
900 return 0;
904 * nbd_co_receive_one_chunk
905 * Read reply, wake up connection_co and set s->quit if needed.
906 * Return value is a fatal error code or normal nbd reply error code
908 static coroutine_fn int nbd_co_receive_one_chunk(
909 BDRVNBDState *s, uint64_t handle, bool only_structured,
910 int *request_ret, QEMUIOVector *qiov, NBDReply *reply, void **payload,
911 Error **errp)
913 int ret = nbd_co_do_receive_one_chunk(s, handle, only_structured,
914 request_ret, qiov, payload, errp);
916 if (ret < 0) {
917 memset(reply, 0, sizeof(*reply));
918 nbd_channel_error(s, ret);
919 } else {
920 /* For assert at loop start in nbd_connection_entry */
921 *reply = s->reply;
923 s->reply.handle = 0;
925 nbd_recv_coroutines_wake(s, false);
927 return ret;
930 typedef struct NBDReplyChunkIter {
931 int ret;
932 int request_ret;
933 Error *err;
934 bool done, only_structured;
935 } NBDReplyChunkIter;
937 static void nbd_iter_channel_error(NBDReplyChunkIter *iter,
938 int ret, Error **local_err)
940 assert(local_err && *local_err);
941 assert(ret < 0);
943 if (!iter->ret) {
944 iter->ret = ret;
945 error_propagate(&iter->err, *local_err);
946 } else {
947 error_free(*local_err);
950 *local_err = NULL;
953 static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret)
955 assert(ret < 0);
957 if (!iter->request_ret) {
958 iter->request_ret = ret;
963 * NBD_FOREACH_REPLY_CHUNK
964 * The pointer stored in @payload requires g_free() to free it.
966 #define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
967 qiov, reply, payload) \
968 for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
969 nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
972 * nbd_reply_chunk_iter_receive
973 * The pointer stored in @payload requires g_free() to free it.
975 static bool nbd_reply_chunk_iter_receive(BDRVNBDState *s,
976 NBDReplyChunkIter *iter,
977 uint64_t handle,
978 QEMUIOVector *qiov, NBDReply *reply,
979 void **payload)
981 int ret, request_ret;
982 NBDReply local_reply;
983 NBDStructuredReplyChunk *chunk;
984 Error *local_err = NULL;
985 if (!nbd_client_connected(s)) {
986 error_setg(&local_err, "Connection closed");
987 nbd_iter_channel_error(iter, -EIO, &local_err);
988 goto break_loop;
991 if (iter->done) {
992 /* Previous iteration was last. */
993 goto break_loop;
996 if (reply == NULL) {
997 reply = &local_reply;
1000 ret = nbd_co_receive_one_chunk(s, handle, iter->only_structured,
1001 &request_ret, qiov, reply, payload,
1002 &local_err);
1003 if (ret < 0) {
1004 nbd_iter_channel_error(iter, ret, &local_err);
1005 } else if (request_ret < 0) {
1006 nbd_iter_request_error(iter, request_ret);
1009 /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
1010 if (nbd_reply_is_simple(reply) || !nbd_client_connected(s)) {
1011 goto break_loop;
1014 chunk = &reply->structured;
1015 iter->only_structured = true;
1017 if (chunk->type == NBD_REPLY_TYPE_NONE) {
1018 /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
1019 assert(chunk->flags & NBD_REPLY_FLAG_DONE);
1020 goto break_loop;
1023 if (chunk->flags & NBD_REPLY_FLAG_DONE) {
1024 /* This iteration is last. */
1025 iter->done = true;
1028 /* Execute the loop body */
1029 return true;
1031 break_loop:
1032 s->requests[HANDLE_TO_INDEX(s, handle)].coroutine = NULL;
1034 qemu_co_mutex_lock(&s->send_mutex);
1035 s->in_flight--;
1036 qemu_co_queue_next(&s->free_sema);
1037 qemu_co_mutex_unlock(&s->send_mutex);
1039 return false;
1042 static int coroutine_fn nbd_co_receive_return_code(BDRVNBDState *s, uint64_t handle,
1043 int *request_ret, Error **errp)
1045 NBDReplyChunkIter iter;
1047 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, NULL, NULL) {
1048 /* nbd_reply_chunk_iter_receive does all the work */
1051 error_propagate(errp, iter.err);
1052 *request_ret = iter.request_ret;
1053 return iter.ret;
1056 static int coroutine_fn nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t handle,
1057 uint64_t offset, QEMUIOVector *qiov,
1058 int *request_ret, Error **errp)
1060 NBDReplyChunkIter iter;
1061 NBDReply reply;
1062 void *payload = NULL;
1063 Error *local_err = NULL;
1065 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, s->info.structured_reply,
1066 qiov, &reply, &payload)
1068 int ret;
1069 NBDStructuredReplyChunk *chunk = &reply.structured;
1071 assert(nbd_reply_is_structured(&reply));
1073 switch (chunk->type) {
1074 case NBD_REPLY_TYPE_OFFSET_DATA:
1076 * special cased in nbd_co_receive_one_chunk, data is already
1077 * in qiov
1079 break;
1080 case NBD_REPLY_TYPE_OFFSET_HOLE:
1081 ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload,
1082 offset, qiov, &local_err);
1083 if (ret < 0) {
1084 nbd_channel_error(s, ret);
1085 nbd_iter_channel_error(&iter, ret, &local_err);
1087 break;
1088 default:
1089 if (!nbd_reply_type_is_error(chunk->type)) {
1090 /* not allowed reply type */
1091 nbd_channel_error(s, -EINVAL);
1092 error_setg(&local_err,
1093 "Unexpected reply type: %d (%s) for CMD_READ",
1094 chunk->type, nbd_reply_type_lookup(chunk->type));
1095 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1099 g_free(payload);
1100 payload = NULL;
1103 error_propagate(errp, iter.err);
1104 *request_ret = iter.request_ret;
1105 return iter.ret;
1108 static int coroutine_fn nbd_co_receive_blockstatus_reply(BDRVNBDState *s,
1109 uint64_t handle, uint64_t length,
1110 NBDExtent *extent,
1111 int *request_ret, Error **errp)
1113 NBDReplyChunkIter iter;
1114 NBDReply reply;
1115 void *payload = NULL;
1116 Error *local_err = NULL;
1117 bool received = false;
1119 assert(!extent->length);
1120 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, &reply, &payload) {
1121 int ret;
1122 NBDStructuredReplyChunk *chunk = &reply.structured;
1124 assert(nbd_reply_is_structured(&reply));
1126 switch (chunk->type) {
1127 case NBD_REPLY_TYPE_BLOCK_STATUS:
1128 if (received) {
1129 nbd_channel_error(s, -EINVAL);
1130 error_setg(&local_err, "Several BLOCK_STATUS chunks in reply");
1131 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1133 received = true;
1135 ret = nbd_parse_blockstatus_payload(s, &reply.structured,
1136 payload, length, extent,
1137 &local_err);
1138 if (ret < 0) {
1139 nbd_channel_error(s, ret);
1140 nbd_iter_channel_error(&iter, ret, &local_err);
1142 break;
1143 default:
1144 if (!nbd_reply_type_is_error(chunk->type)) {
1145 nbd_channel_error(s, -EINVAL);
1146 error_setg(&local_err,
1147 "Unexpected reply type: %d (%s) "
1148 "for CMD_BLOCK_STATUS",
1149 chunk->type, nbd_reply_type_lookup(chunk->type));
1150 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1154 g_free(payload);
1155 payload = NULL;
1158 if (!extent->length && !iter.request_ret) {
1159 error_setg(&local_err, "Server did not reply with any status extents");
1160 nbd_iter_channel_error(&iter, -EIO, &local_err);
1163 error_propagate(errp, iter.err);
1164 *request_ret = iter.request_ret;
1165 return iter.ret;
1168 static int coroutine_fn nbd_co_request(BlockDriverState *bs, NBDRequest *request,
1169 QEMUIOVector *write_qiov)
1171 int ret, request_ret;
1172 Error *local_err = NULL;
1173 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1175 assert(request->type != NBD_CMD_READ);
1176 if (write_qiov) {
1177 assert(request->type == NBD_CMD_WRITE);
1178 assert(request->len == iov_size(write_qiov->iov, write_qiov->niov));
1179 } else {
1180 assert(request->type != NBD_CMD_WRITE);
1183 do {
1184 ret = nbd_co_send_request(bs, request, write_qiov);
1185 if (ret < 0) {
1186 continue;
1189 ret = nbd_co_receive_return_code(s, request->handle,
1190 &request_ret, &local_err);
1191 if (local_err) {
1192 trace_nbd_co_request_fail(request->from, request->len,
1193 request->handle, request->flags,
1194 request->type,
1195 nbd_cmd_lookup(request->type),
1196 ret, error_get_pretty(local_err));
1197 error_free(local_err);
1198 local_err = NULL;
1200 } while (ret < 0 && nbd_client_connecting_wait(s));
1202 return ret ? ret : request_ret;
1205 static int coroutine_fn nbd_client_co_preadv(BlockDriverState *bs, int64_t offset,
1206 int64_t bytes, QEMUIOVector *qiov,
1207 BdrvRequestFlags flags)
1209 int ret, request_ret;
1210 Error *local_err = NULL;
1211 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1212 NBDRequest request = {
1213 .type = NBD_CMD_READ,
1214 .from = offset,
1215 .len = bytes,
1218 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1219 assert(!flags);
1221 if (!bytes) {
1222 return 0;
1225 * Work around the fact that the block layer doesn't do
1226 * byte-accurate sizing yet - if the read exceeds the server's
1227 * advertised size because the block layer rounded size up, then
1228 * truncate the request to the server and tail-pad with zero.
1230 if (offset >= s->info.size) {
1231 assert(bytes < BDRV_SECTOR_SIZE);
1232 qemu_iovec_memset(qiov, 0, 0, bytes);
1233 return 0;
1235 if (offset + bytes > s->info.size) {
1236 uint64_t slop = offset + bytes - s->info.size;
1238 assert(slop < BDRV_SECTOR_SIZE);
1239 qemu_iovec_memset(qiov, bytes - slop, 0, slop);
1240 request.len -= slop;
1243 do {
1244 ret = nbd_co_send_request(bs, &request, NULL);
1245 if (ret < 0) {
1246 continue;
1249 ret = nbd_co_receive_cmdread_reply(s, request.handle, offset, qiov,
1250 &request_ret, &local_err);
1251 if (local_err) {
1252 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1253 request.flags, request.type,
1254 nbd_cmd_lookup(request.type),
1255 ret, error_get_pretty(local_err));
1256 error_free(local_err);
1257 local_err = NULL;
1259 } while (ret < 0 && nbd_client_connecting_wait(s));
1261 return ret ? ret : request_ret;
1264 static int coroutine_fn nbd_client_co_pwritev(BlockDriverState *bs, int64_t offset,
1265 int64_t bytes, QEMUIOVector *qiov,
1266 BdrvRequestFlags flags)
1268 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1269 NBDRequest request = {
1270 .type = NBD_CMD_WRITE,
1271 .from = offset,
1272 .len = bytes,
1275 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1276 if (flags & BDRV_REQ_FUA) {
1277 assert(s->info.flags & NBD_FLAG_SEND_FUA);
1278 request.flags |= NBD_CMD_FLAG_FUA;
1281 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1283 if (!bytes) {
1284 return 0;
1286 return nbd_co_request(bs, &request, qiov);
1289 static int coroutine_fn nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1290 int64_t bytes, BdrvRequestFlags flags)
1292 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1293 NBDRequest request = {
1294 .type = NBD_CMD_WRITE_ZEROES,
1295 .from = offset,
1296 .len = bytes, /* .len is uint32_t actually */
1299 assert(bytes <= UINT32_MAX); /* rely on max_pwrite_zeroes */
1301 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1302 if (!(s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {
1303 return -ENOTSUP;
1306 if (flags & BDRV_REQ_FUA) {
1307 assert(s->info.flags & NBD_FLAG_SEND_FUA);
1308 request.flags |= NBD_CMD_FLAG_FUA;
1310 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1311 request.flags |= NBD_CMD_FLAG_NO_HOLE;
1313 if (flags & BDRV_REQ_NO_FALLBACK) {
1314 assert(s->info.flags & NBD_FLAG_SEND_FAST_ZERO);
1315 request.flags |= NBD_CMD_FLAG_FAST_ZERO;
1318 if (!bytes) {
1319 return 0;
1321 return nbd_co_request(bs, &request, NULL);
1324 static int coroutine_fn nbd_client_co_flush(BlockDriverState *bs)
1326 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1327 NBDRequest request = { .type = NBD_CMD_FLUSH };
1329 if (!(s->info.flags & NBD_FLAG_SEND_FLUSH)) {
1330 return 0;
1333 request.from = 0;
1334 request.len = 0;
1336 return nbd_co_request(bs, &request, NULL);
1339 static int coroutine_fn nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset,
1340 int64_t bytes)
1342 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1343 NBDRequest request = {
1344 .type = NBD_CMD_TRIM,
1345 .from = offset,
1346 .len = bytes, /* len is uint32_t */
1349 assert(bytes <= UINT32_MAX); /* rely on max_pdiscard */
1351 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1352 if (!(s->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) {
1353 return 0;
1356 return nbd_co_request(bs, &request, NULL);
1359 static int coroutine_fn nbd_client_co_block_status(
1360 BlockDriverState *bs, bool want_zero, int64_t offset, int64_t bytes,
1361 int64_t *pnum, int64_t *map, BlockDriverState **file)
1363 int ret, request_ret;
1364 NBDExtent extent = { 0 };
1365 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1366 Error *local_err = NULL;
1368 NBDRequest request = {
1369 .type = NBD_CMD_BLOCK_STATUS,
1370 .from = offset,
1371 .len = MIN(QEMU_ALIGN_DOWN(INT_MAX, bs->bl.request_alignment),
1372 MIN(bytes, s->info.size - offset)),
1373 .flags = NBD_CMD_FLAG_REQ_ONE,
1376 if (!s->info.base_allocation) {
1377 *pnum = bytes;
1378 *map = offset;
1379 *file = bs;
1380 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
1384 * Work around the fact that the block layer doesn't do
1385 * byte-accurate sizing yet - if the status request exceeds the
1386 * server's advertised size because the block layer rounded size
1387 * up, we truncated the request to the server (above), or are
1388 * called on just the hole.
1390 if (offset >= s->info.size) {
1391 *pnum = bytes;
1392 assert(bytes < BDRV_SECTOR_SIZE);
1393 /* Intentionally don't report offset_valid for the hole */
1394 return BDRV_BLOCK_ZERO;
1397 if (s->info.min_block) {
1398 assert(QEMU_IS_ALIGNED(request.len, s->info.min_block));
1400 do {
1401 ret = nbd_co_send_request(bs, &request, NULL);
1402 if (ret < 0) {
1403 continue;
1406 ret = nbd_co_receive_blockstatus_reply(s, request.handle, bytes,
1407 &extent, &request_ret,
1408 &local_err);
1409 if (local_err) {
1410 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1411 request.flags, request.type,
1412 nbd_cmd_lookup(request.type),
1413 ret, error_get_pretty(local_err));
1414 error_free(local_err);
1415 local_err = NULL;
1417 } while (ret < 0 && nbd_client_connecting_wait(s));
1419 if (ret < 0 || request_ret < 0) {
1420 return ret ? ret : request_ret;
1423 assert(extent.length);
1424 *pnum = extent.length;
1425 *map = offset;
1426 *file = bs;
1427 return (extent.flags & NBD_STATE_HOLE ? 0 : BDRV_BLOCK_DATA) |
1428 (extent.flags & NBD_STATE_ZERO ? BDRV_BLOCK_ZERO : 0) |
1429 BDRV_BLOCK_OFFSET_VALID;
1432 static int nbd_client_reopen_prepare(BDRVReopenState *state,
1433 BlockReopenQueue *queue, Error **errp)
1435 BDRVNBDState *s = (BDRVNBDState *)state->bs->opaque;
1437 if ((state->flags & BDRV_O_RDWR) && (s->info.flags & NBD_FLAG_READ_ONLY)) {
1438 error_setg(errp, "Can't reopen read-only NBD mount as read/write");
1439 return -EACCES;
1441 return 0;
1444 static void nbd_yank(void *opaque)
1446 BlockDriverState *bs = opaque;
1447 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1449 qatomic_store_release(&s->state, NBD_CLIENT_QUIT);
1450 qio_channel_shutdown(QIO_CHANNEL(s->ioc), QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
1453 static void nbd_client_close(BlockDriverState *bs)
1455 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1456 NBDRequest request = { .type = NBD_CMD_DISC };
1458 if (s->ioc) {
1459 nbd_send_request(s->ioc, &request);
1462 nbd_teardown_connection(bs);
1467 * Parse nbd_open options
1470 static int nbd_parse_uri(const char *filename, QDict *options)
1472 URI *uri;
1473 const char *p;
1474 QueryParams *qp = NULL;
1475 int ret = 0;
1476 bool is_unix;
1478 uri = uri_parse(filename);
1479 if (!uri) {
1480 return -EINVAL;
1483 /* transport */
1484 if (!g_strcmp0(uri->scheme, "nbd")) {
1485 is_unix = false;
1486 } else if (!g_strcmp0(uri->scheme, "nbd+tcp")) {
1487 is_unix = false;
1488 } else if (!g_strcmp0(uri->scheme, "nbd+unix")) {
1489 is_unix = true;
1490 } else {
1491 ret = -EINVAL;
1492 goto out;
1495 p = uri->path ? uri->path : "";
1496 if (p[0] == '/') {
1497 p++;
1499 if (p[0]) {
1500 qdict_put_str(options, "export", p);
1503 qp = query_params_parse(uri->query);
1504 if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
1505 ret = -EINVAL;
1506 goto out;
1509 if (is_unix) {
1510 /* nbd+unix:///export?socket=path */
1511 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
1512 ret = -EINVAL;
1513 goto out;
1515 qdict_put_str(options, "server.type", "unix");
1516 qdict_put_str(options, "server.path", qp->p[0].value);
1517 } else {
1518 QString *host;
1519 char *port_str;
1521 /* nbd[+tcp]://host[:port]/export */
1522 if (!uri->server) {
1523 ret = -EINVAL;
1524 goto out;
1527 /* strip braces from literal IPv6 address */
1528 if (uri->server[0] == '[') {
1529 host = qstring_from_substr(uri->server, 1,
1530 strlen(uri->server) - 1);
1531 } else {
1532 host = qstring_from_str(uri->server);
1535 qdict_put_str(options, "server.type", "inet");
1536 qdict_put(options, "server.host", host);
1538 port_str = g_strdup_printf("%d", uri->port ?: NBD_DEFAULT_PORT);
1539 qdict_put_str(options, "server.port", port_str);
1540 g_free(port_str);
1543 out:
1544 if (qp) {
1545 query_params_free(qp);
1547 uri_free(uri);
1548 return ret;
1551 static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
1553 const QDictEntry *e;
1555 for (e = qdict_first(options); e; e = qdict_next(options, e)) {
1556 if (!strcmp(e->key, "host") ||
1557 !strcmp(e->key, "port") ||
1558 !strcmp(e->key, "path") ||
1559 !strcmp(e->key, "export") ||
1560 strstart(e->key, "server.", NULL))
1562 error_setg(errp, "Option '%s' cannot be used with a file name",
1563 e->key);
1564 return true;
1568 return false;
1571 static void nbd_parse_filename(const char *filename, QDict *options,
1572 Error **errp)
1574 g_autofree char *file = NULL;
1575 char *export_name;
1576 const char *host_spec;
1577 const char *unixpath;
1579 if (nbd_has_filename_options_conflict(options, errp)) {
1580 return;
1583 if (strstr(filename, "://")) {
1584 int ret = nbd_parse_uri(filename, options);
1585 if (ret < 0) {
1586 error_setg(errp, "No valid URL specified");
1588 return;
1591 file = g_strdup(filename);
1593 export_name = strstr(file, EN_OPTSTR);
1594 if (export_name) {
1595 if (export_name[strlen(EN_OPTSTR)] == 0) {
1596 return;
1598 export_name[0] = 0; /* truncate 'file' */
1599 export_name += strlen(EN_OPTSTR);
1601 qdict_put_str(options, "export", export_name);
1604 /* extract the host_spec - fail if it's not nbd:... */
1605 if (!strstart(file, "nbd:", &host_spec)) {
1606 error_setg(errp, "File name string for NBD must start with 'nbd:'");
1607 return;
1610 if (!*host_spec) {
1611 return;
1614 /* are we a UNIX or TCP socket? */
1615 if (strstart(host_spec, "unix:", &unixpath)) {
1616 qdict_put_str(options, "server.type", "unix");
1617 qdict_put_str(options, "server.path", unixpath);
1618 } else {
1619 InetSocketAddress *addr = g_new(InetSocketAddress, 1);
1621 if (inet_parse(addr, host_spec, errp)) {
1622 goto out_inet;
1625 qdict_put_str(options, "server.type", "inet");
1626 qdict_put_str(options, "server.host", addr->host);
1627 qdict_put_str(options, "server.port", addr->port);
1628 out_inet:
1629 qapi_free_InetSocketAddress(addr);
1633 static bool nbd_process_legacy_socket_options(QDict *output_options,
1634 QemuOpts *legacy_opts,
1635 Error **errp)
1637 const char *path = qemu_opt_get(legacy_opts, "path");
1638 const char *host = qemu_opt_get(legacy_opts, "host");
1639 const char *port = qemu_opt_get(legacy_opts, "port");
1640 const QDictEntry *e;
1642 if (!path && !host && !port) {
1643 return true;
1646 for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
1648 if (strstart(e->key, "server.", NULL)) {
1649 error_setg(errp, "Cannot use 'server' and path/host/port at the "
1650 "same time");
1651 return false;
1655 if (path && host) {
1656 error_setg(errp, "path and host may not be used at the same time");
1657 return false;
1658 } else if (path) {
1659 if (port) {
1660 error_setg(errp, "port may not be used without host");
1661 return false;
1664 qdict_put_str(output_options, "server.type", "unix");
1665 qdict_put_str(output_options, "server.path", path);
1666 } else if (host) {
1667 qdict_put_str(output_options, "server.type", "inet");
1668 qdict_put_str(output_options, "server.host", host);
1669 qdict_put_str(output_options, "server.port",
1670 port ?: stringify(NBD_DEFAULT_PORT));
1673 return true;
1676 static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options,
1677 Error **errp)
1679 SocketAddress *saddr = NULL;
1680 QDict *addr = NULL;
1681 Visitor *iv = NULL;
1683 qdict_extract_subqdict(options, &addr, "server.");
1684 if (!qdict_size(addr)) {
1685 error_setg(errp, "NBD server address missing");
1686 goto done;
1689 iv = qobject_input_visitor_new_flat_confused(addr, errp);
1690 if (!iv) {
1691 goto done;
1694 if (!visit_type_SocketAddress(iv, NULL, &saddr, errp)) {
1695 goto done;
1698 if (socket_address_parse_named_fd(saddr, errp) < 0) {
1699 qapi_free_SocketAddress(saddr);
1700 saddr = NULL;
1701 goto done;
1704 done:
1705 qobject_unref(addr);
1706 visit_free(iv);
1707 return saddr;
1710 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
1712 Object *obj;
1713 QCryptoTLSCreds *creds;
1715 obj = object_resolve_path_component(
1716 object_get_objects_root(), id);
1717 if (!obj) {
1718 error_setg(errp, "No TLS credentials with id '%s'",
1719 id);
1720 return NULL;
1722 creds = (QCryptoTLSCreds *)
1723 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
1724 if (!creds) {
1725 error_setg(errp, "Object with id '%s' is not TLS credentials",
1726 id);
1727 return NULL;
1730 if (!qcrypto_tls_creds_check_endpoint(creds,
1731 QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT,
1732 errp)) {
1733 return NULL;
1735 object_ref(obj);
1736 return creds;
1740 static QemuOptsList nbd_runtime_opts = {
1741 .name = "nbd",
1742 .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
1743 .desc = {
1745 .name = "host",
1746 .type = QEMU_OPT_STRING,
1747 .help = "TCP host to connect to",
1750 .name = "port",
1751 .type = QEMU_OPT_STRING,
1752 .help = "TCP port to connect to",
1755 .name = "path",
1756 .type = QEMU_OPT_STRING,
1757 .help = "Unix socket path to connect to",
1760 .name = "export",
1761 .type = QEMU_OPT_STRING,
1762 .help = "Name of the NBD export to open",
1765 .name = "tls-creds",
1766 .type = QEMU_OPT_STRING,
1767 .help = "ID of the TLS credentials to use",
1770 .name = "tls-hostname",
1771 .type = QEMU_OPT_STRING,
1772 .help = "Override hostname for validating TLS x509 certificate",
1775 .name = "x-dirty-bitmap",
1776 .type = QEMU_OPT_STRING,
1777 .help = "experimental: expose named dirty bitmap in place of "
1778 "block status",
1781 .name = "reconnect-delay",
1782 .type = QEMU_OPT_NUMBER,
1783 .help = "On an unexpected disconnect, the nbd client tries to "
1784 "connect again until succeeding or encountering a serious "
1785 "error. During the first @reconnect-delay seconds, all "
1786 "requests are paused and will be rerun on a successful "
1787 "reconnect. After that time, any delayed requests and all "
1788 "future requests before a successful reconnect will "
1789 "immediately fail. Default 0",
1792 .name = "open-timeout",
1793 .type = QEMU_OPT_NUMBER,
1794 .help = "In seconds. If zero, the nbd driver tries the connection "
1795 "only once, and fails to open if the connection fails. "
1796 "If non-zero, the nbd driver will repeat connection "
1797 "attempts until successful or until @open-timeout seconds "
1798 "have elapsed. Default 0",
1800 { /* end of list */ }
1804 static int nbd_process_options(BlockDriverState *bs, QDict *options,
1805 Error **errp)
1807 BDRVNBDState *s = bs->opaque;
1808 QemuOpts *opts;
1809 int ret = -EINVAL;
1811 opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
1812 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1813 goto error;
1816 /* Translate @host, @port, and @path to a SocketAddress */
1817 if (!nbd_process_legacy_socket_options(options, opts, errp)) {
1818 goto error;
1821 /* Pop the config into our state object. Exit if invalid. */
1822 s->saddr = nbd_config(s, options, errp);
1823 if (!s->saddr) {
1824 goto error;
1827 s->export = g_strdup(qemu_opt_get(opts, "export"));
1828 if (s->export && strlen(s->export) > NBD_MAX_STRING_SIZE) {
1829 error_setg(errp, "export name too long to send to server");
1830 goto error;
1833 s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
1834 if (s->tlscredsid) {
1835 s->tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
1836 if (!s->tlscreds) {
1837 goto error;
1840 s->tlshostname = g_strdup(qemu_opt_get(opts, "tls-hostname"));
1841 if (!s->tlshostname &&
1842 s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
1843 s->tlshostname = g_strdup(s->saddr->u.inet.host);
1847 s->x_dirty_bitmap = g_strdup(qemu_opt_get(opts, "x-dirty-bitmap"));
1848 if (s->x_dirty_bitmap && strlen(s->x_dirty_bitmap) > NBD_MAX_STRING_SIZE) {
1849 error_setg(errp, "x-dirty-bitmap query too long to send to server");
1850 goto error;
1853 s->reconnect_delay = qemu_opt_get_number(opts, "reconnect-delay", 0);
1854 s->open_timeout = qemu_opt_get_number(opts, "open-timeout", 0);
1856 ret = 0;
1858 error:
1859 qemu_opts_del(opts);
1860 return ret;
1863 static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
1864 Error **errp)
1866 int ret;
1867 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1869 s->bs = bs;
1870 qemu_co_mutex_init(&s->send_mutex);
1871 qemu_co_queue_init(&s->free_sema);
1872 qemu_co_mutex_init(&s->receive_mutex);
1874 if (!yank_register_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name), errp)) {
1875 return -EEXIST;
1878 ret = nbd_process_options(bs, options, errp);
1879 if (ret < 0) {
1880 goto fail;
1883 s->conn = nbd_client_connection_new(s->saddr, true, s->export,
1884 s->x_dirty_bitmap, s->tlscreds,
1885 s->tlshostname);
1887 if (s->open_timeout) {
1888 nbd_client_connection_enable_retry(s->conn);
1889 open_timer_init(s, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
1890 s->open_timeout * NANOSECONDS_PER_SECOND);
1893 s->state = NBD_CLIENT_CONNECTING_WAIT;
1894 ret = nbd_do_establish_connection(bs, errp);
1895 if (ret < 0) {
1896 goto fail;
1900 * The connect attempt is done, so we no longer need this timer.
1901 * Delete it, because we do not want it to be around when this node
1902 * is drained or closed.
1904 open_timer_del(s);
1906 nbd_client_connection_enable_retry(s->conn);
1908 return 0;
1910 fail:
1911 open_timer_del(s);
1912 nbd_clear_bdrvstate(bs);
1913 return ret;
1916 static int coroutine_fn nbd_co_flush(BlockDriverState *bs)
1918 return nbd_client_co_flush(bs);
1921 static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
1923 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1924 uint32_t min = s->info.min_block;
1925 uint32_t max = MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE, s->info.max_block);
1928 * If the server did not advertise an alignment:
1929 * - a size that is not sector-aligned implies that an alignment
1930 * of 1 can be used to access those tail bytes
1931 * - advertisement of block status requires an alignment of 1, so
1932 * that we don't violate block layer constraints that block
1933 * status is always aligned (as we can't control whether the
1934 * server will report sub-sector extents, such as a hole at EOF
1935 * on an unaligned POSIX file)
1936 * - otherwise, assume the server is so old that we are safer avoiding
1937 * sub-sector requests
1939 if (!min) {
1940 min = (!QEMU_IS_ALIGNED(s->info.size, BDRV_SECTOR_SIZE) ||
1941 s->info.base_allocation) ? 1 : BDRV_SECTOR_SIZE;
1944 bs->bl.request_alignment = min;
1945 bs->bl.max_pdiscard = QEMU_ALIGN_DOWN(INT_MAX, min);
1946 bs->bl.max_pwrite_zeroes = max;
1947 bs->bl.max_transfer = max;
1949 if (s->info.opt_block &&
1950 s->info.opt_block > bs->bl.opt_transfer) {
1951 bs->bl.opt_transfer = s->info.opt_block;
1955 static void nbd_close(BlockDriverState *bs)
1957 nbd_client_close(bs);
1958 nbd_clear_bdrvstate(bs);
1962 * NBD cannot truncate, but if the caller asks to truncate to the same size, or
1963 * to a smaller size with exact=false, there is no reason to fail the
1964 * operation.
1966 * Preallocation mode is ignored since it does not seems useful to fail when
1967 * we never change anything.
1969 static int coroutine_fn nbd_co_truncate(BlockDriverState *bs, int64_t offset,
1970 bool exact, PreallocMode prealloc,
1971 BdrvRequestFlags flags, Error **errp)
1973 BDRVNBDState *s = bs->opaque;
1975 if (offset != s->info.size && exact) {
1976 error_setg(errp, "Cannot resize NBD nodes");
1977 return -ENOTSUP;
1980 if (offset > s->info.size) {
1981 error_setg(errp, "Cannot grow NBD nodes");
1982 return -EINVAL;
1985 return 0;
1988 static int64_t nbd_getlength(BlockDriverState *bs)
1990 BDRVNBDState *s = bs->opaque;
1992 return s->info.size;
1995 static void nbd_refresh_filename(BlockDriverState *bs)
1997 BDRVNBDState *s = bs->opaque;
1998 const char *host = NULL, *port = NULL, *path = NULL;
1999 size_t len = 0;
2001 if (s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
2002 const InetSocketAddress *inet = &s->saddr->u.inet;
2003 if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) {
2004 host = inet->host;
2005 port = inet->port;
2007 } else if (s->saddr->type == SOCKET_ADDRESS_TYPE_UNIX) {
2008 path = s->saddr->u.q_unix.path;
2009 } /* else can't represent as pseudo-filename */
2011 if (path && s->export) {
2012 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2013 "nbd+unix:///%s?socket=%s", s->export, path);
2014 } else if (path && !s->export) {
2015 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2016 "nbd+unix://?socket=%s", path);
2017 } else if (host && s->export) {
2018 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2019 "nbd://%s:%s/%s", host, port, s->export);
2020 } else if (host && !s->export) {
2021 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2022 "nbd://%s:%s", host, port);
2024 if (len >= sizeof(bs->exact_filename)) {
2025 /* Name is too long to represent exactly, so leave it empty. */
2026 bs->exact_filename[0] = '\0';
2030 static char *nbd_dirname(BlockDriverState *bs, Error **errp)
2032 /* The generic bdrv_dirname() implementation is able to work out some
2033 * directory name for NBD nodes, but that would be wrong. So far there is no
2034 * specification for how "export paths" would work, so NBD does not have
2035 * directory names. */
2036 error_setg(errp, "Cannot generate a base directory for NBD nodes");
2037 return NULL;
2040 static const char *const nbd_strong_runtime_opts[] = {
2041 "path",
2042 "host",
2043 "port",
2044 "export",
2045 "tls-creds",
2046 "tls-hostname",
2047 "server.",
2049 NULL
2052 static void nbd_cancel_in_flight(BlockDriverState *bs)
2054 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2056 reconnect_delay_timer_del(s);
2058 if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
2059 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
2060 qemu_co_queue_restart_all(&s->free_sema);
2063 nbd_co_establish_connection_cancel(s->conn);
2066 static void nbd_attach_aio_context(BlockDriverState *bs,
2067 AioContext *new_context)
2069 BDRVNBDState *s = bs->opaque;
2071 /* The open_timer is used only during nbd_open() */
2072 assert(!s->open_timer);
2075 * The reconnect_delay_timer is scheduled in I/O paths when the
2076 * connection is lost, to cancel the reconnection attempt after a
2077 * given time. Once this attempt is done (successfully or not),
2078 * nbd_reconnect_attempt() ensures the timer is deleted before the
2079 * respective I/O request is resumed.
2080 * Since the AioContext can only be changed when a node is drained,
2081 * the reconnect_delay_timer cannot be active here.
2083 assert(!s->reconnect_delay_timer);
2085 if (s->ioc) {
2086 qio_channel_attach_aio_context(s->ioc, new_context);
2090 static void nbd_detach_aio_context(BlockDriverState *bs)
2092 BDRVNBDState *s = bs->opaque;
2094 assert(!s->open_timer);
2095 assert(!s->reconnect_delay_timer);
2097 if (s->ioc) {
2098 qio_channel_detach_aio_context(s->ioc);
2102 static BlockDriver bdrv_nbd = {
2103 .format_name = "nbd",
2104 .protocol_name = "nbd",
2105 .instance_size = sizeof(BDRVNBDState),
2106 .bdrv_parse_filename = nbd_parse_filename,
2107 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2108 .create_opts = &bdrv_create_opts_simple,
2109 .bdrv_file_open = nbd_open,
2110 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2111 .bdrv_co_preadv = nbd_client_co_preadv,
2112 .bdrv_co_pwritev = nbd_client_co_pwritev,
2113 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2114 .bdrv_close = nbd_close,
2115 .bdrv_co_flush_to_os = nbd_co_flush,
2116 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2117 .bdrv_refresh_limits = nbd_refresh_limits,
2118 .bdrv_co_truncate = nbd_co_truncate,
2119 .bdrv_getlength = nbd_getlength,
2120 .bdrv_refresh_filename = nbd_refresh_filename,
2121 .bdrv_co_block_status = nbd_client_co_block_status,
2122 .bdrv_dirname = nbd_dirname,
2123 .strong_runtime_opts = nbd_strong_runtime_opts,
2124 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2126 .bdrv_attach_aio_context = nbd_attach_aio_context,
2127 .bdrv_detach_aio_context = nbd_detach_aio_context,
2130 static BlockDriver bdrv_nbd_tcp = {
2131 .format_name = "nbd",
2132 .protocol_name = "nbd+tcp",
2133 .instance_size = sizeof(BDRVNBDState),
2134 .bdrv_parse_filename = nbd_parse_filename,
2135 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2136 .create_opts = &bdrv_create_opts_simple,
2137 .bdrv_file_open = nbd_open,
2138 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2139 .bdrv_co_preadv = nbd_client_co_preadv,
2140 .bdrv_co_pwritev = nbd_client_co_pwritev,
2141 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2142 .bdrv_close = nbd_close,
2143 .bdrv_co_flush_to_os = nbd_co_flush,
2144 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2145 .bdrv_refresh_limits = nbd_refresh_limits,
2146 .bdrv_co_truncate = nbd_co_truncate,
2147 .bdrv_getlength = nbd_getlength,
2148 .bdrv_refresh_filename = nbd_refresh_filename,
2149 .bdrv_co_block_status = nbd_client_co_block_status,
2150 .bdrv_dirname = nbd_dirname,
2151 .strong_runtime_opts = nbd_strong_runtime_opts,
2152 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2154 .bdrv_attach_aio_context = nbd_attach_aio_context,
2155 .bdrv_detach_aio_context = nbd_detach_aio_context,
2158 static BlockDriver bdrv_nbd_unix = {
2159 .format_name = "nbd",
2160 .protocol_name = "nbd+unix",
2161 .instance_size = sizeof(BDRVNBDState),
2162 .bdrv_parse_filename = nbd_parse_filename,
2163 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2164 .create_opts = &bdrv_create_opts_simple,
2165 .bdrv_file_open = nbd_open,
2166 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2167 .bdrv_co_preadv = nbd_client_co_preadv,
2168 .bdrv_co_pwritev = nbd_client_co_pwritev,
2169 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2170 .bdrv_close = nbd_close,
2171 .bdrv_co_flush_to_os = nbd_co_flush,
2172 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2173 .bdrv_refresh_limits = nbd_refresh_limits,
2174 .bdrv_co_truncate = nbd_co_truncate,
2175 .bdrv_getlength = nbd_getlength,
2176 .bdrv_refresh_filename = nbd_refresh_filename,
2177 .bdrv_co_block_status = nbd_client_co_block_status,
2178 .bdrv_dirname = nbd_dirname,
2179 .strong_runtime_opts = nbd_strong_runtime_opts,
2180 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2182 .bdrv_attach_aio_context = nbd_attach_aio_context,
2183 .bdrv_detach_aio_context = nbd_detach_aio_context,
2186 static void bdrv_nbd_init(void)
2188 bdrv_register(&bdrv_nbd);
2189 bdrv_register(&bdrv_nbd_tcp);
2190 bdrv_register(&bdrv_nbd_unix);
2193 block_init(bdrv_nbd_init);