xref: /openbmc/qemu/nbd/server.c (revision caf2e8de4ed056acad4fbdb6fe420d8124d38f11)
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) or never
1154  *         wrote anything (i.e. port probe); 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     /*
1179      * Intentionally ignore errors on this first read - we do not want
1180      * to be noisy about a mere port probe, but only for clients that
1181      * start talking the protocol and then quit abruptly.
1182      */
1183     if (nbd_read32(client->ioc, &flags, "flags", NULL) < 0) {
1184         return 1;
1185     }
1186     client->mode = NBD_MODE_EXPORT_NAME;
1187     trace_nbd_negotiate_options_flags(flags);
1188     if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
1189         fixedNewstyle = true;
1190         flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
1191         client->mode = NBD_MODE_SIMPLE;
1192     }
1193     if (flags & NBD_FLAG_C_NO_ZEROES) {
1194         no_zeroes = true;
1195         flags &= ~NBD_FLAG_C_NO_ZEROES;
1196     }
1197     if (flags != 0) {
1198         error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
1199         return -EINVAL;
1200     }
1201 
1202     while (1) {
1203         int ret;
1204         uint32_t option, length;
1205         uint64_t magic;
1206 
1207         if (nbd_read64(client->ioc, &magic, "opts magic", errp) < 0) {
1208             return -EINVAL;
1209         }
1210         trace_nbd_negotiate_options_check_magic(magic);
1211         if (magic != NBD_OPTS_MAGIC) {
1212             error_setg(errp, "Bad magic received");
1213             return -EINVAL;
1214         }
1215 
1216         if (nbd_read32(client->ioc, &option, "option", errp) < 0) {
1217             return -EINVAL;
1218         }
1219         client->opt = option;
1220 
1221         if (nbd_read32(client->ioc, &length, "option length", errp) < 0) {
1222             return -EINVAL;
1223         }
1224         assert(!client->optlen);
1225         client->optlen = length;
1226 
1227         if (length > NBD_MAX_BUFFER_SIZE) {
1228             error_setg(errp, "len (%" PRIu32 ") is larger than max len (%u)",
1229                        length, NBD_MAX_BUFFER_SIZE);
1230             return -EINVAL;
1231         }
1232 
1233         trace_nbd_negotiate_options_check_option(option,
1234                                                  nbd_opt_lookup(option));
1235         if (client->tlscreds &&
1236             client->ioc == (QIOChannel *)client->sioc) {
1237             QIOChannel *tioc;
1238             if (!fixedNewstyle) {
1239                 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
1240                 return -EINVAL;
1241             }
1242             switch (option) {
1243             case NBD_OPT_STARTTLS:
1244                 if (length) {
1245                     /* Unconditionally drop the connection if the client
1246                      * can't start a TLS negotiation correctly */
1247                     return nbd_reject_length(client, true, errp);
1248                 }
1249                 tioc = nbd_negotiate_handle_starttls(client, errp);
1250                 if (!tioc) {
1251                     return -EIO;
1252                 }
1253                 ret = 0;
1254                 object_unref(OBJECT(client->ioc));
1255                 client->ioc = tioc;
1256                 break;
1257 
1258             case NBD_OPT_EXPORT_NAME:
1259                 /* No way to return an error to client, so drop connection */
1260                 error_setg(errp, "Option 0x%x not permitted before TLS",
1261                            option);
1262                 return -EINVAL;
1263 
1264             default:
1265                 /* Let the client keep trying, unless they asked to
1266                  * quit. Always try to give an error back to the
1267                  * client; but when replying to OPT_ABORT, be aware
1268                  * that the client may hang up before receiving the
1269                  * error, in which case we are fine ignoring the
1270                  * resulting EPIPE. */
1271                 ret = nbd_opt_drop(client, NBD_REP_ERR_TLS_REQD,
1272                                    option == NBD_OPT_ABORT ? NULL : errp,
1273                                    "Option 0x%" PRIx32
1274                                    " not permitted before TLS", option);
1275                 if (option == NBD_OPT_ABORT) {
1276                     return 1;
1277                 }
1278                 break;
1279             }
1280         } else if (fixedNewstyle) {
1281             switch (option) {
1282             case NBD_OPT_LIST:
1283                 if (length) {
1284                     ret = nbd_reject_length(client, false, errp);
1285                 } else {
1286                     ret = nbd_negotiate_handle_list(client, errp);
1287                 }
1288                 break;
1289 
1290             case NBD_OPT_ABORT:
1291                 /* NBD spec says we must try to reply before
1292                  * disconnecting, but that we must also tolerate
1293                  * guests that don't wait for our reply. */
1294                 nbd_negotiate_send_rep(client, NBD_REP_ACK, NULL);
1295                 return 1;
1296 
1297             case NBD_OPT_EXPORT_NAME:
1298                 return nbd_negotiate_handle_export_name(client, no_zeroes,
1299                                                         errp);
1300 
1301             case NBD_OPT_INFO:
1302             case NBD_OPT_GO:
1303                 ret = nbd_negotiate_handle_info(client, errp);
1304                 if (ret == 1) {
1305                     assert(option == NBD_OPT_GO);
1306                     return 0;
1307                 }
1308                 break;
1309 
1310             case NBD_OPT_STARTTLS:
1311                 if (length) {
1312                     ret = nbd_reject_length(client, false, errp);
1313                 } else if (client->tlscreds) {
1314                     ret = nbd_negotiate_send_rep_err(client,
1315                                                      NBD_REP_ERR_INVALID, errp,
1316                                                      "TLS already enabled");
1317                 } else {
1318                     ret = nbd_negotiate_send_rep_err(client,
1319                                                      NBD_REP_ERR_POLICY, errp,
1320                                                      "TLS not configured");
1321                 }
1322                 break;
1323 
1324             case NBD_OPT_STRUCTURED_REPLY:
1325                 if (length) {
1326                     ret = nbd_reject_length(client, false, errp);
1327                 } else if (client->mode >= NBD_MODE_EXTENDED) {
1328                     ret = nbd_negotiate_send_rep_err(
1329                         client, NBD_REP_ERR_EXT_HEADER_REQD, errp,
1330                         "extended headers already negotiated");
1331                 } else if (client->mode >= NBD_MODE_STRUCTURED) {
1332                     ret = nbd_negotiate_send_rep_err(
1333                         client, NBD_REP_ERR_INVALID, errp,
1334                         "structured reply already negotiated");
1335                 } else {
1336                     ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1337                     client->mode = NBD_MODE_STRUCTURED;
1338                 }
1339                 break;
1340 
1341             case NBD_OPT_LIST_META_CONTEXT:
1342             case NBD_OPT_SET_META_CONTEXT:
1343                 ret = nbd_negotiate_meta_queries(client, errp);
1344                 break;
1345 
1346             case NBD_OPT_EXTENDED_HEADERS:
1347                 if (length) {
1348                     ret = nbd_reject_length(client, false, errp);
1349                 } else if (client->mode >= NBD_MODE_EXTENDED) {
1350                     ret = nbd_negotiate_send_rep_err(
1351                         client, NBD_REP_ERR_INVALID, errp,
1352                         "extended headers already negotiated");
1353                 } else {
1354                     ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1355                     client->mode = NBD_MODE_EXTENDED;
1356                 }
1357                 break;
1358 
1359             default:
1360                 ret = nbd_opt_drop(client, NBD_REP_ERR_UNSUP, errp,
1361                                    "Unsupported option %" PRIu32 " (%s)",
1362                                    option, nbd_opt_lookup(option));
1363                 break;
1364             }
1365         } else {
1366             /*
1367              * If broken new-style we should drop the connection
1368              * for anything except NBD_OPT_EXPORT_NAME
1369              */
1370             switch (option) {
1371             case NBD_OPT_EXPORT_NAME:
1372                 return nbd_negotiate_handle_export_name(client, no_zeroes,
1373                                                         errp);
1374 
1375             default:
1376                 error_setg(errp, "Unsupported option %" PRIu32 " (%s)",
1377                            option, nbd_opt_lookup(option));
1378                 return -EINVAL;
1379             }
1380         }
1381         if (ret < 0) {
1382             return ret;
1383         }
1384     }
1385 }
1386 
1387 /* nbd_negotiate
1388  * Return:
1389  * -errno  on error, errp is set
1390  * 0       on successful negotiation, errp is not set
1391  * 1       if client sent NBD_OPT_ABORT (i.e. on valid disconnect) or never
1392  *         wrote anything (i.e. port probe); errp is not set
1393  */
1394 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
1395 {
1396     ERRP_GUARD();
1397     char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
1398     int ret;
1399 
1400     /* Old style negotiation header, no room for options
1401         [ 0 ..   7]   passwd       ("NBDMAGIC")
1402         [ 8 ..  15]   magic        (NBD_CLIENT_MAGIC)
1403         [16 ..  23]   size
1404         [24 ..  27]   export flags (zero-extended)
1405         [28 .. 151]   reserved     (0)
1406 
1407        New style negotiation header, client can send options
1408         [ 0 ..   7]   passwd       ("NBDMAGIC")
1409         [ 8 ..  15]   magic        (NBD_OPTS_MAGIC)
1410         [16 ..  17]   server flags (0)
1411         ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
1412      */
1413 
1414     if (!qio_channel_set_blocking(client->ioc, false, errp)) {
1415         return -EINVAL;
1416     }
1417     qio_channel_set_follow_coroutine_ctx(client->ioc, true);
1418 
1419     trace_nbd_negotiate_begin();
1420     memcpy(buf, "NBDMAGIC", 8);
1421 
1422     stq_be_p(buf + 8, NBD_OPTS_MAGIC);
1423     stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
1424 
1425     /*
1426      * Be silent about failure to write our greeting: there is nothing
1427      * wrong with a client testing if our port is alive.
1428      */
1429     if (nbd_write(client->ioc, buf, 18, NULL) < 0) {
1430         return 1;
1431     }
1432     ret = nbd_negotiate_options(client, errp);
1433     if (ret != 0) {
1434         if (ret < 0) {
1435             error_prepend(errp, "option negotiation failed: ");
1436         }
1437         return ret;
1438     }
1439 
1440     assert(!client->optlen);
1441     trace_nbd_negotiate_success();
1442 
1443     return 0;
1444 }
1445 
1446 /* nbd_read_eof
1447  * Tries to read @size bytes from @ioc. This is a local implementation of
1448  * qio_channel_readv_all_eof. We have it here because we need it to be
1449  * interruptible and to know when the coroutine is yielding.
1450  * Returns 1 on success
1451  *         0 on eof, when no data was read (errp is not set)
1452  *         negative errno on failure (errp is set)
1453  */
1454 static inline int coroutine_fn
1455 nbd_read_eof(NBDClient *client, void *buffer, size_t size, Error **errp)
1456 {
1457     bool partial = false;
1458 
1459     assert(size);
1460     while (size > 0) {
1461         struct iovec iov = { .iov_base = buffer, .iov_len = size };
1462         ssize_t len;
1463 
1464         len = qio_channel_readv(client->ioc, &iov, 1, errp);
1465         if (len == QIO_CHANNEL_ERR_BLOCK) {
1466             WITH_QEMU_LOCK_GUARD(&client->lock) {
1467                 client->read_yielding = true;
1468 
1469                 /* Prompt main loop thread to re-run nbd_drained_poll() */
1470                 aio_wait_kick();
1471             }
1472             qio_channel_yield(client->ioc, G_IO_IN);
1473             WITH_QEMU_LOCK_GUARD(&client->lock) {
1474                 client->read_yielding = false;
1475                 if (client->quiescing) {
1476                     return -EAGAIN;
1477                 }
1478             }
1479             continue;
1480         } else if (len < 0) {
1481             return -EIO;
1482         } else if (len == 0) {
1483             if (partial) {
1484                 error_setg(errp,
1485                            "Unexpected end-of-file before all bytes were read");
1486                 return -EIO;
1487             } else {
1488                 return 0;
1489             }
1490         }
1491 
1492         partial = true;
1493         size -= len;
1494         buffer = (uint8_t *) buffer + len;
1495     }
1496     return 1;
1497 }
1498 
1499 static int coroutine_fn nbd_receive_request(NBDClient *client, NBDRequest *request,
1500                                             Error **errp)
1501 {
1502     uint8_t buf[NBD_EXTENDED_REQUEST_SIZE];
1503     uint32_t magic, expect;
1504     int ret;
1505     size_t size = client->mode >= NBD_MODE_EXTENDED ?
1506         NBD_EXTENDED_REQUEST_SIZE : NBD_REQUEST_SIZE;
1507 
1508     ret = nbd_read_eof(client, buf, size, errp);
1509     if (ret < 0) {
1510         return ret;
1511     }
1512     if (ret == 0) {
1513         return -EIO;
1514     }
1515 
1516     /*
1517      * Compact request
1518      *  [ 0 ..  3]   magic   (NBD_REQUEST_MAGIC)
1519      *  [ 4 ..  5]   flags   (NBD_CMD_FLAG_FUA, ...)
1520      *  [ 6 ..  7]   type    (NBD_CMD_READ, ...)
1521      *  [ 8 .. 15]   cookie
1522      *  [16 .. 23]   from
1523      *  [24 .. 27]   len
1524      * Extended request
1525      *  [ 0 ..  3]   magic   (NBD_EXTENDED_REQUEST_MAGIC)
1526      *  [ 4 ..  5]   flags   (NBD_CMD_FLAG_FUA, NBD_CMD_FLAG_PAYLOAD_LEN, ...)
1527      *  [ 6 ..  7]   type    (NBD_CMD_READ, ...)
1528      *  [ 8 .. 15]   cookie
1529      *  [16 .. 23]   from
1530      *  [24 .. 31]   len
1531      */
1532 
1533     magic = ldl_be_p(buf);
1534     request->flags  = lduw_be_p(buf + 4);
1535     request->type   = lduw_be_p(buf + 6);
1536     request->cookie = ldq_be_p(buf + 8);
1537     request->from   = ldq_be_p(buf + 16);
1538     if (client->mode >= NBD_MODE_EXTENDED) {
1539         request->len = ldq_be_p(buf + 24);
1540         expect = NBD_EXTENDED_REQUEST_MAGIC;
1541     } else {
1542         request->len = (uint32_t)ldl_be_p(buf + 24); /* widen 32 to 64 bits */
1543         expect = NBD_REQUEST_MAGIC;
1544     }
1545 
1546     trace_nbd_receive_request(magic, request->flags, request->type,
1547                               request->from, request->len);
1548 
1549     if (magic != expect) {
1550         error_setg(errp, "invalid magic (got 0x%" PRIx32 ", expected 0x%"
1551                    PRIx32 ")", magic, expect);
1552         return -EINVAL;
1553     }
1554     return 0;
1555 }
1556 
1557 #define MAX_NBD_REQUESTS 16
1558 
1559 /* Runs in export AioContext and main loop thread */
1560 void nbd_client_get(NBDClient *client)
1561 {
1562     qatomic_inc(&client->refcount);
1563 }
1564 
1565 void nbd_client_put(NBDClient *client)
1566 {
1567     assert(qemu_in_main_thread());
1568 
1569     if (qatomic_fetch_dec(&client->refcount) == 1) {
1570         /* The last reference should be dropped by client->close,
1571          * which is called by client_close.
1572          */
1573         assert(client->closing);
1574 
1575         object_unref(OBJECT(client->sioc));
1576         object_unref(OBJECT(client->ioc));
1577         if (client->tlscreds) {
1578             object_unref(OBJECT(client->tlscreds));
1579         }
1580         g_free(client->tlsauthz);
1581         if (client->exp) {
1582             QTAILQ_REMOVE(&client->exp->clients, client, next);
1583             blk_exp_unref(&client->exp->common);
1584         }
1585         g_free(client->contexts.bitmaps);
1586         qemu_mutex_destroy(&client->lock);
1587         g_free(client);
1588     }
1589 }
1590 
1591 /*
1592  * Tries to release the reference to @client, but only if other references
1593  * remain. This is an optimization for the common case where we want to avoid
1594  * the expense of scheduling nbd_client_put() in the main loop thread.
1595  *
1596  * Returns true upon success or false if the reference was not released because
1597  * it is the last reference.
1598  */
1599 static bool nbd_client_put_nonzero(NBDClient *client)
1600 {
1601     int old = qatomic_read(&client->refcount);
1602     int expected;
1603 
1604     do {
1605         if (old == 1) {
1606             return false;
1607         }
1608 
1609         expected = old;
1610         old = qatomic_cmpxchg(&client->refcount, expected, expected - 1);
1611     } while (old != expected);
1612 
1613     return true;
1614 }
1615 
1616 static void client_close(NBDClient *client, bool negotiated)
1617 {
1618     assert(qemu_in_main_thread());
1619 
1620     WITH_QEMU_LOCK_GUARD(&client->lock) {
1621         if (client->closing) {
1622             return;
1623         }
1624 
1625         client->closing = true;
1626     }
1627 
1628     /* Force requests to finish.  They will drop their own references,
1629      * then we'll close the socket and free the NBDClient.
1630      */
1631     qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
1632                          NULL);
1633 
1634     /* Also tell the client, so that they release their reference.  */
1635     if (client->close_fn) {
1636         client->close_fn(client, negotiated);
1637     }
1638 }
1639 
1640 /* Runs in export AioContext with client->lock held */
1641 static NBDRequestData *nbd_request_get(NBDClient *client)
1642 {
1643     NBDRequestData *req;
1644 
1645     assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
1646     client->nb_requests++;
1647 
1648     req = g_new0(NBDRequestData, 1);
1649     req->client = client;
1650     return req;
1651 }
1652 
1653 /* Runs in export AioContext with client->lock held */
1654 static void nbd_request_put(NBDRequestData *req)
1655 {
1656     NBDClient *client = req->client;
1657 
1658     if (req->data) {
1659         qemu_vfree(req->data);
1660     }
1661     g_free(req);
1662 
1663     client->nb_requests--;
1664 
1665     if (client->quiescing && client->nb_requests == 0) {
1666         aio_wait_kick();
1667     }
1668 
1669     nbd_client_receive_next_request(client);
1670 }
1671 
1672 static void blk_aio_attached(AioContext *ctx, void *opaque)
1673 {
1674     NBDExport *exp = opaque;
1675     NBDClient *client;
1676 
1677     assert(qemu_in_main_thread());
1678 
1679     trace_nbd_blk_aio_attached(exp->name, ctx);
1680 
1681     exp->common.ctx = ctx;
1682 
1683     QTAILQ_FOREACH(client, &exp->clients, next) {
1684         WITH_QEMU_LOCK_GUARD(&client->lock) {
1685             assert(client->nb_requests == 0);
1686             assert(client->recv_coroutine == NULL);
1687             assert(client->send_coroutine == NULL);
1688         }
1689     }
1690 }
1691 
1692 static void blk_aio_detach(void *opaque)
1693 {
1694     NBDExport *exp = opaque;
1695 
1696     assert(qemu_in_main_thread());
1697 
1698     trace_nbd_blk_aio_detach(exp->name, exp->common.ctx);
1699 
1700     exp->common.ctx = NULL;
1701 }
1702 
1703 static void nbd_drained_begin(void *opaque)
1704 {
1705     NBDExport *exp = opaque;
1706     NBDClient *client;
1707 
1708     assert(qemu_in_main_thread());
1709 
1710     QTAILQ_FOREACH(client, &exp->clients, next) {
1711         WITH_QEMU_LOCK_GUARD(&client->lock) {
1712             client->quiescing = true;
1713         }
1714     }
1715 }
1716 
1717 static void nbd_drained_end(void *opaque)
1718 {
1719     NBDExport *exp = opaque;
1720     NBDClient *client;
1721 
1722     assert(qemu_in_main_thread());
1723 
1724     QTAILQ_FOREACH(client, &exp->clients, next) {
1725         WITH_QEMU_LOCK_GUARD(&client->lock) {
1726             client->quiescing = false;
1727             nbd_client_receive_next_request(client);
1728         }
1729     }
1730 }
1731 
1732 /* Runs in export AioContext */
1733 static void nbd_wake_read_bh(void *opaque)
1734 {
1735     NBDClient *client = opaque;
1736     qio_channel_wake_read(client->ioc);
1737 }
1738 
1739 static bool nbd_drained_poll(void *opaque)
1740 {
1741     NBDExport *exp = opaque;
1742     NBDClient *client;
1743 
1744     assert(qemu_in_main_thread());
1745 
1746     QTAILQ_FOREACH(client, &exp->clients, next) {
1747         WITH_QEMU_LOCK_GUARD(&client->lock) {
1748             if (client->nb_requests != 0) {
1749                 /*
1750                  * If there's a coroutine waiting for a request on nbd_read_eof()
1751                  * enter it here so we don't depend on the client to wake it up.
1752                  *
1753                  * Schedule a BH in the export AioContext to avoid missing the
1754                  * wake up due to the race between qio_channel_wake_read() and
1755                  * qio_channel_yield().
1756                  */
1757                 if (client->recv_coroutine != NULL && client->read_yielding) {
1758                     aio_bh_schedule_oneshot(nbd_export_aio_context(client->exp),
1759                                             nbd_wake_read_bh, client);
1760                 }
1761 
1762                 return true;
1763             }
1764         }
1765     }
1766 
1767     return false;
1768 }
1769 
1770 static void nbd_eject_notifier(Notifier *n, void *data)
1771 {
1772     NBDExport *exp = container_of(n, NBDExport, eject_notifier);
1773 
1774     assert(qemu_in_main_thread());
1775 
1776     blk_exp_request_shutdown(&exp->common);
1777 }
1778 
1779 void nbd_export_set_on_eject_blk(BlockExport *exp, BlockBackend *blk)
1780 {
1781     NBDExport *nbd_exp = container_of(exp, NBDExport, common);
1782     assert(exp->drv == &blk_exp_nbd);
1783     assert(nbd_exp->eject_notifier_blk == NULL);
1784 
1785     blk_ref(blk);
1786     nbd_exp->eject_notifier_blk = blk;
1787     nbd_exp->eject_notifier.notify = nbd_eject_notifier;
1788     blk_add_remove_bs_notifier(blk, &nbd_exp->eject_notifier);
1789 }
1790 
1791 static const BlockDevOps nbd_block_ops = {
1792     .drained_begin = nbd_drained_begin,
1793     .drained_end = nbd_drained_end,
1794     .drained_poll = nbd_drained_poll,
1795 };
1796 
1797 static int nbd_export_create(BlockExport *blk_exp, BlockExportOptions *exp_args,
1798                              Error **errp)
1799 {
1800     NBDExport *exp = container_of(blk_exp, NBDExport, common);
1801     BlockExportOptionsNbd *arg = &exp_args->u.nbd;
1802     const char *name = arg->name ?: exp_args->node_name;
1803     BlockBackend *blk = blk_exp->blk;
1804     int64_t size;
1805     uint64_t perm, shared_perm;
1806     bool readonly = !exp_args->writable;
1807     BlockDirtyBitmapOrStrList *bitmaps;
1808     size_t i;
1809     int ret;
1810 
1811     GLOBAL_STATE_CODE();
1812     assert(exp_args->type == BLOCK_EXPORT_TYPE_NBD);
1813 
1814     if (!nbd_server_is_running()) {
1815         error_setg(errp, "NBD server not running");
1816         return -EINVAL;
1817     }
1818 
1819     if (strlen(name) > NBD_MAX_STRING_SIZE) {
1820         error_setg(errp, "export name '%s' too long", name);
1821         return -EINVAL;
1822     }
1823 
1824     if (arg->description && strlen(arg->description) > NBD_MAX_STRING_SIZE) {
1825         error_setg(errp, "description '%s' too long", arg->description);
1826         return -EINVAL;
1827     }
1828 
1829     if (nbd_export_find(name)) {
1830         error_setg(errp, "NBD server already has export named '%s'", name);
1831         return -EEXIST;
1832     }
1833 
1834     size = blk_getlength(blk);
1835     if (size < 0) {
1836         error_setg_errno(errp, -size,
1837                          "Failed to determine the NBD export's length");
1838         return size;
1839     }
1840 
1841     /* Don't allow resize while the NBD server is running, otherwise we don't
1842      * care what happens with the node. */
1843     blk_get_perm(blk, &perm, &shared_perm);
1844     ret = blk_set_perm(blk, perm, shared_perm & ~BLK_PERM_RESIZE, errp);
1845     if (ret < 0) {
1846         return ret;
1847     }
1848 
1849     QTAILQ_INIT(&exp->clients);
1850     exp->name = g_strdup(name);
1851     exp->description = g_strdup(arg->description);
1852     exp->nbdflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_FLUSH |
1853                      NBD_FLAG_SEND_FUA | NBD_FLAG_SEND_CACHE);
1854 
1855     if (nbd_server_max_connections() != 1) {
1856         exp->nbdflags |= NBD_FLAG_CAN_MULTI_CONN;
1857     }
1858     if (readonly) {
1859         exp->nbdflags |= NBD_FLAG_READ_ONLY;
1860     } else {
1861         exp->nbdflags |= (NBD_FLAG_SEND_TRIM | NBD_FLAG_SEND_WRITE_ZEROES |
1862                           NBD_FLAG_SEND_FAST_ZERO);
1863     }
1864     exp->size = QEMU_ALIGN_DOWN(size, BDRV_SECTOR_SIZE);
1865 
1866     bdrv_graph_rdlock_main_loop();
1867 
1868     for (bitmaps = arg->bitmaps; bitmaps; bitmaps = bitmaps->next) {
1869         exp->nr_export_bitmaps++;
1870     }
1871     exp->export_bitmaps = g_new0(BdrvDirtyBitmap *, exp->nr_export_bitmaps);
1872     for (i = 0, bitmaps = arg->bitmaps; bitmaps;
1873          i++, bitmaps = bitmaps->next)
1874     {
1875         const char *bitmap;
1876         BlockDriverState *bs = blk_bs(blk);
1877         BdrvDirtyBitmap *bm = NULL;
1878 
1879         switch (bitmaps->value->type) {
1880         case QTYPE_QSTRING:
1881             bitmap = bitmaps->value->u.local;
1882             while (bs) {
1883                 bm = bdrv_find_dirty_bitmap(bs, bitmap);
1884                 if (bm != NULL) {
1885                     break;
1886                 }
1887 
1888                 bs = bdrv_filter_or_cow_bs(bs);
1889             }
1890 
1891             if (bm == NULL) {
1892                 ret = -ENOENT;
1893                 error_setg(errp, "Bitmap '%s' is not found",
1894                            bitmaps->value->u.local);
1895                 goto fail;
1896             }
1897 
1898             if (readonly && bdrv_is_writable(bs) &&
1899                 bdrv_dirty_bitmap_enabled(bm)) {
1900                 ret = -EINVAL;
1901                 error_setg(errp, "Enabled bitmap '%s' incompatible with "
1902                            "readonly export", bitmap);
1903                 goto fail;
1904             }
1905             break;
1906         case QTYPE_QDICT:
1907             bitmap = bitmaps->value->u.external.name;
1908             bm = block_dirty_bitmap_lookup(bitmaps->value->u.external.node,
1909                                            bitmap, NULL, errp);
1910             if (!bm) {
1911                 ret = -ENOENT;
1912                 goto fail;
1913             }
1914             break;
1915         default:
1916             abort();
1917         }
1918 
1919         assert(bm);
1920 
1921         if (bdrv_dirty_bitmap_check(bm, BDRV_BITMAP_ALLOW_RO, errp)) {
1922             ret = -EINVAL;
1923             goto fail;
1924         }
1925 
1926         exp->export_bitmaps[i] = bm;
1927         assert(strlen(bitmap) <= BDRV_BITMAP_MAX_NAME_SIZE);
1928     }
1929 
1930     /* Mark bitmaps busy in a separate loop, to simplify roll-back concerns. */
1931     for (i = 0; i < exp->nr_export_bitmaps; i++) {
1932         bdrv_dirty_bitmap_set_busy(exp->export_bitmaps[i], true);
1933     }
1934 
1935     exp->allocation_depth = arg->allocation_depth;
1936 
1937     /*
1938      * We need to inhibit request queuing in the block layer to ensure we can
1939      * be properly quiesced when entering a drained section, as our coroutines
1940      * servicing pending requests might enter blk_pread().
1941      */
1942     blk_set_disable_request_queuing(blk, true);
1943 
1944     blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
1945 
1946     blk_set_dev_ops(blk, &nbd_block_ops, exp);
1947 
1948     QTAILQ_INSERT_TAIL(&exports, exp, next);
1949 
1950     bdrv_graph_rdunlock_main_loop();
1951 
1952     return 0;
1953 
1954 fail:
1955     bdrv_graph_rdunlock_main_loop();
1956     g_free(exp->export_bitmaps);
1957     g_free(exp->name);
1958     g_free(exp->description);
1959     return ret;
1960 }
1961 
1962 NBDExport *nbd_export_find(const char *name)
1963 {
1964     NBDExport *exp;
1965     QTAILQ_FOREACH(exp, &exports, next) {
1966         if (strcmp(name, exp->name) == 0) {
1967             return exp;
1968         }
1969     }
1970 
1971     return NULL;
1972 }
1973 
1974 AioContext *
1975 nbd_export_aio_context(NBDExport *exp)
1976 {
1977     return exp->common.ctx;
1978 }
1979 
1980 static void nbd_export_request_shutdown(BlockExport *blk_exp)
1981 {
1982     NBDExport *exp = container_of(blk_exp, NBDExport, common);
1983     NBDClient *client, *next;
1984 
1985     blk_exp_ref(&exp->common);
1986     /*
1987      * TODO: Should we expand QMP BlockExportRemoveMode enum to allow a
1988      * close mode that stops advertising the export to new clients but
1989      * still permits existing clients to run to completion? Because of
1990      * that possibility, nbd_export_close() can be called more than
1991      * once on an export.
1992      */
1993     QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
1994         client_close(client, true);
1995     }
1996     if (exp->name) {
1997         g_free(exp->name);
1998         exp->name = NULL;
1999         QTAILQ_REMOVE(&exports, exp, next);
2000     }
2001     blk_exp_unref(&exp->common);
2002 }
2003 
2004 static void nbd_export_delete(BlockExport *blk_exp)
2005 {
2006     size_t i;
2007     NBDExport *exp = container_of(blk_exp, NBDExport, common);
2008 
2009     assert(exp->name == NULL);
2010     assert(QTAILQ_EMPTY(&exp->clients));
2011 
2012     g_free(exp->description);
2013     exp->description = NULL;
2014 
2015     if (exp->eject_notifier_blk) {
2016         notifier_remove(&exp->eject_notifier);
2017         blk_unref(exp->eject_notifier_blk);
2018     }
2019     blk_remove_aio_context_notifier(exp->common.blk, blk_aio_attached,
2020                                     blk_aio_detach, exp);
2021     blk_set_disable_request_queuing(exp->common.blk, false);
2022 
2023     for (i = 0; i < exp->nr_export_bitmaps; i++) {
2024         bdrv_dirty_bitmap_set_busy(exp->export_bitmaps[i], false);
2025     }
2026 }
2027 
2028 const BlockExportDriver blk_exp_nbd = {
2029     .type               = BLOCK_EXPORT_TYPE_NBD,
2030     .instance_size      = sizeof(NBDExport),
2031     .supports_inactive  = true,
2032     .create             = nbd_export_create,
2033     .delete             = nbd_export_delete,
2034     .request_shutdown   = nbd_export_request_shutdown,
2035 };
2036 
2037 static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov,
2038                                         unsigned niov, Error **errp)
2039 {
2040     int ret;
2041 
2042     g_assert(qemu_in_coroutine());
2043     qemu_co_mutex_lock(&client->send_lock);
2044     client->send_coroutine = qemu_coroutine_self();
2045 
2046     ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0;
2047 
2048     client->send_coroutine = NULL;
2049     qemu_co_mutex_unlock(&client->send_lock);
2050 
2051     return ret;
2052 }
2053 
2054 static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
2055                                        uint64_t cookie)
2056 {
2057     stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
2058     stl_be_p(&reply->error, error);
2059     stq_be_p(&reply->cookie, cookie);
2060 }
2061 
2062 static int coroutine_fn nbd_co_send_simple_reply(NBDClient *client,
2063                                                  NBDRequest *request,
2064                                                  uint32_t error,
2065                                                  void *data,
2066                                                  uint64_t len,
2067                                                  Error **errp)
2068 {
2069     NBDSimpleReply reply;
2070     int nbd_err = system_errno_to_nbd_errno(error);
2071     struct iovec iov[] = {
2072         {.iov_base = &reply, .iov_len = sizeof(reply)},
2073         {.iov_base = data, .iov_len = len}
2074     };
2075 
2076     assert(!len || !nbd_err);
2077     assert(len <= NBD_MAX_BUFFER_SIZE);
2078     assert(client->mode < NBD_MODE_STRUCTURED ||
2079            (client->mode == NBD_MODE_STRUCTURED &&
2080             request->type != NBD_CMD_READ));
2081     trace_nbd_co_send_simple_reply(request->cookie, nbd_err,
2082                                    nbd_err_lookup(nbd_err), len);
2083     set_be_simple_reply(&reply, nbd_err, request->cookie);
2084 
2085     return nbd_co_send_iov(client, iov, 2, errp);
2086 }
2087 
2088 /*
2089  * Prepare the header of a reply chunk for network transmission.
2090  *
2091  * On input, @iov is partially initialized: iov[0].iov_base must point
2092  * to an uninitialized NBDReply, while the remaining @niov elements
2093  * (if any) must be ready for transmission.  This function then
2094  * populates iov[0] for transmission.
2095  */
2096 static inline void set_be_chunk(NBDClient *client, struct iovec *iov,
2097                                 size_t niov, uint16_t flags, uint16_t type,
2098                                 NBDRequest *request)
2099 {
2100     size_t i, length = 0;
2101 
2102     for (i = 1; i < niov; i++) {
2103         length += iov[i].iov_len;
2104     }
2105     assert(length <= NBD_MAX_BUFFER_SIZE + sizeof(NBDStructuredReadData));
2106 
2107     if (client->mode >= NBD_MODE_EXTENDED) {
2108         NBDExtendedReplyChunk *chunk = iov->iov_base;
2109 
2110         iov[0].iov_len = sizeof(*chunk);
2111         stl_be_p(&chunk->magic, NBD_EXTENDED_REPLY_MAGIC);
2112         stw_be_p(&chunk->flags, flags);
2113         stw_be_p(&chunk->type, type);
2114         stq_be_p(&chunk->cookie, request->cookie);
2115         stq_be_p(&chunk->offset, request->from);
2116         stq_be_p(&chunk->length, length);
2117     } else {
2118         NBDStructuredReplyChunk *chunk = iov->iov_base;
2119 
2120         iov[0].iov_len = sizeof(*chunk);
2121         stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC);
2122         stw_be_p(&chunk->flags, flags);
2123         stw_be_p(&chunk->type, type);
2124         stq_be_p(&chunk->cookie, request->cookie);
2125         stl_be_p(&chunk->length, length);
2126     }
2127 }
2128 
2129 static int coroutine_fn nbd_co_send_chunk_done(NBDClient *client,
2130                                                NBDRequest *request,
2131                                                Error **errp)
2132 {
2133     NBDReply hdr;
2134     struct iovec iov[] = {
2135         {.iov_base = &hdr},
2136     };
2137 
2138     trace_nbd_co_send_chunk_done(request->cookie);
2139     set_be_chunk(client, iov, 1, NBD_REPLY_FLAG_DONE,
2140                  NBD_REPLY_TYPE_NONE, request);
2141     return nbd_co_send_iov(client, iov, 1, errp);
2142 }
2143 
2144 static int coroutine_fn nbd_co_send_chunk_read(NBDClient *client,
2145                                                NBDRequest *request,
2146                                                uint64_t offset,
2147                                                void *data,
2148                                                uint64_t size,
2149                                                bool final,
2150                                                Error **errp)
2151 {
2152     NBDReply hdr;
2153     NBDStructuredReadData chunk;
2154     struct iovec iov[] = {
2155         {.iov_base = &hdr},
2156         {.iov_base = &chunk, .iov_len = sizeof(chunk)},
2157         {.iov_base = data, .iov_len = size}
2158     };
2159 
2160     assert(size && size <= NBD_MAX_BUFFER_SIZE);
2161     trace_nbd_co_send_chunk_read(request->cookie, offset, data, size);
2162     set_be_chunk(client, iov, 3, final ? NBD_REPLY_FLAG_DONE : 0,
2163                  NBD_REPLY_TYPE_OFFSET_DATA, request);
2164     stq_be_p(&chunk.offset, offset);
2165 
2166     return nbd_co_send_iov(client, iov, 3, errp);
2167 }
2168 
2169 static int coroutine_fn nbd_co_send_chunk_error(NBDClient *client,
2170                                                 NBDRequest *request,
2171                                                 uint32_t error,
2172                                                 const char *msg,
2173                                                 Error **errp)
2174 {
2175     NBDReply hdr;
2176     NBDStructuredError chunk;
2177     int nbd_err = system_errno_to_nbd_errno(error);
2178     struct iovec iov[] = {
2179         {.iov_base = &hdr},
2180         {.iov_base = &chunk, .iov_len = sizeof(chunk)},
2181         {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0},
2182     };
2183 
2184     assert(nbd_err);
2185     trace_nbd_co_send_chunk_error(request->cookie, nbd_err,
2186                                   nbd_err_lookup(nbd_err), msg ? msg : "");
2187     set_be_chunk(client, iov, 3, NBD_REPLY_FLAG_DONE,
2188                  NBD_REPLY_TYPE_ERROR, request);
2189     stl_be_p(&chunk.error, nbd_err);
2190     stw_be_p(&chunk.message_length, iov[2].iov_len);
2191 
2192     return nbd_co_send_iov(client, iov, 3, errp);
2193 }
2194 
2195 /* Do a sparse read and send the structured reply to the client.
2196  * Returns -errno if sending fails. blk_co_block_status_above() failure is
2197  * reported to the client, at which point this function succeeds.
2198  */
2199 static int coroutine_fn nbd_co_send_sparse_read(NBDClient *client,
2200                                                 NBDRequest *request,
2201                                                 uint64_t offset,
2202                                                 uint8_t *data,
2203                                                 uint64_t size,
2204                                                 Error **errp)
2205 {
2206     int ret = 0;
2207     NBDExport *exp = client->exp;
2208     size_t progress = 0;
2209 
2210     assert(size <= NBD_MAX_BUFFER_SIZE);
2211     while (progress < size) {
2212         int64_t pnum;
2213         int status = blk_co_block_status_above(exp->common.blk, NULL,
2214                                                offset + progress,
2215                                                size - progress, &pnum, NULL,
2216                                                NULL);
2217         bool final;
2218 
2219         if (status < 0) {
2220             char *msg = g_strdup_printf("unable to check for holes: %s",
2221                                         strerror(-status));
2222 
2223             ret = nbd_co_send_chunk_error(client, request, -status, msg, errp);
2224             g_free(msg);
2225             return ret;
2226         }
2227         assert(pnum && pnum <= size - progress);
2228         final = progress + pnum == size;
2229         if (status & BDRV_BLOCK_ZERO) {
2230             NBDReply hdr;
2231             NBDStructuredReadHole chunk;
2232             struct iovec iov[] = {
2233                 {.iov_base = &hdr},
2234                 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
2235             };
2236 
2237             trace_nbd_co_send_chunk_read_hole(request->cookie,
2238                                               offset + progress, pnum);
2239             set_be_chunk(client, iov, 2,
2240                          final ? NBD_REPLY_FLAG_DONE : 0,
2241                          NBD_REPLY_TYPE_OFFSET_HOLE, request);
2242             stq_be_p(&chunk.offset, offset + progress);
2243             stl_be_p(&chunk.length, pnum);
2244             ret = nbd_co_send_iov(client, iov, 2, errp);
2245         } else {
2246             ret = blk_co_pread(exp->common.blk, offset + progress, pnum,
2247                                data + progress, 0);
2248             if (ret < 0) {
2249                 error_setg_errno(errp, -ret, "reading from file failed");
2250                 break;
2251             }
2252             ret = nbd_co_send_chunk_read(client, request, offset + progress,
2253                                          data + progress, pnum, final, errp);
2254         }
2255 
2256         if (ret < 0) {
2257             break;
2258         }
2259         progress += pnum;
2260     }
2261     return ret;
2262 }
2263 
2264 typedef struct NBDExtentArray {
2265     NBDExtent64 *extents;
2266     unsigned int nb_alloc;
2267     unsigned int count;
2268     uint64_t total_length;
2269     bool extended;
2270     bool can_add;
2271     bool converted_to_be;
2272 } NBDExtentArray;
2273 
2274 static NBDExtentArray *nbd_extent_array_new(unsigned int nb_alloc,
2275                                             NBDMode mode)
2276 {
2277     NBDExtentArray *ea = g_new0(NBDExtentArray, 1);
2278 
2279     assert(mode >= NBD_MODE_STRUCTURED);
2280     ea->nb_alloc = nb_alloc;
2281     ea->extents = g_new(NBDExtent64, nb_alloc);
2282     ea->extended = mode >= NBD_MODE_EXTENDED;
2283     ea->can_add = true;
2284 
2285     return ea;
2286 }
2287 
2288 static void nbd_extent_array_free(NBDExtentArray *ea)
2289 {
2290     g_free(ea->extents);
2291     g_free(ea);
2292 }
2293 G_DEFINE_AUTOPTR_CLEANUP_FUNC(NBDExtentArray, nbd_extent_array_free)
2294 
2295 /* Further modifications of the array after conversion are abandoned */
2296 static void nbd_extent_array_convert_to_be(NBDExtentArray *ea)
2297 {
2298     int i;
2299 
2300     assert(!ea->converted_to_be);
2301     assert(ea->extended);
2302     ea->can_add = false;
2303     ea->converted_to_be = true;
2304 
2305     for (i = 0; i < ea->count; i++) {
2306         ea->extents[i].length = cpu_to_be64(ea->extents[i].length);
2307         ea->extents[i].flags = cpu_to_be64(ea->extents[i].flags);
2308     }
2309 }
2310 
2311 /* Further modifications of the array after conversion are abandoned */
2312 static NBDExtent32 *nbd_extent_array_convert_to_narrow(NBDExtentArray *ea)
2313 {
2314     int i;
2315     NBDExtent32 *extents = g_new(NBDExtent32, ea->count);
2316 
2317     assert(!ea->converted_to_be);
2318     assert(!ea->extended);
2319     ea->can_add = false;
2320     ea->converted_to_be = true;
2321 
2322     for (i = 0; i < ea->count; i++) {
2323         assert((ea->extents[i].length | ea->extents[i].flags) <= UINT32_MAX);
2324         extents[i].length = cpu_to_be32(ea->extents[i].length);
2325         extents[i].flags = cpu_to_be32(ea->extents[i].flags);
2326     }
2327 
2328     return extents;
2329 }
2330 
2331 /*
2332  * Add extent to NBDExtentArray. If extent can't be added (no available space),
2333  * return -1.
2334  * For safety, when returning -1 for the first time, .can_add is set to false,
2335  * and further calls to nbd_extent_array_add() will crash.
2336  * (this avoids the situation where a caller ignores failure to add one extent,
2337  * where adding another extent that would squash into the last array entry
2338  * would result in an incorrect range reported to the client)
2339  */
2340 static int nbd_extent_array_add(NBDExtentArray *ea,
2341                                 uint64_t length, uint32_t flags)
2342 {
2343     assert(ea->can_add);
2344 
2345     if (!length) {
2346         return 0;
2347     }
2348     if (!ea->extended) {
2349         assert(length <= UINT32_MAX);
2350     }
2351 
2352     /* Extend previous extent if flags are the same */
2353     if (ea->count > 0 && flags == ea->extents[ea->count - 1].flags) {
2354         uint64_t sum = length + ea->extents[ea->count - 1].length;
2355 
2356         /*
2357          * sum cannot overflow: the block layer bounds image size at
2358          * 2^63, and ea->extents[].length comes from the block layer.
2359          */
2360         assert(sum >= length);
2361         if (sum <= UINT32_MAX || ea->extended) {
2362             ea->extents[ea->count - 1].length = sum;
2363             ea->total_length += length;
2364             return 0;
2365         }
2366     }
2367 
2368     if (ea->count >= ea->nb_alloc) {
2369         ea->can_add = false;
2370         return -1;
2371     }
2372 
2373     ea->total_length += length;
2374     ea->extents[ea->count] = (NBDExtent64) {.length = length, .flags = flags};
2375     ea->count++;
2376 
2377     return 0;
2378 }
2379 
2380 static int coroutine_fn blockstatus_to_extents(BlockBackend *blk,
2381                                                uint64_t offset, uint64_t bytes,
2382                                                NBDExtentArray *ea)
2383 {
2384     while (bytes) {
2385         uint32_t flags;
2386         int64_t num;
2387         int ret = blk_co_block_status_above(blk, NULL, offset, bytes, &num,
2388                                             NULL, NULL);
2389 
2390         if (ret < 0) {
2391             return ret;
2392         }
2393 
2394         flags = (ret & BDRV_BLOCK_DATA ? 0 : NBD_STATE_HOLE) |
2395                 (ret & BDRV_BLOCK_ZERO ? NBD_STATE_ZERO : 0);
2396 
2397         if (nbd_extent_array_add(ea, num, flags) < 0) {
2398             return 0;
2399         }
2400 
2401         offset += num;
2402         bytes -= num;
2403     }
2404 
2405     return 0;
2406 }
2407 
2408 static int coroutine_fn blockalloc_to_extents(BlockBackend *blk,
2409                                               uint64_t offset, uint64_t bytes,
2410                                               NBDExtentArray *ea)
2411 {
2412     while (bytes) {
2413         int64_t num;
2414         int ret = blk_co_is_allocated_above(blk, NULL, false, offset, bytes,
2415                                             &num);
2416 
2417         if (ret < 0) {
2418             return ret;
2419         }
2420 
2421         if (nbd_extent_array_add(ea, num, ret) < 0) {
2422             return 0;
2423         }
2424 
2425         offset += num;
2426         bytes -= num;
2427     }
2428 
2429     return 0;
2430 }
2431 
2432 /*
2433  * nbd_co_send_extents
2434  *
2435  * @ea is converted to BE by the function
2436  * @last controls whether NBD_REPLY_FLAG_DONE is sent.
2437  */
2438 static int coroutine_fn
2439 nbd_co_send_extents(NBDClient *client, NBDRequest *request, NBDExtentArray *ea,
2440                     bool last, uint32_t context_id, Error **errp)
2441 {
2442     NBDReply hdr;
2443     NBDStructuredMeta meta;
2444     NBDExtendedMeta meta_ext;
2445     g_autofree NBDExtent32 *extents = NULL;
2446     uint16_t type;
2447     struct iovec iov[] = { {.iov_base = &hdr}, {0}, {0} };
2448 
2449     if (client->mode >= NBD_MODE_EXTENDED) {
2450         type = NBD_REPLY_TYPE_BLOCK_STATUS_EXT;
2451 
2452         iov[1].iov_base = &meta_ext;
2453         iov[1].iov_len = sizeof(meta_ext);
2454         stl_be_p(&meta_ext.context_id, context_id);
2455         stl_be_p(&meta_ext.count, ea->count);
2456 
2457         nbd_extent_array_convert_to_be(ea);
2458         iov[2].iov_base = ea->extents;
2459         iov[2].iov_len = ea->count * sizeof(ea->extents[0]);
2460     } else {
2461         type = NBD_REPLY_TYPE_BLOCK_STATUS;
2462 
2463         iov[1].iov_base = &meta;
2464         iov[1].iov_len = sizeof(meta);
2465         stl_be_p(&meta.context_id, context_id);
2466 
2467         extents = nbd_extent_array_convert_to_narrow(ea);
2468         iov[2].iov_base = extents;
2469         iov[2].iov_len = ea->count * sizeof(extents[0]);
2470     }
2471 
2472     trace_nbd_co_send_extents(request->cookie, ea->count, context_id,
2473                               ea->total_length, last);
2474     set_be_chunk(client, iov, 3, last ? NBD_REPLY_FLAG_DONE : 0, type,
2475                  request);
2476 
2477     return nbd_co_send_iov(client, iov, 3, errp);
2478 }
2479 
2480 /* Get block status from the exported device and send it to the client */
2481 static int
2482 coroutine_fn nbd_co_send_block_status(NBDClient *client, NBDRequest *request,
2483                                       BlockBackend *blk, uint64_t offset,
2484                                       uint64_t length, bool dont_fragment,
2485                                       bool last, uint32_t context_id,
2486                                       Error **errp)
2487 {
2488     int ret;
2489     unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
2490     g_autoptr(NBDExtentArray) ea =
2491         nbd_extent_array_new(nb_extents, client->mode);
2492 
2493     if (context_id == NBD_META_ID_BASE_ALLOCATION) {
2494         ret = blockstatus_to_extents(blk, offset, length, ea);
2495     } else {
2496         ret = blockalloc_to_extents(blk, offset, length, ea);
2497     }
2498     if (ret < 0) {
2499         return nbd_co_send_chunk_error(client, request, -ret,
2500                                        "can't get block status", errp);
2501     }
2502 
2503     return nbd_co_send_extents(client, request, ea, last, context_id, errp);
2504 }
2505 
2506 /* Populate @ea from a dirty bitmap. */
2507 static void bitmap_to_extents(BdrvDirtyBitmap *bitmap,
2508                               uint64_t offset, uint64_t length,
2509                               NBDExtentArray *es)
2510 {
2511     int64_t start, dirty_start, dirty_count;
2512     int64_t end = offset + length;
2513     bool full = false;
2514     int64_t bound = es->extended ? INT64_MAX : INT32_MAX;
2515 
2516     bdrv_dirty_bitmap_lock(bitmap);
2517 
2518     for (start = offset;
2519          bdrv_dirty_bitmap_next_dirty_area(bitmap, start, end, bound,
2520                                            &dirty_start, &dirty_count);
2521          start = dirty_start + dirty_count)
2522     {
2523         if ((nbd_extent_array_add(es, dirty_start - start, 0) < 0) ||
2524             (nbd_extent_array_add(es, dirty_count, NBD_STATE_DIRTY) < 0))
2525         {
2526             full = true;
2527             break;
2528         }
2529     }
2530 
2531     if (!full) {
2532         /* last non dirty extent, nothing to do if array is now full */
2533         (void) nbd_extent_array_add(es, end - start, 0);
2534     }
2535 
2536     bdrv_dirty_bitmap_unlock(bitmap);
2537 }
2538 
2539 static int coroutine_fn nbd_co_send_bitmap(NBDClient *client,
2540                                            NBDRequest *request,
2541                                            BdrvDirtyBitmap *bitmap,
2542                                            uint64_t offset,
2543                                            uint64_t length, bool dont_fragment,
2544                                            bool last, uint32_t context_id,
2545                                            Error **errp)
2546 {
2547     unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
2548     g_autoptr(NBDExtentArray) ea =
2549         nbd_extent_array_new(nb_extents, client->mode);
2550 
2551     bitmap_to_extents(bitmap, offset, length, ea);
2552 
2553     return nbd_co_send_extents(client, request, ea, last, context_id, errp);
2554 }
2555 
2556 /*
2557  * nbd_co_block_status_payload_read
2558  * Called when a client wants a subset of negotiated contexts via a
2559  * BLOCK_STATUS payload.  Check the payload for valid length and
2560  * contents.  On success, return 0 with request updated to effective
2561  * length.  If request was invalid but all payload consumed, return 0
2562  * with request->len and request->contexts->count set to 0 (which will
2563  * trigger an appropriate NBD_EINVAL response later on).  Return
2564  * negative errno if the payload was not fully consumed.
2565  */
2566 static int
2567 nbd_co_block_status_payload_read(NBDClient *client, NBDRequest *request,
2568                                  Error **errp)
2569 {
2570     uint64_t payload_len = request->len;
2571     g_autofree char *buf = NULL;
2572     size_t count, i, nr_bitmaps;
2573     uint32_t id;
2574 
2575     if (payload_len > NBD_MAX_BUFFER_SIZE) {
2576         error_setg(errp, "len (%" PRIu64 ") is larger than max len (%u)",
2577                    request->len, NBD_MAX_BUFFER_SIZE);
2578         return -EINVAL;
2579     }
2580 
2581     assert(client->contexts.exp == client->exp);
2582     nr_bitmaps = client->exp->nr_export_bitmaps;
2583     request->contexts = g_new0(NBDMetaContexts, 1);
2584     request->contexts->exp = client->exp;
2585 
2586     if (payload_len % sizeof(uint32_t) ||
2587         payload_len < sizeof(NBDBlockStatusPayload) ||
2588         payload_len > (sizeof(NBDBlockStatusPayload) +
2589                        sizeof(id) * client->contexts.count)) {
2590         goto skip;
2591     }
2592 
2593     buf = g_malloc(payload_len);
2594     if (nbd_read(client->ioc, buf, payload_len,
2595                  "CMD_BLOCK_STATUS data", errp) < 0) {
2596         return -EIO;
2597     }
2598     trace_nbd_co_receive_request_payload_received(request->cookie,
2599                                                   payload_len);
2600     request->contexts->bitmaps = g_new0(bool, nr_bitmaps);
2601     count = (payload_len - sizeof(NBDBlockStatusPayload)) / sizeof(id);
2602     payload_len = 0;
2603 
2604     for (i = 0; i < count; i++) {
2605         id = ldl_be_p(buf + sizeof(NBDBlockStatusPayload) + sizeof(id) * i);
2606         if (id == NBD_META_ID_BASE_ALLOCATION) {
2607             if (!client->contexts.base_allocation ||
2608                 request->contexts->base_allocation) {
2609                 goto skip;
2610             }
2611             request->contexts->base_allocation = true;
2612         } else if (id == NBD_META_ID_ALLOCATION_DEPTH) {
2613             if (!client->contexts.allocation_depth ||
2614                 request->contexts->allocation_depth) {
2615                 goto skip;
2616             }
2617             request->contexts->allocation_depth = true;
2618         } else {
2619             unsigned idx = id - NBD_META_ID_DIRTY_BITMAP;
2620 
2621             if (idx >= nr_bitmaps || !client->contexts.bitmaps[idx] ||
2622                 request->contexts->bitmaps[idx]) {
2623                 goto skip;
2624             }
2625             request->contexts->bitmaps[idx] = true;
2626         }
2627     }
2628 
2629     request->len = ldq_be_p(buf);
2630     request->contexts->count = count;
2631     return 0;
2632 
2633  skip:
2634     trace_nbd_co_receive_block_status_payload_compliance(request->from,
2635                                                          request->len);
2636     request->len = request->contexts->count = 0;
2637     return nbd_drop(client->ioc, payload_len, errp);
2638 }
2639 
2640 /* nbd_co_receive_request
2641  * Collect a client request. Return 0 if request looks valid, -EIO to drop
2642  * connection right away, -EAGAIN to indicate we were interrupted and the
2643  * channel should be quiesced, and any other negative value to report an error
2644  * to the client (although the caller may still need to disconnect after
2645  * reporting the error).
2646  */
2647 static int coroutine_fn nbd_co_receive_request(NBDRequestData *req,
2648                                                NBDRequest *request,
2649                                                Error **errp)
2650 {
2651     NBDClient *client = req->client;
2652     bool extended_with_payload;
2653     bool check_length = false;
2654     bool check_rofs = false;
2655     bool allocate_buffer = false;
2656     bool payload_okay = false;
2657     uint64_t payload_len = 0;
2658     int valid_flags = NBD_CMD_FLAG_FUA;
2659     int ret;
2660 
2661     g_assert(qemu_in_coroutine());
2662     ret = nbd_receive_request(client, request, errp);
2663     if (ret < 0) {
2664         return ret;
2665     }
2666 
2667     trace_nbd_co_receive_request_decode_type(request->cookie, request->type,
2668                                              nbd_cmd_lookup(request->type));
2669     extended_with_payload = client->mode >= NBD_MODE_EXTENDED &&
2670         request->flags & NBD_CMD_FLAG_PAYLOAD_LEN;
2671     if (extended_with_payload) {
2672         payload_len = request->len;
2673         check_length = true;
2674     }
2675 
2676     switch (request->type) {
2677     case NBD_CMD_DISC:
2678         /* Special case: we're going to disconnect without a reply,
2679          * whether or not flags, from, or len are bogus */
2680         req->complete = true;
2681         return -EIO;
2682 
2683     case NBD_CMD_READ:
2684         if (client->mode >= NBD_MODE_STRUCTURED) {
2685             valid_flags |= NBD_CMD_FLAG_DF;
2686         }
2687         check_length = true;
2688         allocate_buffer = true;
2689         break;
2690 
2691     case NBD_CMD_WRITE:
2692         if (client->mode >= NBD_MODE_EXTENDED) {
2693             if (!extended_with_payload) {
2694                 /* The client is noncompliant. Trace it, but proceed. */
2695                 trace_nbd_co_receive_ext_payload_compliance(request->from,
2696                                                             request->len);
2697             }
2698             valid_flags |= NBD_CMD_FLAG_PAYLOAD_LEN;
2699         }
2700         payload_okay = true;
2701         payload_len = request->len;
2702         check_length = true;
2703         allocate_buffer = true;
2704         check_rofs = true;
2705         break;
2706 
2707     case NBD_CMD_FLUSH:
2708         break;
2709 
2710     case NBD_CMD_TRIM:
2711         check_rofs = true;
2712         break;
2713 
2714     case NBD_CMD_CACHE:
2715         check_length = true;
2716         break;
2717 
2718     case NBD_CMD_WRITE_ZEROES:
2719         valid_flags |= NBD_CMD_FLAG_NO_HOLE | NBD_CMD_FLAG_FAST_ZERO;
2720         check_rofs = true;
2721         break;
2722 
2723     case NBD_CMD_BLOCK_STATUS:
2724         if (extended_with_payload) {
2725             ret = nbd_co_block_status_payload_read(client, request, errp);
2726             if (ret < 0) {
2727                 return ret;
2728             }
2729             /* payload now consumed */
2730             check_length = false;
2731             payload_len = 0;
2732             valid_flags |= NBD_CMD_FLAG_PAYLOAD_LEN;
2733         } else {
2734             request->contexts = &client->contexts;
2735         }
2736         valid_flags |= NBD_CMD_FLAG_REQ_ONE;
2737         break;
2738 
2739     default:
2740         /* Unrecognized, will fail later */
2741         ;
2742     }
2743 
2744     /* Payload and buffer handling. */
2745     if (!payload_len) {
2746         req->complete = true;
2747     }
2748     if (check_length && request->len > NBD_MAX_BUFFER_SIZE) {
2749         /* READ, WRITE, CACHE */
2750         error_setg(errp, "len (%" PRIu64 ") is larger than max len (%u)",
2751                    request->len, NBD_MAX_BUFFER_SIZE);
2752         return -EINVAL;
2753     }
2754     if (payload_len && !payload_okay) {
2755         /*
2756          * For now, we don't support payloads on other commands; but
2757          * we can keep the connection alive by ignoring the payload.
2758          * We will fail the command later with NBD_EINVAL for the use
2759          * of an unsupported flag (and not for access beyond bounds).
2760          */
2761         assert(request->type != NBD_CMD_WRITE);
2762         request->len = 0;
2763     }
2764     if (allocate_buffer) {
2765         /* READ, WRITE */
2766         req->data = blk_try_blockalign(client->exp->common.blk,
2767                                        request->len);
2768         if (req->data == NULL) {
2769             error_setg(errp, "No memory");
2770             return -ENOMEM;
2771         }
2772     }
2773     if (payload_len) {
2774         if (payload_okay) {
2775             /* WRITE */
2776             assert(req->data);
2777             ret = nbd_read(client->ioc, req->data, payload_len,
2778                            "CMD_WRITE data", errp);
2779         } else {
2780             ret = nbd_drop(client->ioc, payload_len, errp);
2781         }
2782         if (ret < 0) {
2783             return -EIO;
2784         }
2785         req->complete = true;
2786         trace_nbd_co_receive_request_payload_received(request->cookie,
2787                                                       payload_len);
2788     }
2789 
2790     /* Sanity checks. */
2791     if (client->exp->nbdflags & NBD_FLAG_READ_ONLY && check_rofs) {
2792         /* WRITE, TRIM, WRITE_ZEROES */
2793         error_setg(errp, "Export is read-only");
2794         return -EROFS;
2795     }
2796     if (request->from > client->exp->size ||
2797         request->len > client->exp->size - request->from) {
2798         error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu64
2799                    ", Size: %" PRIu64, request->from, request->len,
2800                    client->exp->size);
2801         return (request->type == NBD_CMD_WRITE ||
2802                 request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL;
2803     }
2804     if (client->check_align && !QEMU_IS_ALIGNED(request->from | request->len,
2805                                                 client->check_align)) {
2806         /*
2807          * The block layer gracefully handles unaligned requests, but
2808          * it's still worth tracing client non-compliance
2809          */
2810         trace_nbd_co_receive_align_compliance(nbd_cmd_lookup(request->type),
2811                                               request->from,
2812                                               request->len,
2813                                               client->check_align);
2814     }
2815     if (request->flags & ~valid_flags) {
2816         error_setg(errp, "unsupported flags for command %s (got 0x%x)",
2817                    nbd_cmd_lookup(request->type), request->flags);
2818         return -EINVAL;
2819     }
2820 
2821     return 0;
2822 }
2823 
2824 /* Send simple reply without a payload, or a structured error
2825  * @error_msg is ignored if @ret >= 0
2826  * Returns 0 if connection is still live, -errno on failure to talk to client
2827  */
2828 static coroutine_fn int nbd_send_generic_reply(NBDClient *client,
2829                                                NBDRequest *request,
2830                                                int ret,
2831                                                const char *error_msg,
2832                                                Error **errp)
2833 {
2834     if (client->mode >= NBD_MODE_STRUCTURED && ret < 0) {
2835         return nbd_co_send_chunk_error(client, request, -ret, error_msg, errp);
2836     } else if (client->mode >= NBD_MODE_EXTENDED) {
2837         return nbd_co_send_chunk_done(client, request, errp);
2838     } else {
2839         return nbd_co_send_simple_reply(client, request, ret < 0 ? -ret : 0,
2840                                         NULL, 0, errp);
2841     }
2842 }
2843 
2844 /* Handle NBD_CMD_READ request.
2845  * Return -errno if sending fails. Other errors are reported directly to the
2846  * client as an error reply. */
2847 static coroutine_fn int nbd_do_cmd_read(NBDClient *client, NBDRequest *request,
2848                                         uint8_t *data, Error **errp)
2849 {
2850     int ret;
2851     NBDExport *exp = client->exp;
2852 
2853     assert(request->type == NBD_CMD_READ);
2854     assert(request->len <= NBD_MAX_BUFFER_SIZE);
2855 
2856     /* XXX: NBD Protocol only documents use of FUA with WRITE */
2857     if (request->flags & NBD_CMD_FLAG_FUA) {
2858         ret = blk_co_flush(exp->common.blk);
2859         if (ret < 0) {
2860             return nbd_send_generic_reply(client, request, ret,
2861                                           "flush failed", errp);
2862         }
2863     }
2864 
2865     if (client->mode >= NBD_MODE_STRUCTURED &&
2866         !(request->flags & NBD_CMD_FLAG_DF) && request->len)
2867     {
2868         return nbd_co_send_sparse_read(client, request, request->from,
2869                                        data, request->len, errp);
2870     }
2871 
2872     ret = blk_co_pread(exp->common.blk, request->from, request->len, data, 0);
2873     if (ret < 0) {
2874         return nbd_send_generic_reply(client, request, ret,
2875                                       "reading from file failed", errp);
2876     }
2877 
2878     if (client->mode >= NBD_MODE_STRUCTURED) {
2879         if (request->len) {
2880             return nbd_co_send_chunk_read(client, request, request->from, data,
2881                                           request->len, true, errp);
2882         } else {
2883             return nbd_co_send_chunk_done(client, request, errp);
2884         }
2885     } else {
2886         return nbd_co_send_simple_reply(client, request, 0,
2887                                         data, request->len, errp);
2888     }
2889 }
2890 
2891 /*
2892  * nbd_do_cmd_cache
2893  *
2894  * Handle NBD_CMD_CACHE request.
2895  * Return -errno if sending fails. Other errors are reported directly to the
2896  * client as an error reply.
2897  */
2898 static coroutine_fn int nbd_do_cmd_cache(NBDClient *client, NBDRequest *request,
2899                                          Error **errp)
2900 {
2901     int ret;
2902     NBDExport *exp = client->exp;
2903 
2904     assert(request->type == NBD_CMD_CACHE);
2905     assert(request->len <= NBD_MAX_BUFFER_SIZE);
2906 
2907     ret = blk_co_preadv(exp->common.blk, request->from, request->len,
2908                         NULL, BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH);
2909 
2910     return nbd_send_generic_reply(client, request, ret,
2911                                   "caching data failed", errp);
2912 }
2913 
2914 /* Handle NBD request.
2915  * Return -errno if sending fails. Other errors are reported directly to the
2916  * client as an error reply. */
2917 static coroutine_fn int nbd_handle_request(NBDClient *client,
2918                                            NBDRequest *request,
2919                                            uint8_t *data, Error **errp)
2920 {
2921     int ret;
2922     int flags;
2923     NBDExport *exp = client->exp;
2924     char *msg;
2925     size_t i;
2926     bool inactive;
2927 
2928     WITH_GRAPH_RDLOCK_GUARD() {
2929         inactive = bdrv_is_inactive(blk_bs(exp->common.blk));
2930         if (inactive) {
2931             switch (request->type) {
2932             case NBD_CMD_READ:
2933                 /* These commands are allowed on inactive nodes */
2934                 break;
2935             default:
2936                 /* Return an error for the rest */
2937                 return nbd_send_generic_reply(client, request, -EPERM,
2938                                               "export is inactive", errp);
2939             }
2940         }
2941     }
2942 
2943     switch (request->type) {
2944     case NBD_CMD_CACHE:
2945         return nbd_do_cmd_cache(client, request, errp);
2946 
2947     case NBD_CMD_READ:
2948         return nbd_do_cmd_read(client, request, data, errp);
2949 
2950     case NBD_CMD_WRITE:
2951         flags = 0;
2952         if (request->flags & NBD_CMD_FLAG_FUA) {
2953             flags |= BDRV_REQ_FUA;
2954         }
2955         assert(request->len <= NBD_MAX_BUFFER_SIZE);
2956         ret = blk_co_pwrite(exp->common.blk, request->from, request->len, data,
2957                             flags);
2958         return nbd_send_generic_reply(client, request, ret,
2959                                       "writing to file failed", errp);
2960 
2961     case NBD_CMD_WRITE_ZEROES:
2962         flags = 0;
2963         if (request->flags & NBD_CMD_FLAG_FUA) {
2964             flags |= BDRV_REQ_FUA;
2965         }
2966         if (!(request->flags & NBD_CMD_FLAG_NO_HOLE)) {
2967             flags |= BDRV_REQ_MAY_UNMAP;
2968         }
2969         if (request->flags & NBD_CMD_FLAG_FAST_ZERO) {
2970             flags |= BDRV_REQ_NO_FALLBACK;
2971         }
2972         ret = blk_co_pwrite_zeroes(exp->common.blk, request->from, request->len,
2973                                    flags);
2974         return nbd_send_generic_reply(client, request, ret,
2975                                       "writing to file failed", errp);
2976 
2977     case NBD_CMD_DISC:
2978         /* unreachable, thanks to special case in nbd_co_receive_request() */
2979         abort();
2980 
2981     case NBD_CMD_FLUSH:
2982         ret = blk_co_flush(exp->common.blk);
2983         return nbd_send_generic_reply(client, request, ret,
2984                                       "flush failed", errp);
2985 
2986     case NBD_CMD_TRIM:
2987         ret = blk_co_pdiscard(exp->common.blk, request->from, request->len);
2988         if (ret >= 0 && request->flags & NBD_CMD_FLAG_FUA) {
2989             ret = blk_co_flush(exp->common.blk);
2990         }
2991         return nbd_send_generic_reply(client, request, ret,
2992                                       "discard failed", errp);
2993 
2994     case NBD_CMD_BLOCK_STATUS:
2995         assert(request->contexts);
2996         assert(client->mode >= NBD_MODE_EXTENDED ||
2997                request->len <= UINT32_MAX);
2998         if (request->contexts->count) {
2999             bool dont_fragment = request->flags & NBD_CMD_FLAG_REQ_ONE;
3000             int contexts_remaining = request->contexts->count;
3001 
3002             if (!request->len) {
3003                 return nbd_send_generic_reply(client, request, -EINVAL,
3004                                               "need non-zero length", errp);
3005             }
3006             if (request->contexts->base_allocation) {
3007                 ret = nbd_co_send_block_status(client, request,
3008                                                exp->common.blk,
3009                                                request->from,
3010                                                request->len, dont_fragment,
3011                                                !--contexts_remaining,
3012                                                NBD_META_ID_BASE_ALLOCATION,
3013                                                errp);
3014                 if (ret < 0) {
3015                     return ret;
3016                 }
3017             }
3018 
3019             if (request->contexts->allocation_depth) {
3020                 ret = nbd_co_send_block_status(client, request,
3021                                                exp->common.blk,
3022                                                request->from, request->len,
3023                                                dont_fragment,
3024                                                !--contexts_remaining,
3025                                                NBD_META_ID_ALLOCATION_DEPTH,
3026                                                errp);
3027                 if (ret < 0) {
3028                     return ret;
3029                 }
3030             }
3031 
3032             assert(request->contexts->exp == client->exp);
3033             for (i = 0; i < client->exp->nr_export_bitmaps; i++) {
3034                 if (!request->contexts->bitmaps[i]) {
3035                     continue;
3036                 }
3037                 ret = nbd_co_send_bitmap(client, request,
3038                                          client->exp->export_bitmaps[i],
3039                                          request->from, request->len,
3040                                          dont_fragment, !--contexts_remaining,
3041                                          NBD_META_ID_DIRTY_BITMAP + i, errp);
3042                 if (ret < 0) {
3043                     return ret;
3044                 }
3045             }
3046 
3047             assert(!contexts_remaining);
3048 
3049             return 0;
3050         } else if (client->contexts.count) {
3051             return nbd_send_generic_reply(client, request, -EINVAL,
3052                                           "CMD_BLOCK_STATUS payload not valid",
3053                                           errp);
3054         } else {
3055             return nbd_send_generic_reply(client, request, -EINVAL,
3056                                           "CMD_BLOCK_STATUS not negotiated",
3057                                           errp);
3058         }
3059 
3060     default:
3061         msg = g_strdup_printf("invalid request type (%" PRIu32 ") received",
3062                               request->type);
3063         ret = nbd_send_generic_reply(client, request, -EINVAL, msg,
3064                                      errp);
3065         g_free(msg);
3066         return ret;
3067     }
3068 }
3069 
3070 /* Owns a reference to the NBDClient passed as opaque.  */
3071 static coroutine_fn void nbd_trip(void *opaque)
3072 {
3073     NBDRequestData *req = opaque;
3074     NBDClient *client = req->client;
3075     NBDRequest request = { 0 };    /* GCC thinks it can be used uninitialized */
3076     int ret;
3077     Error *local_err = NULL;
3078 
3079     /*
3080      * Note that nbd_client_put() and client_close() must be called from the
3081      * main loop thread. Use aio_co_reschedule_self() to switch AioContext
3082      * before calling these functions.
3083      */
3084 
3085     trace_nbd_trip();
3086 
3087     qemu_mutex_lock(&client->lock);
3088 
3089     if (client->closing) {
3090         goto done;
3091     }
3092 
3093     if (client->quiescing) {
3094         /*
3095          * We're switching between AIO contexts. Don't attempt to receive a new
3096          * request and kick the main context which may be waiting for us.
3097          */
3098         client->recv_coroutine = NULL;
3099         aio_wait_kick();
3100         goto done;
3101     }
3102 
3103     /*
3104      * nbd_co_receive_request() returns -EAGAIN when nbd_drained_begin() has
3105      * set client->quiescing but by the time we get back nbd_drained_end() may
3106      * have already cleared client->quiescing. In that case we try again
3107      * because nothing else will spawn an nbd_trip() coroutine until we set
3108      * client->recv_coroutine = NULL further down.
3109      */
3110     do {
3111         assert(client->recv_coroutine == qemu_coroutine_self());
3112         qemu_mutex_unlock(&client->lock);
3113         ret = nbd_co_receive_request(req, &request, &local_err);
3114         qemu_mutex_lock(&client->lock);
3115     } while (ret == -EAGAIN && !client->quiescing);
3116 
3117     client->recv_coroutine = NULL;
3118 
3119     if (client->closing) {
3120         /*
3121          * The client may be closed when we are blocked in
3122          * nbd_co_receive_request()
3123          */
3124         goto done;
3125     }
3126 
3127     if (ret == -EAGAIN) {
3128         goto done;
3129     }
3130 
3131     nbd_client_receive_next_request(client);
3132 
3133     if (ret == -EIO) {
3134         goto disconnect;
3135     }
3136 
3137     qemu_mutex_unlock(&client->lock);
3138     qio_channel_set_cork(client->ioc, true);
3139 
3140     if (ret < 0) {
3141         /* It wasn't -EIO, so, according to nbd_co_receive_request()
3142          * semantics, we should return the error to the client. */
3143         Error *export_err = local_err;
3144 
3145         local_err = NULL;
3146         ret = nbd_send_generic_reply(client, &request, -EINVAL,
3147                                      error_get_pretty(export_err), &local_err);
3148         error_free(export_err);
3149     } else {
3150         ret = nbd_handle_request(client, &request, req->data, &local_err);
3151     }
3152     if (request.contexts && request.contexts != &client->contexts) {
3153         assert(request.type == NBD_CMD_BLOCK_STATUS);
3154         g_free(request.contexts->bitmaps);
3155         g_free(request.contexts);
3156     }
3157 
3158     qio_channel_set_cork(client->ioc, false);
3159     qemu_mutex_lock(&client->lock);
3160 
3161     if (ret < 0) {
3162         error_prepend(&local_err, "Failed to send reply: ");
3163         goto disconnect;
3164     }
3165 
3166     /*
3167      * We must disconnect after NBD_CMD_WRITE or BLOCK_STATUS with
3168      * payload if we did not read the payload.
3169      */
3170     if (!req->complete) {
3171         error_setg(&local_err, "Request handling failed in intermediate state");
3172         goto disconnect;
3173     }
3174 
3175 done:
3176     nbd_request_put(req);
3177 
3178     qemu_mutex_unlock(&client->lock);
3179 
3180     if (!nbd_client_put_nonzero(client)) {
3181         aio_co_reschedule_self(qemu_get_aio_context());
3182         nbd_client_put(client);
3183     }
3184     return;
3185 
3186 disconnect:
3187     if (local_err) {
3188         error_reportf_err(local_err, "Disconnect client, due to: ");
3189     }
3190 
3191     nbd_request_put(req);
3192     qemu_mutex_unlock(&client->lock);
3193 
3194     aio_co_reschedule_self(qemu_get_aio_context());
3195     client_close(client, true);
3196     nbd_client_put(client);
3197 }
3198 
3199 /*
3200  * Runs in export AioContext and main loop thread. Caller must hold
3201  * client->lock.
3202  */
3203 static void nbd_client_receive_next_request(NBDClient *client)
3204 {
3205     NBDRequestData *req;
3206 
3207     if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS &&
3208         !client->quiescing) {
3209         nbd_client_get(client);
3210         req = nbd_request_get(client);
3211         client->recv_coroutine = qemu_coroutine_create(nbd_trip, req);
3212         aio_co_schedule(client->exp->common.ctx, client->recv_coroutine);
3213     }
3214 }
3215 
3216 static void nbd_handshake_timer_cb(void *opaque)
3217 {
3218     QIOChannel *ioc = opaque;
3219 
3220     trace_nbd_handshake_timer_cb();
3221     qio_channel_shutdown(ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
3222 }
3223 
3224 static coroutine_fn void nbd_co_client_start(void *opaque)
3225 {
3226     NBDClient *client = opaque;
3227     Error *local_err = NULL;
3228     QEMUTimer *handshake_timer = NULL;
3229 
3230     qemu_co_mutex_init(&client->send_lock);
3231 
3232     /*
3233      * Create a timer to bound the time spent in negotiation. If the
3234      * timer expires, it is likely nbd_negotiate will fail because the
3235      * socket was shutdown.
3236      */
3237     if (client->handshake_max_secs > 0) {
3238         handshake_timer = aio_timer_new(qemu_get_aio_context(),
3239                                         QEMU_CLOCK_REALTIME,
3240                                         SCALE_NS,
3241                                         nbd_handshake_timer_cb,
3242                                         client->sioc);
3243         timer_mod(handshake_timer,
3244                   qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
3245                   client->handshake_max_secs * NANOSECONDS_PER_SECOND);
3246     }
3247 
3248     if (nbd_negotiate(client, &local_err)) {
3249         if (local_err) {
3250             error_report_err(local_err);
3251         }
3252         timer_free(handshake_timer);
3253         client_close(client, false);
3254         return;
3255     }
3256 
3257     timer_free(handshake_timer);
3258     WITH_QEMU_LOCK_GUARD(&client->lock) {
3259         nbd_client_receive_next_request(client);
3260     }
3261 }
3262 
3263 /*
3264  * Create a new client listener using the given channel @sioc and @owner.
3265  * Begin servicing it in a coroutine.  When the connection closes, call
3266  * @close_fn with an indication of whether the client completed negotiation
3267  * within @handshake_max_secs seconds (0 for unbounded).
3268  */
3269 void nbd_client_new(QIOChannelSocket *sioc,
3270                     uint32_t handshake_max_secs,
3271                     QCryptoTLSCreds *tlscreds,
3272                     const char *tlsauthz,
3273                     void (*close_fn)(NBDClient *, bool),
3274                     void *owner)
3275 {
3276     NBDClient *client;
3277     Coroutine *co;
3278 
3279     client = g_new0(NBDClient, 1);
3280     qemu_mutex_init(&client->lock);
3281     client->refcount = 1;
3282     client->tlscreds = tlscreds;
3283     if (tlscreds) {
3284         object_ref(OBJECT(client->tlscreds));
3285     }
3286     client->tlsauthz = g_strdup(tlsauthz);
3287     client->handshake_max_secs = handshake_max_secs;
3288     client->sioc = sioc;
3289     qio_channel_set_delay(QIO_CHANNEL(sioc), false);
3290     object_ref(OBJECT(client->sioc));
3291     client->ioc = QIO_CHANNEL(sioc);
3292     object_ref(OBJECT(client->ioc));
3293     client->close_fn = close_fn;
3294     client->owner = owner;
3295 
3296     nbd_set_socket_send_buffer(sioc);
3297 
3298     co = qemu_coroutine_create(nbd_co_client_start, client);
3299     qemu_coroutine_enter(co);
3300 }
3301 
3302 void *
3303 nbd_client_owner(NBDClient *client)
3304 {
3305     return client->owner;
3306 }
3307