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