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