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