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