]> git.ipfire.org Git - thirdparty/qemu.git/blame - block/nbd.c
iotests/279: Fix for non-qcow2 formats
[thirdparty/qemu.git] / block / nbd.c
CommitLineData
75818250
TS
1/*
2 * QEMU Block driver for NBD
3 *
f7651539 4 * Copyright (c) 2019 Virtuozzo International GmbH.
86f8cdf3 5 * Copyright (C) 2016 Red Hat, Inc.
75818250 6 * Copyright (C) 2008 Bull S.A.S.
bd5921b4 7 * Author: Laurent Vivier <Laurent.Vivier@bull.net>
75818250
TS
8 *
9 * Some parts:
10 * Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
11 *
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:
18 *
19 * The above copyright notice and this permission notice shall be included in
20 * all copies or substantial portions of the Software.
21 *
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.
29 */
30
80c71a24 31#include "qemu/osdep.h"
86f8cdf3
VSO
32
33#include "trace.h"
1de7afc9 34#include "qemu/uri.h"
922a01a0 35#include "qemu/option.h"
86f8cdf3 36#include "qemu/cutils.h"
db725815 37#include "qemu/main-loop.h"
86f8cdf3 38
9af23989 39#include "qapi/qapi-visit-sockets.h"
2019d68b 40#include "qapi/qmp/qstring.h"
86f8cdf3
VSO
41
42#include "block/qdict.h"
43#include "block/nbd.h"
44#include "block/block_int.h"
75818250 45
1d45f8b5 46#define EN_OPTSTR ":exportname="
86f8cdf3
VSO
47#define MAX_NBD_REQUESTS 16
48
49#define HANDLE_TO_INDEX(bs, handle) ((handle) ^ (uint64_t)(intptr_t)(bs))
50#define INDEX_TO_HANDLE(bs, index) ((index) ^ (uint64_t)(intptr_t)(bs))
51
52typedef struct {
53 Coroutine *coroutine;
54 uint64_t offset; /* original offset of the request */
55 bool receiving; /* waiting for connection_co? */
56} NBDClientRequest;
57
a34b1e5e 58typedef enum NBDClientState {
f7651539
VSO
59 NBD_CLIENT_CONNECTING_WAIT,
60 NBD_CLIENT_CONNECTING_NOWAIT,
a34b1e5e
VSO
61 NBD_CLIENT_CONNECTED,
62 NBD_CLIENT_QUIT
63} NBDClientState;
64
611ae1d7 65typedef struct BDRVNBDState {
86f8cdf3
VSO
66 QIOChannelSocket *sioc; /* The master data channel */
67 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
68 NBDExportInfo info;
69
70 CoMutex send_mutex;
71 CoQueue free_sema;
72 Coroutine *connection_co;
f7651539
VSO
73 QemuCoSleepState *connection_co_sleep_ns_state;
74 bool drained;
75 bool wait_drained_end;
86f8cdf3 76 int in_flight;
a34b1e5e 77 NBDClientState state;
f7651539
VSO
78 int connect_status;
79 Error *connect_err;
80 bool wait_in_flight;
86f8cdf3
VSO
81
82 NBDClientRequest requests[MAX_NBD_REQUESTS];
83 NBDReply reply;
84 BlockDriverState *bs;
03504d05 85
8f071c9d
VSO
86 /* Connection parameters */
87 uint32_t reconnect_delay;
62cf396b 88 SocketAddress *saddr;
491d6c7c 89 char *export, *tlscredsid;
8f071c9d
VSO
90 QCryptoTLSCreds *tlscreds;
91 const char *hostname;
92 char *x_dirty_bitmap;
75818250
TS
93} BDRVNBDState;
94
f7651539
VSO
95static int nbd_client_connect(BlockDriverState *bs, Error **errp);
96
a34b1e5e
VSO
97static void nbd_channel_error(BDRVNBDState *s, int ret)
98{
f7651539
VSO
99 if (ret == -EIO) {
100 if (s->state == NBD_CLIENT_CONNECTED) {
101 s->state = s->reconnect_delay ? NBD_CLIENT_CONNECTING_WAIT :
102 NBD_CLIENT_CONNECTING_NOWAIT;
103 }
104 } else {
105 if (s->state == NBD_CLIENT_CONNECTED) {
106 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
107 }
108 s->state = NBD_CLIENT_QUIT;
109 }
a34b1e5e
VSO
110}
111
611ae1d7 112static void nbd_recv_coroutines_wake_all(BDRVNBDState *s)
86f8cdf3
VSO
113{
114 int i;
115
116 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
117 NBDClientRequest *req = &s->requests[i];
118
119 if (req->coroutine && req->receiving) {
120 aio_co_wake(req->coroutine);
121 }
122 }
123}
124
125static void nbd_client_detach_aio_context(BlockDriverState *bs)
126{
611ae1d7
VSO
127 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
128
129 qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
86f8cdf3
VSO
130}
131
132static void nbd_client_attach_aio_context_bh(void *opaque)
133{
134 BlockDriverState *bs = opaque;
611ae1d7 135 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
136
137 /*
138 * The node is still drained, so we know the coroutine has yielded in
139 * nbd_read_eof(), the only place where bs->in_flight can reach 0, or it is
140 * entered for the first time. Both places are safe for entering the
141 * coroutine.
142 */
611ae1d7 143 qemu_aio_coroutine_enter(bs->aio_context, s->connection_co);
86f8cdf3
VSO
144 bdrv_dec_in_flight(bs);
145}
146
147static void nbd_client_attach_aio_context(BlockDriverState *bs,
148 AioContext *new_context)
149{
611ae1d7
VSO
150 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
151
f7651539
VSO
152 /*
153 * s->connection_co is either yielded from nbd_receive_reply or from
154 * nbd_co_reconnect_loop()
155 */
156 if (s->state == NBD_CLIENT_CONNECTED) {
157 qio_channel_attach_aio_context(QIO_CHANNEL(s->ioc), new_context);
158 }
86f8cdf3
VSO
159
160 bdrv_inc_in_flight(bs);
161
162 /*
163 * Need to wait here for the BH to run because the BH must run while the
164 * node is still drained.
165 */
166 aio_wait_bh_oneshot(new_context, nbd_client_attach_aio_context_bh, bs);
167}
168
f7651539
VSO
169static void coroutine_fn nbd_client_co_drain_begin(BlockDriverState *bs)
170{
171 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3 172
f7651539
VSO
173 s->drained = true;
174 if (s->connection_co_sleep_ns_state) {
175 qemu_co_sleep_wake(s->connection_co_sleep_ns_state);
176 }
177}
178
179static void coroutine_fn nbd_client_co_drain_end(BlockDriverState *bs)
86f8cdf3 180{
611ae1d7 181 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3 182
f7651539
VSO
183 s->drained = false;
184 if (s->wait_drained_end) {
185 s->wait_drained_end = false;
186 aio_co_wake(s->connection_co);
187 }
188}
189
86f8cdf3 190
f7651539
VSO
191static void nbd_teardown_connection(BlockDriverState *bs)
192{
193 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
194
195 if (s->state == NBD_CLIENT_CONNECTED) {
196 /* finish any pending coroutines */
197 assert(s->ioc);
198 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
199 }
200 s->state = NBD_CLIENT_QUIT;
201 if (s->connection_co) {
202 if (s->connection_co_sleep_ns_state) {
203 qemu_co_sleep_wake(s->connection_co_sleep_ns_state);
204 }
205 }
611ae1d7 206 BDRV_POLL_WHILE(bs, s->connection_co);
f7651539 207}
86f8cdf3 208
f7651539
VSO
209static bool nbd_client_connecting(BDRVNBDState *s)
210{
211 return s->state == NBD_CLIENT_CONNECTING_WAIT ||
212 s->state == NBD_CLIENT_CONNECTING_NOWAIT;
213}
214
215static bool nbd_client_connecting_wait(BDRVNBDState *s)
216{
217 return s->state == NBD_CLIENT_CONNECTING_WAIT;
218}
219
220static coroutine_fn void nbd_reconnect_attempt(BDRVNBDState *s)
221{
222 Error *local_err = NULL;
223
224 if (!nbd_client_connecting(s)) {
225 return;
226 }
227
228 /* Wait for completion of all in-flight requests */
229
230 qemu_co_mutex_lock(&s->send_mutex);
231
232 while (s->in_flight > 0) {
233 qemu_co_mutex_unlock(&s->send_mutex);
234 nbd_recv_coroutines_wake_all(s);
235 s->wait_in_flight = true;
236 qemu_coroutine_yield();
237 s->wait_in_flight = false;
238 qemu_co_mutex_lock(&s->send_mutex);
239 }
240
241 qemu_co_mutex_unlock(&s->send_mutex);
242
243 if (!nbd_client_connecting(s)) {
244 return;
245 }
246
247 /*
248 * Now we are sure that nobody is accessing the channel, and no one will
249 * try until we set the state to CONNECTED.
250 */
251
252 /* Finalize previous connection if any */
253 if (s->ioc) {
254 nbd_client_detach_aio_context(s->bs);
255 object_unref(OBJECT(s->sioc));
256 s->sioc = NULL;
257 object_unref(OBJECT(s->ioc));
258 s->ioc = NULL;
259 }
260
261 s->connect_status = nbd_client_connect(s->bs, &local_err);
262 error_free(s->connect_err);
263 s->connect_err = NULL;
264 error_propagate(&s->connect_err, local_err);
265
266 if (s->connect_status < 0) {
267 /* failed attempt */
268 return;
269 }
270
271 /* successfully connected */
272 s->state = NBD_CLIENT_CONNECTED;
273 qemu_co_queue_restart_all(&s->free_sema);
274}
275
276static coroutine_fn void nbd_co_reconnect_loop(BDRVNBDState *s)
277{
278 uint64_t start_time_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
279 uint64_t delay_ns = s->reconnect_delay * NANOSECONDS_PER_SECOND;
280 uint64_t timeout = 1 * NANOSECONDS_PER_SECOND;
281 uint64_t max_timeout = 16 * NANOSECONDS_PER_SECOND;
282
283 nbd_reconnect_attempt(s);
284
285 while (nbd_client_connecting(s)) {
286 if (s->state == NBD_CLIENT_CONNECTING_WAIT &&
287 qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - start_time_ns > delay_ns)
288 {
289 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
290 qemu_co_queue_restart_all(&s->free_sema);
291 }
292
293 qemu_co_sleep_ns_wakeable(QEMU_CLOCK_REALTIME, timeout,
294 &s->connection_co_sleep_ns_state);
295 if (s->drained) {
296 bdrv_dec_in_flight(s->bs);
297 s->wait_drained_end = true;
298 while (s->drained) {
299 /*
300 * We may be entered once from nbd_client_attach_aio_context_bh
301 * and then from nbd_client_co_drain_end. So here is a loop.
302 */
303 qemu_coroutine_yield();
304 }
305 bdrv_inc_in_flight(s->bs);
306 }
307 if (timeout < max_timeout) {
308 timeout *= 2;
309 }
310
311 nbd_reconnect_attempt(s);
312 }
86f8cdf3
VSO
313}
314
315static coroutine_fn void nbd_connection_entry(void *opaque)
316{
611ae1d7 317 BDRVNBDState *s = opaque;
86f8cdf3
VSO
318 uint64_t i;
319 int ret = 0;
320 Error *local_err = NULL;
321
a34b1e5e 322 while (s->state != NBD_CLIENT_QUIT) {
86f8cdf3
VSO
323 /*
324 * The NBD client can only really be considered idle when it has
325 * yielded from qio_channel_readv_all_eof(), waiting for data. This is
326 * the point where the additional scheduled coroutine entry happens
327 * after nbd_client_attach_aio_context().
328 *
329 * Therefore we keep an additional in_flight reference all the time and
330 * only drop it temporarily here.
331 */
f7651539
VSO
332
333 if (nbd_client_connecting(s)) {
334 nbd_co_reconnect_loop(s);
335 }
336
337 if (s->state != NBD_CLIENT_CONNECTED) {
338 continue;
339 }
340
86f8cdf3
VSO
341 assert(s->reply.handle == 0);
342 ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, &local_err);
343
344 if (local_err) {
345 trace_nbd_read_reply_entry_fail(ret, error_get_pretty(local_err));
346 error_free(local_err);
f7651539 347 local_err = NULL;
86f8cdf3
VSO
348 }
349 if (ret <= 0) {
a34b1e5e 350 nbd_channel_error(s, ret ? ret : -EIO);
f7651539 351 continue;
86f8cdf3
VSO
352 }
353
354 /*
355 * There's no need for a mutex on the receive side, because the
356 * handler acts as a synchronization point and ensures that only
357 * one coroutine is called until the reply finishes.
358 */
359 i = HANDLE_TO_INDEX(s, s->reply.handle);
360 if (i >= MAX_NBD_REQUESTS ||
361 !s->requests[i].coroutine ||
362 !s->requests[i].receiving ||
363 (nbd_reply_is_structured(&s->reply) && !s->info.structured_reply))
364 {
a34b1e5e 365 nbd_channel_error(s, -EINVAL);
f7651539 366 continue;
86f8cdf3
VSO
367 }
368
369 /*
370 * We're woken up again by the request itself. Note that there
371 * is no race between yielding and reentering connection_co. This
372 * is because:
373 *
374 * - if the request runs on the same AioContext, it is only
375 * entered after we yield
376 *
377 * - if the request runs on a different AioContext, reentering
378 * connection_co happens through a bottom half, which can only
379 * run after we yield.
380 */
381 aio_co_wake(s->requests[i].coroutine);
382 qemu_coroutine_yield();
383 }
384
f7651539 385 qemu_co_queue_restart_all(&s->free_sema);
86f8cdf3
VSO
386 nbd_recv_coroutines_wake_all(s);
387 bdrv_dec_in_flight(s->bs);
388
389 s->connection_co = NULL;
f7651539
VSO
390 if (s->ioc) {
391 nbd_client_detach_aio_context(s->bs);
392 object_unref(OBJECT(s->sioc));
393 s->sioc = NULL;
394 object_unref(OBJECT(s->ioc));
395 s->ioc = NULL;
396 }
397
86f8cdf3
VSO
398 aio_wait_kick();
399}
400
401static int nbd_co_send_request(BlockDriverState *bs,
402 NBDRequest *request,
403 QEMUIOVector *qiov)
404{
611ae1d7 405 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
a34b1e5e 406 int rc, i = -1;
86f8cdf3
VSO
407
408 qemu_co_mutex_lock(&s->send_mutex);
f7651539 409 while (s->in_flight == MAX_NBD_REQUESTS || nbd_client_connecting_wait(s)) {
86f8cdf3
VSO
410 qemu_co_queue_wait(&s->free_sema, &s->send_mutex);
411 }
a34b1e5e
VSO
412
413 if (s->state != NBD_CLIENT_CONNECTED) {
414 rc = -EIO;
415 goto err;
416 }
417
86f8cdf3
VSO
418 s->in_flight++;
419
420 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
421 if (s->requests[i].coroutine == NULL) {
422 break;
423 }
424 }
425
426 g_assert(qemu_in_coroutine());
427 assert(i < MAX_NBD_REQUESTS);
428
429 s->requests[i].coroutine = qemu_coroutine_self();
430 s->requests[i].offset = request->from;
431 s->requests[i].receiving = false;
432
433 request->handle = INDEX_TO_HANDLE(s, i);
434
86f8cdf3
VSO
435 assert(s->ioc);
436
437 if (qiov) {
438 qio_channel_set_cork(s->ioc, true);
439 rc = nbd_send_request(s->ioc, request);
a34b1e5e 440 if (rc >= 0 && s->state == NBD_CLIENT_CONNECTED) {
86f8cdf3
VSO
441 if (qio_channel_writev_all(s->ioc, qiov->iov, qiov->niov,
442 NULL) < 0) {
443 rc = -EIO;
444 }
445 } else if (rc >= 0) {
446 rc = -EIO;
447 }
448 qio_channel_set_cork(s->ioc, false);
449 } else {
450 rc = nbd_send_request(s->ioc, request);
451 }
452
453err:
454 if (rc < 0) {
a34b1e5e
VSO
455 nbd_channel_error(s, rc);
456 if (i != -1) {
457 s->requests[i].coroutine = NULL;
458 s->in_flight--;
459 }
f7651539
VSO
460 if (s->in_flight == 0 && s->wait_in_flight) {
461 aio_co_wake(s->connection_co);
462 } else {
463 qemu_co_queue_next(&s->free_sema);
464 }
86f8cdf3
VSO
465 }
466 qemu_co_mutex_unlock(&s->send_mutex);
467 return rc;
468}
469
470static inline uint16_t payload_advance16(uint8_t **payload)
471{
472 *payload += 2;
473 return lduw_be_p(*payload - 2);
474}
475
476static inline uint32_t payload_advance32(uint8_t **payload)
477{
478 *payload += 4;
479 return ldl_be_p(*payload - 4);
480}
481
482static inline uint64_t payload_advance64(uint8_t **payload)
483{
484 *payload += 8;
485 return ldq_be_p(*payload - 8);
486}
487
611ae1d7 488static int nbd_parse_offset_hole_payload(BDRVNBDState *s,
86f8cdf3
VSO
489 NBDStructuredReplyChunk *chunk,
490 uint8_t *payload, uint64_t orig_offset,
491 QEMUIOVector *qiov, Error **errp)
492{
493 uint64_t offset;
494 uint32_t hole_size;
495
496 if (chunk->length != sizeof(offset) + sizeof(hole_size)) {
497 error_setg(errp, "Protocol error: invalid payload for "
498 "NBD_REPLY_TYPE_OFFSET_HOLE");
499 return -EINVAL;
500 }
501
502 offset = payload_advance64(&payload);
503 hole_size = payload_advance32(&payload);
504
505 if (!hole_size || offset < orig_offset || hole_size > qiov->size ||
506 offset > orig_offset + qiov->size - hole_size) {
507 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
508 " region");
509 return -EINVAL;
510 }
611ae1d7
VSO
511 if (s->info.min_block &&
512 !QEMU_IS_ALIGNED(hole_size, s->info.min_block)) {
86f8cdf3
VSO
513 trace_nbd_structured_read_compliance("hole");
514 }
515
516 qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size);
517
518 return 0;
519}
520
521/*
522 * nbd_parse_blockstatus_payload
523 * Based on our request, we expect only one extent in reply, for the
524 * base:allocation context.
525 */
611ae1d7 526static int nbd_parse_blockstatus_payload(BDRVNBDState *s,
86f8cdf3
VSO
527 NBDStructuredReplyChunk *chunk,
528 uint8_t *payload, uint64_t orig_length,
529 NBDExtent *extent, Error **errp)
530{
531 uint32_t context_id;
532
533 /* The server succeeded, so it must have sent [at least] one extent */
534 if (chunk->length < sizeof(context_id) + sizeof(*extent)) {
535 error_setg(errp, "Protocol error: invalid payload for "
536 "NBD_REPLY_TYPE_BLOCK_STATUS");
537 return -EINVAL;
538 }
539
540 context_id = payload_advance32(&payload);
611ae1d7 541 if (s->info.context_id != context_id) {
86f8cdf3
VSO
542 error_setg(errp, "Protocol error: unexpected context id %d for "
543 "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
544 "id is %d", context_id,
611ae1d7 545 s->info.context_id);
86f8cdf3
VSO
546 return -EINVAL;
547 }
548
549 extent->length = payload_advance32(&payload);
550 extent->flags = payload_advance32(&payload);
551
552 if (extent->length == 0) {
553 error_setg(errp, "Protocol error: server sent status chunk with "
554 "zero length");
555 return -EINVAL;
556 }
557
558 /*
559 * A server sending unaligned block status is in violation of the
560 * protocol, but as qemu-nbd 3.1 is such a server (at least for
561 * POSIX files that are not a multiple of 512 bytes, since qemu
562 * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
563 * still sees an implicit hole beyond the real EOF), it's nicer to
564 * work around the misbehaving server. If the request included
565 * more than the final unaligned block, truncate it back to an
566 * aligned result; if the request was only the final block, round
567 * up to the full block and change the status to fully-allocated
568 * (always a safe status, even if it loses information).
569 */
611ae1d7
VSO
570 if (s->info.min_block && !QEMU_IS_ALIGNED(extent->length,
571 s->info.min_block)) {
86f8cdf3 572 trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
611ae1d7 573 if (extent->length > s->info.min_block) {
86f8cdf3 574 extent->length = QEMU_ALIGN_DOWN(extent->length,
611ae1d7 575 s->info.min_block);
86f8cdf3 576 } else {
611ae1d7 577 extent->length = s->info.min_block;
86f8cdf3
VSO
578 extent->flags = 0;
579 }
580 }
581
582 /*
583 * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
584 * sent us any more than one extent, nor should it have included
585 * status beyond our request in that extent. However, it's easy
586 * enough to ignore the server's noncompliance without killing the
587 * connection; just ignore trailing extents, and clamp things to
588 * the length of our request.
589 */
590 if (chunk->length > sizeof(context_id) + sizeof(*extent)) {
591 trace_nbd_parse_blockstatus_compliance("more than one extent");
592 }
593 if (extent->length > orig_length) {
594 extent->length = orig_length;
595 trace_nbd_parse_blockstatus_compliance("extent length too large");
596 }
597
598 return 0;
599}
600
601/*
602 * nbd_parse_error_payload
603 * on success @errp contains message describing nbd error reply
604 */
605static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
606 uint8_t *payload, int *request_ret,
607 Error **errp)
608{
609 uint32_t error;
610 uint16_t message_size;
611
612 assert(chunk->type & (1 << 15));
613
614 if (chunk->length < sizeof(error) + sizeof(message_size)) {
615 error_setg(errp,
616 "Protocol error: invalid payload for structured error");
617 return -EINVAL;
618 }
619
620 error = nbd_errno_to_system_errno(payload_advance32(&payload));
621 if (error == 0) {
622 error_setg(errp, "Protocol error: server sent structured error chunk "
623 "with error = 0");
624 return -EINVAL;
625 }
626
627 *request_ret = -error;
628 message_size = payload_advance16(&payload);
629
630 if (message_size > chunk->length - sizeof(error) - sizeof(message_size)) {
631 error_setg(errp, "Protocol error: server sent structured error chunk "
632 "with incorrect message size");
633 return -EINVAL;
634 }
635
636 /* TODO: Add a trace point to mention the server complaint */
637
638 /* TODO handle ERROR_OFFSET */
639
640 return 0;
641}
642
611ae1d7 643static int nbd_co_receive_offset_data_payload(BDRVNBDState *s,
86f8cdf3
VSO
644 uint64_t orig_offset,
645 QEMUIOVector *qiov, Error **errp)
646{
647 QEMUIOVector sub_qiov;
648 uint64_t offset;
649 size_t data_size;
650 int ret;
651 NBDStructuredReplyChunk *chunk = &s->reply.structured;
652
653 assert(nbd_reply_is_structured(&s->reply));
654
655 /* The NBD spec requires at least one byte of payload */
656 if (chunk->length <= sizeof(offset)) {
657 error_setg(errp, "Protocol error: invalid payload for "
658 "NBD_REPLY_TYPE_OFFSET_DATA");
659 return -EINVAL;
660 }
661
662 if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) {
663 return -EIO;
664 }
665
666 data_size = chunk->length - sizeof(offset);
667 assert(data_size);
668 if (offset < orig_offset || data_size > qiov->size ||
669 offset > orig_offset + qiov->size - data_size) {
670 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
671 " region");
672 return -EINVAL;
673 }
674 if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) {
675 trace_nbd_structured_read_compliance("data");
676 }
677
678 qemu_iovec_init(&sub_qiov, qiov->niov);
679 qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size);
680 ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);
681 qemu_iovec_destroy(&sub_qiov);
682
683 return ret < 0 ? -EIO : 0;
684}
685
686#define NBD_MAX_MALLOC_PAYLOAD 1000
687static coroutine_fn int nbd_co_receive_structured_payload(
611ae1d7 688 BDRVNBDState *s, void **payload, Error **errp)
86f8cdf3
VSO
689{
690 int ret;
691 uint32_t len;
692
693 assert(nbd_reply_is_structured(&s->reply));
694
695 len = s->reply.structured.length;
696
697 if (len == 0) {
698 return 0;
699 }
700
701 if (payload == NULL) {
702 error_setg(errp, "Unexpected structured payload");
703 return -EINVAL;
704 }
705
706 if (len > NBD_MAX_MALLOC_PAYLOAD) {
707 error_setg(errp, "Payload too large");
708 return -EINVAL;
709 }
710
711 *payload = g_new(char, len);
712 ret = nbd_read(s->ioc, *payload, len, "structured payload", errp);
713 if (ret < 0) {
714 g_free(*payload);
715 *payload = NULL;
716 return ret;
717 }
718
719 return 0;
720}
721
722/*
723 * nbd_co_do_receive_one_chunk
724 * for simple reply:
725 * set request_ret to received reply error
726 * if qiov is not NULL: read payload to @qiov
727 * for structured reply chunk:
728 * if error chunk: read payload, set @request_ret, do not set @payload
729 * else if offset_data chunk: read payload data to @qiov, do not set @payload
730 * else: read payload to @payload
731 *
732 * If function fails, @errp contains corresponding error message, and the
733 * connection with the server is suspect. If it returns 0, then the
734 * transaction succeeded (although @request_ret may be a negative errno
735 * corresponding to the server's error reply), and errp is unchanged.
736 */
737static coroutine_fn int nbd_co_do_receive_one_chunk(
611ae1d7 738 BDRVNBDState *s, uint64_t handle, bool only_structured,
86f8cdf3
VSO
739 int *request_ret, QEMUIOVector *qiov, void **payload, Error **errp)
740{
741 int ret;
742 int i = HANDLE_TO_INDEX(s, handle);
743 void *local_payload = NULL;
744 NBDStructuredReplyChunk *chunk;
745
746 if (payload) {
747 *payload = NULL;
748 }
749 *request_ret = 0;
750
751 /* Wait until we're woken up by nbd_connection_entry. */
752 s->requests[i].receiving = true;
753 qemu_coroutine_yield();
754 s->requests[i].receiving = false;
a34b1e5e 755 if (s->state != NBD_CLIENT_CONNECTED) {
86f8cdf3
VSO
756 error_setg(errp, "Connection closed");
757 return -EIO;
758 }
759 assert(s->ioc);
760
761 assert(s->reply.handle == handle);
762
763 if (nbd_reply_is_simple(&s->reply)) {
764 if (only_structured) {
765 error_setg(errp, "Protocol error: simple reply when structured "
766 "reply chunk was expected");
767 return -EINVAL;
768 }
769
770 *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error);
771 if (*request_ret < 0 || !qiov) {
772 return 0;
773 }
774
775 return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov,
776 errp) < 0 ? -EIO : 0;
777 }
778
779 /* handle structured reply chunk */
780 assert(s->info.structured_reply);
781 chunk = &s->reply.structured;
782
783 if (chunk->type == NBD_REPLY_TYPE_NONE) {
784 if (!(chunk->flags & NBD_REPLY_FLAG_DONE)) {
785 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
786 " NBD_REPLY_FLAG_DONE flag set");
787 return -EINVAL;
788 }
789 if (chunk->length) {
790 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
791 " nonzero length");
792 return -EINVAL;
793 }
794 return 0;
795 }
796
797 if (chunk->type == NBD_REPLY_TYPE_OFFSET_DATA) {
798 if (!qiov) {
799 error_setg(errp, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
800 return -EINVAL;
801 }
802
803 return nbd_co_receive_offset_data_payload(s, s->requests[i].offset,
804 qiov, errp);
805 }
806
807 if (nbd_reply_type_is_error(chunk->type)) {
808 payload = &local_payload;
809 }
810
811 ret = nbd_co_receive_structured_payload(s, payload, errp);
812 if (ret < 0) {
813 return ret;
814 }
815
816 if (nbd_reply_type_is_error(chunk->type)) {
817 ret = nbd_parse_error_payload(chunk, local_payload, request_ret, errp);
818 g_free(local_payload);
819 return ret;
820 }
821
822 return 0;
823}
824
825/*
826 * nbd_co_receive_one_chunk
827 * Read reply, wake up connection_co and set s->quit if needed.
828 * Return value is a fatal error code or normal nbd reply error code
829 */
830static coroutine_fn int nbd_co_receive_one_chunk(
611ae1d7 831 BDRVNBDState *s, uint64_t handle, bool only_structured,
86f8cdf3
VSO
832 int *request_ret, QEMUIOVector *qiov, NBDReply *reply, void **payload,
833 Error **errp)
834{
835 int ret = nbd_co_do_receive_one_chunk(s, handle, only_structured,
836 request_ret, qiov, payload, errp);
837
838 if (ret < 0) {
5cf42b1c 839 memset(reply, 0, sizeof(*reply));
a34b1e5e 840 nbd_channel_error(s, ret);
86f8cdf3
VSO
841 } else {
842 /* For assert at loop start in nbd_connection_entry */
5cf42b1c 843 *reply = s->reply;
86f8cdf3 844 }
f7651539 845 s->reply.handle = 0;
86f8cdf3 846
f7651539
VSO
847 if (s->connection_co && !s->wait_in_flight) {
848 /*
849 * We must check s->wait_in_flight, because we may entered by
850 * nbd_recv_coroutines_wake_all(), in this case we should not
851 * wake connection_co here, it will woken by last request.
852 */
86f8cdf3
VSO
853 aio_co_wake(s->connection_co);
854 }
855
856 return ret;
857}
858
859typedef struct NBDReplyChunkIter {
860 int ret;
861 int request_ret;
862 Error *err;
863 bool done, only_structured;
864} NBDReplyChunkIter;
865
866static void nbd_iter_channel_error(NBDReplyChunkIter *iter,
867 int ret, Error **local_err)
868{
d9366135 869 assert(local_err && *local_err);
86f8cdf3
VSO
870 assert(ret < 0);
871
872 if (!iter->ret) {
873 iter->ret = ret;
874 error_propagate(&iter->err, *local_err);
875 } else {
876 error_free(*local_err);
877 }
878
879 *local_err = NULL;
880}
881
882static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret)
883{
884 assert(ret < 0);
885
886 if (!iter->request_ret) {
887 iter->request_ret = ret;
888 }
889}
890
891/*
892 * NBD_FOREACH_REPLY_CHUNK
893 * The pointer stored in @payload requires g_free() to free it.
894 */
895#define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
896 qiov, reply, payload) \
897 for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
898 nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
899
900/*
901 * nbd_reply_chunk_iter_receive
902 * The pointer stored in @payload requires g_free() to free it.
903 */
611ae1d7 904static bool nbd_reply_chunk_iter_receive(BDRVNBDState *s,
86f8cdf3
VSO
905 NBDReplyChunkIter *iter,
906 uint64_t handle,
907 QEMUIOVector *qiov, NBDReply *reply,
908 void **payload)
909{
910 int ret, request_ret;
911 NBDReply local_reply;
912 NBDStructuredReplyChunk *chunk;
913 Error *local_err = NULL;
a34b1e5e 914 if (s->state != NBD_CLIENT_CONNECTED) {
86f8cdf3
VSO
915 error_setg(&local_err, "Connection closed");
916 nbd_iter_channel_error(iter, -EIO, &local_err);
917 goto break_loop;
918 }
919
920 if (iter->done) {
921 /* Previous iteration was last. */
922 goto break_loop;
923 }
924
925 if (reply == NULL) {
926 reply = &local_reply;
927 }
928
929 ret = nbd_co_receive_one_chunk(s, handle, iter->only_structured,
930 &request_ret, qiov, reply, payload,
931 &local_err);
932 if (ret < 0) {
933 nbd_iter_channel_error(iter, ret, &local_err);
934 } else if (request_ret < 0) {
935 nbd_iter_request_error(iter, request_ret);
936 }
937
938 /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
a34b1e5e 939 if (nbd_reply_is_simple(reply) || s->state != NBD_CLIENT_CONNECTED) {
86f8cdf3
VSO
940 goto break_loop;
941 }
942
943 chunk = &reply->structured;
944 iter->only_structured = true;
945
946 if (chunk->type == NBD_REPLY_TYPE_NONE) {
947 /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
948 assert(chunk->flags & NBD_REPLY_FLAG_DONE);
949 goto break_loop;
950 }
951
952 if (chunk->flags & NBD_REPLY_FLAG_DONE) {
953 /* This iteration is last. */
954 iter->done = true;
955 }
956
957 /* Execute the loop body */
958 return true;
959
960break_loop:
961 s->requests[HANDLE_TO_INDEX(s, handle)].coroutine = NULL;
962
963 qemu_co_mutex_lock(&s->send_mutex);
964 s->in_flight--;
f7651539
VSO
965 if (s->in_flight == 0 && s->wait_in_flight) {
966 aio_co_wake(s->connection_co);
967 } else {
968 qemu_co_queue_next(&s->free_sema);
969 }
86f8cdf3
VSO
970 qemu_co_mutex_unlock(&s->send_mutex);
971
972 return false;
973}
974
611ae1d7 975static int nbd_co_receive_return_code(BDRVNBDState *s, uint64_t handle,
86f8cdf3
VSO
976 int *request_ret, Error **errp)
977{
978 NBDReplyChunkIter iter;
979
980 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, NULL, NULL) {
981 /* nbd_reply_chunk_iter_receive does all the work */
982 }
983
984 error_propagate(errp, iter.err);
985 *request_ret = iter.request_ret;
986 return iter.ret;
987}
988
611ae1d7 989static int nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t handle,
86f8cdf3
VSO
990 uint64_t offset, QEMUIOVector *qiov,
991 int *request_ret, Error **errp)
992{
993 NBDReplyChunkIter iter;
994 NBDReply reply;
995 void *payload = NULL;
996 Error *local_err = NULL;
997
998 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, s->info.structured_reply,
999 qiov, &reply, &payload)
1000 {
1001 int ret;
1002 NBDStructuredReplyChunk *chunk = &reply.structured;
1003
1004 assert(nbd_reply_is_structured(&reply));
1005
1006 switch (chunk->type) {
1007 case NBD_REPLY_TYPE_OFFSET_DATA:
1008 /*
1009 * special cased in nbd_co_receive_one_chunk, data is already
1010 * in qiov
1011 */
1012 break;
1013 case NBD_REPLY_TYPE_OFFSET_HOLE:
1014 ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload,
1015 offset, qiov, &local_err);
1016 if (ret < 0) {
a34b1e5e 1017 nbd_channel_error(s, ret);
86f8cdf3
VSO
1018 nbd_iter_channel_error(&iter, ret, &local_err);
1019 }
1020 break;
1021 default:
1022 if (!nbd_reply_type_is_error(chunk->type)) {
1023 /* not allowed reply type */
a34b1e5e 1024 nbd_channel_error(s, -EINVAL);
86f8cdf3
VSO
1025 error_setg(&local_err,
1026 "Unexpected reply type: %d (%s) for CMD_READ",
1027 chunk->type, nbd_reply_type_lookup(chunk->type));
1028 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1029 }
1030 }
1031
1032 g_free(payload);
1033 payload = NULL;
1034 }
1035
1036 error_propagate(errp, iter.err);
1037 *request_ret = iter.request_ret;
1038 return iter.ret;
1039}
1040
611ae1d7 1041static int nbd_co_receive_blockstatus_reply(BDRVNBDState *s,
86f8cdf3
VSO
1042 uint64_t handle, uint64_t length,
1043 NBDExtent *extent,
1044 int *request_ret, Error **errp)
1045{
1046 NBDReplyChunkIter iter;
1047 NBDReply reply;
1048 void *payload = NULL;
1049 Error *local_err = NULL;
1050 bool received = false;
1051
1052 assert(!extent->length);
1053 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, &reply, &payload) {
1054 int ret;
1055 NBDStructuredReplyChunk *chunk = &reply.structured;
1056
1057 assert(nbd_reply_is_structured(&reply));
1058
1059 switch (chunk->type) {
1060 case NBD_REPLY_TYPE_BLOCK_STATUS:
1061 if (received) {
a34b1e5e 1062 nbd_channel_error(s, -EINVAL);
86f8cdf3
VSO
1063 error_setg(&local_err, "Several BLOCK_STATUS chunks in reply");
1064 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1065 }
1066 received = true;
1067
1068 ret = nbd_parse_blockstatus_payload(s, &reply.structured,
1069 payload, length, extent,
1070 &local_err);
1071 if (ret < 0) {
a34b1e5e 1072 nbd_channel_error(s, ret);
86f8cdf3
VSO
1073 nbd_iter_channel_error(&iter, ret, &local_err);
1074 }
1075 break;
1076 default:
1077 if (!nbd_reply_type_is_error(chunk->type)) {
a34b1e5e 1078 nbd_channel_error(s, -EINVAL);
86f8cdf3
VSO
1079 error_setg(&local_err,
1080 "Unexpected reply type: %d (%s) "
1081 "for CMD_BLOCK_STATUS",
1082 chunk->type, nbd_reply_type_lookup(chunk->type));
1083 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1084 }
1085 }
1086
1087 g_free(payload);
1088 payload = NULL;
1089 }
1090
1091 if (!extent->length && !iter.request_ret) {
1092 error_setg(&local_err, "Server did not reply with any status extents");
1093 nbd_iter_channel_error(&iter, -EIO, &local_err);
1094 }
1095
1096 error_propagate(errp, iter.err);
1097 *request_ret = iter.request_ret;
1098 return iter.ret;
1099}
1100
1101static int nbd_co_request(BlockDriverState *bs, NBDRequest *request,
1102 QEMUIOVector *write_qiov)
1103{
1104 int ret, request_ret;
1105 Error *local_err = NULL;
611ae1d7 1106 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1107
1108 assert(request->type != NBD_CMD_READ);
1109 if (write_qiov) {
1110 assert(request->type == NBD_CMD_WRITE);
1111 assert(request->len == iov_size(write_qiov->iov, write_qiov->niov));
1112 } else {
1113 assert(request->type != NBD_CMD_WRITE);
1114 }
86f8cdf3 1115
f7651539
VSO
1116 do {
1117 ret = nbd_co_send_request(bs, request, write_qiov);
1118 if (ret < 0) {
1119 continue;
1120 }
1121
1122 ret = nbd_co_receive_return_code(s, request->handle,
1123 &request_ret, &local_err);
1124 if (local_err) {
1125 trace_nbd_co_request_fail(request->from, request->len,
1126 request->handle, request->flags,
1127 request->type,
1128 nbd_cmd_lookup(request->type),
1129 ret, error_get_pretty(local_err));
1130 error_free(local_err);
1131 local_err = NULL;
1132 }
1133 } while (ret < 0 && nbd_client_connecting_wait(s));
1134
86f8cdf3
VSO
1135 return ret ? ret : request_ret;
1136}
1137
1138static int nbd_client_co_preadv(BlockDriverState *bs, uint64_t offset,
1139 uint64_t bytes, QEMUIOVector *qiov, int flags)
1140{
1141 int ret, request_ret;
1142 Error *local_err = NULL;
611ae1d7 1143 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1144 NBDRequest request = {
1145 .type = NBD_CMD_READ,
1146 .from = offset,
1147 .len = bytes,
1148 };
1149
1150 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1151 assert(!flags);
1152
1153 if (!bytes) {
1154 return 0;
1155 }
1156 /*
1157 * Work around the fact that the block layer doesn't do
1158 * byte-accurate sizing yet - if the read exceeds the server's
1159 * advertised size because the block layer rounded size up, then
1160 * truncate the request to the server and tail-pad with zero.
1161 */
611ae1d7 1162 if (offset >= s->info.size) {
86f8cdf3
VSO
1163 assert(bytes < BDRV_SECTOR_SIZE);
1164 qemu_iovec_memset(qiov, 0, 0, bytes);
1165 return 0;
1166 }
611ae1d7
VSO
1167 if (offset + bytes > s->info.size) {
1168 uint64_t slop = offset + bytes - s->info.size;
86f8cdf3
VSO
1169
1170 assert(slop < BDRV_SECTOR_SIZE);
1171 qemu_iovec_memset(qiov, bytes - slop, 0, slop);
1172 request.len -= slop;
1173 }
1174
f7651539
VSO
1175 do {
1176 ret = nbd_co_send_request(bs, &request, NULL);
1177 if (ret < 0) {
1178 continue;
1179 }
1180
1181 ret = nbd_co_receive_cmdread_reply(s, request.handle, offset, qiov,
1182 &request_ret, &local_err);
1183 if (local_err) {
1184 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1185 request.flags, request.type,
1186 nbd_cmd_lookup(request.type),
1187 ret, error_get_pretty(local_err));
1188 error_free(local_err);
1189 local_err = NULL;
1190 }
1191 } while (ret < 0 && nbd_client_connecting_wait(s));
86f8cdf3 1192
86f8cdf3
VSO
1193 return ret ? ret : request_ret;
1194}
1195
1196static int nbd_client_co_pwritev(BlockDriverState *bs, uint64_t offset,
1197 uint64_t bytes, QEMUIOVector *qiov, int flags)
1198{
611ae1d7 1199 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1200 NBDRequest request = {
1201 .type = NBD_CMD_WRITE,
1202 .from = offset,
1203 .len = bytes,
1204 };
1205
611ae1d7 1206 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
86f8cdf3 1207 if (flags & BDRV_REQ_FUA) {
611ae1d7 1208 assert(s->info.flags & NBD_FLAG_SEND_FUA);
86f8cdf3
VSO
1209 request.flags |= NBD_CMD_FLAG_FUA;
1210 }
1211
1212 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1213
1214 if (!bytes) {
1215 return 0;
1216 }
1217 return nbd_co_request(bs, &request, qiov);
1218}
1219
1220static int nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1221 int bytes, BdrvRequestFlags flags)
1222{
611ae1d7 1223 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1224 NBDRequest request = {
1225 .type = NBD_CMD_WRITE_ZEROES,
1226 .from = offset,
1227 .len = bytes,
1228 };
1229
611ae1d7
VSO
1230 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1231 if (!(s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {
86f8cdf3
VSO
1232 return -ENOTSUP;
1233 }
1234
1235 if (flags & BDRV_REQ_FUA) {
611ae1d7 1236 assert(s->info.flags & NBD_FLAG_SEND_FUA);
86f8cdf3
VSO
1237 request.flags |= NBD_CMD_FLAG_FUA;
1238 }
1239 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1240 request.flags |= NBD_CMD_FLAG_NO_HOLE;
1241 }
f061656c
EB
1242 if (flags & BDRV_REQ_NO_FALLBACK) {
1243 assert(s->info.flags & NBD_FLAG_SEND_FAST_ZERO);
1244 request.flags |= NBD_CMD_FLAG_FAST_ZERO;
1245 }
86f8cdf3
VSO
1246
1247 if (!bytes) {
1248 return 0;
1249 }
1250 return nbd_co_request(bs, &request, NULL);
1251}
1252
1253static int nbd_client_co_flush(BlockDriverState *bs)
1254{
611ae1d7 1255 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1256 NBDRequest request = { .type = NBD_CMD_FLUSH };
1257
611ae1d7 1258 if (!(s->info.flags & NBD_FLAG_SEND_FLUSH)) {
86f8cdf3
VSO
1259 return 0;
1260 }
1261
1262 request.from = 0;
1263 request.len = 0;
1264
1265 return nbd_co_request(bs, &request, NULL);
1266}
1267
1268static int nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset,
1269 int bytes)
1270{
611ae1d7 1271 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1272 NBDRequest request = {
1273 .type = NBD_CMD_TRIM,
1274 .from = offset,
1275 .len = bytes,
1276 };
1277
611ae1d7
VSO
1278 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1279 if (!(s->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) {
86f8cdf3
VSO
1280 return 0;
1281 }
1282
1283 return nbd_co_request(bs, &request, NULL);
1284}
1285
1286static int coroutine_fn nbd_client_co_block_status(
1287 BlockDriverState *bs, bool want_zero, int64_t offset, int64_t bytes,
1288 int64_t *pnum, int64_t *map, BlockDriverState **file)
1289{
1290 int ret, request_ret;
1291 NBDExtent extent = { 0 };
611ae1d7 1292 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1293 Error *local_err = NULL;
1294
1295 NBDRequest request = {
1296 .type = NBD_CMD_BLOCK_STATUS,
1297 .from = offset,
1298 .len = MIN(MIN_NON_ZERO(QEMU_ALIGN_DOWN(INT_MAX,
1299 bs->bl.request_alignment),
611ae1d7
VSO
1300 s->info.max_block),
1301 MIN(bytes, s->info.size - offset)),
86f8cdf3
VSO
1302 .flags = NBD_CMD_FLAG_REQ_ONE,
1303 };
1304
611ae1d7 1305 if (!s->info.base_allocation) {
86f8cdf3
VSO
1306 *pnum = bytes;
1307 *map = offset;
1308 *file = bs;
1309 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
1310 }
1311
1312 /*
1313 * Work around the fact that the block layer doesn't do
1314 * byte-accurate sizing yet - if the status request exceeds the
1315 * server's advertised size because the block layer rounded size
1316 * up, we truncated the request to the server (above), or are
1317 * called on just the hole.
1318 */
611ae1d7 1319 if (offset >= s->info.size) {
86f8cdf3
VSO
1320 *pnum = bytes;
1321 assert(bytes < BDRV_SECTOR_SIZE);
1322 /* Intentionally don't report offset_valid for the hole */
1323 return BDRV_BLOCK_ZERO;
1324 }
1325
611ae1d7
VSO
1326 if (s->info.min_block) {
1327 assert(QEMU_IS_ALIGNED(request.len, s->info.min_block));
86f8cdf3 1328 }
f7651539
VSO
1329 do {
1330 ret = nbd_co_send_request(bs, &request, NULL);
1331 if (ret < 0) {
1332 continue;
1333 }
1334
1335 ret = nbd_co_receive_blockstatus_reply(s, request.handle, bytes,
1336 &extent, &request_ret,
1337 &local_err);
1338 if (local_err) {
1339 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1340 request.flags, request.type,
1341 nbd_cmd_lookup(request.type),
1342 ret, error_get_pretty(local_err));
1343 error_free(local_err);
1344 local_err = NULL;
1345 }
1346 } while (ret < 0 && nbd_client_connecting_wait(s));
86f8cdf3 1347
86f8cdf3
VSO
1348 if (ret < 0 || request_ret < 0) {
1349 return ret ? ret : request_ret;
1350 }
1351
1352 assert(extent.length);
1353 *pnum = extent.length;
1354 *map = offset;
1355 *file = bs;
1356 return (extent.flags & NBD_STATE_HOLE ? 0 : BDRV_BLOCK_DATA) |
1357 (extent.flags & NBD_STATE_ZERO ? BDRV_BLOCK_ZERO : 0) |
1358 BDRV_BLOCK_OFFSET_VALID;
1359}
1360
e99754b4
ML
1361static int nbd_client_reopen_prepare(BDRVReopenState *state,
1362 BlockReopenQueue *queue, Error **errp)
1363{
1364 BDRVNBDState *s = (BDRVNBDState *)state->bs->opaque;
1365
1366 if ((state->flags & BDRV_O_RDWR) && (s->info.flags & NBD_FLAG_READ_ONLY)) {
1367 error_setg(errp, "Can't reopen read-only NBD mount as read/write");
1368 return -EACCES;
1369 }
1370 return 0;
1371}
1372
86f8cdf3
VSO
1373static void nbd_client_close(BlockDriverState *bs)
1374{
611ae1d7 1375 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1376 NBDRequest request = { .type = NBD_CMD_DISC };
1377
f7651539
VSO
1378 if (s->ioc) {
1379 nbd_send_request(s->ioc, &request);
1380 }
86f8cdf3
VSO
1381
1382 nbd_teardown_connection(bs);
1383}
1384
1385static QIOChannelSocket *nbd_establish_connection(SocketAddress *saddr,
1386 Error **errp)
1387{
1388 QIOChannelSocket *sioc;
1389 Error *local_err = NULL;
1390
1391 sioc = qio_channel_socket_new();
1392 qio_channel_set_name(QIO_CHANNEL(sioc), "nbd-client");
1393
1394 qio_channel_socket_connect_sync(sioc, saddr, &local_err);
1395 if (local_err) {
1396 object_unref(OBJECT(sioc));
1397 error_propagate(errp, local_err);
1398 return NULL;
1399 }
1400
1401 qio_channel_set_delay(QIO_CHANNEL(sioc), false);
1402
1403 return sioc;
1404}
1405
8f071c9d 1406static int nbd_client_connect(BlockDriverState *bs, Error **errp)
86f8cdf3 1407{
611ae1d7 1408 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
a8e2bb6a 1409 AioContext *aio_context = bdrv_get_aio_context(bs);
86f8cdf3
VSO
1410 int ret;
1411
1412 /*
1413 * establish TCP connection, return error if it fails
1414 * TODO: Configurable retry-until-timeout behaviour.
1415 */
8f071c9d 1416 QIOChannelSocket *sioc = nbd_establish_connection(s->saddr, errp);
86f8cdf3
VSO
1417
1418 if (!sioc) {
1419 return -ECONNREFUSED;
1420 }
1421
1422 /* NBD handshake */
8f071c9d 1423 trace_nbd_client_connect(s->export);
a8e2bb6a
VSO
1424 qio_channel_set_blocking(QIO_CHANNEL(sioc), false, NULL);
1425 qio_channel_attach_aio_context(QIO_CHANNEL(sioc), aio_context);
86f8cdf3 1426
611ae1d7
VSO
1427 s->info.request_sizes = true;
1428 s->info.structured_reply = true;
1429 s->info.base_allocation = true;
8f071c9d
VSO
1430 s->info.x_dirty_bitmap = g_strdup(s->x_dirty_bitmap);
1431 s->info.name = g_strdup(s->export ?: "");
1432 ret = nbd_receive_negotiate(aio_context, QIO_CHANNEL(sioc), s->tlscreds,
1433 s->hostname, &s->ioc, &s->info, errp);
611ae1d7
VSO
1434 g_free(s->info.x_dirty_bitmap);
1435 g_free(s->info.name);
86f8cdf3
VSO
1436 if (ret < 0) {
1437 object_unref(OBJECT(sioc));
1438 return ret;
1439 }
8f071c9d 1440 if (s->x_dirty_bitmap && !s->info.base_allocation) {
86f8cdf3 1441 error_setg(errp, "requested x-dirty-bitmap %s not found",
8f071c9d 1442 s->x_dirty_bitmap);
86f8cdf3
VSO
1443 ret = -EINVAL;
1444 goto fail;
1445 }
611ae1d7 1446 if (s->info.flags & NBD_FLAG_READ_ONLY) {
86f8cdf3
VSO
1447 ret = bdrv_apply_auto_read_only(bs, "NBD export is read-only", errp);
1448 if (ret < 0) {
1449 goto fail;
1450 }
1451 }
611ae1d7 1452 if (s->info.flags & NBD_FLAG_SEND_FUA) {
86f8cdf3
VSO
1453 bs->supported_write_flags = BDRV_REQ_FUA;
1454 bs->supported_zero_flags |= BDRV_REQ_FUA;
1455 }
611ae1d7 1456 if (s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES) {
86f8cdf3 1457 bs->supported_zero_flags |= BDRV_REQ_MAY_UNMAP;
f061656c
EB
1458 if (s->info.flags & NBD_FLAG_SEND_FAST_ZERO) {
1459 bs->supported_zero_flags |= BDRV_REQ_NO_FALLBACK;
1460 }
86f8cdf3
VSO
1461 }
1462
611ae1d7 1463 s->sioc = sioc;
86f8cdf3 1464
611ae1d7
VSO
1465 if (!s->ioc) {
1466 s->ioc = QIO_CHANNEL(sioc);
1467 object_ref(OBJECT(s->ioc));
86f8cdf3
VSO
1468 }
1469
8f071c9d 1470 trace_nbd_client_connect_success(s->export);
86f8cdf3
VSO
1471
1472 return 0;
1473
1474 fail:
1475 /*
a8e2bb6a
VSO
1476 * We have connected, but must fail for other reasons.
1477 * Send NBD_CMD_DISC as a courtesy to the server.
86f8cdf3
VSO
1478 */
1479 {
1480 NBDRequest request = { .type = NBD_CMD_DISC };
1481
611ae1d7 1482 nbd_send_request(s->ioc ?: QIO_CHANNEL(sioc), &request);
86f8cdf3
VSO
1483
1484 object_unref(OBJECT(sioc));
1485
1486 return ret;
1487 }
1488}
1489
8f071c9d
VSO
1490/*
1491 * Parse nbd_open options
1492 */
86f8cdf3 1493
f53a1feb 1494static int nbd_parse_uri(const char *filename, QDict *options)
1d7d2a9d
PB
1495{
1496 URI *uri;
1497 const char *p;
1498 QueryParams *qp = NULL;
1499 int ret = 0;
f53a1feb 1500 bool is_unix;
1d7d2a9d
PB
1501
1502 uri = uri_parse(filename);
1503 if (!uri) {
1504 return -EINVAL;
1505 }
1506
1507 /* transport */
f69165a8 1508 if (!g_strcmp0(uri->scheme, "nbd")) {
f53a1feb 1509 is_unix = false;
f69165a8 1510 } else if (!g_strcmp0(uri->scheme, "nbd+tcp")) {
f53a1feb 1511 is_unix = false;
f69165a8 1512 } else if (!g_strcmp0(uri->scheme, "nbd+unix")) {
f53a1feb 1513 is_unix = true;
1d7d2a9d
PB
1514 } else {
1515 ret = -EINVAL;
1516 goto out;
1517 }
1518
1519 p = uri->path ? uri->path : "/";
1520 p += strspn(p, "/");
1521 if (p[0]) {
46f5ac20 1522 qdict_put_str(options, "export", p);
1d7d2a9d
PB
1523 }
1524
1525 qp = query_params_parse(uri->query);
f53a1feb 1526 if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
1d7d2a9d
PB
1527 ret = -EINVAL;
1528 goto out;
1529 }
1530
f53a1feb 1531 if (is_unix) {
1d7d2a9d
PB
1532 /* nbd+unix:///export?socket=path */
1533 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
1534 ret = -EINVAL;
1535 goto out;
1536 }
46f5ac20
EB
1537 qdict_put_str(options, "server.type", "unix");
1538 qdict_put_str(options, "server.path", qp->p[0].value);
1d7d2a9d 1539 } else {
23307908 1540 QString *host;
f84d431b
HR
1541 char *port_str;
1542
bebbf7fa 1543 /* nbd[+tcp]://host[:port]/export */
1d7d2a9d
PB
1544 if (!uri->server) {
1545 ret = -EINVAL;
1546 goto out;
1547 }
f17c90be 1548
23307908
JT
1549 /* strip braces from literal IPv6 address */
1550 if (uri->server[0] == '[') {
1551 host = qstring_from_substr(uri->server, 1,
ba891d68 1552 strlen(uri->server) - 1);
23307908
JT
1553 } else {
1554 host = qstring_from_str(uri->server);
1555 }
1556
46f5ac20 1557 qdict_put_str(options, "server.type", "inet");
9445673e 1558 qdict_put(options, "server.host", host);
f84d431b
HR
1559
1560 port_str = g_strdup_printf("%d", uri->port ?: NBD_DEFAULT_PORT);
46f5ac20 1561 qdict_put_str(options, "server.port", port_str);
f84d431b 1562 g_free(port_str);
1d7d2a9d
PB
1563 }
1564
1565out:
1566 if (qp) {
1567 query_params_free(qp);
1568 }
1569 uri_free(uri);
1570 return ret;
1571}
1572
48c38e0b
HR
1573static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
1574{
1575 const QDictEntry *e;
1576
1577 for (e = qdict_first(options); e; e = qdict_next(options, e)) {
1578 if (!strcmp(e->key, "host") ||
1579 !strcmp(e->key, "port") ||
1580 !strcmp(e->key, "path") ||
491d6c7c
HR
1581 !strcmp(e->key, "export") ||
1582 strstart(e->key, "server.", NULL))
48c38e0b
HR
1583 {
1584 error_setg(errp, "Option '%s' cannot be used with a file name",
1585 e->key);
1586 return true;
1587 }
1588 }
1589
1590 return false;
1591}
1592
6963a30d
KW
1593static void nbd_parse_filename(const char *filename, QDict *options,
1594 Error **errp)
75818250 1595{
df18c04e 1596 g_autofree char *file = NULL;
33897dc7
NT
1597 char *export_name;
1598 const char *host_spec;
75818250 1599 const char *unixpath;
75818250 1600
48c38e0b 1601 if (nbd_has_filename_options_conflict(options, errp)) {
681e7ad0
KW
1602 return;
1603 }
1604
1d7d2a9d 1605 if (strstr(filename, "://")) {
6963a30d
KW
1606 int ret = nbd_parse_uri(filename, options);
1607 if (ret < 0) {
1608 error_setg(errp, "No valid URL specified");
1609 }
1610 return;
1d7d2a9d
PB
1611 }
1612
7267c094 1613 file = g_strdup(filename);
1d45f8b5 1614
33897dc7
NT
1615 export_name = strstr(file, EN_OPTSTR);
1616 if (export_name) {
1617 if (export_name[strlen(EN_OPTSTR)] == 0) {
df18c04e 1618 return;
1d45f8b5 1619 }
33897dc7
NT
1620 export_name[0] = 0; /* truncate 'file' */
1621 export_name += strlen(EN_OPTSTR);
f53a1feb 1622
46f5ac20 1623 qdict_put_str(options, "export", export_name);
1d45f8b5
LV
1624 }
1625
33897dc7
NT
1626 /* extract the host_spec - fail if it's not nbd:... */
1627 if (!strstart(file, "nbd:", &host_spec)) {
6963a30d 1628 error_setg(errp, "File name string for NBD must start with 'nbd:'");
df18c04e 1629 return;
1d45f8b5 1630 }
75818250 1631
f53a1feb 1632 if (!*host_spec) {
df18c04e 1633 return;
f53a1feb
KW
1634 }
1635
33897dc7
NT
1636 /* are we a UNIX or TCP socket? */
1637 if (strstart(host_spec, "unix:", &unixpath)) {
46f5ac20
EB
1638 qdict_put_str(options, "server.type", "unix");
1639 qdict_put_str(options, "server.path", unixpath);
75818250 1640 } else {
0785bd7a 1641 InetSocketAddress *addr = g_new(InetSocketAddress, 1);
f53a1feb 1642
0785bd7a
MA
1643 if (inet_parse(addr, host_spec, errp)) {
1644 goto out_inet;
f17c90be 1645 }
75818250 1646
46f5ac20
EB
1647 qdict_put_str(options, "server.type", "inet");
1648 qdict_put_str(options, "server.host", addr->host);
1649 qdict_put_str(options, "server.port", addr->port);
0785bd7a 1650 out_inet:
f53a1feb
KW
1651 qapi_free_InetSocketAddress(addr);
1652 }
f53a1feb
KW
1653}
1654
491d6c7c
HR
1655static bool nbd_process_legacy_socket_options(QDict *output_options,
1656 QemuOpts *legacy_opts,
1657 Error **errp)
f53a1feb 1658{
491d6c7c
HR
1659 const char *path = qemu_opt_get(legacy_opts, "path");
1660 const char *host = qemu_opt_get(legacy_opts, "host");
1661 const char *port = qemu_opt_get(legacy_opts, "port");
1662 const QDictEntry *e;
f53a1feb 1663
491d6c7c
HR
1664 if (!path && !host && !port) {
1665 return true;
1666 }
03504d05 1667
491d6c7c
HR
1668 for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
1669 {
1670 if (strstart(e->key, "server.", NULL)) {
1671 error_setg(errp, "Cannot use 'server' and path/host/port at the "
1672 "same time");
1673 return false;
681e7ad0 1674 }
33897dc7 1675 }
491d6c7c
HR
1676
1677 if (path && host) {
1678 error_setg(errp, "path and host may not be used at the same time");
1679 return false;
1680 } else if (path) {
1681 if (port) {
1682 error_setg(errp, "port may not be used without host");
1683 return false;
1684 }
1685
46f5ac20
EB
1686 qdict_put_str(output_options, "server.type", "unix");
1687 qdict_put_str(output_options, "server.path", path);
491d6c7c 1688 } else if (host) {
46f5ac20
EB
1689 qdict_put_str(output_options, "server.type", "inet");
1690 qdict_put_str(output_options, "server.host", host);
1691 qdict_put_str(output_options, "server.port",
1692 port ?: stringify(NBD_DEFAULT_PORT));
442045cb 1693 }
f53a1feb 1694
491d6c7c
HR
1695 return true;
1696}
f53a1feb 1697
62cf396b
MA
1698static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options,
1699 Error **errp)
491d6c7c 1700{
62cf396b 1701 SocketAddress *saddr = NULL;
491d6c7c 1702 QDict *addr = NULL;
491d6c7c
HR
1703 Visitor *iv = NULL;
1704 Error *local_err = NULL;
1705
1706 qdict_extract_subqdict(options, &addr, "server.");
1707 if (!qdict_size(addr)) {
1708 error_setg(errp, "NBD server address missing");
1709 goto done;
f53a1feb
KW
1710 }
1711
af91062e
MA
1712 iv = qobject_input_visitor_new_flat_confused(addr, errp);
1713 if (!iv) {
491d6c7c
HR
1714 goto done;
1715 }
bebbf7fa 1716
62cf396b 1717 visit_type_SocketAddress(iv, NULL, &saddr, &local_err);
491d6c7c
HR
1718 if (local_err) {
1719 error_propagate(errp, local_err);
1720 goto done;
1721 }
7a5ed437 1722
491d6c7c 1723done:
cb3e7f08 1724 qobject_unref(addr);
491d6c7c 1725 visit_free(iv);
7a5ed437 1726 return saddr;
33897dc7 1727}
1d45f8b5 1728
75822a12
DB
1729static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
1730{
1731 Object *obj;
1732 QCryptoTLSCreds *creds;
1733
1734 obj = object_resolve_path_component(
1735 object_get_objects_root(), id);
1736 if (!obj) {
1737 error_setg(errp, "No TLS credentials with id '%s'",
1738 id);
1739 return NULL;
1740 }
1741 creds = (QCryptoTLSCreds *)
1742 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
1743 if (!creds) {
1744 error_setg(errp, "Object with id '%s' is not TLS credentials",
1745 id);
1746 return NULL;
1747 }
1748
1749 if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
1750 error_setg(errp,
1751 "Expecting TLS credentials with a client endpoint");
1752 return NULL;
1753 }
1754 object_ref(obj);
1755 return creds;
1756}
1757
1758
7ccc44fd
HR
1759static QemuOptsList nbd_runtime_opts = {
1760 .name = "nbd",
1761 .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
1762 .desc = {
1763 {
1764 .name = "host",
1765 .type = QEMU_OPT_STRING,
1766 .help = "TCP host to connect to",
1767 },
1768 {
1769 .name = "port",
1770 .type = QEMU_OPT_STRING,
1771 .help = "TCP port to connect to",
1772 },
1773 {
1774 .name = "path",
1775 .type = QEMU_OPT_STRING,
1776 .help = "Unix socket path to connect to",
1777 },
1778 {
1779 .name = "export",
1780 .type = QEMU_OPT_STRING,
1781 .help = "Name of the NBD export to open",
1782 },
1783 {
1784 .name = "tls-creds",
1785 .type = QEMU_OPT_STRING,
1786 .help = "ID of the TLS credentials to use",
1787 },
216ee365
EB
1788 {
1789 .name = "x-dirty-bitmap",
1790 .type = QEMU_OPT_STRING,
1791 .help = "experimental: expose named dirty bitmap in place of "
1792 "block status",
1793 },
b172ae2e
VSO
1794 {
1795 .name = "reconnect-delay",
1796 .type = QEMU_OPT_NUMBER,
1797 .help = "On an unexpected disconnect, the nbd client tries to "
1798 "connect again until succeeding or encountering a serious "
1799 "error. During the first @reconnect-delay seconds, all "
1800 "requests are paused and will be rerun on a successful "
1801 "reconnect. After that time, any delayed requests and all "
1802 "future requests before a successful reconnect will "
1803 "immediately fail. Default 0",
1804 },
c4365735 1805 { /* end of list */ }
7ccc44fd
HR
1806 },
1807};
1808
8f071c9d
VSO
1809static int nbd_process_options(BlockDriverState *bs, QDict *options,
1810 Error **errp)
33897dc7
NT
1811{
1812 BDRVNBDState *s = bs->opaque;
8f071c9d 1813 QemuOpts *opts;
7ccc44fd 1814 Error *local_err = NULL;
75822a12 1815 int ret = -EINVAL;
ae255e52 1816
7ccc44fd
HR
1817 opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
1818 qemu_opts_absorb_qdict(opts, options, &local_err);
1819 if (local_err) {
1820 error_propagate(errp, local_err);
1821 goto error;
1822 }
1823
62cf396b 1824 /* Translate @host, @port, and @path to a SocketAddress */
491d6c7c
HR
1825 if (!nbd_process_legacy_socket_options(options, opts, errp)) {
1826 goto error;
1827 }
1828
33897dc7 1829 /* Pop the config into our state object. Exit if invalid. */
491d6c7c
HR
1830 s->saddr = nbd_config(s, options, errp);
1831 if (!s->saddr) {
75822a12
DB
1832 goto error;
1833 }
1834
491d6c7c 1835 s->export = g_strdup(qemu_opt_get(opts, "export"));
93676c88
EB
1836 if (s->export && strlen(s->export) > NBD_MAX_STRING_SIZE) {
1837 error_setg(errp, "export name too long to send to server");
1838 goto error;
1839 }
491d6c7c 1840
03504d05
HR
1841 s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
1842 if (s->tlscredsid) {
8f071c9d
VSO
1843 s->tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
1844 if (!s->tlscreds) {
75822a12
DB
1845 goto error;
1846 }
1847
ca0b64e5 1848 /* TODO SOCKET_ADDRESS_KIND_FD where fd has AF_INET or AF_INET6 */
62cf396b 1849 if (s->saddr->type != SOCKET_ADDRESS_TYPE_INET) {
75822a12
DB
1850 error_setg(errp, "TLS only supported over IP sockets");
1851 goto error;
1852 }
8f071c9d 1853 s->hostname = s->saddr->u.inet.host;
33897dc7
NT
1854 }
1855
8f071c9d 1856 s->x_dirty_bitmap = g_strdup(qemu_opt_get(opts, "x-dirty-bitmap"));
93676c88
EB
1857 if (s->x_dirty_bitmap && strlen(s->x_dirty_bitmap) > NBD_MAX_STRING_SIZE) {
1858 error_setg(errp, "x-dirty-bitmap query too long to send to server");
1859 goto error;
1860 }
1861
8f071c9d
VSO
1862 s->reconnect_delay = qemu_opt_get_number(opts, "reconnect-delay", 0);
1863
1864 ret = 0;
d42f78e9 1865
75822a12 1866 error:
03504d05 1867 if (ret < 0) {
8f071c9d 1868 object_unref(OBJECT(s->tlscreds));
62cf396b 1869 qapi_free_SocketAddress(s->saddr);
03504d05
HR
1870 g_free(s->export);
1871 g_free(s->tlscredsid);
93676c88 1872 g_free(s->x_dirty_bitmap);
03504d05 1873 }
7ccc44fd 1874 qemu_opts_del(opts);
75822a12 1875 return ret;
e183ef75
PB
1876}
1877
8f071c9d
VSO
1878static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
1879 Error **errp)
1880{
1881 int ret;
1882 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1883
1884 ret = nbd_process_options(bs, options, errp);
1885 if (ret < 0) {
1886 return ret;
1887 }
1888
1889 s->bs = bs;
1890 qemu_co_mutex_init(&s->send_mutex);
1891 qemu_co_queue_init(&s->free_sema);
1892
1893 ret = nbd_client_connect(bs, errp);
1894 if (ret < 0) {
1895 return ret;
1896 }
1897 /* successfully connected */
1898 s->state = NBD_CLIENT_CONNECTED;
1899
1900 s->connection_co = qemu_coroutine_create(nbd_connection_entry, s);
1901 bdrv_inc_in_flight(bs);
1902 aio_co_schedule(bdrv_get_aio_context(bs), s->connection_co);
1903
1904 return 0;
1905}
1906
1486d04a
PB
1907static int nbd_co_flush(BlockDriverState *bs)
1908{
f53a829b 1909 return nbd_client_co_flush(bs);
1486d04a
PB
1910}
1911
fa21e6fa
DL
1912static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
1913{
611ae1d7 1914 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
fd8d372d 1915 uint32_t min = s->info.min_block;
081dd1fe
EB
1916 uint32_t max = MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE, s->info.max_block);
1917
7da537f7
EB
1918 /*
1919 * If the server did not advertise an alignment:
1920 * - a size that is not sector-aligned implies that an alignment
1921 * of 1 can be used to access those tail bytes
1922 * - advertisement of block status requires an alignment of 1, so
1923 * that we don't violate block layer constraints that block
1924 * status is always aligned (as we can't control whether the
1925 * server will report sub-sector extents, such as a hole at EOF
1926 * on an unaligned POSIX file)
1927 * - otherwise, assume the server is so old that we are safer avoiding
1928 * sub-sector requests
1929 */
1930 if (!min) {
1931 min = (!QEMU_IS_ALIGNED(s->info.size, BDRV_SECTOR_SIZE) ||
1932 s->info.base_allocation) ? 1 : BDRV_SECTOR_SIZE;
1933 }
1934
1935 bs->bl.request_alignment = min;
081dd1fe
EB
1936 bs->bl.max_pdiscard = max;
1937 bs->bl.max_pwrite_zeroes = max;
1938 bs->bl.max_transfer = max;
1939
1940 if (s->info.opt_block &&
1941 s->info.opt_block > bs->bl.opt_transfer) {
1942 bs->bl.opt_transfer = s->info.opt_block;
1943 }
fa21e6fa
DL
1944}
1945
75818250
TS
1946static void nbd_close(BlockDriverState *bs)
1947{
03504d05
HR
1948 BDRVNBDState *s = bs->opaque;
1949
f53a829b 1950 nbd_client_close(bs);
03504d05 1951
8f071c9d 1952 object_unref(OBJECT(s->tlscreds));
62cf396b 1953 qapi_free_SocketAddress(s->saddr);
03504d05
HR
1954 g_free(s->export);
1955 g_free(s->tlscredsid);
8f071c9d 1956 g_free(s->x_dirty_bitmap);
75818250
TS
1957}
1958
1959static int64_t nbd_getlength(BlockDriverState *bs)
1960{
1961 BDRVNBDState *s = bs->opaque;
1962
611ae1d7 1963 return s->info.size;
75818250
TS
1964}
1965
998b3a1e 1966static void nbd_refresh_filename(BlockDriverState *bs)
2019d68b 1967{
03504d05 1968 BDRVNBDState *s = bs->opaque;
491d6c7c
HR
1969 const char *host = NULL, *port = NULL, *path = NULL;
1970
62cf396b 1971 if (s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
9445673e 1972 const InetSocketAddress *inet = &s->saddr->u.inet;
491d6c7c
HR
1973 if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) {
1974 host = inet->host;
1975 port = inet->port;
1976 }
62cf396b 1977 } else if (s->saddr->type == SOCKET_ADDRESS_TYPE_UNIX) {
9445673e
MA
1978 path = s->saddr->u.q_unix.path;
1979 } /* else can't represent as pseudo-filename */
2019d68b 1980
491d6c7c 1981 if (path && s->export) {
2019d68b 1982 snprintf(bs->exact_filename, sizeof(bs->exact_filename),
491d6c7c
HR
1983 "nbd+unix:///%s?socket=%s", s->export, path);
1984 } else if (path && !s->export) {
2019d68b 1985 snprintf(bs->exact_filename, sizeof(bs->exact_filename),
491d6c7c
HR
1986 "nbd+unix://?socket=%s", path);
1987 } else if (host && s->export) {
ec0de768 1988 snprintf(bs->exact_filename, sizeof(bs->exact_filename),
491d6c7c
HR
1989 "nbd://%s:%s/%s", host, port, s->export);
1990 } else if (host && !s->export) {
ec0de768 1991 snprintf(bs->exact_filename, sizeof(bs->exact_filename),
491d6c7c 1992 "nbd://%s:%s", host, port);
ec0de768 1993 }
2019d68b
HR
1994}
1995
8a6239c0
HR
1996static char *nbd_dirname(BlockDriverState *bs, Error **errp)
1997{
1998 /* The generic bdrv_dirname() implementation is able to work out some
1999 * directory name for NBD nodes, but that would be wrong. So far there is no
2000 * specification for how "export paths" would work, so NBD does not have
2001 * directory names. */
2002 error_setg(errp, "Cannot generate a base directory for NBD nodes");
2003 return NULL;
2004}
2005
2654267c
HR
2006static const char *const nbd_strong_runtime_opts[] = {
2007 "path",
2008 "host",
2009 "port",
2010 "export",
2011 "tls-creds",
2012 "server.",
2013
2014 NULL
2015};
2016
5efa9d5a 2017static BlockDriver bdrv_nbd = {
69447cd8
SH
2018 .format_name = "nbd",
2019 .protocol_name = "nbd",
2020 .instance_size = sizeof(BDRVNBDState),
2021 .bdrv_parse_filename = nbd_parse_filename,
2022 .bdrv_file_open = nbd_open,
e99754b4 2023 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
70c4fb26
EB
2024 .bdrv_co_preadv = nbd_client_co_preadv,
2025 .bdrv_co_pwritev = nbd_client_co_pwritev,
fa778fff 2026 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
69447cd8
SH
2027 .bdrv_close = nbd_close,
2028 .bdrv_co_flush_to_os = nbd_co_flush,
447e57c3 2029 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
fa21e6fa 2030 .bdrv_refresh_limits = nbd_refresh_limits,
69447cd8 2031 .bdrv_getlength = nbd_getlength,
86f8cdf3
VSO
2032 .bdrv_detach_aio_context = nbd_client_detach_aio_context,
2033 .bdrv_attach_aio_context = nbd_client_attach_aio_context,
f7651539
VSO
2034 .bdrv_co_drain_begin = nbd_client_co_drain_begin,
2035 .bdrv_co_drain_end = nbd_client_co_drain_end,
2019d68b 2036 .bdrv_refresh_filename = nbd_refresh_filename,
78a33ab5 2037 .bdrv_co_block_status = nbd_client_co_block_status,
8a6239c0 2038 .bdrv_dirname = nbd_dirname,
2654267c 2039 .strong_runtime_opts = nbd_strong_runtime_opts,
1d7d2a9d
PB
2040};
2041
2042static BlockDriver bdrv_nbd_tcp = {
69447cd8
SH
2043 .format_name = "nbd",
2044 .protocol_name = "nbd+tcp",
2045 .instance_size = sizeof(BDRVNBDState),
2046 .bdrv_parse_filename = nbd_parse_filename,
2047 .bdrv_file_open = nbd_open,
e99754b4 2048 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
70c4fb26
EB
2049 .bdrv_co_preadv = nbd_client_co_preadv,
2050 .bdrv_co_pwritev = nbd_client_co_pwritev,
fa778fff 2051 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
69447cd8
SH
2052 .bdrv_close = nbd_close,
2053 .bdrv_co_flush_to_os = nbd_co_flush,
447e57c3 2054 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
fa21e6fa 2055 .bdrv_refresh_limits = nbd_refresh_limits,
69447cd8 2056 .bdrv_getlength = nbd_getlength,
86f8cdf3
VSO
2057 .bdrv_detach_aio_context = nbd_client_detach_aio_context,
2058 .bdrv_attach_aio_context = nbd_client_attach_aio_context,
f7651539
VSO
2059 .bdrv_co_drain_begin = nbd_client_co_drain_begin,
2060 .bdrv_co_drain_end = nbd_client_co_drain_end,
2019d68b 2061 .bdrv_refresh_filename = nbd_refresh_filename,
78a33ab5 2062 .bdrv_co_block_status = nbd_client_co_block_status,
8a6239c0 2063 .bdrv_dirname = nbd_dirname,
2654267c 2064 .strong_runtime_opts = nbd_strong_runtime_opts,
1d7d2a9d
PB
2065};
2066
2067static BlockDriver bdrv_nbd_unix = {
69447cd8
SH
2068 .format_name = "nbd",
2069 .protocol_name = "nbd+unix",
2070 .instance_size = sizeof(BDRVNBDState),
2071 .bdrv_parse_filename = nbd_parse_filename,
2072 .bdrv_file_open = nbd_open,
e99754b4 2073 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
70c4fb26
EB
2074 .bdrv_co_preadv = nbd_client_co_preadv,
2075 .bdrv_co_pwritev = nbd_client_co_pwritev,
fa778fff 2076 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
69447cd8
SH
2077 .bdrv_close = nbd_close,
2078 .bdrv_co_flush_to_os = nbd_co_flush,
447e57c3 2079 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
fa21e6fa 2080 .bdrv_refresh_limits = nbd_refresh_limits,
69447cd8 2081 .bdrv_getlength = nbd_getlength,
86f8cdf3
VSO
2082 .bdrv_detach_aio_context = nbd_client_detach_aio_context,
2083 .bdrv_attach_aio_context = nbd_client_attach_aio_context,
f7651539
VSO
2084 .bdrv_co_drain_begin = nbd_client_co_drain_begin,
2085 .bdrv_co_drain_end = nbd_client_co_drain_end,
2019d68b 2086 .bdrv_refresh_filename = nbd_refresh_filename,
78a33ab5 2087 .bdrv_co_block_status = nbd_client_co_block_status,
8a6239c0 2088 .bdrv_dirname = nbd_dirname,
2654267c 2089 .strong_runtime_opts = nbd_strong_runtime_opts,
75818250 2090};
5efa9d5a
AL
2091
2092static void bdrv_nbd_init(void)
2093{
2094 bdrv_register(&bdrv_nbd);
1d7d2a9d
PB
2095 bdrv_register(&bdrv_nbd_tcp);
2096 bdrv_register(&bdrv_nbd_unix);
5efa9d5a
AL
2097}
2098
2099block_init(bdrv_nbd_init);