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