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