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