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