xref: /qemu/nbd/server.c (revision 246f530c)
1 /*
2  *  Copyright (C) 2016-2020 Red Hat, Inc.
3  *  Copyright (C) 2005  Anthony Liguori <anthony@codemonkey.ws>
4  *
5  *  Network Block Device Server Side
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; under version 2 of the License.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include "qemu/osdep.h"
21 
22 #include "block/export.h"
23 #include "qapi/error.h"
24 #include "qemu/queue.h"
25 #include "trace.h"
26 #include "nbd-internal.h"
27 #include "qemu/units.h"
28 
29 #define NBD_META_ID_BASE_ALLOCATION 0
30 #define NBD_META_ID_ALLOCATION_DEPTH 1
31 /* Dirty bitmaps use 'NBD_META_ID_DIRTY_BITMAP + i', so keep this id last. */
32 #define NBD_META_ID_DIRTY_BITMAP 2
33 
34 /*
35  * NBD_MAX_BLOCK_STATUS_EXTENTS: 1 MiB of extents data. An empirical
36  * constant. If an increase is needed, note that the NBD protocol
37  * recommends no larger than 32 mb, so that the client won't consider
38  * the reply as a denial of service attack.
39  */
40 #define NBD_MAX_BLOCK_STATUS_EXTENTS (1 * MiB / 8)
41 
42 static int system_errno_to_nbd_errno(int err)
43 {
44     switch (err) {
45     case 0:
46         return NBD_SUCCESS;
47     case EPERM:
48     case EROFS:
49         return NBD_EPERM;
50     case EIO:
51         return NBD_EIO;
52     case ENOMEM:
53         return NBD_ENOMEM;
54 #ifdef EDQUOT
55     case EDQUOT:
56 #endif
57     case EFBIG:
58     case ENOSPC:
59         return NBD_ENOSPC;
60     case EOVERFLOW:
61         return NBD_EOVERFLOW;
62     case ENOTSUP:
63 #if ENOTSUP != EOPNOTSUPP
64     case EOPNOTSUPP:
65 #endif
66         return NBD_ENOTSUP;
67     case ESHUTDOWN:
68         return NBD_ESHUTDOWN;
69     case EINVAL:
70     default:
71         return NBD_EINVAL;
72     }
73 }
74 
75 /* Definitions for opaque data types */
76 
77 typedef struct NBDRequestData NBDRequestData;
78 
79 struct NBDRequestData {
80     QSIMPLEQ_ENTRY(NBDRequestData) entry;
81     NBDClient *client;
82     uint8_t *data;
83     bool complete;
84 };
85 
86 struct NBDExport {
87     BlockExport common;
88 
89     char *name;
90     char *description;
91     uint64_t size;
92     uint16_t nbdflags;
93     QTAILQ_HEAD(, NBDClient) clients;
94     QTAILQ_ENTRY(NBDExport) next;
95 
96     BlockBackend *eject_notifier_blk;
97     Notifier eject_notifier;
98 
99     bool allocation_depth;
100     BdrvDirtyBitmap **export_bitmaps;
101     size_t nr_export_bitmaps;
102 };
103 
104 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
105 
106 /* NBDExportMetaContexts represents a list of contexts to be exported,
107  * as selected by NBD_OPT_SET_META_CONTEXT. Also used for
108  * NBD_OPT_LIST_META_CONTEXT. */
109 typedef struct NBDExportMetaContexts {
110     NBDExport *exp;
111     size_t count; /* number of negotiated contexts */
112     bool base_allocation; /* export base:allocation context (block status) */
113     bool allocation_depth; /* export qemu:allocation-depth */
114     bool *bitmaps; /*
115                     * export qemu:dirty-bitmap:<export bitmap name>,
116                     * sized by exp->nr_export_bitmaps
117                     */
118 } NBDExportMetaContexts;
119 
120 struct NBDClient {
121     int refcount;
122     void (*close_fn)(NBDClient *client, bool negotiated);
123 
124     NBDExport *exp;
125     QCryptoTLSCreds *tlscreds;
126     char *tlsauthz;
127     QIOChannelSocket *sioc; /* The underlying data channel */
128     QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
129 
130     Coroutine *recv_coroutine;
131 
132     CoMutex send_lock;
133     Coroutine *send_coroutine;
134 
135     bool read_yielding;
136     bool quiescing;
137 
138     QTAILQ_ENTRY(NBDClient) next;
139     int nb_requests;
140     bool closing;
141 
142     uint32_t check_align; /* If non-zero, check for aligned client requests */
143 
144     bool structured_reply;
145     NBDExportMetaContexts export_meta;
146 
147     uint32_t opt; /* Current option being negotiated */
148     uint32_t optlen; /* remaining length of data in ioc for the option being
149                         negotiated now */
150 };
151 
152 static void nbd_client_receive_next_request(NBDClient *client);
153 
154 /* Basic flow for negotiation
155 
156    Server         Client
157    Negotiate
158 
159    or
160 
161    Server         Client
162    Negotiate #1
163                   Option
164    Negotiate #2
165 
166    ----
167 
168    followed by
169 
170    Server         Client
171                   Request
172    Response
173                   Request
174    Response
175                   ...
176    ...
177                   Request (type == 2)
178 
179 */
180 
181 static inline void set_be_option_rep(NBDOptionReply *rep, uint32_t option,
182                                      uint32_t type, uint32_t length)
183 {
184     stq_be_p(&rep->magic, NBD_REP_MAGIC);
185     stl_be_p(&rep->option, option);
186     stl_be_p(&rep->type, type);
187     stl_be_p(&rep->length, length);
188 }
189 
190 /* Send a reply header, including length, but no payload.
191  * Return -errno on error, 0 on success. */
192 static int nbd_negotiate_send_rep_len(NBDClient *client, uint32_t type,
193                                       uint32_t len, Error **errp)
194 {
195     NBDOptionReply rep;
196 
197     trace_nbd_negotiate_send_rep_len(client->opt, nbd_opt_lookup(client->opt),
198                                      type, nbd_rep_lookup(type), len);
199 
200     assert(len < NBD_MAX_BUFFER_SIZE);
201 
202     set_be_option_rep(&rep, client->opt, type, len);
203     return nbd_write(client->ioc, &rep, sizeof(rep), errp);
204 }
205 
206 /* Send a reply header with default 0 length.
207  * Return -errno on error, 0 on success. */
208 static int nbd_negotiate_send_rep(NBDClient *client, uint32_t type,
209                                   Error **errp)
210 {
211     return nbd_negotiate_send_rep_len(client, type, 0, errp);
212 }
213 
214 /* Send an error reply.
215  * Return -errno on error, 0 on success. */
216 static int GCC_FMT_ATTR(4, 0)
217 nbd_negotiate_send_rep_verr(NBDClient *client, uint32_t type,
218                             Error **errp, const char *fmt, va_list va)
219 {
220     ERRP_GUARD();
221     g_autofree char *msg = NULL;
222     int ret;
223     size_t len;
224 
225     msg = g_strdup_vprintf(fmt, va);
226     len = strlen(msg);
227     assert(len < NBD_MAX_STRING_SIZE);
228     trace_nbd_negotiate_send_rep_err(msg);
229     ret = nbd_negotiate_send_rep_len(client, type, len, errp);
230     if (ret < 0) {
231         return ret;
232     }
233     if (nbd_write(client->ioc, msg, len, errp) < 0) {
234         error_prepend(errp, "write failed (error message): ");
235         return -EIO;
236     }
237 
238     return 0;
239 }
240 
241 /*
242  * Return a malloc'd copy of @name suitable for use in an error reply.
243  */
244 static char *
245 nbd_sanitize_name(const char *name)
246 {
247     if (strnlen(name, 80) < 80) {
248         return g_strdup(name);
249     }
250     /* XXX Should we also try to sanitize any control characters? */
251     return g_strdup_printf("%.80s...", name);
252 }
253 
254 /* Send an error reply.
255  * Return -errno on error, 0 on success. */
256 static int GCC_FMT_ATTR(4, 5)
257 nbd_negotiate_send_rep_err(NBDClient *client, uint32_t type,
258                            Error **errp, const char *fmt, ...)
259 {
260     va_list va;
261     int ret;
262 
263     va_start(va, fmt);
264     ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
265     va_end(va);
266     return ret;
267 }
268 
269 /* Drop remainder of the current option, and send a reply with the
270  * given error type and message. Return -errno on read or write
271  * failure; or 0 if connection is still live. */
272 static int GCC_FMT_ATTR(4, 0)
273 nbd_opt_vdrop(NBDClient *client, uint32_t type, Error **errp,
274               const char *fmt, va_list va)
275 {
276     int ret = nbd_drop(client->ioc, client->optlen, errp);
277 
278     client->optlen = 0;
279     if (!ret) {
280         ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
281     }
282     return ret;
283 }
284 
285 static int GCC_FMT_ATTR(4, 5)
286 nbd_opt_drop(NBDClient *client, uint32_t type, Error **errp,
287              const char *fmt, ...)
288 {
289     int ret;
290     va_list va;
291 
292     va_start(va, fmt);
293     ret = nbd_opt_vdrop(client, type, errp, fmt, va);
294     va_end(va);
295 
296     return ret;
297 }
298 
299 static int GCC_FMT_ATTR(3, 4)
300 nbd_opt_invalid(NBDClient *client, Error **errp, const char *fmt, ...)
301 {
302     int ret;
303     va_list va;
304 
305     va_start(va, fmt);
306     ret = nbd_opt_vdrop(client, NBD_REP_ERR_INVALID, errp, fmt, va);
307     va_end(va);
308 
309     return ret;
310 }
311 
312 /* Read size bytes from the unparsed payload of the current option.
313  * If @check_nul, require that no NUL bytes appear in buffer.
314  * Return -errno on I/O error, 0 if option was completely handled by
315  * sending a reply about inconsistent lengths, or 1 on success. */
316 static int nbd_opt_read(NBDClient *client, void *buffer, size_t size,
317                         bool check_nul, Error **errp)
318 {
319     if (size > client->optlen) {
320         return nbd_opt_invalid(client, errp,
321                                "Inconsistent lengths in option %s",
322                                nbd_opt_lookup(client->opt));
323     }
324     client->optlen -= size;
325     if (qio_channel_read_all(client->ioc, buffer, size, errp) < 0) {
326         return -EIO;
327     }
328 
329     if (check_nul && strnlen(buffer, size) != size) {
330         return nbd_opt_invalid(client, errp,
331                                "Unexpected embedded NUL in option %s",
332                                nbd_opt_lookup(client->opt));
333     }
334     return 1;
335 }
336 
337 /* Drop size bytes from the unparsed payload of the current option.
338  * Return -errno on I/O error, 0 if option was completely handled by
339  * sending a reply about inconsistent lengths, or 1 on success. */
340 static int nbd_opt_skip(NBDClient *client, size_t size, Error **errp)
341 {
342     if (size > client->optlen) {
343         return nbd_opt_invalid(client, errp,
344                                "Inconsistent lengths in option %s",
345                                nbd_opt_lookup(client->opt));
346     }
347     client->optlen -= size;
348     return nbd_drop(client->ioc, size, errp) < 0 ? -EIO : 1;
349 }
350 
351 /* nbd_opt_read_name
352  *
353  * Read a string with the format:
354  *   uint32_t len     (<= NBD_MAX_STRING_SIZE)
355  *   len bytes string (not 0-terminated)
356  *
357  * On success, @name will be allocated.
358  * If @length is non-null, it will be set to the actual string length.
359  *
360  * Return -errno on I/O error, 0 if option was completely handled by
361  * sending a reply about inconsistent lengths, or 1 on success.
362  */
363 static int nbd_opt_read_name(NBDClient *client, char **name, uint32_t *length,
364                              Error **errp)
365 {
366     int ret;
367     uint32_t len;
368     g_autofree char *local_name = NULL;
369 
370     *name = NULL;
371     ret = nbd_opt_read(client, &len, sizeof(len), false, errp);
372     if (ret <= 0) {
373         return ret;
374     }
375     len = cpu_to_be32(len);
376 
377     if (len > NBD_MAX_STRING_SIZE) {
378         return nbd_opt_invalid(client, errp,
379                                "Invalid name length: %" PRIu32, len);
380     }
381 
382     local_name = g_malloc(len + 1);
383     ret = nbd_opt_read(client, local_name, len, true, errp);
384     if (ret <= 0) {
385         return ret;
386     }
387     local_name[len] = '\0';
388 
389     if (length) {
390         *length = len;
391     }
392     *name = g_steal_pointer(&local_name);
393 
394     return 1;
395 }
396 
397 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
398  * Return -errno on error, 0 on success. */
399 static int nbd_negotiate_send_rep_list(NBDClient *client, NBDExport *exp,
400                                        Error **errp)
401 {
402     ERRP_GUARD();
403     size_t name_len, desc_len;
404     uint32_t len;
405     const char *name = exp->name ? exp->name : "";
406     const char *desc = exp->description ? exp->description : "";
407     QIOChannel *ioc = client->ioc;
408     int ret;
409 
410     trace_nbd_negotiate_send_rep_list(name, desc);
411     name_len = strlen(name);
412     desc_len = strlen(desc);
413     assert(name_len <= NBD_MAX_STRING_SIZE && desc_len <= NBD_MAX_STRING_SIZE);
414     len = name_len + desc_len + sizeof(len);
415     ret = nbd_negotiate_send_rep_len(client, NBD_REP_SERVER, len, errp);
416     if (ret < 0) {
417         return ret;
418     }
419 
420     len = cpu_to_be32(name_len);
421     if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
422         error_prepend(errp, "write failed (name length): ");
423         return -EINVAL;
424     }
425 
426     if (nbd_write(ioc, name, name_len, errp) < 0) {
427         error_prepend(errp, "write failed (name buffer): ");
428         return -EINVAL;
429     }
430 
431     if (nbd_write(ioc, desc, desc_len, errp) < 0) {
432         error_prepend(errp, "write failed (description buffer): ");
433         return -EINVAL;
434     }
435 
436     return 0;
437 }
438 
439 /* Process the NBD_OPT_LIST command, with a potential series of replies.
440  * Return -errno on error, 0 on success. */
441 static int nbd_negotiate_handle_list(NBDClient *client, Error **errp)
442 {
443     NBDExport *exp;
444     assert(client->opt == NBD_OPT_LIST);
445 
446     /* For each export, send a NBD_REP_SERVER reply. */
447     QTAILQ_FOREACH(exp, &exports, next) {
448         if (nbd_negotiate_send_rep_list(client, exp, errp)) {
449             return -EINVAL;
450         }
451     }
452     /* Finish with a NBD_REP_ACK. */
453     return nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
454 }
455 
456 static void nbd_check_meta_export(NBDClient *client)
457 {
458     if (client->exp != client->export_meta.exp) {
459         client->export_meta.count = 0;
460     }
461 }
462 
463 /* Send a reply to NBD_OPT_EXPORT_NAME.
464  * Return -errno on error, 0 on success. */
465 static int nbd_negotiate_handle_export_name(NBDClient *client, bool no_zeroes,
466                                             Error **errp)
467 {
468     ERRP_GUARD();
469     g_autofree char *name = NULL;
470     char buf[NBD_REPLY_EXPORT_NAME_SIZE] = "";
471     size_t len;
472     int ret;
473     uint16_t myflags;
474 
475     /* Client sends:
476         [20 ..  xx]   export name (length bytes)
477        Server replies:
478         [ 0 ..   7]   size
479         [ 8 ..   9]   export flags
480         [10 .. 133]   reserved     (0) [unless no_zeroes]
481      */
482     trace_nbd_negotiate_handle_export_name();
483     if (client->optlen > NBD_MAX_STRING_SIZE) {
484         error_setg(errp, "Bad length received");
485         return -EINVAL;
486     }
487     name = g_malloc(client->optlen + 1);
488     if (nbd_read(client->ioc, name, client->optlen, "export name", errp) < 0) {
489         return -EIO;
490     }
491     name[client->optlen] = '\0';
492     client->optlen = 0;
493 
494     trace_nbd_negotiate_handle_export_name_request(name);
495 
496     client->exp = nbd_export_find(name);
497     if (!client->exp) {
498         error_setg(errp, "export not found");
499         return -EINVAL;
500     }
501 
502     myflags = client->exp->nbdflags;
503     if (client->structured_reply) {
504         myflags |= NBD_FLAG_SEND_DF;
505     }
506     trace_nbd_negotiate_new_style_size_flags(client->exp->size, myflags);
507     stq_be_p(buf, client->exp->size);
508     stw_be_p(buf + 8, myflags);
509     len = no_zeroes ? 10 : sizeof(buf);
510     ret = nbd_write(client->ioc, buf, len, errp);
511     if (ret < 0) {
512         error_prepend(errp, "write failed: ");
513         return ret;
514     }
515 
516     QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
517     blk_exp_ref(&client->exp->common);
518     nbd_check_meta_export(client);
519 
520     return 0;
521 }
522 
523 /* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
524  * The buffer does NOT include the info type prefix.
525  * Return -errno on error, 0 if ready to send more. */
526 static int nbd_negotiate_send_info(NBDClient *client,
527                                    uint16_t info, uint32_t length, void *buf,
528                                    Error **errp)
529 {
530     int rc;
531 
532     trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length);
533     rc = nbd_negotiate_send_rep_len(client, NBD_REP_INFO,
534                                     sizeof(info) + length, errp);
535     if (rc < 0) {
536         return rc;
537     }
538     info = cpu_to_be16(info);
539     if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
540         return -EIO;
541     }
542     if (nbd_write(client->ioc, buf, length, errp) < 0) {
543         return -EIO;
544     }
545     return 0;
546 }
547 
548 /* nbd_reject_length: Handle any unexpected payload.
549  * @fatal requests that we quit talking to the client, even if we are able
550  * to successfully send an error reply.
551  * Return:
552  * -errno  transmission error occurred or @fatal was requested, errp is set
553  * 0       error message successfully sent to client, errp is not set
554  */
555 static int nbd_reject_length(NBDClient *client, bool fatal, Error **errp)
556 {
557     int ret;
558 
559     assert(client->optlen);
560     ret = nbd_opt_invalid(client, errp, "option '%s' has unexpected length",
561                           nbd_opt_lookup(client->opt));
562     if (fatal && !ret) {
563         error_setg(errp, "option '%s' has unexpected length",
564                    nbd_opt_lookup(client->opt));
565         return -EINVAL;
566     }
567     return ret;
568 }
569 
570 /* Handle NBD_OPT_INFO and NBD_OPT_GO.
571  * Return -errno on error, 0 if ready for next option, and 1 to move
572  * into transmission phase.  */
573 static int nbd_negotiate_handle_info(NBDClient *client, Error **errp)
574 {
575     int rc;
576     g_autofree char *name = NULL;
577     NBDExport *exp;
578     uint16_t requests;
579     uint16_t request;
580     uint32_t namelen = 0;
581     bool sendname = false;
582     bool blocksize = false;
583     uint32_t sizes[3];
584     char buf[sizeof(uint64_t) + sizeof(uint16_t)];
585     uint32_t check_align = 0;
586     uint16_t myflags;
587 
588     /* Client sends:
589         4 bytes: L, name length (can be 0)
590         L bytes: export name
591         2 bytes: N, number of requests (can be 0)
592         N * 2 bytes: N requests
593     */
594     rc = nbd_opt_read_name(client, &name, &namelen, errp);
595     if (rc <= 0) {
596         return rc;
597     }
598     trace_nbd_negotiate_handle_export_name_request(name);
599 
600     rc = nbd_opt_read(client, &requests, sizeof(requests), false, errp);
601     if (rc <= 0) {
602         return rc;
603     }
604     requests = be16_to_cpu(requests);
605     trace_nbd_negotiate_handle_info_requests(requests);
606     while (requests--) {
607         rc = nbd_opt_read(client, &request, sizeof(request), false, errp);
608         if (rc <= 0) {
609             return rc;
610         }
611         request = be16_to_cpu(request);
612         trace_nbd_negotiate_handle_info_request(request,
613                                                 nbd_info_lookup(request));
614         /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
615          * everything else is either a request we don't know or
616          * something we send regardless of request */
617         switch (request) {
618         case NBD_INFO_NAME:
619             sendname = true;
620             break;
621         case NBD_INFO_BLOCK_SIZE:
622             blocksize = true;
623             break;
624         }
625     }
626     if (client->optlen) {
627         return nbd_reject_length(client, false, errp);
628     }
629 
630     exp = nbd_export_find(name);
631     if (!exp) {
632         g_autofree char *sane_name = nbd_sanitize_name(name);
633 
634         return nbd_negotiate_send_rep_err(client, NBD_REP_ERR_UNKNOWN,
635                                           errp, "export '%s' not present",
636                                           sane_name);
637     }
638 
639     /* Don't bother sending NBD_INFO_NAME unless client requested it */
640     if (sendname) {
641         rc = nbd_negotiate_send_info(client, NBD_INFO_NAME, namelen, name,
642                                      errp);
643         if (rc < 0) {
644             return rc;
645         }
646     }
647 
648     /* Send NBD_INFO_DESCRIPTION only if available, regardless of
649      * client request */
650     if (exp->description) {
651         size_t len = strlen(exp->description);
652 
653         assert(len <= NBD_MAX_STRING_SIZE);
654         rc = nbd_negotiate_send_info(client, NBD_INFO_DESCRIPTION,
655                                      len, exp->description, errp);
656         if (rc < 0) {
657             return rc;
658         }
659     }
660 
661     /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
662      * according to whether the client requested it, and according to
663      * whether this is OPT_INFO or OPT_GO. */
664     /* minimum - 1 for back-compat, or actual if client will obey it. */
665     if (client->opt == NBD_OPT_INFO || blocksize) {
666         check_align = sizes[0] = blk_get_request_alignment(exp->common.blk);
667     } else {
668         sizes[0] = 1;
669     }
670     assert(sizes[0] <= NBD_MAX_BUFFER_SIZE);
671     /* preferred - Hard-code to 4096 for now.
672      * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
673     sizes[1] = MAX(4096, sizes[0]);
674     /* maximum - At most 32M, but smaller as appropriate. */
675     sizes[2] = MIN(blk_get_max_transfer(exp->common.blk), NBD_MAX_BUFFER_SIZE);
676     trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);
677     sizes[0] = cpu_to_be32(sizes[0]);
678     sizes[1] = cpu_to_be32(sizes[1]);
679     sizes[2] = cpu_to_be32(sizes[2]);
680     rc = nbd_negotiate_send_info(client, NBD_INFO_BLOCK_SIZE,
681                                  sizeof(sizes), sizes, errp);
682     if (rc < 0) {
683         return rc;
684     }
685 
686     /* Send NBD_INFO_EXPORT always */
687     myflags = exp->nbdflags;
688     if (client->structured_reply) {
689         myflags |= NBD_FLAG_SEND_DF;
690     }
691     trace_nbd_negotiate_new_style_size_flags(exp->size, myflags);
692     stq_be_p(buf, exp->size);
693     stw_be_p(buf + 8, myflags);
694     rc = nbd_negotiate_send_info(client, NBD_INFO_EXPORT,
695                                  sizeof(buf), buf, errp);
696     if (rc < 0) {
697         return rc;
698     }
699 
700     /*
701      * If the client is just asking for NBD_OPT_INFO, but forgot to
702      * request block sizes in a situation that would impact
703      * performance, then return an error. But for NBD_OPT_GO, we
704      * tolerate all clients, regardless of alignments.
705      */
706     if (client->opt == NBD_OPT_INFO && !blocksize &&
707         blk_get_request_alignment(exp->common.blk) > 1) {
708         return nbd_negotiate_send_rep_err(client,
709                                           NBD_REP_ERR_BLOCK_SIZE_REQD,
710                                           errp,
711                                           "request NBD_INFO_BLOCK_SIZE to "
712                                           "use this export");
713     }
714 
715     /* Final reply */
716     rc = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
717     if (rc < 0) {
718         return rc;
719     }
720 
721     if (client->opt == NBD_OPT_GO) {
722         client->exp = exp;
723         client->check_align = check_align;
724         QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
725         blk_exp_ref(&client->exp->common);
726         nbd_check_meta_export(client);
727         rc = 1;
728     }
729     return rc;
730 }
731 
732 
733 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
734  * new channel for all further (now-encrypted) communication. */
735 static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
736                                                  Error **errp)
737 {
738     QIOChannel *ioc;
739     QIOChannelTLS *tioc;
740     struct NBDTLSHandshakeData data = { 0 };
741 
742     assert(client->opt == NBD_OPT_STARTTLS);
743 
744     trace_nbd_negotiate_handle_starttls();
745     ioc = client->ioc;
746 
747     if (nbd_negotiate_send_rep(client, NBD_REP_ACK, errp) < 0) {
748         return NULL;
749     }
750 
751     tioc = qio_channel_tls_new_server(ioc,
752                                       client->tlscreds,
753                                       client->tlsauthz,
754                                       errp);
755     if (!tioc) {
756         return NULL;
757     }
758 
759     qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
760     trace_nbd_negotiate_handle_starttls_handshake();
761     data.loop = g_main_loop_new(g_main_context_default(), FALSE);
762     qio_channel_tls_handshake(tioc,
763                               nbd_tls_handshake,
764                               &data,
765                               NULL,
766                               NULL);
767 
768     if (!data.complete) {
769         g_main_loop_run(data.loop);
770     }
771     g_main_loop_unref(data.loop);
772     if (data.error) {
773         object_unref(OBJECT(tioc));
774         error_propagate(errp, data.error);
775         return NULL;
776     }
777 
778     return QIO_CHANNEL(tioc);
779 }
780 
781 /* nbd_negotiate_send_meta_context
782  *
783  * Send one chunk of reply to NBD_OPT_{LIST,SET}_META_CONTEXT
784  *
785  * For NBD_OPT_LIST_META_CONTEXT @context_id is ignored, 0 is used instead.
786  */
787 static int nbd_negotiate_send_meta_context(NBDClient *client,
788                                            const char *context,
789                                            uint32_t context_id,
790                                            Error **errp)
791 {
792     NBDOptionReplyMetaContext opt;
793     struct iovec iov[] = {
794         {.iov_base = &opt, .iov_len = sizeof(opt)},
795         {.iov_base = (void *)context, .iov_len = strlen(context)}
796     };
797 
798     assert(iov[1].iov_len <= NBD_MAX_STRING_SIZE);
799     if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
800         context_id = 0;
801     }
802 
803     trace_nbd_negotiate_meta_query_reply(context, context_id);
804     set_be_option_rep(&opt.h, client->opt, NBD_REP_META_CONTEXT,
805                       sizeof(opt) - sizeof(opt.h) + iov[1].iov_len);
806     stl_be_p(&opt.context_id, context_id);
807 
808     return qio_channel_writev_all(client->ioc, iov, 2, errp) < 0 ? -EIO : 0;
809 }
810 
811 /*
812  * Return true if @query matches @pattern, or if @query is empty when
813  * the @client is performing _LIST_.
814  */
815 static bool nbd_meta_empty_or_pattern(NBDClient *client, const char *pattern,
816                                       const char *query)
817 {
818     if (!*query) {
819         trace_nbd_negotiate_meta_query_parse("empty");
820         return client->opt == NBD_OPT_LIST_META_CONTEXT;
821     }
822     if (strcmp(query, pattern) == 0) {
823         trace_nbd_negotiate_meta_query_parse(pattern);
824         return true;
825     }
826     trace_nbd_negotiate_meta_query_skip("pattern not matched");
827     return false;
828 }
829 
830 /*
831  * Return true and adjust @str in place if it begins with @prefix.
832  */
833 static bool nbd_strshift(const char **str, const char *prefix)
834 {
835     size_t len = strlen(prefix);
836 
837     if (strncmp(*str, prefix, len) == 0) {
838         *str += len;
839         return true;
840     }
841     return false;
842 }
843 
844 /* nbd_meta_base_query
845  *
846  * Handle queries to 'base' namespace. For now, only the base:allocation
847  * context is available.  Return true if @query has been handled.
848  */
849 static bool nbd_meta_base_query(NBDClient *client, NBDExportMetaContexts *meta,
850                                 const char *query)
851 {
852     if (!nbd_strshift(&query, "base:")) {
853         return false;
854     }
855     trace_nbd_negotiate_meta_query_parse("base:");
856 
857     if (nbd_meta_empty_or_pattern(client, "allocation", query)) {
858         meta->base_allocation = true;
859     }
860     return true;
861 }
862 
863 /* nbd_meta_qemu_query
864  *
865  * Handle queries to 'qemu' namespace. For now, only the qemu:dirty-bitmap:
866  * and qemu:allocation-depth contexts are available.  Return true if @query
867  * has been handled.
868  */
869 static bool nbd_meta_qemu_query(NBDClient *client, NBDExportMetaContexts *meta,
870                                 const char *query)
871 {
872     size_t i;
873 
874     if (!nbd_strshift(&query, "qemu:")) {
875         return false;
876     }
877     trace_nbd_negotiate_meta_query_parse("qemu:");
878 
879     if (!*query) {
880         if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
881             meta->allocation_depth = meta->exp->allocation_depth;
882             memset(meta->bitmaps, 1, meta->exp->nr_export_bitmaps);
883         }
884         trace_nbd_negotiate_meta_query_parse("empty");
885         return true;
886     }
887 
888     if (strcmp(query, "allocation-depth") == 0) {
889         trace_nbd_negotiate_meta_query_parse("allocation-depth");
890         meta->allocation_depth = meta->exp->allocation_depth;
891         return true;
892     }
893 
894     if (nbd_strshift(&query, "dirty-bitmap:")) {
895         trace_nbd_negotiate_meta_query_parse("dirty-bitmap:");
896         if (!*query) {
897             if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
898                 memset(meta->bitmaps, 1, meta->exp->nr_export_bitmaps);
899             }
900             trace_nbd_negotiate_meta_query_parse("empty");
901             return true;
902         }
903 
904         for (i = 0; i < meta->exp->nr_export_bitmaps; i++) {
905             const char *bm_name;
906 
907             bm_name = bdrv_dirty_bitmap_name(meta->exp->export_bitmaps[i]);
908             if (strcmp(bm_name, query) == 0) {
909                 meta->bitmaps[i] = true;
910                 trace_nbd_negotiate_meta_query_parse(query);
911                 return true;
912             }
913         }
914         trace_nbd_negotiate_meta_query_skip("no dirty-bitmap match");
915         return true;
916     }
917 
918     trace_nbd_negotiate_meta_query_skip("unknown qemu context");
919     return true;
920 }
921 
922 /* nbd_negotiate_meta_query
923  *
924  * Parse namespace name and call corresponding function to parse body of the
925  * query.
926  *
927  * The only supported namespaces are 'base' and 'qemu'.
928  *
929  * Return -errno on I/O error, 0 if option was completely handled by
930  * sending a reply about inconsistent lengths, or 1 on success. */
931 static int nbd_negotiate_meta_query(NBDClient *client,
932                                     NBDExportMetaContexts *meta, Error **errp)
933 {
934     int ret;
935     g_autofree char *query = NULL;
936     uint32_t len;
937 
938     ret = nbd_opt_read(client, &len, sizeof(len), false, errp);
939     if (ret <= 0) {
940         return ret;
941     }
942     len = cpu_to_be32(len);
943 
944     if (len > NBD_MAX_STRING_SIZE) {
945         trace_nbd_negotiate_meta_query_skip("length too long");
946         return nbd_opt_skip(client, len, errp);
947     }
948 
949     query = g_malloc(len + 1);
950     ret = nbd_opt_read(client, query, len, true, errp);
951     if (ret <= 0) {
952         return ret;
953     }
954     query[len] = '\0';
955 
956     if (nbd_meta_base_query(client, meta, query)) {
957         return 1;
958     }
959     if (nbd_meta_qemu_query(client, meta, query)) {
960         return 1;
961     }
962 
963     trace_nbd_negotiate_meta_query_skip("unknown namespace");
964     return 1;
965 }
966 
967 /* nbd_negotiate_meta_queries
968  * Handle NBD_OPT_LIST_META_CONTEXT and NBD_OPT_SET_META_CONTEXT
969  *
970  * Return -errno on I/O error, or 0 if option was completely handled. */
971 static int nbd_negotiate_meta_queries(NBDClient *client,
972                                       NBDExportMetaContexts *meta, Error **errp)
973 {
974     int ret;
975     g_autofree char *export_name = NULL;
976     g_autofree bool *bitmaps = NULL;
977     NBDExportMetaContexts local_meta = {0};
978     uint32_t nb_queries;
979     size_t i;
980     size_t count = 0;
981 
982     if (!client->structured_reply) {
983         return nbd_opt_invalid(client, errp,
984                                "request option '%s' when structured reply "
985                                "is not negotiated",
986                                nbd_opt_lookup(client->opt));
987     }
988 
989     if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
990         /* Only change the caller's meta on SET. */
991         meta = &local_meta;
992     }
993 
994     g_free(meta->bitmaps);
995     memset(meta, 0, sizeof(*meta));
996 
997     ret = nbd_opt_read_name(client, &export_name, NULL, errp);
998     if (ret <= 0) {
999         return ret;
1000     }
1001 
1002     meta->exp = nbd_export_find(export_name);
1003     if (meta->exp == NULL) {
1004         g_autofree char *sane_name = nbd_sanitize_name(export_name);
1005 
1006         return nbd_opt_drop(client, NBD_REP_ERR_UNKNOWN, errp,
1007                             "export '%s' not present", sane_name);
1008     }
1009     meta->bitmaps = g_new0(bool, meta->exp->nr_export_bitmaps);
1010     if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
1011         bitmaps = meta->bitmaps;
1012     }
1013 
1014     ret = nbd_opt_read(client, &nb_queries, sizeof(nb_queries), false, errp);
1015     if (ret <= 0) {
1016         return ret;
1017     }
1018     nb_queries = cpu_to_be32(nb_queries);
1019     trace_nbd_negotiate_meta_context(nbd_opt_lookup(client->opt),
1020                                      export_name, nb_queries);
1021 
1022     if (client->opt == NBD_OPT_LIST_META_CONTEXT && !nb_queries) {
1023         /* enable all known contexts */
1024         meta->base_allocation = true;
1025         meta->allocation_depth = meta->exp->allocation_depth;
1026         memset(meta->bitmaps, 1, meta->exp->nr_export_bitmaps);
1027     } else {
1028         for (i = 0; i < nb_queries; ++i) {
1029             ret = nbd_negotiate_meta_query(client, meta, errp);
1030             if (ret <= 0) {
1031                 return ret;
1032             }
1033         }
1034     }
1035 
1036     if (meta->base_allocation) {
1037         ret = nbd_negotiate_send_meta_context(client, "base:allocation",
1038                                               NBD_META_ID_BASE_ALLOCATION,
1039                                               errp);
1040         if (ret < 0) {
1041             return ret;
1042         }
1043         count++;
1044     }
1045 
1046     if (meta->allocation_depth) {
1047         ret = nbd_negotiate_send_meta_context(client, "qemu:allocation-depth",
1048                                               NBD_META_ID_ALLOCATION_DEPTH,
1049                                               errp);
1050         if (ret < 0) {
1051             return ret;
1052         }
1053         count++;
1054     }
1055 
1056     for (i = 0; i < meta->exp->nr_export_bitmaps; i++) {
1057         const char *bm_name;
1058         g_autofree char *context = NULL;
1059 
1060         if (!meta->bitmaps[i]) {
1061             continue;
1062         }
1063 
1064         bm_name = bdrv_dirty_bitmap_name(meta->exp->export_bitmaps[i]);
1065         context = g_strdup_printf("qemu:dirty-bitmap:%s", bm_name);
1066 
1067         ret = nbd_negotiate_send_meta_context(client, context,
1068                                               NBD_META_ID_DIRTY_BITMAP + i,
1069                                               errp);
1070         if (ret < 0) {
1071             return ret;
1072         }
1073         count++;
1074     }
1075 
1076     ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1077     if (ret == 0) {
1078         meta->count = count;
1079     }
1080 
1081     return ret;
1082 }
1083 
1084 /* nbd_negotiate_options
1085  * Process all NBD_OPT_* client option commands, during fixed newstyle
1086  * negotiation.
1087  * Return:
1088  * -errno  on error, errp is set
1089  * 0       on successful negotiation, errp is not set
1090  * 1       if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1091  *         errp is not set
1092  */
1093 static int nbd_negotiate_options(NBDClient *client, Error **errp)
1094 {
1095     uint32_t flags;
1096     bool fixedNewstyle = false;
1097     bool no_zeroes = false;
1098 
1099     /* Client sends:
1100         [ 0 ..   3]   client flags
1101 
1102        Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
1103         [ 0 ..   7]   NBD_OPTS_MAGIC
1104         [ 8 ..  11]   NBD option
1105         [12 ..  15]   Data length
1106         ...           Rest of request
1107 
1108         [ 0 ..   7]   NBD_OPTS_MAGIC
1109         [ 8 ..  11]   Second NBD option
1110         [12 ..  15]   Data length
1111         ...           Rest of request
1112     */
1113 
1114     if (nbd_read32(client->ioc, &flags, "flags", errp) < 0) {
1115         return -EIO;
1116     }
1117     trace_nbd_negotiate_options_flags(flags);
1118     if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
1119         fixedNewstyle = true;
1120         flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
1121     }
1122     if (flags & NBD_FLAG_C_NO_ZEROES) {
1123         no_zeroes = true;
1124         flags &= ~NBD_FLAG_C_NO_ZEROES;
1125     }
1126     if (flags != 0) {
1127         error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
1128         return -EINVAL;
1129     }
1130 
1131     while (1) {
1132         int ret;
1133         uint32_t option, length;
1134         uint64_t magic;
1135 
1136         if (nbd_read64(client->ioc, &magic, "opts magic", errp) < 0) {
1137             return -EINVAL;
1138         }
1139         trace_nbd_negotiate_options_check_magic(magic);
1140         if (magic != NBD_OPTS_MAGIC) {
1141             error_setg(errp, "Bad magic received");
1142             return -EINVAL;
1143         }
1144 
1145         if (nbd_read32(client->ioc, &option, "option", errp) < 0) {
1146             return -EINVAL;
1147         }
1148         client->opt = option;
1149 
1150         if (nbd_read32(client->ioc, &length, "option length", errp) < 0) {
1151             return -EINVAL;
1152         }
1153         assert(!client->optlen);
1154         client->optlen = length;
1155 
1156         if (length > NBD_MAX_BUFFER_SIZE) {
1157             error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1158                        length, NBD_MAX_BUFFER_SIZE);
1159             return -EINVAL;
1160         }
1161 
1162         trace_nbd_negotiate_options_check_option(option,
1163                                                  nbd_opt_lookup(option));
1164         if (client->tlscreds &&
1165             client->ioc == (QIOChannel *)client->sioc) {
1166             QIOChannel *tioc;
1167             if (!fixedNewstyle) {
1168                 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
1169                 return -EINVAL;
1170             }
1171             switch (option) {
1172             case NBD_OPT_STARTTLS:
1173                 if (length) {
1174                     /* Unconditionally drop the connection if the client
1175                      * can't start a TLS negotiation correctly */
1176                     return nbd_reject_length(client, true, errp);
1177                 }
1178                 tioc = nbd_negotiate_handle_starttls(client, errp);
1179                 if (!tioc) {
1180                     return -EIO;
1181                 }
1182                 ret = 0;
1183                 object_unref(OBJECT(client->ioc));
1184                 client->ioc = QIO_CHANNEL(tioc);
1185                 break;
1186 
1187             case NBD_OPT_EXPORT_NAME:
1188                 /* No way to return an error to client, so drop connection */
1189                 error_setg(errp, "Option 0x%x not permitted before TLS",
1190                            option);
1191                 return -EINVAL;
1192 
1193             default:
1194                 /* Let the client keep trying, unless they asked to
1195                  * quit. Always try to give an error back to the
1196                  * client; but when replying to OPT_ABORT, be aware
1197                  * that the client may hang up before receiving the
1198                  * error, in which case we are fine ignoring the
1199                  * resulting EPIPE. */
1200                 ret = nbd_opt_drop(client, NBD_REP_ERR_TLS_REQD,
1201                                    option == NBD_OPT_ABORT ? NULL : errp,
1202                                    "Option 0x%" PRIx32
1203                                    " not permitted before TLS", option);
1204                 if (option == NBD_OPT_ABORT) {
1205                     return 1;
1206                 }
1207                 break;
1208             }
1209         } else if (fixedNewstyle) {
1210             switch (option) {
1211             case NBD_OPT_LIST:
1212                 if (length) {
1213                     ret = nbd_reject_length(client, false, errp);
1214                 } else {
1215                     ret = nbd_negotiate_handle_list(client, errp);
1216                 }
1217                 break;
1218 
1219             case NBD_OPT_ABORT:
1220                 /* NBD spec says we must try to reply before
1221                  * disconnecting, but that we must also tolerate
1222                  * guests that don't wait for our reply. */
1223                 nbd_negotiate_send_rep(client, NBD_REP_ACK, NULL);
1224                 return 1;
1225 
1226             case NBD_OPT_EXPORT_NAME:
1227                 return nbd_negotiate_handle_export_name(client, no_zeroes,
1228                                                         errp);
1229 
1230             case NBD_OPT_INFO:
1231             case NBD_OPT_GO:
1232                 ret = nbd_negotiate_handle_info(client, errp);
1233                 if (ret == 1) {
1234                     assert(option == NBD_OPT_GO);
1235                     return 0;
1236                 }
1237                 break;
1238 
1239             case NBD_OPT_STARTTLS:
1240                 if (length) {
1241                     ret = nbd_reject_length(client, false, errp);
1242                 } else if (client->tlscreds) {
1243                     ret = nbd_negotiate_send_rep_err(client,
1244                                                      NBD_REP_ERR_INVALID, errp,
1245                                                      "TLS already enabled");
1246                 } else {
1247                     ret = nbd_negotiate_send_rep_err(client,
1248                                                      NBD_REP_ERR_POLICY, errp,
1249                                                      "TLS not configured");
1250                 }
1251                 break;
1252 
1253             case NBD_OPT_STRUCTURED_REPLY:
1254                 if (length) {
1255                     ret = nbd_reject_length(client, false, errp);
1256                 } else if (client->structured_reply) {
1257                     ret = nbd_negotiate_send_rep_err(
1258                         client, NBD_REP_ERR_INVALID, errp,
1259                         "structured reply already negotiated");
1260                 } else {
1261                     ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1262                     client->structured_reply = true;
1263                 }
1264                 break;
1265 
1266             case NBD_OPT_LIST_META_CONTEXT:
1267             case NBD_OPT_SET_META_CONTEXT:
1268                 ret = nbd_negotiate_meta_queries(client, &client->export_meta,
1269                                                  errp);
1270                 break;
1271 
1272             default:
1273                 ret = nbd_opt_drop(client, NBD_REP_ERR_UNSUP, errp,
1274                                    "Unsupported option %" PRIu32 " (%s)",
1275                                    option, nbd_opt_lookup(option));
1276                 break;
1277             }
1278         } else {
1279             /*
1280              * If broken new-style we should drop the connection
1281              * for anything except NBD_OPT_EXPORT_NAME
1282              */
1283             switch (option) {
1284             case NBD_OPT_EXPORT_NAME:
1285                 return nbd_negotiate_handle_export_name(client, no_zeroes,
1286                                                         errp);
1287 
1288             default:
1289                 error_setg(errp, "Unsupported option %" PRIu32 " (%s)",
1290                            option, nbd_opt_lookup(option));
1291                 return -EINVAL;
1292             }
1293         }
1294         if (ret < 0) {
1295             return ret;
1296         }
1297     }
1298 }
1299 
1300 /* nbd_negotiate
1301  * Return:
1302  * -errno  on error, errp is set
1303  * 0       on successful negotiation, errp is not set
1304  * 1       if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1305  *         errp is not set
1306  */
1307 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
1308 {
1309     ERRP_GUARD();
1310     char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
1311     int ret;
1312 
1313     /* Old style negotiation header, no room for options
1314         [ 0 ..   7]   passwd       ("NBDMAGIC")
1315         [ 8 ..  15]   magic        (NBD_CLIENT_MAGIC)
1316         [16 ..  23]   size
1317         [24 ..  27]   export flags (zero-extended)
1318         [28 .. 151]   reserved     (0)
1319 
1320        New style negotiation header, client can send options
1321         [ 0 ..   7]   passwd       ("NBDMAGIC")
1322         [ 8 ..  15]   magic        (NBD_OPTS_MAGIC)
1323         [16 ..  17]   server flags (0)
1324         ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
1325      */
1326 
1327     qio_channel_set_blocking(client->ioc, false, NULL);
1328 
1329     trace_nbd_negotiate_begin();
1330     memcpy(buf, "NBDMAGIC", 8);
1331 
1332     stq_be_p(buf + 8, NBD_OPTS_MAGIC);
1333     stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
1334 
1335     if (nbd_write(client->ioc, buf, 18, errp) < 0) {
1336         error_prepend(errp, "write failed: ");
1337         return -EINVAL;
1338     }
1339     ret = nbd_negotiate_options(client, errp);
1340     if (ret != 0) {
1341         if (ret < 0) {
1342             error_prepend(errp, "option negotiation failed: ");
1343         }
1344         return ret;
1345     }
1346 
1347     /* Attach the channel to the same AioContext as the export */
1348     if (client->exp && client->exp->common.ctx) {
1349         qio_channel_attach_aio_context(client->ioc, client->exp->common.ctx);
1350     }
1351 
1352     assert(!client->optlen);
1353     trace_nbd_negotiate_success();
1354 
1355     return 0;
1356 }
1357 
1358 /* nbd_read_eof
1359  * Tries to read @size bytes from @ioc. This is a local implementation of
1360  * qio_channel_readv_all_eof. We have it here because we need it to be
1361  * interruptible and to know when the coroutine is yielding.
1362  * Returns 1 on success
1363  *         0 on eof, when no data was read (errp is not set)
1364  *         negative errno on failure (errp is set)
1365  */
1366 static inline int coroutine_fn
1367 nbd_read_eof(NBDClient *client, void *buffer, size_t size, Error **errp)
1368 {
1369     bool partial = false;
1370 
1371     assert(size);
1372     while (size > 0) {
1373         struct iovec iov = { .iov_base = buffer, .iov_len = size };
1374         ssize_t len;
1375 
1376         len = qio_channel_readv(client->ioc, &iov, 1, errp);
1377         if (len == QIO_CHANNEL_ERR_BLOCK) {
1378             client->read_yielding = true;
1379             qio_channel_yield(client->ioc, G_IO_IN);
1380             client->read_yielding = false;
1381             if (client->quiescing) {
1382                 return -EAGAIN;
1383             }
1384             continue;
1385         } else if (len < 0) {
1386             return -EIO;
1387         } else if (len == 0) {
1388             if (partial) {
1389                 error_setg(errp,
1390                            "Unexpected end-of-file before all bytes were read");
1391                 return -EIO;
1392             } else {
1393                 return 0;
1394             }
1395         }
1396 
1397         partial = true;
1398         size -= len;
1399         buffer = (uint8_t *) buffer + len;
1400     }
1401     return 1;
1402 }
1403 
1404 static int nbd_receive_request(NBDClient *client, NBDRequest *request,
1405                                Error **errp)
1406 {
1407     uint8_t buf[NBD_REQUEST_SIZE];
1408     uint32_t magic;
1409     int ret;
1410 
1411     ret = nbd_read_eof(client, buf, sizeof(buf), errp);
1412     if (ret < 0) {
1413         return ret;
1414     }
1415 
1416     /* Request
1417        [ 0 ..  3]   magic   (NBD_REQUEST_MAGIC)
1418        [ 4 ..  5]   flags   (NBD_CMD_FLAG_FUA, ...)
1419        [ 6 ..  7]   type    (NBD_CMD_READ, ...)
1420        [ 8 .. 15]   handle
1421        [16 .. 23]   from
1422        [24 .. 27]   len
1423      */
1424 
1425     magic = ldl_be_p(buf);
1426     request->flags  = lduw_be_p(buf + 4);
1427     request->type   = lduw_be_p(buf + 6);
1428     request->handle = ldq_be_p(buf + 8);
1429     request->from   = ldq_be_p(buf + 16);
1430     request->len    = ldl_be_p(buf + 24);
1431 
1432     trace_nbd_receive_request(magic, request->flags, request->type,
1433                               request->from, request->len);
1434 
1435     if (magic != NBD_REQUEST_MAGIC) {
1436         error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
1437         return -EINVAL;
1438     }
1439     return 0;
1440 }
1441 
1442 #define MAX_NBD_REQUESTS 16
1443 
1444 void nbd_client_get(NBDClient *client)
1445 {
1446     client->refcount++;
1447 }
1448 
1449 void nbd_client_put(NBDClient *client)
1450 {
1451     if (--client->refcount == 0) {
1452         /* The last reference should be dropped by client->close,
1453          * which is called by client_close.
1454          */
1455         assert(client->closing);
1456 
1457         qio_channel_detach_aio_context(client->ioc);
1458         object_unref(OBJECT(client->sioc));
1459         object_unref(OBJECT(client->ioc));
1460         if (client->tlscreds) {
1461             object_unref(OBJECT(client->tlscreds));
1462         }
1463         g_free(client->tlsauthz);
1464         if (client->exp) {
1465             QTAILQ_REMOVE(&client->exp->clients, client, next);
1466             blk_exp_unref(&client->exp->common);
1467         }
1468         g_free(client->export_meta.bitmaps);
1469         g_free(client);
1470     }
1471 }
1472 
1473 static void client_close(NBDClient *client, bool negotiated)
1474 {
1475     if (client->closing) {
1476         return;
1477     }
1478 
1479     client->closing = true;
1480 
1481     /* Force requests to finish.  They will drop their own references,
1482      * then we'll close the socket and free the NBDClient.
1483      */
1484     qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
1485                          NULL);
1486 
1487     /* Also tell the client, so that they release their reference.  */
1488     if (client->close_fn) {
1489         client->close_fn(client, negotiated);
1490     }
1491 }
1492 
1493 static NBDRequestData *nbd_request_get(NBDClient *client)
1494 {
1495     NBDRequestData *req;
1496 
1497     assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
1498     client->nb_requests++;
1499 
1500     req = g_new0(NBDRequestData, 1);
1501     nbd_client_get(client);
1502     req->client = client;
1503     return req;
1504 }
1505 
1506 static void nbd_request_put(NBDRequestData *req)
1507 {
1508     NBDClient *client = req->client;
1509 
1510     if (req->data) {
1511         qemu_vfree(req->data);
1512     }
1513     g_free(req);
1514 
1515     client->nb_requests--;
1516 
1517     if (client->quiescing && client->nb_requests == 0) {
1518         aio_wait_kick();
1519     }
1520 
1521     nbd_client_receive_next_request(client);
1522 
1523     nbd_client_put(client);
1524 }
1525 
1526 static void blk_aio_attached(AioContext *ctx, void *opaque)
1527 {
1528     NBDExport *exp = opaque;
1529     NBDClient *client;
1530 
1531     trace_nbd_blk_aio_attached(exp->name, ctx);
1532 
1533     exp->common.ctx = ctx;
1534 
1535     QTAILQ_FOREACH(client, &exp->clients, next) {
1536         qio_channel_attach_aio_context(client->ioc, ctx);
1537 
1538         assert(client->nb_requests == 0);
1539         assert(client->recv_coroutine == NULL);
1540         assert(client->send_coroutine == NULL);
1541     }
1542 }
1543 
1544 static void blk_aio_detach(void *opaque)
1545 {
1546     NBDExport *exp = opaque;
1547     NBDClient *client;
1548 
1549     trace_nbd_blk_aio_detach(exp->name, exp->common.ctx);
1550 
1551     QTAILQ_FOREACH(client, &exp->clients, next) {
1552         qio_channel_detach_aio_context(client->ioc);
1553     }
1554 
1555     exp->common.ctx = NULL;
1556 }
1557 
1558 static void nbd_drained_begin(void *opaque)
1559 {
1560     NBDExport *exp = opaque;
1561     NBDClient *client;
1562 
1563     QTAILQ_FOREACH(client, &exp->clients, next) {
1564         client->quiescing = true;
1565     }
1566 }
1567 
1568 static void nbd_drained_end(void *opaque)
1569 {
1570     NBDExport *exp = opaque;
1571     NBDClient *client;
1572 
1573     QTAILQ_FOREACH(client, &exp->clients, next) {
1574         client->quiescing = false;
1575         nbd_client_receive_next_request(client);
1576     }
1577 }
1578 
1579 static bool nbd_drained_poll(void *opaque)
1580 {
1581     NBDExport *exp = opaque;
1582     NBDClient *client;
1583 
1584     QTAILQ_FOREACH(client, &exp->clients, next) {
1585         if (client->nb_requests != 0) {
1586             /*
1587              * If there's a coroutine waiting for a request on nbd_read_eof()
1588              * enter it here so we don't depend on the client to wake it up.
1589              */
1590             if (client->recv_coroutine != NULL && client->read_yielding) {
1591                 qemu_aio_coroutine_enter(exp->common.ctx,
1592                                          client->recv_coroutine);
1593             }
1594 
1595             return true;
1596         }
1597     }
1598 
1599     return false;
1600 }
1601 
1602 static void nbd_eject_notifier(Notifier *n, void *data)
1603 {
1604     NBDExport *exp = container_of(n, NBDExport, eject_notifier);
1605 
1606     blk_exp_request_shutdown(&exp->common);
1607 }
1608 
1609 void nbd_export_set_on_eject_blk(BlockExport *exp, BlockBackend *blk)
1610 {
1611     NBDExport *nbd_exp = container_of(exp, NBDExport, common);
1612     assert(exp->drv == &blk_exp_nbd);
1613     assert(nbd_exp->eject_notifier_blk == NULL);
1614 
1615     blk_ref(blk);
1616     nbd_exp->eject_notifier_blk = blk;
1617     nbd_exp->eject_notifier.notify = nbd_eject_notifier;
1618     blk_add_remove_bs_notifier(blk, &nbd_exp->eject_notifier);
1619 }
1620 
1621 static const BlockDevOps nbd_block_ops = {
1622     .drained_begin = nbd_drained_begin,
1623     .drained_end = nbd_drained_end,
1624     .drained_poll = nbd_drained_poll,
1625 };
1626 
1627 static int nbd_export_create(BlockExport *blk_exp, BlockExportOptions *exp_args,
1628                              Error **errp)
1629 {
1630     NBDExport *exp = container_of(blk_exp, NBDExport, common);
1631     BlockExportOptionsNbd *arg = &exp_args->u.nbd;
1632     BlockBackend *blk = blk_exp->blk;
1633     int64_t size;
1634     uint64_t perm, shared_perm;
1635     bool readonly = !exp_args->writable;
1636     bool shared = !exp_args->writable;
1637     strList *bitmaps;
1638     size_t i;
1639     int ret;
1640 
1641     assert(exp_args->type == BLOCK_EXPORT_TYPE_NBD);
1642 
1643     if (!nbd_server_is_running()) {
1644         error_setg(errp, "NBD server not running");
1645         return -EINVAL;
1646     }
1647 
1648     if (!arg->has_name) {
1649         arg->name = exp_args->node_name;
1650     }
1651 
1652     if (strlen(arg->name) > NBD_MAX_STRING_SIZE) {
1653         error_setg(errp, "export name '%s' too long", arg->name);
1654         return -EINVAL;
1655     }
1656 
1657     if (arg->description && strlen(arg->description) > NBD_MAX_STRING_SIZE) {
1658         error_setg(errp, "description '%s' too long", arg->description);
1659         return -EINVAL;
1660     }
1661 
1662     if (nbd_export_find(arg->name)) {
1663         error_setg(errp, "NBD server already has export named '%s'", arg->name);
1664         return -EEXIST;
1665     }
1666 
1667     size = blk_getlength(blk);
1668     if (size < 0) {
1669         error_setg_errno(errp, -size,
1670                          "Failed to determine the NBD export's length");
1671         return size;
1672     }
1673 
1674     /* Don't allow resize while the NBD server is running, otherwise we don't
1675      * care what happens with the node. */
1676     blk_get_perm(blk, &perm, &shared_perm);
1677     ret = blk_set_perm(blk, perm, shared_perm & ~BLK_PERM_RESIZE, errp);
1678     if (ret < 0) {
1679         return ret;
1680     }
1681 
1682     QTAILQ_INIT(&exp->clients);
1683     exp->name = g_strdup(arg->name);
1684     exp->description = g_strdup(arg->description);
1685     exp->nbdflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_FLUSH |
1686                      NBD_FLAG_SEND_FUA | NBD_FLAG_SEND_CACHE);
1687     if (readonly) {
1688         exp->nbdflags |= NBD_FLAG_READ_ONLY;
1689         if (shared) {
1690             exp->nbdflags |= NBD_FLAG_CAN_MULTI_CONN;
1691         }
1692     } else {
1693         exp->nbdflags |= (NBD_FLAG_SEND_TRIM | NBD_FLAG_SEND_WRITE_ZEROES |
1694                           NBD_FLAG_SEND_FAST_ZERO);
1695     }
1696     exp->size = QEMU_ALIGN_DOWN(size, BDRV_SECTOR_SIZE);
1697 
1698     for (bitmaps = arg->bitmaps; bitmaps; bitmaps = bitmaps->next) {
1699         exp->nr_export_bitmaps++;
1700     }
1701     exp->export_bitmaps = g_new0(BdrvDirtyBitmap *, exp->nr_export_bitmaps);
1702     for (i = 0, bitmaps = arg->bitmaps; bitmaps;
1703          i++, bitmaps = bitmaps->next) {
1704         const char *bitmap = bitmaps->value;
1705         BlockDriverState *bs = blk_bs(blk);
1706         BdrvDirtyBitmap *bm = NULL;
1707 
1708         while (bs) {
1709             bm = bdrv_find_dirty_bitmap(bs, bitmap);
1710             if (bm != NULL) {
1711                 break;
1712             }
1713 
1714             bs = bdrv_filter_or_cow_bs(bs);
1715         }
1716 
1717         if (bm == NULL) {
1718             ret = -ENOENT;
1719             error_setg(errp, "Bitmap '%s' is not found", bitmap);
1720             goto fail;
1721         }
1722 
1723         if (bdrv_dirty_bitmap_check(bm, BDRV_BITMAP_ALLOW_RO, errp)) {
1724             ret = -EINVAL;
1725             goto fail;
1726         }
1727 
1728         if (readonly && bdrv_is_writable(bs) &&
1729             bdrv_dirty_bitmap_enabled(bm)) {
1730             ret = -EINVAL;
1731             error_setg(errp,
1732                        "Enabled bitmap '%s' incompatible with readonly export",
1733                        bitmap);
1734             goto fail;
1735         }
1736 
1737         exp->export_bitmaps[i] = bm;
1738         assert(strlen(bitmap) <= BDRV_BITMAP_MAX_NAME_SIZE);
1739     }
1740 
1741     /* Mark bitmaps busy in a separate loop, to simplify roll-back concerns. */
1742     for (i = 0; i < exp->nr_export_bitmaps; i++) {
1743         bdrv_dirty_bitmap_set_busy(exp->export_bitmaps[i], true);
1744     }
1745 
1746     exp->allocation_depth = arg->allocation_depth;
1747 
1748     /*
1749      * We need to inhibit request queuing in the block layer to ensure we can
1750      * be properly quiesced when entering a drained section, as our coroutines
1751      * servicing pending requests might enter blk_pread().
1752      */
1753     blk_set_disable_request_queuing(blk, true);
1754 
1755     blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
1756 
1757     blk_set_dev_ops(blk, &nbd_block_ops, exp);
1758 
1759     QTAILQ_INSERT_TAIL(&exports, exp, next);
1760 
1761     return 0;
1762 
1763 fail:
1764     g_free(exp->export_bitmaps);
1765     g_free(exp->name);
1766     g_free(exp->description);
1767     return ret;
1768 }
1769 
1770 NBDExport *nbd_export_find(const char *name)
1771 {
1772     NBDExport *exp;
1773     QTAILQ_FOREACH(exp, &exports, next) {
1774         if (strcmp(name, exp->name) == 0) {
1775             return exp;
1776         }
1777     }
1778 
1779     return NULL;
1780 }
1781 
1782 AioContext *
1783 nbd_export_aio_context(NBDExport *exp)
1784 {
1785     return exp->common.ctx;
1786 }
1787 
1788 static void nbd_export_request_shutdown(BlockExport *blk_exp)
1789 {
1790     NBDExport *exp = container_of(blk_exp, NBDExport, common);
1791     NBDClient *client, *next;
1792 
1793     blk_exp_ref(&exp->common);
1794     /*
1795      * TODO: Should we expand QMP NbdServerRemoveNode enum to allow a
1796      * close mode that stops advertising the export to new clients but
1797      * still permits existing clients to run to completion? Because of
1798      * that possibility, nbd_export_close() can be called more than
1799      * once on an export.
1800      */
1801     QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
1802         client_close(client, true);
1803     }
1804     if (exp->name) {
1805         g_free(exp->name);
1806         exp->name = NULL;
1807         QTAILQ_REMOVE(&exports, exp, next);
1808     }
1809     blk_exp_unref(&exp->common);
1810 }
1811 
1812 static void nbd_export_delete(BlockExport *blk_exp)
1813 {
1814     size_t i;
1815     NBDExport *exp = container_of(blk_exp, NBDExport, common);
1816 
1817     assert(exp->name == NULL);
1818     assert(QTAILQ_EMPTY(&exp->clients));
1819 
1820     g_free(exp->description);
1821     exp->description = NULL;
1822 
1823     if (exp->common.blk) {
1824         if (exp->eject_notifier_blk) {
1825             notifier_remove(&exp->eject_notifier);
1826             blk_unref(exp->eject_notifier_blk);
1827         }
1828         blk_remove_aio_context_notifier(exp->common.blk, blk_aio_attached,
1829                                         blk_aio_detach, exp);
1830         blk_set_disable_request_queuing(exp->common.blk, false);
1831     }
1832 
1833     for (i = 0; i < exp->nr_export_bitmaps; i++) {
1834         bdrv_dirty_bitmap_set_busy(exp->export_bitmaps[i], false);
1835     }
1836 }
1837 
1838 const BlockExportDriver blk_exp_nbd = {
1839     .type               = BLOCK_EXPORT_TYPE_NBD,
1840     .instance_size      = sizeof(NBDExport),
1841     .create             = nbd_export_create,
1842     .delete             = nbd_export_delete,
1843     .request_shutdown   = nbd_export_request_shutdown,
1844 };
1845 
1846 static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov,
1847                                         unsigned niov, Error **errp)
1848 {
1849     int ret;
1850 
1851     g_assert(qemu_in_coroutine());
1852     qemu_co_mutex_lock(&client->send_lock);
1853     client->send_coroutine = qemu_coroutine_self();
1854 
1855     ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0;
1856 
1857     client->send_coroutine = NULL;
1858     qemu_co_mutex_unlock(&client->send_lock);
1859 
1860     return ret;
1861 }
1862 
1863 static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
1864                                        uint64_t handle)
1865 {
1866     stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
1867     stl_be_p(&reply->error, error);
1868     stq_be_p(&reply->handle, handle);
1869 }
1870 
1871 static int nbd_co_send_simple_reply(NBDClient *client,
1872                                     uint64_t handle,
1873                                     uint32_t error,
1874                                     void *data,
1875                                     size_t len,
1876                                     Error **errp)
1877 {
1878     NBDSimpleReply reply;
1879     int nbd_err = system_errno_to_nbd_errno(error);
1880     struct iovec iov[] = {
1881         {.iov_base = &reply, .iov_len = sizeof(reply)},
1882         {.iov_base = data, .iov_len = len}
1883     };
1884 
1885     trace_nbd_co_send_simple_reply(handle, nbd_err, nbd_err_lookup(nbd_err),
1886                                    len);
1887     set_be_simple_reply(&reply, nbd_err, handle);
1888 
1889     return nbd_co_send_iov(client, iov, len ? 2 : 1, errp);
1890 }
1891 
1892 static inline void set_be_chunk(NBDStructuredReplyChunk *chunk, uint16_t flags,
1893                                 uint16_t type, uint64_t handle, uint32_t length)
1894 {
1895     stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC);
1896     stw_be_p(&chunk->flags, flags);
1897     stw_be_p(&chunk->type, type);
1898     stq_be_p(&chunk->handle, handle);
1899     stl_be_p(&chunk->length, length);
1900 }
1901 
1902 static int coroutine_fn nbd_co_send_structured_done(NBDClient *client,
1903                                                     uint64_t handle,
1904                                                     Error **errp)
1905 {
1906     NBDStructuredReplyChunk chunk;
1907     struct iovec iov[] = {
1908         {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1909     };
1910 
1911     trace_nbd_co_send_structured_done(handle);
1912     set_be_chunk(&chunk, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_NONE, handle, 0);
1913 
1914     return nbd_co_send_iov(client, iov, 1, errp);
1915 }
1916 
1917 static int coroutine_fn nbd_co_send_structured_read(NBDClient *client,
1918                                                     uint64_t handle,
1919                                                     uint64_t offset,
1920                                                     void *data,
1921                                                     size_t size,
1922                                                     bool final,
1923                                                     Error **errp)
1924 {
1925     NBDStructuredReadData chunk;
1926     struct iovec iov[] = {
1927         {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1928         {.iov_base = data, .iov_len = size}
1929     };
1930 
1931     assert(size);
1932     trace_nbd_co_send_structured_read(handle, offset, data, size);
1933     set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1934                  NBD_REPLY_TYPE_OFFSET_DATA, handle,
1935                  sizeof(chunk) - sizeof(chunk.h) + size);
1936     stq_be_p(&chunk.offset, offset);
1937 
1938     return nbd_co_send_iov(client, iov, 2, errp);
1939 }
1940 
1941 static int coroutine_fn nbd_co_send_structured_error(NBDClient *client,
1942                                                      uint64_t handle,
1943                                                      uint32_t error,
1944                                                      const char *msg,
1945                                                      Error **errp)
1946 {
1947     NBDStructuredError chunk;
1948     int nbd_err = system_errno_to_nbd_errno(error);
1949     struct iovec iov[] = {
1950         {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1951         {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0},
1952     };
1953 
1954     assert(nbd_err);
1955     trace_nbd_co_send_structured_error(handle, nbd_err,
1956                                        nbd_err_lookup(nbd_err), msg ? msg : "");
1957     set_be_chunk(&chunk.h, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_ERROR, handle,
1958                  sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1959     stl_be_p(&chunk.error, nbd_err);
1960     stw_be_p(&chunk.message_length, iov[1].iov_len);
1961 
1962     return nbd_co_send_iov(client, iov, 1 + !!iov[1].iov_len, errp);
1963 }
1964 
1965 /* Do a sparse read and send the structured reply to the client.
1966  * Returns -errno if sending fails. bdrv_block_status_above() failure is
1967  * reported to the client, at which point this function succeeds.
1968  */
1969 static int coroutine_fn nbd_co_send_sparse_read(NBDClient *client,
1970                                                 uint64_t handle,
1971                                                 uint64_t offset,
1972                                                 uint8_t *data,
1973                                                 size_t size,
1974                                                 Error **errp)
1975 {
1976     int ret = 0;
1977     NBDExport *exp = client->exp;
1978     size_t progress = 0;
1979 
1980     while (progress < size) {
1981         int64_t pnum;
1982         int status = bdrv_block_status_above(blk_bs(exp->common.blk), NULL,
1983                                              offset + progress,
1984                                              size - progress, &pnum, NULL,
1985                                              NULL);
1986         bool final;
1987 
1988         if (status < 0) {
1989             char *msg = g_strdup_printf("unable to check for holes: %s",
1990                                         strerror(-status));
1991 
1992             ret = nbd_co_send_structured_error(client, handle, -status, msg,
1993                                                errp);
1994             g_free(msg);
1995             return ret;
1996         }
1997         assert(pnum && pnum <= size - progress);
1998         final = progress + pnum == size;
1999         if (status & BDRV_BLOCK_ZERO) {
2000             NBDStructuredReadHole chunk;
2001             struct iovec iov[] = {
2002                 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
2003             };
2004 
2005             trace_nbd_co_send_structured_read_hole(handle, offset + progress,
2006                                                    pnum);
2007             set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
2008                          NBD_REPLY_TYPE_OFFSET_HOLE,
2009                          handle, sizeof(chunk) - sizeof(chunk.h));
2010             stq_be_p(&chunk.offset, offset + progress);
2011             stl_be_p(&chunk.length, pnum);
2012             ret = nbd_co_send_iov(client, iov, 1, errp);
2013         } else {
2014             ret = blk_pread(exp->common.blk, offset + progress,
2015                             data + progress, pnum);
2016             if (ret < 0) {
2017                 error_setg_errno(errp, -ret, "reading from file failed");
2018                 break;
2019             }
2020             ret = nbd_co_send_structured_read(client, handle, offset + progress,
2021                                               data + progress, pnum, final,
2022                                               errp);
2023         }
2024 
2025         if (ret < 0) {
2026             break;
2027         }
2028         progress += pnum;
2029     }
2030     return ret;
2031 }
2032 
2033 typedef struct NBDExtentArray {
2034     NBDExtent *extents;
2035     unsigned int nb_alloc;
2036     unsigned int count;
2037     uint64_t total_length;
2038     bool can_add;
2039     bool converted_to_be;
2040 } NBDExtentArray;
2041 
2042 static NBDExtentArray *nbd_extent_array_new(unsigned int nb_alloc)
2043 {
2044     NBDExtentArray *ea = g_new0(NBDExtentArray, 1);
2045 
2046     ea->nb_alloc = nb_alloc;
2047     ea->extents = g_new(NBDExtent, nb_alloc);
2048     ea->can_add = true;
2049 
2050     return ea;
2051 }
2052 
2053 static void nbd_extent_array_free(NBDExtentArray *ea)
2054 {
2055     g_free(ea->extents);
2056     g_free(ea);
2057 }
2058 G_DEFINE_AUTOPTR_CLEANUP_FUNC(NBDExtentArray, nbd_extent_array_free);
2059 
2060 /* Further modifications of the array after conversion are abandoned */
2061 static void nbd_extent_array_convert_to_be(NBDExtentArray *ea)
2062 {
2063     int i;
2064 
2065     assert(!ea->converted_to_be);
2066     ea->can_add = false;
2067     ea->converted_to_be = true;
2068 
2069     for (i = 0; i < ea->count; i++) {
2070         ea->extents[i].flags = cpu_to_be32(ea->extents[i].flags);
2071         ea->extents[i].length = cpu_to_be32(ea->extents[i].length);
2072     }
2073 }
2074 
2075 /*
2076  * Add extent to NBDExtentArray. If extent can't be added (no available space),
2077  * return -1.
2078  * For safety, when returning -1 for the first time, .can_add is set to false,
2079  * further call to nbd_extent_array_add() will crash.
2080  * (to avoid the situation, when after failing to add an extent (returned -1),
2081  * user miss this failure and add another extent, which is successfully added
2082  * (array is full, but new extent may be squashed into the last one), then we
2083  * have invalid array with skipped extent)
2084  */
2085 static int nbd_extent_array_add(NBDExtentArray *ea,
2086                                 uint32_t length, uint32_t flags)
2087 {
2088     assert(ea->can_add);
2089 
2090     if (!length) {
2091         return 0;
2092     }
2093 
2094     /* Extend previous extent if flags are the same */
2095     if (ea->count > 0 && flags == ea->extents[ea->count - 1].flags) {
2096         uint64_t sum = (uint64_t)length + ea->extents[ea->count - 1].length;
2097 
2098         if (sum <= UINT32_MAX) {
2099             ea->extents[ea->count - 1].length = sum;
2100             ea->total_length += length;
2101             return 0;
2102         }
2103     }
2104 
2105     if (ea->count >= ea->nb_alloc) {
2106         ea->can_add = false;
2107         return -1;
2108     }
2109 
2110     ea->total_length += length;
2111     ea->extents[ea->count] = (NBDExtent) {.length = length, .flags = flags};
2112     ea->count++;
2113 
2114     return 0;
2115 }
2116 
2117 static int blockstatus_to_extents(BlockDriverState *bs, uint64_t offset,
2118                                   uint64_t bytes, NBDExtentArray *ea)
2119 {
2120     while (bytes) {
2121         uint32_t flags;
2122         int64_t num;
2123         int ret = bdrv_block_status_above(bs, NULL, offset, bytes, &num,
2124                                           NULL, NULL);
2125 
2126         if (ret < 0) {
2127             return ret;
2128         }
2129 
2130         flags = (ret & BDRV_BLOCK_DATA ? 0 : NBD_STATE_HOLE) |
2131                 (ret & BDRV_BLOCK_ZERO ? NBD_STATE_ZERO : 0);
2132 
2133         if (nbd_extent_array_add(ea, num, flags) < 0) {
2134             return 0;
2135         }
2136 
2137         offset += num;
2138         bytes -= num;
2139     }
2140 
2141     return 0;
2142 }
2143 
2144 static int blockalloc_to_extents(BlockDriverState *bs, uint64_t offset,
2145                                  uint64_t bytes, NBDExtentArray *ea)
2146 {
2147     while (bytes) {
2148         int64_t num;
2149         int ret = bdrv_is_allocated_above(bs, NULL, false, offset, bytes,
2150                                           &num);
2151 
2152         if (ret < 0) {
2153             return ret;
2154         }
2155 
2156         if (nbd_extent_array_add(ea, num, ret) < 0) {
2157             return 0;
2158         }
2159 
2160         offset += num;
2161         bytes -= num;
2162     }
2163 
2164     return 0;
2165 }
2166 
2167 /*
2168  * nbd_co_send_extents
2169  *
2170  * @ea is converted to BE by the function
2171  * @last controls whether NBD_REPLY_FLAG_DONE is sent.
2172  */
2173 static int nbd_co_send_extents(NBDClient *client, uint64_t handle,
2174                                NBDExtentArray *ea,
2175                                bool last, uint32_t context_id, Error **errp)
2176 {
2177     NBDStructuredMeta chunk;
2178     struct iovec iov[] = {
2179         {.iov_base = &chunk, .iov_len = sizeof(chunk)},
2180         {.iov_base = ea->extents, .iov_len = ea->count * sizeof(ea->extents[0])}
2181     };
2182 
2183     nbd_extent_array_convert_to_be(ea);
2184 
2185     trace_nbd_co_send_extents(handle, ea->count, context_id, ea->total_length,
2186                               last);
2187     set_be_chunk(&chunk.h, last ? NBD_REPLY_FLAG_DONE : 0,
2188                  NBD_REPLY_TYPE_BLOCK_STATUS,
2189                  handle, sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
2190     stl_be_p(&chunk.context_id, context_id);
2191 
2192     return nbd_co_send_iov(client, iov, 2, errp);
2193 }
2194 
2195 /* Get block status from the exported device and send it to the client */
2196 static int nbd_co_send_block_status(NBDClient *client, uint64_t handle,
2197                                     BlockDriverState *bs, uint64_t offset,
2198                                     uint32_t length, bool dont_fragment,
2199                                     bool last, uint32_t context_id,
2200                                     Error **errp)
2201 {
2202     int ret;
2203     unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
2204     g_autoptr(NBDExtentArray) ea = nbd_extent_array_new(nb_extents);
2205 
2206     if (context_id == NBD_META_ID_BASE_ALLOCATION) {
2207         ret = blockstatus_to_extents(bs, offset, length, ea);
2208     } else {
2209         ret = blockalloc_to_extents(bs, offset, length, ea);
2210     }
2211     if (ret < 0) {
2212         return nbd_co_send_structured_error(
2213                 client, handle, -ret, "can't get block status", errp);
2214     }
2215 
2216     return nbd_co_send_extents(client, handle, ea, last, context_id, errp);
2217 }
2218 
2219 /* Populate @ea from a dirty bitmap. */
2220 static void bitmap_to_extents(BdrvDirtyBitmap *bitmap,
2221                               uint64_t offset, uint64_t length,
2222                               NBDExtentArray *es)
2223 {
2224     int64_t start, dirty_start, dirty_count;
2225     int64_t end = offset + length;
2226     bool full = false;
2227 
2228     bdrv_dirty_bitmap_lock(bitmap);
2229 
2230     for (start = offset;
2231          bdrv_dirty_bitmap_next_dirty_area(bitmap, start, end, INT32_MAX,
2232                                            &dirty_start, &dirty_count);
2233          start = dirty_start + dirty_count)
2234     {
2235         if ((nbd_extent_array_add(es, dirty_start - start, 0) < 0) ||
2236             (nbd_extent_array_add(es, dirty_count, NBD_STATE_DIRTY) < 0))
2237         {
2238             full = true;
2239             break;
2240         }
2241     }
2242 
2243     if (!full) {
2244         /* last non dirty extent, nothing to do if array is now full */
2245         (void) nbd_extent_array_add(es, end - start, 0);
2246     }
2247 
2248     bdrv_dirty_bitmap_unlock(bitmap);
2249 }
2250 
2251 static int nbd_co_send_bitmap(NBDClient *client, uint64_t handle,
2252                               BdrvDirtyBitmap *bitmap, uint64_t offset,
2253                               uint32_t length, bool dont_fragment, bool last,
2254                               uint32_t context_id, Error **errp)
2255 {
2256     unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
2257     g_autoptr(NBDExtentArray) ea = nbd_extent_array_new(nb_extents);
2258 
2259     bitmap_to_extents(bitmap, offset, length, ea);
2260 
2261     return nbd_co_send_extents(client, handle, ea, last, context_id, errp);
2262 }
2263 
2264 /* nbd_co_receive_request
2265  * Collect a client request. Return 0 if request looks valid, -EIO to drop
2266  * connection right away, -EAGAIN to indicate we were interrupted and the
2267  * channel should be quiesced, and any other negative value to report an error
2268  * to the client (although the caller may still need to disconnect after
2269  * reporting the error).
2270  */
2271 static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
2272                                   Error **errp)
2273 {
2274     NBDClient *client = req->client;
2275     int valid_flags;
2276     int ret;
2277 
2278     g_assert(qemu_in_coroutine());
2279     assert(client->recv_coroutine == qemu_coroutine_self());
2280     ret = nbd_receive_request(client, request, errp);
2281     if (ret < 0) {
2282         return  ret;
2283     }
2284 
2285     trace_nbd_co_receive_request_decode_type(request->handle, request->type,
2286                                              nbd_cmd_lookup(request->type));
2287 
2288     if (request->type != NBD_CMD_WRITE) {
2289         /* No payload, we are ready to read the next request.  */
2290         req->complete = true;
2291     }
2292 
2293     if (request->type == NBD_CMD_DISC) {
2294         /* Special case: we're going to disconnect without a reply,
2295          * whether or not flags, from, or len are bogus */
2296         return -EIO;
2297     }
2298 
2299     if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE ||
2300         request->type == NBD_CMD_CACHE)
2301     {
2302         if (request->len > NBD_MAX_BUFFER_SIZE) {
2303             error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
2304                        request->len, NBD_MAX_BUFFER_SIZE);
2305             return -EINVAL;
2306         }
2307 
2308         if (request->type != NBD_CMD_CACHE) {
2309             req->data = blk_try_blockalign(client->exp->common.blk,
2310                                            request->len);
2311             if (req->data == NULL) {
2312                 error_setg(errp, "No memory");
2313                 return -ENOMEM;
2314             }
2315         }
2316     }
2317 
2318     if (request->type == NBD_CMD_WRITE) {
2319         if (nbd_read(client->ioc, req->data, request->len, "CMD_WRITE data",
2320                      errp) < 0)
2321         {
2322             return -EIO;
2323         }
2324         req->complete = true;
2325 
2326         trace_nbd_co_receive_request_payload_received(request->handle,
2327                                                       request->len);
2328     }
2329 
2330     /* Sanity checks. */
2331     if (client->exp->nbdflags & NBD_FLAG_READ_ONLY &&
2332         (request->type == NBD_CMD_WRITE ||
2333          request->type == NBD_CMD_WRITE_ZEROES ||
2334          request->type == NBD_CMD_TRIM)) {
2335         error_setg(errp, "Export is read-only");
2336         return -EROFS;
2337     }
2338     if (request->from > client->exp->size ||
2339         request->len > client->exp->size - request->from) {
2340         error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
2341                    ", Size: %" PRIu64, request->from, request->len,
2342                    client->exp->size);
2343         return (request->type == NBD_CMD_WRITE ||
2344                 request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL;
2345     }
2346     if (client->check_align && !QEMU_IS_ALIGNED(request->from | request->len,
2347                                                 client->check_align)) {
2348         /*
2349          * The block layer gracefully handles unaligned requests, but
2350          * it's still worth tracing client non-compliance
2351          */
2352         trace_nbd_co_receive_align_compliance(nbd_cmd_lookup(request->type),
2353                                               request->from,
2354                                               request->len,
2355                                               client->check_align);
2356     }
2357     valid_flags = NBD_CMD_FLAG_FUA;
2358     if (request->type == NBD_CMD_READ && client->structured_reply) {
2359         valid_flags |= NBD_CMD_FLAG_DF;
2360     } else if (request->type == NBD_CMD_WRITE_ZEROES) {
2361         valid_flags |= NBD_CMD_FLAG_NO_HOLE | NBD_CMD_FLAG_FAST_ZERO;
2362     } else if (request->type == NBD_CMD_BLOCK_STATUS) {
2363         valid_flags |= NBD_CMD_FLAG_REQ_ONE;
2364     }
2365     if (request->flags & ~valid_flags) {
2366         error_setg(errp, "unsupported flags for command %s (got 0x%x)",
2367                    nbd_cmd_lookup(request->type), request->flags);
2368         return -EINVAL;
2369     }
2370 
2371     return 0;
2372 }
2373 
2374 /* Send simple reply without a payload, or a structured error
2375  * @error_msg is ignored if @ret >= 0
2376  * Returns 0 if connection is still live, -errno on failure to talk to client
2377  */
2378 static coroutine_fn int nbd_send_generic_reply(NBDClient *client,
2379                                                uint64_t handle,
2380                                                int ret,
2381                                                const char *error_msg,
2382                                                Error **errp)
2383 {
2384     if (client->structured_reply && ret < 0) {
2385         return nbd_co_send_structured_error(client, handle, -ret, error_msg,
2386                                             errp);
2387     } else {
2388         return nbd_co_send_simple_reply(client, handle, ret < 0 ? -ret : 0,
2389                                         NULL, 0, errp);
2390     }
2391 }
2392 
2393 /* Handle NBD_CMD_READ request.
2394  * Return -errno if sending fails. Other errors are reported directly to the
2395  * client as an error reply. */
2396 static coroutine_fn int nbd_do_cmd_read(NBDClient *client, NBDRequest *request,
2397                                         uint8_t *data, Error **errp)
2398 {
2399     int ret;
2400     NBDExport *exp = client->exp;
2401 
2402     assert(request->type == NBD_CMD_READ);
2403 
2404     /* XXX: NBD Protocol only documents use of FUA with WRITE */
2405     if (request->flags & NBD_CMD_FLAG_FUA) {
2406         ret = blk_co_flush(exp->common.blk);
2407         if (ret < 0) {
2408             return nbd_send_generic_reply(client, request->handle, ret,
2409                                           "flush failed", errp);
2410         }
2411     }
2412 
2413     if (client->structured_reply && !(request->flags & NBD_CMD_FLAG_DF) &&
2414         request->len)
2415     {
2416         return nbd_co_send_sparse_read(client, request->handle, request->from,
2417                                        data, request->len, errp);
2418     }
2419 
2420     ret = blk_pread(exp->common.blk, request->from, data, request->len);
2421     if (ret < 0) {
2422         return nbd_send_generic_reply(client, request->handle, ret,
2423                                       "reading from file failed", errp);
2424     }
2425 
2426     if (client->structured_reply) {
2427         if (request->len) {
2428             return nbd_co_send_structured_read(client, request->handle,
2429                                                request->from, data,
2430                                                request->len, true, errp);
2431         } else {
2432             return nbd_co_send_structured_done(client, request->handle, errp);
2433         }
2434     } else {
2435         return nbd_co_send_simple_reply(client, request->handle, 0,
2436                                         data, request->len, errp);
2437     }
2438 }
2439 
2440 /*
2441  * nbd_do_cmd_cache
2442  *
2443  * Handle NBD_CMD_CACHE request.
2444  * Return -errno if sending fails. Other errors are reported directly to the
2445  * client as an error reply.
2446  */
2447 static coroutine_fn int nbd_do_cmd_cache(NBDClient *client, NBDRequest *request,
2448                                          Error **errp)
2449 {
2450     int ret;
2451     NBDExport *exp = client->exp;
2452 
2453     assert(request->type == NBD_CMD_CACHE);
2454 
2455     ret = blk_co_preadv(exp->common.blk, request->from, request->len,
2456                         NULL, BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH);
2457 
2458     return nbd_send_generic_reply(client, request->handle, ret,
2459                                   "caching data failed", errp);
2460 }
2461 
2462 /* Handle NBD request.
2463  * Return -errno if sending fails. Other errors are reported directly to the
2464  * client as an error reply. */
2465 static coroutine_fn int nbd_handle_request(NBDClient *client,
2466                                            NBDRequest *request,
2467                                            uint8_t *data, Error **errp)
2468 {
2469     int ret;
2470     int flags;
2471     NBDExport *exp = client->exp;
2472     char *msg;
2473     size_t i;
2474 
2475     switch (request->type) {
2476     case NBD_CMD_CACHE:
2477         return nbd_do_cmd_cache(client, request, errp);
2478 
2479     case NBD_CMD_READ:
2480         return nbd_do_cmd_read(client, request, data, errp);
2481 
2482     case NBD_CMD_WRITE:
2483         flags = 0;
2484         if (request->flags & NBD_CMD_FLAG_FUA) {
2485             flags |= BDRV_REQ_FUA;
2486         }
2487         ret = blk_pwrite(exp->common.blk, request->from, data, request->len,
2488                          flags);
2489         return nbd_send_generic_reply(client, request->handle, ret,
2490                                       "writing to file failed", errp);
2491 
2492     case NBD_CMD_WRITE_ZEROES:
2493         flags = 0;
2494         if (request->flags & NBD_CMD_FLAG_FUA) {
2495             flags |= BDRV_REQ_FUA;
2496         }
2497         if (!(request->flags & NBD_CMD_FLAG_NO_HOLE)) {
2498             flags |= BDRV_REQ_MAY_UNMAP;
2499         }
2500         if (request->flags & NBD_CMD_FLAG_FAST_ZERO) {
2501             flags |= BDRV_REQ_NO_FALLBACK;
2502         }
2503         ret = 0;
2504         /* FIXME simplify this when blk_pwrite_zeroes switches to 64-bit */
2505         while (ret >= 0 && request->len) {
2506             int align = client->check_align ?: 1;
2507             int len = MIN(request->len, QEMU_ALIGN_DOWN(BDRV_REQUEST_MAX_BYTES,
2508                                                         align));
2509             ret = blk_pwrite_zeroes(exp->common.blk, request->from, len, flags);
2510             request->len -= len;
2511             request->from += len;
2512         }
2513         return nbd_send_generic_reply(client, request->handle, ret,
2514                                       "writing to file failed", errp);
2515 
2516     case NBD_CMD_DISC:
2517         /* unreachable, thanks to special case in nbd_co_receive_request() */
2518         abort();
2519 
2520     case NBD_CMD_FLUSH:
2521         ret = blk_co_flush(exp->common.blk);
2522         return nbd_send_generic_reply(client, request->handle, ret,
2523                                       "flush failed", errp);
2524 
2525     case NBD_CMD_TRIM:
2526         ret = 0;
2527         /* FIXME simplify this when blk_co_pdiscard switches to 64-bit */
2528         while (ret >= 0 && request->len) {
2529             int align = client->check_align ?: 1;
2530             int len = MIN(request->len, QEMU_ALIGN_DOWN(BDRV_REQUEST_MAX_BYTES,
2531                                                         align));
2532             ret = blk_co_pdiscard(exp->common.blk, request->from, len);
2533             request->len -= len;
2534             request->from += len;
2535         }
2536         if (ret >= 0 && request->flags & NBD_CMD_FLAG_FUA) {
2537             ret = blk_co_flush(exp->common.blk);
2538         }
2539         return nbd_send_generic_reply(client, request->handle, ret,
2540                                       "discard failed", errp);
2541 
2542     case NBD_CMD_BLOCK_STATUS:
2543         if (!request->len) {
2544             return nbd_send_generic_reply(client, request->handle, -EINVAL,
2545                                           "need non-zero length", errp);
2546         }
2547         if (client->export_meta.count) {
2548             bool dont_fragment = request->flags & NBD_CMD_FLAG_REQ_ONE;
2549             int contexts_remaining = client->export_meta.count;
2550 
2551             if (client->export_meta.base_allocation) {
2552                 ret = nbd_co_send_block_status(client, request->handle,
2553                                                blk_bs(exp->common.blk),
2554                                                request->from,
2555                                                request->len, dont_fragment,
2556                                                !--contexts_remaining,
2557                                                NBD_META_ID_BASE_ALLOCATION,
2558                                                errp);
2559                 if (ret < 0) {
2560                     return ret;
2561                 }
2562             }
2563 
2564             if (client->export_meta.allocation_depth) {
2565                 ret = nbd_co_send_block_status(client, request->handle,
2566                                                blk_bs(exp->common.blk),
2567                                                request->from, request->len,
2568                                                dont_fragment,
2569                                                !--contexts_remaining,
2570                                                NBD_META_ID_ALLOCATION_DEPTH,
2571                                                errp);
2572                 if (ret < 0) {
2573                     return ret;
2574                 }
2575             }
2576 
2577             for (i = 0; i < client->exp->nr_export_bitmaps; i++) {
2578                 if (!client->export_meta.bitmaps[i]) {
2579                     continue;
2580                 }
2581                 ret = nbd_co_send_bitmap(client, request->handle,
2582                                          client->exp->export_bitmaps[i],
2583                                          request->from, request->len,
2584                                          dont_fragment, !--contexts_remaining,
2585                                          NBD_META_ID_DIRTY_BITMAP + i, errp);
2586                 if (ret < 0) {
2587                     return ret;
2588                 }
2589             }
2590 
2591             assert(!contexts_remaining);
2592 
2593             return 0;
2594         } else {
2595             return nbd_send_generic_reply(client, request->handle, -EINVAL,
2596                                           "CMD_BLOCK_STATUS not negotiated",
2597                                           errp);
2598         }
2599 
2600     default:
2601         msg = g_strdup_printf("invalid request type (%" PRIu32 ") received",
2602                               request->type);
2603         ret = nbd_send_generic_reply(client, request->handle, -EINVAL, msg,
2604                                      errp);
2605         g_free(msg);
2606         return ret;
2607     }
2608 }
2609 
2610 /* Owns a reference to the NBDClient passed as opaque.  */
2611 static coroutine_fn void nbd_trip(void *opaque)
2612 {
2613     NBDClient *client = opaque;
2614     NBDRequestData *req;
2615     NBDRequest request = { 0 };    /* GCC thinks it can be used uninitialized */
2616     int ret;
2617     Error *local_err = NULL;
2618 
2619     trace_nbd_trip();
2620     if (client->closing) {
2621         nbd_client_put(client);
2622         return;
2623     }
2624 
2625     if (client->quiescing) {
2626         /*
2627          * We're switching between AIO contexts. Don't attempt to receive a new
2628          * request and kick the main context which may be waiting for us.
2629          */
2630         nbd_client_put(client);
2631         client->recv_coroutine = NULL;
2632         aio_wait_kick();
2633         return;
2634     }
2635 
2636     req = nbd_request_get(client);
2637     ret = nbd_co_receive_request(req, &request, &local_err);
2638     client->recv_coroutine = NULL;
2639 
2640     if (client->closing) {
2641         /*
2642          * The client may be closed when we are blocked in
2643          * nbd_co_receive_request()
2644          */
2645         goto done;
2646     }
2647 
2648     if (ret == -EAGAIN) {
2649         assert(client->quiescing);
2650         goto done;
2651     }
2652 
2653     nbd_client_receive_next_request(client);
2654     if (ret == -EIO) {
2655         goto disconnect;
2656     }
2657 
2658     if (ret < 0) {
2659         /* It wans't -EIO, so, according to nbd_co_receive_request()
2660          * semantics, we should return the error to the client. */
2661         Error *export_err = local_err;
2662 
2663         local_err = NULL;
2664         ret = nbd_send_generic_reply(client, request.handle, -EINVAL,
2665                                      error_get_pretty(export_err), &local_err);
2666         error_free(export_err);
2667     } else {
2668         ret = nbd_handle_request(client, &request, req->data, &local_err);
2669     }
2670     if (ret < 0) {
2671         error_prepend(&local_err, "Failed to send reply: ");
2672         goto disconnect;
2673     }
2674 
2675     /* We must disconnect after NBD_CMD_WRITE if we did not
2676      * read the payload.
2677      */
2678     if (!req->complete) {
2679         error_setg(&local_err, "Request handling failed in intermediate state");
2680         goto disconnect;
2681     }
2682 
2683 done:
2684     nbd_request_put(req);
2685     nbd_client_put(client);
2686     return;
2687 
2688 disconnect:
2689     if (local_err) {
2690         error_reportf_err(local_err, "Disconnect client, due to: ");
2691     }
2692     nbd_request_put(req);
2693     client_close(client, true);
2694     nbd_client_put(client);
2695 }
2696 
2697 static void nbd_client_receive_next_request(NBDClient *client)
2698 {
2699     if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS &&
2700         !client->quiescing) {
2701         nbd_client_get(client);
2702         client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
2703         aio_co_schedule(client->exp->common.ctx, client->recv_coroutine);
2704     }
2705 }
2706 
2707 static coroutine_fn void nbd_co_client_start(void *opaque)
2708 {
2709     NBDClient *client = opaque;
2710     Error *local_err = NULL;
2711 
2712     qemu_co_mutex_init(&client->send_lock);
2713 
2714     if (nbd_negotiate(client, &local_err)) {
2715         if (local_err) {
2716             error_report_err(local_err);
2717         }
2718         client_close(client, false);
2719         return;
2720     }
2721 
2722     nbd_client_receive_next_request(client);
2723 }
2724 
2725 /*
2726  * Create a new client listener using the given channel @sioc.
2727  * Begin servicing it in a coroutine.  When the connection closes, call
2728  * @close_fn with an indication of whether the client completed negotiation.
2729  */
2730 void nbd_client_new(QIOChannelSocket *sioc,
2731                     QCryptoTLSCreds *tlscreds,
2732                     const char *tlsauthz,
2733                     void (*close_fn)(NBDClient *, bool))
2734 {
2735     NBDClient *client;
2736     Coroutine *co;
2737 
2738     client = g_new0(NBDClient, 1);
2739     client->refcount = 1;
2740     client->tlscreds = tlscreds;
2741     if (tlscreds) {
2742         object_ref(OBJECT(client->tlscreds));
2743     }
2744     client->tlsauthz = g_strdup(tlsauthz);
2745     client->sioc = sioc;
2746     object_ref(OBJECT(client->sioc));
2747     client->ioc = QIO_CHANNEL(sioc);
2748     object_ref(OBJECT(client->ioc));
2749     client->close_fn = close_fn;
2750 
2751     co = qemu_coroutine_create(nbd_co_client_start, client);
2752     qemu_coroutine_enter(co);
2753 }
2754