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