ppc/pnv: set phb4 properties in stk_realize()
[qemu/rayw.git] / block / nbd.c
blob63dbfa807d023000894c78cac3e93703c4d684d3
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 static coroutine_fn int nbd_receive_replies(BDRVNBDState *s, uint64_t handle)
388 int ret;
389 uint64_t ind = HANDLE_TO_INDEX(s, handle), ind2;
390 QEMU_LOCK_GUARD(&s->receive_mutex);
392 while (true) {
393 if (s->reply.handle == handle) {
394 /* We are done */
395 return 0;
398 if (!nbd_client_connected(s)) {
399 return -EIO;
402 if (s->reply.handle != 0) {
404 * Some other request is being handled now. It should already be
405 * woken by whoever set s->reply.handle (or never wait in this
406 * yield). So, we should not wake it here.
408 ind2 = HANDLE_TO_INDEX(s, s->reply.handle);
409 assert(!s->requests[ind2].receiving);
411 s->requests[ind].receiving = true;
412 qemu_co_mutex_unlock(&s->receive_mutex);
414 qemu_coroutine_yield();
416 * We may be woken for 3 reasons:
417 * 1. From this function, executing in parallel coroutine, when our
418 * handle is received.
419 * 2. From nbd_channel_error(), when connection is lost.
420 * 3. From nbd_co_receive_one_chunk(), when previous request is
421 * finished and s->reply.handle set to 0.
422 * Anyway, it's OK to lock the mutex and go to the next iteration.
425 qemu_co_mutex_lock(&s->receive_mutex);
426 assert(!s->requests[ind].receiving);
427 continue;
430 /* We are under mutex and handle is 0. We have to do the dirty work. */
431 assert(s->reply.handle == 0);
432 ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, NULL);
433 if (ret <= 0) {
434 ret = ret ? ret : -EIO;
435 nbd_channel_error(s, ret);
436 return ret;
438 if (nbd_reply_is_structured(&s->reply) && !s->info.structured_reply) {
439 nbd_channel_error(s, -EINVAL);
440 return -EINVAL;
442 if (s->reply.handle == handle) {
443 /* We are done */
444 return 0;
446 ind2 = HANDLE_TO_INDEX(s, s->reply.handle);
447 if (ind2 >= MAX_NBD_REQUESTS || !s->requests[ind2].reply_possible) {
448 nbd_channel_error(s, -EINVAL);
449 return -EINVAL;
451 nbd_recv_coroutine_wake_one(&s->requests[ind2]);
455 static int nbd_co_send_request(BlockDriverState *bs,
456 NBDRequest *request,
457 QEMUIOVector *qiov)
459 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
460 int rc, i = -1;
462 qemu_co_mutex_lock(&s->send_mutex);
464 while (s->in_flight == MAX_NBD_REQUESTS ||
465 (!nbd_client_connected(s) && s->in_flight > 0))
467 qemu_co_queue_wait(&s->free_sema, &s->send_mutex);
470 if (nbd_client_connecting(s)) {
471 nbd_reconnect_attempt(s);
474 if (!nbd_client_connected(s)) {
475 rc = -EIO;
476 goto err;
479 s->in_flight++;
481 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
482 if (s->requests[i].coroutine == NULL) {
483 break;
487 g_assert(qemu_in_coroutine());
488 assert(i < MAX_NBD_REQUESTS);
490 s->requests[i].coroutine = qemu_coroutine_self();
491 s->requests[i].offset = request->from;
492 s->requests[i].receiving = false;
493 s->requests[i].reply_possible = true;
495 request->handle = INDEX_TO_HANDLE(s, i);
497 assert(s->ioc);
499 if (qiov) {
500 qio_channel_set_cork(s->ioc, true);
501 rc = nbd_send_request(s->ioc, request);
502 if (nbd_client_connected(s) && rc >= 0) {
503 if (qio_channel_writev_all(s->ioc, qiov->iov, qiov->niov,
504 NULL) < 0) {
505 rc = -EIO;
507 } else if (rc >= 0) {
508 rc = -EIO;
510 qio_channel_set_cork(s->ioc, false);
511 } else {
512 rc = nbd_send_request(s->ioc, request);
515 err:
516 if (rc < 0) {
517 nbd_channel_error(s, rc);
518 if (i != -1) {
519 s->requests[i].coroutine = NULL;
520 s->in_flight--;
521 qemu_co_queue_next(&s->free_sema);
524 qemu_co_mutex_unlock(&s->send_mutex);
525 return rc;
528 static inline uint16_t payload_advance16(uint8_t **payload)
530 *payload += 2;
531 return lduw_be_p(*payload - 2);
534 static inline uint32_t payload_advance32(uint8_t **payload)
536 *payload += 4;
537 return ldl_be_p(*payload - 4);
540 static inline uint64_t payload_advance64(uint8_t **payload)
542 *payload += 8;
543 return ldq_be_p(*payload - 8);
546 static int nbd_parse_offset_hole_payload(BDRVNBDState *s,
547 NBDStructuredReplyChunk *chunk,
548 uint8_t *payload, uint64_t orig_offset,
549 QEMUIOVector *qiov, Error **errp)
551 uint64_t offset;
552 uint32_t hole_size;
554 if (chunk->length != sizeof(offset) + sizeof(hole_size)) {
555 error_setg(errp, "Protocol error: invalid payload for "
556 "NBD_REPLY_TYPE_OFFSET_HOLE");
557 return -EINVAL;
560 offset = payload_advance64(&payload);
561 hole_size = payload_advance32(&payload);
563 if (!hole_size || offset < orig_offset || hole_size > qiov->size ||
564 offset > orig_offset + qiov->size - hole_size) {
565 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
566 " region");
567 return -EINVAL;
569 if (s->info.min_block &&
570 !QEMU_IS_ALIGNED(hole_size, s->info.min_block)) {
571 trace_nbd_structured_read_compliance("hole");
574 qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size);
576 return 0;
580 * nbd_parse_blockstatus_payload
581 * Based on our request, we expect only one extent in reply, for the
582 * base:allocation context.
584 static int nbd_parse_blockstatus_payload(BDRVNBDState *s,
585 NBDStructuredReplyChunk *chunk,
586 uint8_t *payload, uint64_t orig_length,
587 NBDExtent *extent, Error **errp)
589 uint32_t context_id;
591 /* The server succeeded, so it must have sent [at least] one extent */
592 if (chunk->length < sizeof(context_id) + sizeof(*extent)) {
593 error_setg(errp, "Protocol error: invalid payload for "
594 "NBD_REPLY_TYPE_BLOCK_STATUS");
595 return -EINVAL;
598 context_id = payload_advance32(&payload);
599 if (s->info.context_id != context_id) {
600 error_setg(errp, "Protocol error: unexpected context id %d for "
601 "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
602 "id is %d", context_id,
603 s->info.context_id);
604 return -EINVAL;
607 extent->length = payload_advance32(&payload);
608 extent->flags = payload_advance32(&payload);
610 if (extent->length == 0) {
611 error_setg(errp, "Protocol error: server sent status chunk with "
612 "zero length");
613 return -EINVAL;
617 * A server sending unaligned block status is in violation of the
618 * protocol, but as qemu-nbd 3.1 is such a server (at least for
619 * POSIX files that are not a multiple of 512 bytes, since qemu
620 * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
621 * still sees an implicit hole beyond the real EOF), it's nicer to
622 * work around the misbehaving server. If the request included
623 * more than the final unaligned block, truncate it back to an
624 * aligned result; if the request was only the final block, round
625 * up to the full block and change the status to fully-allocated
626 * (always a safe status, even if it loses information).
628 if (s->info.min_block && !QEMU_IS_ALIGNED(extent->length,
629 s->info.min_block)) {
630 trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
631 if (extent->length > s->info.min_block) {
632 extent->length = QEMU_ALIGN_DOWN(extent->length,
633 s->info.min_block);
634 } else {
635 extent->length = s->info.min_block;
636 extent->flags = 0;
641 * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
642 * sent us any more than one extent, nor should it have included
643 * status beyond our request in that extent. However, it's easy
644 * enough to ignore the server's noncompliance without killing the
645 * connection; just ignore trailing extents, and clamp things to
646 * the length of our request.
648 if (chunk->length > sizeof(context_id) + sizeof(*extent)) {
649 trace_nbd_parse_blockstatus_compliance("more than one extent");
651 if (extent->length > orig_length) {
652 extent->length = orig_length;
653 trace_nbd_parse_blockstatus_compliance("extent length too large");
657 * HACK: if we are using x-dirty-bitmaps to access
658 * qemu:allocation-depth, treat all depths > 2 the same as 2,
659 * since nbd_client_co_block_status is only expecting the low two
660 * bits to be set.
662 if (s->alloc_depth && extent->flags > 2) {
663 extent->flags = 2;
666 return 0;
670 * nbd_parse_error_payload
671 * on success @errp contains message describing nbd error reply
673 static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
674 uint8_t *payload, int *request_ret,
675 Error **errp)
677 uint32_t error;
678 uint16_t message_size;
680 assert(chunk->type & (1 << 15));
682 if (chunk->length < sizeof(error) + sizeof(message_size)) {
683 error_setg(errp,
684 "Protocol error: invalid payload for structured error");
685 return -EINVAL;
688 error = nbd_errno_to_system_errno(payload_advance32(&payload));
689 if (error == 0) {
690 error_setg(errp, "Protocol error: server sent structured error chunk "
691 "with error = 0");
692 return -EINVAL;
695 *request_ret = -error;
696 message_size = payload_advance16(&payload);
698 if (message_size > chunk->length - sizeof(error) - sizeof(message_size)) {
699 error_setg(errp, "Protocol error: server sent structured error chunk "
700 "with incorrect message size");
701 return -EINVAL;
704 /* TODO: Add a trace point to mention the server complaint */
706 /* TODO handle ERROR_OFFSET */
708 return 0;
711 static int nbd_co_receive_offset_data_payload(BDRVNBDState *s,
712 uint64_t orig_offset,
713 QEMUIOVector *qiov, Error **errp)
715 QEMUIOVector sub_qiov;
716 uint64_t offset;
717 size_t data_size;
718 int ret;
719 NBDStructuredReplyChunk *chunk = &s->reply.structured;
721 assert(nbd_reply_is_structured(&s->reply));
723 /* The NBD spec requires at least one byte of payload */
724 if (chunk->length <= sizeof(offset)) {
725 error_setg(errp, "Protocol error: invalid payload for "
726 "NBD_REPLY_TYPE_OFFSET_DATA");
727 return -EINVAL;
730 if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) {
731 return -EIO;
734 data_size = chunk->length - sizeof(offset);
735 assert(data_size);
736 if (offset < orig_offset || data_size > qiov->size ||
737 offset > orig_offset + qiov->size - data_size) {
738 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
739 " region");
740 return -EINVAL;
742 if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) {
743 trace_nbd_structured_read_compliance("data");
746 qemu_iovec_init(&sub_qiov, qiov->niov);
747 qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size);
748 ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);
749 qemu_iovec_destroy(&sub_qiov);
751 return ret < 0 ? -EIO : 0;
754 #define NBD_MAX_MALLOC_PAYLOAD 1000
755 static coroutine_fn int nbd_co_receive_structured_payload(
756 BDRVNBDState *s, void **payload, Error **errp)
758 int ret;
759 uint32_t len;
761 assert(nbd_reply_is_structured(&s->reply));
763 len = s->reply.structured.length;
765 if (len == 0) {
766 return 0;
769 if (payload == NULL) {
770 error_setg(errp, "Unexpected structured payload");
771 return -EINVAL;
774 if (len > NBD_MAX_MALLOC_PAYLOAD) {
775 error_setg(errp, "Payload too large");
776 return -EINVAL;
779 *payload = g_new(char, len);
780 ret = nbd_read(s->ioc, *payload, len, "structured payload", errp);
781 if (ret < 0) {
782 g_free(*payload);
783 *payload = NULL;
784 return ret;
787 return 0;
791 * nbd_co_do_receive_one_chunk
792 * for simple reply:
793 * set request_ret to received reply error
794 * if qiov is not NULL: read payload to @qiov
795 * for structured reply chunk:
796 * if error chunk: read payload, set @request_ret, do not set @payload
797 * else if offset_data chunk: read payload data to @qiov, do not set @payload
798 * else: read payload to @payload
800 * If function fails, @errp contains corresponding error message, and the
801 * connection with the server is suspect. If it returns 0, then the
802 * transaction succeeded (although @request_ret may be a negative errno
803 * corresponding to the server's error reply), and errp is unchanged.
805 static coroutine_fn int nbd_co_do_receive_one_chunk(
806 BDRVNBDState *s, uint64_t handle, bool only_structured,
807 int *request_ret, QEMUIOVector *qiov, void **payload, Error **errp)
809 int ret;
810 int i = HANDLE_TO_INDEX(s, handle);
811 void *local_payload = NULL;
812 NBDStructuredReplyChunk *chunk;
814 if (payload) {
815 *payload = NULL;
817 *request_ret = 0;
819 nbd_receive_replies(s, handle);
820 if (!nbd_client_connected(s)) {
821 error_setg(errp, "Connection closed");
822 return -EIO;
824 assert(s->ioc);
826 assert(s->reply.handle == handle);
828 if (nbd_reply_is_simple(&s->reply)) {
829 if (only_structured) {
830 error_setg(errp, "Protocol error: simple reply when structured "
831 "reply chunk was expected");
832 return -EINVAL;
835 *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error);
836 if (*request_ret < 0 || !qiov) {
837 return 0;
840 return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov,
841 errp) < 0 ? -EIO : 0;
844 /* handle structured reply chunk */
845 assert(s->info.structured_reply);
846 chunk = &s->reply.structured;
848 if (chunk->type == NBD_REPLY_TYPE_NONE) {
849 if (!(chunk->flags & NBD_REPLY_FLAG_DONE)) {
850 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
851 " NBD_REPLY_FLAG_DONE flag set");
852 return -EINVAL;
854 if (chunk->length) {
855 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
856 " nonzero length");
857 return -EINVAL;
859 return 0;
862 if (chunk->type == NBD_REPLY_TYPE_OFFSET_DATA) {
863 if (!qiov) {
864 error_setg(errp, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
865 return -EINVAL;
868 return nbd_co_receive_offset_data_payload(s, s->requests[i].offset,
869 qiov, errp);
872 if (nbd_reply_type_is_error(chunk->type)) {
873 payload = &local_payload;
876 ret = nbd_co_receive_structured_payload(s, payload, errp);
877 if (ret < 0) {
878 return ret;
881 if (nbd_reply_type_is_error(chunk->type)) {
882 ret = nbd_parse_error_payload(chunk, local_payload, request_ret, errp);
883 g_free(local_payload);
884 return ret;
887 return 0;
891 * nbd_co_receive_one_chunk
892 * Read reply, wake up connection_co and set s->quit if needed.
893 * Return value is a fatal error code or normal nbd reply error code
895 static coroutine_fn int nbd_co_receive_one_chunk(
896 BDRVNBDState *s, uint64_t handle, bool only_structured,
897 int *request_ret, QEMUIOVector *qiov, NBDReply *reply, void **payload,
898 Error **errp)
900 int ret = nbd_co_do_receive_one_chunk(s, handle, only_structured,
901 request_ret, qiov, payload, errp);
903 if (ret < 0) {
904 memset(reply, 0, sizeof(*reply));
905 nbd_channel_error(s, ret);
906 } else {
907 /* For assert at loop start in nbd_connection_entry */
908 *reply = s->reply;
910 s->reply.handle = 0;
912 nbd_recv_coroutines_wake(s, false);
914 return ret;
917 typedef struct NBDReplyChunkIter {
918 int ret;
919 int request_ret;
920 Error *err;
921 bool done, only_structured;
922 } NBDReplyChunkIter;
924 static void nbd_iter_channel_error(NBDReplyChunkIter *iter,
925 int ret, Error **local_err)
927 assert(local_err && *local_err);
928 assert(ret < 0);
930 if (!iter->ret) {
931 iter->ret = ret;
932 error_propagate(&iter->err, *local_err);
933 } else {
934 error_free(*local_err);
937 *local_err = NULL;
940 static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret)
942 assert(ret < 0);
944 if (!iter->request_ret) {
945 iter->request_ret = ret;
950 * NBD_FOREACH_REPLY_CHUNK
951 * The pointer stored in @payload requires g_free() to free it.
953 #define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
954 qiov, reply, payload) \
955 for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
956 nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
959 * nbd_reply_chunk_iter_receive
960 * The pointer stored in @payload requires g_free() to free it.
962 static bool nbd_reply_chunk_iter_receive(BDRVNBDState *s,
963 NBDReplyChunkIter *iter,
964 uint64_t handle,
965 QEMUIOVector *qiov, NBDReply *reply,
966 void **payload)
968 int ret, request_ret;
969 NBDReply local_reply;
970 NBDStructuredReplyChunk *chunk;
971 Error *local_err = NULL;
972 if (!nbd_client_connected(s)) {
973 error_setg(&local_err, "Connection closed");
974 nbd_iter_channel_error(iter, -EIO, &local_err);
975 goto break_loop;
978 if (iter->done) {
979 /* Previous iteration was last. */
980 goto break_loop;
983 if (reply == NULL) {
984 reply = &local_reply;
987 ret = nbd_co_receive_one_chunk(s, handle, iter->only_structured,
988 &request_ret, qiov, reply, payload,
989 &local_err);
990 if (ret < 0) {
991 nbd_iter_channel_error(iter, ret, &local_err);
992 } else if (request_ret < 0) {
993 nbd_iter_request_error(iter, request_ret);
996 /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
997 if (nbd_reply_is_simple(reply) || !nbd_client_connected(s)) {
998 goto break_loop;
1001 chunk = &reply->structured;
1002 iter->only_structured = true;
1004 if (chunk->type == NBD_REPLY_TYPE_NONE) {
1005 /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
1006 assert(chunk->flags & NBD_REPLY_FLAG_DONE);
1007 goto break_loop;
1010 if (chunk->flags & NBD_REPLY_FLAG_DONE) {
1011 /* This iteration is last. */
1012 iter->done = true;
1015 /* Execute the loop body */
1016 return true;
1018 break_loop:
1019 s->requests[HANDLE_TO_INDEX(s, handle)].coroutine = NULL;
1021 qemu_co_mutex_lock(&s->send_mutex);
1022 s->in_flight--;
1023 qemu_co_queue_next(&s->free_sema);
1024 qemu_co_mutex_unlock(&s->send_mutex);
1026 return false;
1029 static int nbd_co_receive_return_code(BDRVNBDState *s, uint64_t handle,
1030 int *request_ret, Error **errp)
1032 NBDReplyChunkIter iter;
1034 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, NULL, NULL) {
1035 /* nbd_reply_chunk_iter_receive does all the work */
1038 error_propagate(errp, iter.err);
1039 *request_ret = iter.request_ret;
1040 return iter.ret;
1043 static int nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t handle,
1044 uint64_t offset, QEMUIOVector *qiov,
1045 int *request_ret, Error **errp)
1047 NBDReplyChunkIter iter;
1048 NBDReply reply;
1049 void *payload = NULL;
1050 Error *local_err = NULL;
1052 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, s->info.structured_reply,
1053 qiov, &reply, &payload)
1055 int ret;
1056 NBDStructuredReplyChunk *chunk = &reply.structured;
1058 assert(nbd_reply_is_structured(&reply));
1060 switch (chunk->type) {
1061 case NBD_REPLY_TYPE_OFFSET_DATA:
1063 * special cased in nbd_co_receive_one_chunk, data is already
1064 * in qiov
1066 break;
1067 case NBD_REPLY_TYPE_OFFSET_HOLE:
1068 ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload,
1069 offset, qiov, &local_err);
1070 if (ret < 0) {
1071 nbd_channel_error(s, ret);
1072 nbd_iter_channel_error(&iter, ret, &local_err);
1074 break;
1075 default:
1076 if (!nbd_reply_type_is_error(chunk->type)) {
1077 /* not allowed reply type */
1078 nbd_channel_error(s, -EINVAL);
1079 error_setg(&local_err,
1080 "Unexpected reply type: %d (%s) for CMD_READ",
1081 chunk->type, nbd_reply_type_lookup(chunk->type));
1082 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1086 g_free(payload);
1087 payload = NULL;
1090 error_propagate(errp, iter.err);
1091 *request_ret = iter.request_ret;
1092 return iter.ret;
1095 static int nbd_co_receive_blockstatus_reply(BDRVNBDState *s,
1096 uint64_t handle, uint64_t length,
1097 NBDExtent *extent,
1098 int *request_ret, Error **errp)
1100 NBDReplyChunkIter iter;
1101 NBDReply reply;
1102 void *payload = NULL;
1103 Error *local_err = NULL;
1104 bool received = false;
1106 assert(!extent->length);
1107 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, &reply, &payload) {
1108 int ret;
1109 NBDStructuredReplyChunk *chunk = &reply.structured;
1111 assert(nbd_reply_is_structured(&reply));
1113 switch (chunk->type) {
1114 case NBD_REPLY_TYPE_BLOCK_STATUS:
1115 if (received) {
1116 nbd_channel_error(s, -EINVAL);
1117 error_setg(&local_err, "Several BLOCK_STATUS chunks in reply");
1118 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1120 received = true;
1122 ret = nbd_parse_blockstatus_payload(s, &reply.structured,
1123 payload, length, extent,
1124 &local_err);
1125 if (ret < 0) {
1126 nbd_channel_error(s, ret);
1127 nbd_iter_channel_error(&iter, ret, &local_err);
1129 break;
1130 default:
1131 if (!nbd_reply_type_is_error(chunk->type)) {
1132 nbd_channel_error(s, -EINVAL);
1133 error_setg(&local_err,
1134 "Unexpected reply type: %d (%s) "
1135 "for CMD_BLOCK_STATUS",
1136 chunk->type, nbd_reply_type_lookup(chunk->type));
1137 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1141 g_free(payload);
1142 payload = NULL;
1145 if (!extent->length && !iter.request_ret) {
1146 error_setg(&local_err, "Server did not reply with any status extents");
1147 nbd_iter_channel_error(&iter, -EIO, &local_err);
1150 error_propagate(errp, iter.err);
1151 *request_ret = iter.request_ret;
1152 return iter.ret;
1155 static int nbd_co_request(BlockDriverState *bs, NBDRequest *request,
1156 QEMUIOVector *write_qiov)
1158 int ret, request_ret;
1159 Error *local_err = NULL;
1160 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1162 assert(request->type != NBD_CMD_READ);
1163 if (write_qiov) {
1164 assert(request->type == NBD_CMD_WRITE);
1165 assert(request->len == iov_size(write_qiov->iov, write_qiov->niov));
1166 } else {
1167 assert(request->type != NBD_CMD_WRITE);
1170 do {
1171 ret = nbd_co_send_request(bs, request, write_qiov);
1172 if (ret < 0) {
1173 continue;
1176 ret = nbd_co_receive_return_code(s, request->handle,
1177 &request_ret, &local_err);
1178 if (local_err) {
1179 trace_nbd_co_request_fail(request->from, request->len,
1180 request->handle, request->flags,
1181 request->type,
1182 nbd_cmd_lookup(request->type),
1183 ret, error_get_pretty(local_err));
1184 error_free(local_err);
1185 local_err = NULL;
1187 } while (ret < 0 && nbd_client_connecting_wait(s));
1189 return ret ? ret : request_ret;
1192 static int nbd_client_co_preadv(BlockDriverState *bs, int64_t offset,
1193 int64_t bytes, QEMUIOVector *qiov,
1194 BdrvRequestFlags flags)
1196 int ret, request_ret;
1197 Error *local_err = NULL;
1198 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1199 NBDRequest request = {
1200 .type = NBD_CMD_READ,
1201 .from = offset,
1202 .len = bytes,
1205 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1206 assert(!flags);
1208 if (!bytes) {
1209 return 0;
1212 * Work around the fact that the block layer doesn't do
1213 * byte-accurate sizing yet - if the read exceeds the server's
1214 * advertised size because the block layer rounded size up, then
1215 * truncate the request to the server and tail-pad with zero.
1217 if (offset >= s->info.size) {
1218 assert(bytes < BDRV_SECTOR_SIZE);
1219 qemu_iovec_memset(qiov, 0, 0, bytes);
1220 return 0;
1222 if (offset + bytes > s->info.size) {
1223 uint64_t slop = offset + bytes - s->info.size;
1225 assert(slop < BDRV_SECTOR_SIZE);
1226 qemu_iovec_memset(qiov, bytes - slop, 0, slop);
1227 request.len -= slop;
1230 do {
1231 ret = nbd_co_send_request(bs, &request, NULL);
1232 if (ret < 0) {
1233 continue;
1236 ret = nbd_co_receive_cmdread_reply(s, request.handle, offset, qiov,
1237 &request_ret, &local_err);
1238 if (local_err) {
1239 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1240 request.flags, request.type,
1241 nbd_cmd_lookup(request.type),
1242 ret, error_get_pretty(local_err));
1243 error_free(local_err);
1244 local_err = NULL;
1246 } while (ret < 0 && nbd_client_connecting_wait(s));
1248 return ret ? ret : request_ret;
1251 static int nbd_client_co_pwritev(BlockDriverState *bs, int64_t offset,
1252 int64_t bytes, QEMUIOVector *qiov,
1253 BdrvRequestFlags flags)
1255 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1256 NBDRequest request = {
1257 .type = NBD_CMD_WRITE,
1258 .from = offset,
1259 .len = bytes,
1262 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1263 if (flags & BDRV_REQ_FUA) {
1264 assert(s->info.flags & NBD_FLAG_SEND_FUA);
1265 request.flags |= NBD_CMD_FLAG_FUA;
1268 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1270 if (!bytes) {
1271 return 0;
1273 return nbd_co_request(bs, &request, qiov);
1276 static int nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1277 int64_t bytes, BdrvRequestFlags flags)
1279 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1280 NBDRequest request = {
1281 .type = NBD_CMD_WRITE_ZEROES,
1282 .from = offset,
1283 .len = bytes, /* .len is uint32_t actually */
1286 assert(bytes <= UINT32_MAX); /* rely on max_pwrite_zeroes */
1288 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1289 if (!(s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {
1290 return -ENOTSUP;
1293 if (flags & BDRV_REQ_FUA) {
1294 assert(s->info.flags & NBD_FLAG_SEND_FUA);
1295 request.flags |= NBD_CMD_FLAG_FUA;
1297 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1298 request.flags |= NBD_CMD_FLAG_NO_HOLE;
1300 if (flags & BDRV_REQ_NO_FALLBACK) {
1301 assert(s->info.flags & NBD_FLAG_SEND_FAST_ZERO);
1302 request.flags |= NBD_CMD_FLAG_FAST_ZERO;
1305 if (!bytes) {
1306 return 0;
1308 return nbd_co_request(bs, &request, NULL);
1311 static int nbd_client_co_flush(BlockDriverState *bs)
1313 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1314 NBDRequest request = { .type = NBD_CMD_FLUSH };
1316 if (!(s->info.flags & NBD_FLAG_SEND_FLUSH)) {
1317 return 0;
1320 request.from = 0;
1321 request.len = 0;
1323 return nbd_co_request(bs, &request, NULL);
1326 static int nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset,
1327 int64_t bytes)
1329 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1330 NBDRequest request = {
1331 .type = NBD_CMD_TRIM,
1332 .from = offset,
1333 .len = bytes, /* len is uint32_t */
1336 assert(bytes <= UINT32_MAX); /* rely on max_pdiscard */
1338 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1339 if (!(s->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) {
1340 return 0;
1343 return nbd_co_request(bs, &request, NULL);
1346 static int coroutine_fn nbd_client_co_block_status(
1347 BlockDriverState *bs, bool want_zero, int64_t offset, int64_t bytes,
1348 int64_t *pnum, int64_t *map, BlockDriverState **file)
1350 int ret, request_ret;
1351 NBDExtent extent = { 0 };
1352 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1353 Error *local_err = NULL;
1355 NBDRequest request = {
1356 .type = NBD_CMD_BLOCK_STATUS,
1357 .from = offset,
1358 .len = MIN(QEMU_ALIGN_DOWN(INT_MAX, bs->bl.request_alignment),
1359 MIN(bytes, s->info.size - offset)),
1360 .flags = NBD_CMD_FLAG_REQ_ONE,
1363 if (!s->info.base_allocation) {
1364 *pnum = bytes;
1365 *map = offset;
1366 *file = bs;
1367 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
1371 * Work around the fact that the block layer doesn't do
1372 * byte-accurate sizing yet - if the status request exceeds the
1373 * server's advertised size because the block layer rounded size
1374 * up, we truncated the request to the server (above), or are
1375 * called on just the hole.
1377 if (offset >= s->info.size) {
1378 *pnum = bytes;
1379 assert(bytes < BDRV_SECTOR_SIZE);
1380 /* Intentionally don't report offset_valid for the hole */
1381 return BDRV_BLOCK_ZERO;
1384 if (s->info.min_block) {
1385 assert(QEMU_IS_ALIGNED(request.len, s->info.min_block));
1387 do {
1388 ret = nbd_co_send_request(bs, &request, NULL);
1389 if (ret < 0) {
1390 continue;
1393 ret = nbd_co_receive_blockstatus_reply(s, request.handle, bytes,
1394 &extent, &request_ret,
1395 &local_err);
1396 if (local_err) {
1397 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1398 request.flags, request.type,
1399 nbd_cmd_lookup(request.type),
1400 ret, error_get_pretty(local_err));
1401 error_free(local_err);
1402 local_err = NULL;
1404 } while (ret < 0 && nbd_client_connecting_wait(s));
1406 if (ret < 0 || request_ret < 0) {
1407 return ret ? ret : request_ret;
1410 assert(extent.length);
1411 *pnum = extent.length;
1412 *map = offset;
1413 *file = bs;
1414 return (extent.flags & NBD_STATE_HOLE ? 0 : BDRV_BLOCK_DATA) |
1415 (extent.flags & NBD_STATE_ZERO ? BDRV_BLOCK_ZERO : 0) |
1416 BDRV_BLOCK_OFFSET_VALID;
1419 static int nbd_client_reopen_prepare(BDRVReopenState *state,
1420 BlockReopenQueue *queue, Error **errp)
1422 BDRVNBDState *s = (BDRVNBDState *)state->bs->opaque;
1424 if ((state->flags & BDRV_O_RDWR) && (s->info.flags & NBD_FLAG_READ_ONLY)) {
1425 error_setg(errp, "Can't reopen read-only NBD mount as read/write");
1426 return -EACCES;
1428 return 0;
1431 static void nbd_yank(void *opaque)
1433 BlockDriverState *bs = opaque;
1434 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1436 qatomic_store_release(&s->state, NBD_CLIENT_QUIT);
1437 qio_channel_shutdown(QIO_CHANNEL(s->ioc), QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
1440 static void nbd_client_close(BlockDriverState *bs)
1442 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1443 NBDRequest request = { .type = NBD_CMD_DISC };
1445 if (s->ioc) {
1446 nbd_send_request(s->ioc, &request);
1449 nbd_teardown_connection(bs);
1454 * Parse nbd_open options
1457 static int nbd_parse_uri(const char *filename, QDict *options)
1459 URI *uri;
1460 const char *p;
1461 QueryParams *qp = NULL;
1462 int ret = 0;
1463 bool is_unix;
1465 uri = uri_parse(filename);
1466 if (!uri) {
1467 return -EINVAL;
1470 /* transport */
1471 if (!g_strcmp0(uri->scheme, "nbd")) {
1472 is_unix = false;
1473 } else if (!g_strcmp0(uri->scheme, "nbd+tcp")) {
1474 is_unix = false;
1475 } else if (!g_strcmp0(uri->scheme, "nbd+unix")) {
1476 is_unix = true;
1477 } else {
1478 ret = -EINVAL;
1479 goto out;
1482 p = uri->path ? uri->path : "";
1483 if (p[0] == '/') {
1484 p++;
1486 if (p[0]) {
1487 qdict_put_str(options, "export", p);
1490 qp = query_params_parse(uri->query);
1491 if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
1492 ret = -EINVAL;
1493 goto out;
1496 if (is_unix) {
1497 /* nbd+unix:///export?socket=path */
1498 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
1499 ret = -EINVAL;
1500 goto out;
1502 qdict_put_str(options, "server.type", "unix");
1503 qdict_put_str(options, "server.path", qp->p[0].value);
1504 } else {
1505 QString *host;
1506 char *port_str;
1508 /* nbd[+tcp]://host[:port]/export */
1509 if (!uri->server) {
1510 ret = -EINVAL;
1511 goto out;
1514 /* strip braces from literal IPv6 address */
1515 if (uri->server[0] == '[') {
1516 host = qstring_from_substr(uri->server, 1,
1517 strlen(uri->server) - 1);
1518 } else {
1519 host = qstring_from_str(uri->server);
1522 qdict_put_str(options, "server.type", "inet");
1523 qdict_put(options, "server.host", host);
1525 port_str = g_strdup_printf("%d", uri->port ?: NBD_DEFAULT_PORT);
1526 qdict_put_str(options, "server.port", port_str);
1527 g_free(port_str);
1530 out:
1531 if (qp) {
1532 query_params_free(qp);
1534 uri_free(uri);
1535 return ret;
1538 static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
1540 const QDictEntry *e;
1542 for (e = qdict_first(options); e; e = qdict_next(options, e)) {
1543 if (!strcmp(e->key, "host") ||
1544 !strcmp(e->key, "port") ||
1545 !strcmp(e->key, "path") ||
1546 !strcmp(e->key, "export") ||
1547 strstart(e->key, "server.", NULL))
1549 error_setg(errp, "Option '%s' cannot be used with a file name",
1550 e->key);
1551 return true;
1555 return false;
1558 static void nbd_parse_filename(const char *filename, QDict *options,
1559 Error **errp)
1561 g_autofree char *file = NULL;
1562 char *export_name;
1563 const char *host_spec;
1564 const char *unixpath;
1566 if (nbd_has_filename_options_conflict(options, errp)) {
1567 return;
1570 if (strstr(filename, "://")) {
1571 int ret = nbd_parse_uri(filename, options);
1572 if (ret < 0) {
1573 error_setg(errp, "No valid URL specified");
1575 return;
1578 file = g_strdup(filename);
1580 export_name = strstr(file, EN_OPTSTR);
1581 if (export_name) {
1582 if (export_name[strlen(EN_OPTSTR)] == 0) {
1583 return;
1585 export_name[0] = 0; /* truncate 'file' */
1586 export_name += strlen(EN_OPTSTR);
1588 qdict_put_str(options, "export", export_name);
1591 /* extract the host_spec - fail if it's not nbd:... */
1592 if (!strstart(file, "nbd:", &host_spec)) {
1593 error_setg(errp, "File name string for NBD must start with 'nbd:'");
1594 return;
1597 if (!*host_spec) {
1598 return;
1601 /* are we a UNIX or TCP socket? */
1602 if (strstart(host_spec, "unix:", &unixpath)) {
1603 qdict_put_str(options, "server.type", "unix");
1604 qdict_put_str(options, "server.path", unixpath);
1605 } else {
1606 InetSocketAddress *addr = g_new(InetSocketAddress, 1);
1608 if (inet_parse(addr, host_spec, errp)) {
1609 goto out_inet;
1612 qdict_put_str(options, "server.type", "inet");
1613 qdict_put_str(options, "server.host", addr->host);
1614 qdict_put_str(options, "server.port", addr->port);
1615 out_inet:
1616 qapi_free_InetSocketAddress(addr);
1620 static bool nbd_process_legacy_socket_options(QDict *output_options,
1621 QemuOpts *legacy_opts,
1622 Error **errp)
1624 const char *path = qemu_opt_get(legacy_opts, "path");
1625 const char *host = qemu_opt_get(legacy_opts, "host");
1626 const char *port = qemu_opt_get(legacy_opts, "port");
1627 const QDictEntry *e;
1629 if (!path && !host && !port) {
1630 return true;
1633 for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
1635 if (strstart(e->key, "server.", NULL)) {
1636 error_setg(errp, "Cannot use 'server' and path/host/port at the "
1637 "same time");
1638 return false;
1642 if (path && host) {
1643 error_setg(errp, "path and host may not be used at the same time");
1644 return false;
1645 } else if (path) {
1646 if (port) {
1647 error_setg(errp, "port may not be used without host");
1648 return false;
1651 qdict_put_str(output_options, "server.type", "unix");
1652 qdict_put_str(output_options, "server.path", path);
1653 } else if (host) {
1654 qdict_put_str(output_options, "server.type", "inet");
1655 qdict_put_str(output_options, "server.host", host);
1656 qdict_put_str(output_options, "server.port",
1657 port ?: stringify(NBD_DEFAULT_PORT));
1660 return true;
1663 static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options,
1664 Error **errp)
1666 SocketAddress *saddr = NULL;
1667 QDict *addr = NULL;
1668 Visitor *iv = NULL;
1670 qdict_extract_subqdict(options, &addr, "server.");
1671 if (!qdict_size(addr)) {
1672 error_setg(errp, "NBD server address missing");
1673 goto done;
1676 iv = qobject_input_visitor_new_flat_confused(addr, errp);
1677 if (!iv) {
1678 goto done;
1681 if (!visit_type_SocketAddress(iv, NULL, &saddr, errp)) {
1682 goto done;
1685 if (socket_address_parse_named_fd(saddr, errp) < 0) {
1686 qapi_free_SocketAddress(saddr);
1687 saddr = NULL;
1688 goto done;
1691 done:
1692 qobject_unref(addr);
1693 visit_free(iv);
1694 return saddr;
1697 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
1699 Object *obj;
1700 QCryptoTLSCreds *creds;
1702 obj = object_resolve_path_component(
1703 object_get_objects_root(), id);
1704 if (!obj) {
1705 error_setg(errp, "No TLS credentials with id '%s'",
1706 id);
1707 return NULL;
1709 creds = (QCryptoTLSCreds *)
1710 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
1711 if (!creds) {
1712 error_setg(errp, "Object with id '%s' is not TLS credentials",
1713 id);
1714 return NULL;
1717 if (!qcrypto_tls_creds_check_endpoint(creds,
1718 QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT,
1719 errp)) {
1720 return NULL;
1722 object_ref(obj);
1723 return creds;
1727 static QemuOptsList nbd_runtime_opts = {
1728 .name = "nbd",
1729 .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
1730 .desc = {
1732 .name = "host",
1733 .type = QEMU_OPT_STRING,
1734 .help = "TCP host to connect to",
1737 .name = "port",
1738 .type = QEMU_OPT_STRING,
1739 .help = "TCP port to connect to",
1742 .name = "path",
1743 .type = QEMU_OPT_STRING,
1744 .help = "Unix socket path to connect to",
1747 .name = "export",
1748 .type = QEMU_OPT_STRING,
1749 .help = "Name of the NBD export to open",
1752 .name = "tls-creds",
1753 .type = QEMU_OPT_STRING,
1754 .help = "ID of the TLS credentials to use",
1757 .name = "x-dirty-bitmap",
1758 .type = QEMU_OPT_STRING,
1759 .help = "experimental: expose named dirty bitmap in place of "
1760 "block status",
1763 .name = "reconnect-delay",
1764 .type = QEMU_OPT_NUMBER,
1765 .help = "On an unexpected disconnect, the nbd client tries to "
1766 "connect again until succeeding or encountering a serious "
1767 "error. During the first @reconnect-delay seconds, all "
1768 "requests are paused and will be rerun on a successful "
1769 "reconnect. After that time, any delayed requests and all "
1770 "future requests before a successful reconnect will "
1771 "immediately fail. Default 0",
1774 .name = "open-timeout",
1775 .type = QEMU_OPT_NUMBER,
1776 .help = "In seconds. If zero, the nbd driver tries the connection "
1777 "only once, and fails to open if the connection fails. "
1778 "If non-zero, the nbd driver will repeat connection "
1779 "attempts until successful or until @open-timeout seconds "
1780 "have elapsed. Default 0",
1782 { /* end of list */ }
1786 static int nbd_process_options(BlockDriverState *bs, QDict *options,
1787 Error **errp)
1789 BDRVNBDState *s = bs->opaque;
1790 QemuOpts *opts;
1791 int ret = -EINVAL;
1793 opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
1794 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1795 goto error;
1798 /* Translate @host, @port, and @path to a SocketAddress */
1799 if (!nbd_process_legacy_socket_options(options, opts, errp)) {
1800 goto error;
1803 /* Pop the config into our state object. Exit if invalid. */
1804 s->saddr = nbd_config(s, options, errp);
1805 if (!s->saddr) {
1806 goto error;
1809 s->export = g_strdup(qemu_opt_get(opts, "export"));
1810 if (s->export && strlen(s->export) > NBD_MAX_STRING_SIZE) {
1811 error_setg(errp, "export name too long to send to server");
1812 goto error;
1815 s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
1816 if (s->tlscredsid) {
1817 s->tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
1818 if (!s->tlscreds) {
1819 goto error;
1822 /* TODO SOCKET_ADDRESS_KIND_FD where fd has AF_INET or AF_INET6 */
1823 if (s->saddr->type != SOCKET_ADDRESS_TYPE_INET) {
1824 error_setg(errp, "TLS only supported over IP sockets");
1825 goto error;
1827 s->hostname = s->saddr->u.inet.host;
1830 s->x_dirty_bitmap = g_strdup(qemu_opt_get(opts, "x-dirty-bitmap"));
1831 if (s->x_dirty_bitmap && strlen(s->x_dirty_bitmap) > NBD_MAX_STRING_SIZE) {
1832 error_setg(errp, "x-dirty-bitmap query too long to send to server");
1833 goto error;
1836 s->reconnect_delay = qemu_opt_get_number(opts, "reconnect-delay", 0);
1837 s->open_timeout = qemu_opt_get_number(opts, "open-timeout", 0);
1839 ret = 0;
1841 error:
1842 qemu_opts_del(opts);
1843 return ret;
1846 static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
1847 Error **errp)
1849 int ret;
1850 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1852 s->bs = bs;
1853 qemu_co_mutex_init(&s->send_mutex);
1854 qemu_co_queue_init(&s->free_sema);
1855 qemu_co_mutex_init(&s->receive_mutex);
1857 if (!yank_register_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name), errp)) {
1858 return -EEXIST;
1861 ret = nbd_process_options(bs, options, errp);
1862 if (ret < 0) {
1863 goto fail;
1866 s->conn = nbd_client_connection_new(s->saddr, true, s->export,
1867 s->x_dirty_bitmap, s->tlscreds);
1869 if (s->open_timeout) {
1870 nbd_client_connection_enable_retry(s->conn);
1871 open_timer_init(s, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
1872 s->open_timeout * NANOSECONDS_PER_SECOND);
1875 s->state = NBD_CLIENT_CONNECTING_WAIT;
1876 ret = nbd_do_establish_connection(bs, errp);
1877 if (ret < 0) {
1878 goto fail;
1881 nbd_client_connection_enable_retry(s->conn);
1883 return 0;
1885 fail:
1886 nbd_clear_bdrvstate(bs);
1887 return ret;
1890 static int nbd_co_flush(BlockDriverState *bs)
1892 return nbd_client_co_flush(bs);
1895 static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
1897 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1898 uint32_t min = s->info.min_block;
1899 uint32_t max = MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE, s->info.max_block);
1902 * If the server did not advertise an alignment:
1903 * - a size that is not sector-aligned implies that an alignment
1904 * of 1 can be used to access those tail bytes
1905 * - advertisement of block status requires an alignment of 1, so
1906 * that we don't violate block layer constraints that block
1907 * status is always aligned (as we can't control whether the
1908 * server will report sub-sector extents, such as a hole at EOF
1909 * on an unaligned POSIX file)
1910 * - otherwise, assume the server is so old that we are safer avoiding
1911 * sub-sector requests
1913 if (!min) {
1914 min = (!QEMU_IS_ALIGNED(s->info.size, BDRV_SECTOR_SIZE) ||
1915 s->info.base_allocation) ? 1 : BDRV_SECTOR_SIZE;
1918 bs->bl.request_alignment = min;
1919 bs->bl.max_pdiscard = QEMU_ALIGN_DOWN(INT_MAX, min);
1920 bs->bl.max_pwrite_zeroes = max;
1921 bs->bl.max_transfer = max;
1923 if (s->info.opt_block &&
1924 s->info.opt_block > bs->bl.opt_transfer) {
1925 bs->bl.opt_transfer = s->info.opt_block;
1929 static void nbd_close(BlockDriverState *bs)
1931 nbd_client_close(bs);
1932 nbd_clear_bdrvstate(bs);
1936 * NBD cannot truncate, but if the caller asks to truncate to the same size, or
1937 * to a smaller size with exact=false, there is no reason to fail the
1938 * operation.
1940 * Preallocation mode is ignored since it does not seems useful to fail when
1941 * we never change anything.
1943 static int coroutine_fn nbd_co_truncate(BlockDriverState *bs, int64_t offset,
1944 bool exact, PreallocMode prealloc,
1945 BdrvRequestFlags flags, Error **errp)
1947 BDRVNBDState *s = bs->opaque;
1949 if (offset != s->info.size && exact) {
1950 error_setg(errp, "Cannot resize NBD nodes");
1951 return -ENOTSUP;
1954 if (offset > s->info.size) {
1955 error_setg(errp, "Cannot grow NBD nodes");
1956 return -EINVAL;
1959 return 0;
1962 static int64_t nbd_getlength(BlockDriverState *bs)
1964 BDRVNBDState *s = bs->opaque;
1966 return s->info.size;
1969 static void nbd_refresh_filename(BlockDriverState *bs)
1971 BDRVNBDState *s = bs->opaque;
1972 const char *host = NULL, *port = NULL, *path = NULL;
1973 size_t len = 0;
1975 if (s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
1976 const InetSocketAddress *inet = &s->saddr->u.inet;
1977 if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) {
1978 host = inet->host;
1979 port = inet->port;
1981 } else if (s->saddr->type == SOCKET_ADDRESS_TYPE_UNIX) {
1982 path = s->saddr->u.q_unix.path;
1983 } /* else can't represent as pseudo-filename */
1985 if (path && s->export) {
1986 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1987 "nbd+unix:///%s?socket=%s", s->export, path);
1988 } else if (path && !s->export) {
1989 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1990 "nbd+unix://?socket=%s", path);
1991 } else if (host && s->export) {
1992 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1993 "nbd://%s:%s/%s", host, port, s->export);
1994 } else if (host && !s->export) {
1995 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1996 "nbd://%s:%s", host, port);
1998 if (len >= sizeof(bs->exact_filename)) {
1999 /* Name is too long to represent exactly, so leave it empty. */
2000 bs->exact_filename[0] = '\0';
2004 static char *nbd_dirname(BlockDriverState *bs, Error **errp)
2006 /* The generic bdrv_dirname() implementation is able to work out some
2007 * directory name for NBD nodes, but that would be wrong. So far there is no
2008 * specification for how "export paths" would work, so NBD does not have
2009 * directory names. */
2010 error_setg(errp, "Cannot generate a base directory for NBD nodes");
2011 return NULL;
2014 static const char *const nbd_strong_runtime_opts[] = {
2015 "path",
2016 "host",
2017 "port",
2018 "export",
2019 "tls-creds",
2020 "server.",
2022 NULL
2025 static void nbd_cancel_in_flight(BlockDriverState *bs)
2027 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2029 reconnect_delay_timer_del(s);
2031 if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
2032 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
2033 qemu_co_queue_restart_all(&s->free_sema);
2036 nbd_co_establish_connection_cancel(s->conn);
2039 static BlockDriver bdrv_nbd = {
2040 .format_name = "nbd",
2041 .protocol_name = "nbd",
2042 .instance_size = sizeof(BDRVNBDState),
2043 .bdrv_parse_filename = nbd_parse_filename,
2044 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2045 .create_opts = &bdrv_create_opts_simple,
2046 .bdrv_file_open = nbd_open,
2047 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2048 .bdrv_co_preadv = nbd_client_co_preadv,
2049 .bdrv_co_pwritev = nbd_client_co_pwritev,
2050 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2051 .bdrv_close = nbd_close,
2052 .bdrv_co_flush_to_os = nbd_co_flush,
2053 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2054 .bdrv_refresh_limits = nbd_refresh_limits,
2055 .bdrv_co_truncate = nbd_co_truncate,
2056 .bdrv_getlength = nbd_getlength,
2057 .bdrv_refresh_filename = nbd_refresh_filename,
2058 .bdrv_co_block_status = nbd_client_co_block_status,
2059 .bdrv_dirname = nbd_dirname,
2060 .strong_runtime_opts = nbd_strong_runtime_opts,
2061 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2064 static BlockDriver bdrv_nbd_tcp = {
2065 .format_name = "nbd",
2066 .protocol_name = "nbd+tcp",
2067 .instance_size = sizeof(BDRVNBDState),
2068 .bdrv_parse_filename = nbd_parse_filename,
2069 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2070 .create_opts = &bdrv_create_opts_simple,
2071 .bdrv_file_open = nbd_open,
2072 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2073 .bdrv_co_preadv = nbd_client_co_preadv,
2074 .bdrv_co_pwritev = nbd_client_co_pwritev,
2075 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2076 .bdrv_close = nbd_close,
2077 .bdrv_co_flush_to_os = nbd_co_flush,
2078 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2079 .bdrv_refresh_limits = nbd_refresh_limits,
2080 .bdrv_co_truncate = nbd_co_truncate,
2081 .bdrv_getlength = nbd_getlength,
2082 .bdrv_refresh_filename = nbd_refresh_filename,
2083 .bdrv_co_block_status = nbd_client_co_block_status,
2084 .bdrv_dirname = nbd_dirname,
2085 .strong_runtime_opts = nbd_strong_runtime_opts,
2086 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2089 static BlockDriver bdrv_nbd_unix = {
2090 .format_name = "nbd",
2091 .protocol_name = "nbd+unix",
2092 .instance_size = sizeof(BDRVNBDState),
2093 .bdrv_parse_filename = nbd_parse_filename,
2094 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2095 .create_opts = &bdrv_create_opts_simple,
2096 .bdrv_file_open = nbd_open,
2097 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2098 .bdrv_co_preadv = nbd_client_co_preadv,
2099 .bdrv_co_pwritev = nbd_client_co_pwritev,
2100 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2101 .bdrv_close = nbd_close,
2102 .bdrv_co_flush_to_os = nbd_co_flush,
2103 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2104 .bdrv_refresh_limits = nbd_refresh_limits,
2105 .bdrv_co_truncate = nbd_co_truncate,
2106 .bdrv_getlength = nbd_getlength,
2107 .bdrv_refresh_filename = nbd_refresh_filename,
2108 .bdrv_co_block_status = nbd_client_co_block_status,
2109 .bdrv_dirname = nbd_dirname,
2110 .strong_runtime_opts = nbd_strong_runtime_opts,
2111 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2114 static void bdrv_nbd_init(void)
2116 bdrv_register(&bdrv_nbd);
2117 bdrv_register(&bdrv_nbd_tcp);
2118 bdrv_register(&bdrv_nbd_unix);
2121 block_init(bdrv_nbd_init);